Passed
Push — master ( d477d4...8fee2a )
by Roeland
14:43 queued 10s
created

JSCombiner   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 225
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 105
c 1
b 0
f 0
dl 0
loc 225
rs 9.84
wmc 32

7 Methods

Rating   Name   Duplication   Size   Complexity  
A process() 0 21 5
A __construct() 0 11 1
A resetCache() 0 6 3
B cache() 0 48 7
A getCachedJS() 0 6 1
C isCached() 0 42 12
A getContent() 0 17 3
1
<?php
2
/**
3
 * @copyright 2017, Roeland Jago Douma <[email protected]>
4
 *
5
 * @author Christoph Wurst <[email protected]>
6
 * @author Julius Härtl <[email protected]>
7
 * @author Lukas Reschke <[email protected]>
8
 * @author Morris Jobke <[email protected]>
9
 * @author Roeland Jago Douma <[email protected]>
10
 *
11
 * @license GNU AGPL version 3 or any later version
12
 *
13
 * This program is free software: you can redistribute it and/or modify
14
 * it under the terms of the GNU Affero General Public License as
15
 * published by the Free Software Foundation, either version 3 of the
16
 * License, or (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU Affero General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU Affero General Public License
24
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25
 *
26
 */
27
28
namespace OC\Template;
29
30
use OC\SystemConfig;
31
use OCP\Files\IAppData;
32
use OCP\Files\NotFoundException;
33
use OCP\Files\NotPermittedException;
34
use OCP\Files\SimpleFS\ISimpleFolder;
35
use OCP\ICache;
36
use OCP\ICacheFactory;
37
use OCP\ILogger;
38
use OCP\IURLGenerator;
39
40
class JSCombiner {
41
42
	/** @var IAppData */
43
	protected $appData;
44
45
	/** @var IURLGenerator */
46
	protected $urlGenerator;
47
48
	/** @var ICache */
49
	protected $depsCache;
50
51
	/** @var SystemConfig */
52
	protected $config;
53
54
	/** @var ILogger */
55
	protected $logger;
56
57
	/** @var ICacheFactory */
58
	private $cacheFactory;
59
60
	/**
61
	 * @param IAppData $appData
62
	 * @param IURLGenerator $urlGenerator
63
	 * @param ICacheFactory $cacheFactory
64
	 * @param SystemConfig $config
65
	 * @param ILogger $logger
66
	 */
67
	public function __construct(IAppData $appData,
68
								IURLGenerator $urlGenerator,
69
								ICacheFactory $cacheFactory,
70
								SystemConfig $config,
71
								ILogger $logger) {
72
		$this->appData = $appData;
73
		$this->urlGenerator = $urlGenerator;
74
		$this->cacheFactory = $cacheFactory;
75
		$this->depsCache = $this->cacheFactory->createDistributed('JS-' . md5($this->urlGenerator->getBaseUrl()));
76
		$this->config = $config;
77
		$this->logger = $logger;
78
	}
79
80
	/**
81
	 * @param string $root
82
	 * @param string $file
83
	 * @param string $app
84
	 * @return bool
85
	 */
86
	public function process($root, $file, $app) {
87
		if ($this->config->getValue('debug') || !$this->config->getValue('installed')) {
88
			return false;
89
		}
90
91
		$path = explode('/', $root . '/' . $file);
92
93
		$fileName = array_pop($path);
94
		$path = implode('/', $path);
95
96
		try {
97
			$folder = $this->appData->getFolder($app);
98
		} catch (NotFoundException $e) {
99
			// creating css appdata folder
100
			$folder = $this->appData->newFolder($app);
101
		}
102
103
		if ($this->isCached($fileName, $folder)) {
104
			return true;
105
		}
106
		return $this->cache($path, $fileName, $folder);
107
	}
108
109
	/**
110
	 * @param string $fileName
111
	 * @param ISimpleFolder $folder
112
	 * @return bool
113
	 */
114
	protected function isCached($fileName, ISimpleFolder $folder) {
115
		$fileName = str_replace('.json', '.js', $fileName);
116
117
		if (!$folder->fileExists($fileName)) {
118
			return false;
119
		}
120
121
		$fileName = $fileName . '.deps';
122
		try {
123
			$deps = $this->depsCache->get($folder->getName() . '-' . $fileName);
124
			$fromCache = true;
125
			if ($deps === null || $deps === '') {
126
				$fromCache = false;
127
				$depFile = $folder->getFile($fileName);
128
				$deps = $depFile->getContent();
129
			}
130
131
			// check again
132
			if ($deps === null || $deps === '') {
133
				$this->logger->info('JSCombiner: deps file empty: ' . $fileName);
134
				return false;
135
			}
136
137
			$deps = json_decode($deps, true);
138
139
			if ($deps === null) {
140
				return false;
141
			}
142
143
			foreach ($deps as $file => $mtime) {
144
				if (!file_exists($file) || filemtime($file) > $mtime) {
145
					return false;
146
				}
147
			}
148
149
			if ($fromCache === false) {
150
				$this->depsCache->set($folder->getName() . '-' . $fileName, json_encode($deps));
151
			}
152
153
			return true;
154
		} catch (NotFoundException $e) {
155
			return false;
156
		}
157
	}
158
159
	/**
160
	 * @param string $path
161
	 * @param string $fileName
162
	 * @param ISimpleFolder $folder
163
	 * @return bool
164
	 */
165
	protected function cache($path, $fileName, ISimpleFolder $folder) {
166
		$deps = [];
167
		$fullPath = $path . '/' . $fileName;
168
		$data = json_decode(file_get_contents($fullPath));
169
		$deps[$fullPath] = filemtime($fullPath);
170
171
		$res = '';
172
		foreach ($data as $file) {
173
			$filePath = $path . '/' . $file;
174
175
			if (is_file($filePath)) {
176
				$res .= file_get_contents($filePath);
177
				$res .= PHP_EOL . PHP_EOL;
178
				$deps[$filePath] = filemtime($filePath);
179
			}
180
		}
181
182
		$fileName = str_replace('.json', '.js', $fileName);
183
		try {
184
			$cachedfile = $folder->getFile($fileName);
185
		} catch (NotFoundException $e) {
186
			$cachedfile = $folder->newFile($fileName);
187
		}
188
189
		$depFileName = $fileName . '.deps';
190
		try {
191
			$depFile = $folder->getFile($depFileName);
192
		} catch (NotFoundException $e) {
193
			$depFile = $folder->newFile($depFileName);
194
		}
195
196
		try {
197
			$gzipFile = $folder->getFile($fileName . '.gzip'); # Safari doesn't like .gz
198
		} catch (NotFoundException $e) {
199
			$gzipFile = $folder->newFile($fileName . '.gzip'); # Safari doesn't like .gz
200
		}
201
202
		try {
203
			$cachedfile->putContent($res);
204
			$deps = json_encode($deps);
205
			$depFile->putContent($deps);
206
			$this->depsCache->set($folder->getName() . '-' . $depFileName, $deps);
207
			$gzipFile->putContent(gzencode($res, 9));
208
			$this->logger->debug('JSCombiner: successfully cached: ' . $fileName);
209
			return true;
210
		} catch (NotPermittedException $e) {
211
			$this->logger->error('JSCombiner: unable to cache: ' . $fileName);
212
			return false;
213
		}
214
	}
215
216
	/**
217
	 * @param string $appName
218
	 * @param string $fileName
219
	 * @return string
220
	 */
221
	public function getCachedJS($appName, $fileName) {
222
		$tmpfileLoc = explode('/', $fileName);
223
		$fileName = array_pop($tmpfileLoc);
224
		$fileName = str_replace('.json', '.js', $fileName);
225
226
		return substr($this->urlGenerator->linkToRoute('core.Js.getJs', ['fileName' => $fileName, 'appName' => $appName]), strlen(\OC::$WEBROOT) + 1);
227
	}
228
229
	/**
230
	 * @param string $root
231
	 * @param string $file
232
	 * @return string[]
233
	 */
234
	public function getContent($root, $file) {
235
		/** @var array $data */
236
		$data = json_decode(file_get_contents($root . '/' . $file));
237
		if (!is_array($data)) {
0 ignored issues
show
introduced by
The condition is_array($data) is always true.
Loading history...
238
			return [];
239
		}
240
241
		$path = explode('/', $file);
242
		array_pop($path);
243
		$path = implode('/', $path);
244
245
		$result = [];
246
		foreach ($data as $f) {
247
			$result[] = $path . '/' . $f;
248
		}
249
250
		return $result;
251
	}
252
253
254
	/**
255
	 * Clear cache with combined javascript files
256
	 *
257
	 * @throws NotFoundException
258
	 */
259
	public function resetCache() {
260
		$this->cacheFactory->createDistributed('JS-')->clear();
261
		$appDirectory = $this->appData->getDirectoryListing();
262
		foreach ($appDirectory as $folder) {
263
			foreach ($folder->getDirectoryListing() as $file) {
264
				$file->delete();
265
			}
266
		}
267
	}
268
}
269