-
Notifications
You must be signed in to change notification settings - Fork 264
/
MediaService.php
441 lines (371 loc) · 15.6 KB
/
MediaService.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
<?php
/*
* Copyright (c) 2022 Xibo Signage Ltd
*
* Xibo - Digital Signage - http://www.xibo.org.uk
*
* This file is part of Xibo.
*
* Xibo is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Xibo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Xibo. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Xibo\Service;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Mimey\MimeTypes;
use Slim\Routing\RouteParser;
use Stash\Interfaces\PoolInterface;
use Stash\Invalidation;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Xibo\Entity\User;
use Xibo\Event\MediaDeleteEvent;
use Xibo\Factory\MediaFactory;
use Xibo\Helper\ByteFormatter;
use Xibo\Helper\DateFormatHelper;
use Xibo\Helper\Environment;
use Xibo\Helper\SanitizerService;
use Xibo\Storage\StorageServiceInterface;
use Xibo\Support\Exception\ConfigurationException;
use Xibo\Support\Exception\InvalidArgumentException;
use Xibo\Support\Exception\LibraryFullException;
/**
* MediaService
*/
class MediaService implements MediaServiceInterface
{
/** @var ConfigServiceInterface */
private $configService;
/** @var LogServiceInterface */
private $log;
/** @var StorageServiceInterface */
private $store;
/** @var SanitizerService */
private $sanitizerService;
/** @var PoolInterface */
private $pool;
/** @var MediaFactory */
private $mediaFactory;
/** @var User */
private $user;
/** @var EventDispatcherInterface */
private $dispatcher;
/** @inheritDoc */
public function __construct(
ConfigServiceInterface $configService,
LogServiceInterface $logService,
StorageServiceInterface $store,
SanitizerService $sanitizerService,
PoolInterface $pool,
MediaFactory $mediaFactory
) {
$this->configService = $configService;
$this->log = $logService;
$this->store = $store;
$this->sanitizerService = $sanitizerService;
$this->pool = $pool;
$this->mediaFactory = $mediaFactory;
}
/** @inheritDoc */
public function setUser(User $user) : MediaServiceInterface
{
$this->user = $user;
return $this;
}
/** @inheritDoc */
public function getUser() : User
{
return $this->user;
}
/** @inheritDoc */
public function setDispatcher(EventDispatcherInterface $dispatcher): MediaServiceInterface
{
$this->dispatcher = $dispatcher;
return $this;
}
/** @inheritDoc */
public function fontCKEditorConfig(RouteParser $routeParser): string
{
// Regenerate the CSS for fonts
$css = $this->installFonts($routeParser, ['invalidateCache' => false]);
return $css['ckeditor'];
}
/** @inheritDoc */
public function libraryUsage(): int
{
$results = $this->store->select('SELECT IFNULL(SUM(FileSize), 0) AS SumSize FROM media', []);
return $this->sanitizerService->getSanitizer($results[0])->getInt('SumSize');
}
/** @inheritDoc */
public function initLibrary(): MediaServiceInterface
{
MediaService::ensureLibraryExists($this->configService->getSetting('LIBRARY_LOCATION'));
return $this;
}
/** @inheritDoc */
public function checkLibraryOrQuotaFull($isCheckUser = false): MediaServiceInterface
{
// Check that we have some space in our library
$librarySizeLimit = $this->configService->getSetting('LIBRARY_SIZE_LIMIT_KB') * 1024;
$librarySizeLimitMB = round(($librarySizeLimit / 1024) / 1024, 2);
if ($librarySizeLimit > 0 && $this->libraryUsage() > $librarySizeLimit) {
throw new LibraryFullException(sprintf(__('Your library is full. Library Limit: %s MB'), $librarySizeLimitMB));
}
if ($isCheckUser) {
$this->getUser()->isQuotaFullByUser();
}
return $this;
}
/** @inheritDoc */
public function checkMaxUploadSize($size): MediaServiceInterface
{
if (ByteFormatter::toBytes(Environment::getMaxUploadSize()) < $size) {
throw new InvalidArgumentException(
sprintf(__('This file size exceeds your environment Max Upload Size %s'), Environment::getMaxUploadSize()),
'size'
);
}
return $this;
}
/** @inheritDoc */
public function getDownloadInfo($url): array
{
$downloadInfo = [];
$guzzle = new Client($this->configService->getGuzzleProxy());
// first try to get the extension from pathinfo
$info = pathinfo(parse_url($url, PHP_URL_PATH));
$extension = $info['extension'] ?? '';
$size = -1;
try {
$head = $guzzle->head($url);
// First chance at getting the content length so that we can fail early.
// Will fail for downloads with redirects.
if ($head->hasHeader('Content-Length')) {
$contentLength = $head->getHeader('Content-Length');
foreach ($contentLength as $value) {
$size = $value;
}
}
if (empty($extension)) {
$contentType = $head->getHeaderLine('Content-Type');
$extension = $contentType;
if ($contentType === 'binary/octet-stream' && $head->hasHeader('x-amz-meta-filetype')) {
$amazonContentType = $head->getHeaderLine('x-amz-meta-filetype');
$extension = $amazonContentType;
}
// get the extension corresponding to the mime type
$mimeTypes = new MimeTypes();
$extension = $mimeTypes->getExtension($extension);
}
} catch (RequestException $e) {
$this->log->debug('Upload from url head request failed for URL ' . $url
. ' with following message ' . $e->getMessage());
}
$downloadInfo['size'] = $size;
$downloadInfo['extension'] = $extension;
$downloadInfo['filename'] = $info['filename'];
return $downloadInfo;
}
/** @inheritDoc */
public function installFonts(RouteParser $routeParser, $options = [])
{
$options = array_merge([
'invalidateCache' => true
], $options);
$this->log->debug('Install Fonts called with options: ' . json_encode($options));
// Drop the entire font cache as we cannot selectively tell whether the change that caused
// this effects all users or not.
// Important to note, that we aren't regenerating each user at this point in time, we're only clearing the cache
// for them all and generating the current user.
// We then make sure that subsequent generates do not change the library fonts.css
if ($options['invalidateCache']) {
$this->log->debug('Dropping font cache and regenerating.');
$this->pool->deleteItem('fontCss/');
}
// Each user has their own font cache (due to permissions) and the displays have their own font cache too
// Get the item from the cache
$cssItem = $this->pool->getItem('fontCss/' . $this->getUser()->userId);
$cssItem->setInvalidationMethod(Invalidation::SLEEP, 5000, 15);
// Get the CSS
$cssDetails = $cssItem->get();
if ($options['invalidateCache'] || $cssItem->isMiss()) {
$this->log->debug('Regenerating font cache');
// lock the cache
$cssItem->lock(60);
// Go through all installed fonts each time and regenerate.
$fontTemplate = '@font-face {
font-family: \'[family]\';
src: url(\'[url]\');
}';
// Save a fonts.css file to the library for use as a module
$fonts = $this->mediaFactory->getByMediaType('font');
$css = '';
$localCss = '';
$ckEditorString = '';
$fontList = [];
// Check the library exists
$libraryLocation = $this->configService->getSetting('LIBRARY_LOCATION');
MediaService::ensureLibraryExists($this->configService->getSetting('LIBRARY_LOCATION'));
if (count($fonts) > 0) {
// Build our font strings.
foreach ($fonts as $font) {
// Skip unreleased fonts
if ($font->released == 0) {
continue;
}
// Separate out the display name and the referenced name
// (referenced name cannot contain any odd characters or numbers)
$displayName = $font->name;
$familyName = strtolower(preg_replace('/\s+/', ' ', preg_replace('/\d+/u', '', $font->name)));
// Css for the player contains the actual stored as location of the font.
$css .= str_replace('[url]', $font->storedAs, str_replace('[family]', $familyName, $fontTemplate));
// Test to see if this user should have access to this font
if ($this->getUser()->checkViewable($font)) {
// Css for the local CMS contains the full download path to the font
$url = $routeParser->urlFor('library.download', ['type' => 'font', 'id' => $font->mediaId]);
$localCss .= str_replace('[url]', $url, str_replace('[family]', $familyName, $fontTemplate));
// CKEditor string
$ckEditorString .= $displayName . '/' . $familyName . ';';
// Font list
$fontList[] = [
'displayName' => $displayName,
'familyName' => $familyName
];
}
}
// If we're a full regenerate, we want to also update the fonts.css file.
if ($options['invalidateCache']) {
// Pull out the currently stored fonts.css from the library (if it exists)
$existingLibraryFontsCss = '';
if (file_exists($libraryLocation . 'fonts.css')) {
$existingLibraryFontsCss = file_get_contents($libraryLocation . 'fonts.css');
}
// Put the player CSS into the temporary library location
$tempUrl = $this->configService->getSetting('LIBRARY_LOCATION') . 'temp/fonts.css';
file_put_contents($tempUrl, $css);
// Install it (doesn't expire, isn't a system file, force update)
$media = $this->mediaFactory->createModuleSystemFile('fonts.css', $tempUrl);
$media->expires = 0;
$media->moduleSystemFile = true;
$media->isSaveRequired = true;
$media->save(['saveTags' => false]);
// We can remove the temp file
@unlink($tempUrl);
// Check to see if the existing file is different from the new one
if ($existingLibraryFontsCss == '' || md5($existingLibraryFontsCss) !== $media->md5) {
$this->log->info('Detected change in fonts.css file, dropping the Display cache');
// Clear the display cache
$this->pool->deleteItem('/display');
} else {
$this->log->debug('Newly generated font cache is the same as the old cache. Ignoring.');
}
}
$cssDetails = [
'css' => $localCss,
'ckeditor' => $ckEditorString,
'list' => $fontList
];
$cssItem->set($cssDetails);
$cssItem->expiresAfter(new \DateInterval('P30D'));
$this->pool->saveDeferred($cssItem);
} else {
$cssDetails = [
'css' => '',
'ckeditor' => '',
'list' => []
];
}
} else {
$this->log->debug('CMS font CSS returned from Cache.');
}
// Return a fonts css string for use locally (in the CMS)
return $cssDetails;
}
/** @inheritDoc */
public static function ensureLibraryExists($libraryFolder)
{
// Check that this location exists - and if not create it..
if (!file_exists($libraryFolder)) {
mkdir($libraryFolder, 0777, true);
}
if (!file_exists($libraryFolder . '/temp')) {
mkdir($libraryFolder . '/temp', 0777, true);
}
if (!file_exists($libraryFolder . '/cache')) {
mkdir($libraryFolder . '/cache', 0777, true);
}
if (!file_exists($libraryFolder . '/screenshots')) {
mkdir($libraryFolder . '/screenshots', 0777, true);
}
if (!file_exists($libraryFolder . '/attachment')) {
mkdir($libraryFolder . '/attachment', 0777, true);
}
if (!file_exists($libraryFolder . '/thumbs')) {
mkdir($libraryFolder . '/thumbs', 0777, true);
}
// Check that we are now writable - if not then error
if (!is_writable($libraryFolder)) {
throw new ConfigurationException(__('Library not writable'));
}
}
/** @inheritDoc */
public function removeTempFiles()
{
$libraryTemp = $this->configService->getSetting('LIBRARY_LOCATION') . 'temp';
if (!is_dir($libraryTemp)) {
return;
}
// Dump the files in the temp folder
foreach (scandir($libraryTemp) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
// Has this file been written to recently?
if (filemtime($libraryTemp . DIRECTORY_SEPARATOR . $item) > Carbon::now()->subSeconds(86400)->format('U')) {
$this->log->debug('Skipping active file: ' . $item);
continue;
}
$this->log->debug('Deleting temp file: ' . $item);
unlink($libraryTemp . DIRECTORY_SEPARATOR . $item);
}
}
/** @inheritDoc */
public function removeExpiredFiles()
{
// Get a list of all expired files and delete them
foreach ($this->mediaFactory->query(
null,
[
'expires' => Carbon::now()->format('U'),
'allModules' => 1,
'length' => 100
]
) as $entry) {
// If the media type is a module, then pretend it's a generic file
$this->log->info(sprintf('Removing Expired File %s', $entry->name));
$this->log->audit(
'Media',
$entry->mediaId,
'Removing Expired',
[
'mediaId' => $entry->mediaId,
'name' => $entry->name,
'expired' => Carbon::createFromTimestamp($entry->expires)
->format(DateFormatHelper::getSystemFormat())
]
);
$this->dispatcher->dispatch(new MediaDeleteEvent($entry), MediaDeleteEvent::$NAME);
$entry->delete();
}
}
}