-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBynderDriver.php
More file actions
827 lines (752 loc) · 23.8 KB
/
BynderDriver.php
File metadata and controls
827 lines (752 loc) · 23.8 KB
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
<?php
declare(strict_types=1);
namespace BeechIt\Bynder\Resource;
/*
* This source file is proprietary property of Beech.it
* Date: 19-2-18
* All code (c) Beech.it all rights reserved
*/
use BeechIt\Bynder\Exception\NotImplementedException;
use BeechIt\Bynder\Service\BynderService;
use Bynder\Api\Impl\AssetBankManager;
use TYPO3\CMS\Core\Resource\Driver\DriverInterface;
use TYPO3\CMS\Core\Resource\Exception;
use TYPO3\CMS\Core\Resource\ResourceStorage;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* Class BynderDriver
*/
class BynderDriver implements DriverInterface
{
const KEY = 'bynder';
const ASSET_TYPE_VIDEO = 'video';
const ASSET_TYPE_IMAGE = 'image';
/**
* @var array
*/
protected static $tempFiles = [];
/**
* @var string
*/
protected $rootFolder = '';
/**
* The capabilities of this driver. See Storage::CAPABILITY_* constants for possible values.
*
* @var int
*/
protected $capabilities = 0;
/**
* The storage uid the driver was instantiated for
*
* @var int
*/
protected $storageUid;
/**
* The configuration of this driver
*
* @var array
*/
protected $configuration = [];
/**
* @var AssetBankManager
*/
protected $assetBankManager;
/**
* @var BynderService
*/
protected $bynderService;
/**
* Creates this object.
*
* @param array $configuration
*/
public function __construct(array $configuration = [])
{
$this->capabilities =
ResourceStorage::CAPABILITY_BROWSABLE
| ResourceStorage::CAPABILITY_PUBLIC
| ResourceStorage::CAPABILITY_WRITABLE;
}
public function processConfiguration()
{
}
/**
* Checks a fileName for validity. This could be overidden in concrete
* drivers if they have different file naming rules.
*
* @param string $fileName
* @return bool TRUE if file name is valid
*/
protected function isValidFilename($fileName)
{
if (strpos($fileName, '/') !== false) {
return false;
}
if (!preg_match('/^[\\pL\\d[:blank:]._-]*$/u', $fileName)) {
return false;
}
return true;
}
/**
* Sets the storage uid the driver belongs to
*
* @param int $storageUid
*/
public function setStorageUid($storageUid)
{
$this->storageUid = $storageUid;
}
/**
* Returns the capabilities of this driver.
*
* @return int
* @see Storage::CAPABILITY_* constants
*/
public function getCapabilities()
{
return $this->capabilities;
}
public function initialize()
{
}
/**
* @param int $capabilities
* @return int
*/
public function mergeConfigurationCapabilities($capabilities)
{
$this->capabilities &= $capabilities;
return $this->capabilities;
}
/**
* @param int $capability
* @return bool|int
*/
public function hasCapability($capability)
{
return $this->capabilities & $capability === (int)$capability;
}
/**
* @return bool
*/
public function isCaseSensitiveFileSystem()
{
return true;
}
/**
* @param string $fileName
* @param string $charset
* @return string
*/
public function sanitizeFileName($fileName, $charset = '')
{
// Bynder allows all
return $fileName;
}
/**
* @param string $identifier
* @return string
*/
public function hashIdentifier($identifier)
{
return sha1($identifier);
}
/**
* @return string
*/
public function getRootLevelFolder()
{
return $this->rootFolder;
}
/**
* @return string
*/
public function getDefaultFolder()
{
return $this->rootFolder;
}
/**
* For now we handle every folder as it's own parent
*
* @param string $fileIdentifier
* @return string
*/
public function getParentFolderIdentifierOfIdentifier($fileIdentifier)
{
return $this->rootFolder;
}
/**
* Returns the (temp) public URL to a file.
*
* @param string $identifier
* @return string
* @throws Exception\FileDoesNotExistException
*/
public function getPublicUrl($identifier)
{
$format = '';
if (preg_match('/^processed_([0-9A-Z\-]{35})_([a-z]+)/', $identifier, $matches)) {
$identifier = $matches[1];
$format = $matches[2];
}
try {
$fileInfo = $this->getBynderService()->getMediaInfo($identifier);
switch ($fileInfo['type']) {
case BynderDriver::ASSET_TYPE_IMAGE:
if (!in_array($format, ['mini', 'thul', 'webimage'])) {
$format = 'webimage';
}
return $fileInfo['thumbnails'][$format];
case BynderDriver::ASSET_TYPE_VIDEO:
$urls = array_filter($fileInfo['videoPreviewURLs'], function ($url) {
return preg_match('/mp4$/i', $url);
});
if (empty($urls)) {
throw new Exception\FileDoesNotExistException(
'mp4 not found in video URL\'s',
1530626116454
);
}
return reset($urls);
}
} catch (\Exception $exception) {
throw new Exception\FileDoesNotExistException(
sprintf('Requested file "%s" couldn\'t be found', $identifier),
1519115242,
$exception
);
}
}
public function createFolder($newFolderName, $parentFolderIdentifier = '', $recursive = false)
{
throw new NotImplementedException(sprintf('Method %s::%s() is not implemented', __CLASS__, __METHOD__), 1519045381);
}
public function renameFolder($folderIdentifier, $newName)
{
throw new NotImplementedException(sprintf('Method %s::%s() is not implemented', __CLASS__, __METHOD__), 1519045382);
}
public function deleteFolder($folderIdentifier, $deleteRecursively = false)
{
throw new NotImplementedException(sprintf('Method %s::%s() is not implemented', __CLASS__, __METHOD__), 1519045383);
}
/**
* @param string $fileIdentifier
* @return bool
*/
public function fileExists($fileIdentifier)
{
// We just assume that the processed file exists as this is just a CDN link
if ($this->isProcessedFile($fileIdentifier)) {
return true;
}
try {
$asset = $this->getBynderService()->getMediaInfo($fileIdentifier);
return true;
} catch (\Exception $exception) {
return false;
}
}
/**
* @param string $folderIdentifier
* @return bool
*/
public function folderExists($folderIdentifier)
{
// We only know the root folder
return $folderIdentifier === $this->rootFolder;
}
/**
* @param string $folderIdentifier
* @return bool
*/
public function isFolderEmpty($folderIdentifier)
{
// We just say that every folder has some content as
// Bynder doesn't know the concept of folders and we don't want
// any call like deleteFolder()
return false;
}
/**
* @param string $localFilePath
* @param string $targetFolderIdentifier
* @param string $newFileName
* @param bool $removeOriginal
* @return string|void
* @throws NotImplementedException
*/
public function addFile($localFilePath, $targetFolderIdentifier, $newFileName = '', $removeOriginal = true)
{
throw new NotImplementedException(sprintf('Method %s::%s() is not implemented', __CLASS__, __METHOD__), 1519045386);
}
/**
* @param string $fileName
* @param string $parentFolderIdentifier
* @return string|void
* @throws NotImplementedException
*/
public function createFile($fileName, $parentFolderIdentifier)
{
throw new NotImplementedException(sprintf('Method %s::%s() is not implemented', __CLASS__, __METHOD__), 1519045387);
}
/**
* @param string $fileIdentifier
* @param string $targetFolderIdentifier
* @param string $fileName
* @return string|void
* @throws NotImplementedException
*/
public function copyFileWithinStorage($fileIdentifier, $targetFolderIdentifier, $fileName)
{
throw new NotImplementedException(sprintf('Method %s::%s() is not implemented', __CLASS__, __METHOD__), 1519045388);
}
/**
* @param string $fileIdentifier
* @param string $newName
* @return string|void
* @throws NotImplementedException
*/
public function renameFile($fileIdentifier, $newName)
{
throw new NotImplementedException(sprintf('Method %s::%s() is not implemented', __CLASS__, __METHOD__), 1519045389);
}
/**
* @param string $fileIdentifier
* @param string $localFilePath
* @return bool|void
* @throws NotImplementedException
*/
public function replaceFile($fileIdentifier, $localFilePath)
{
throw new NotImplementedException(sprintf('Method %s::%s() is not implemented', __CLASS__, __METHOD__), 1519045390);
}
/**
* @param string $fileIdentifier
* @return bool
* @throws NotImplementedException
*/
public function deleteFile($fileIdentifier)
{
// Deleting processed files isn't needed as this is just a link to a file in the CDN
// to prevent false errors for the user we just tell the API that deleting was successful
if ($this->isProcessedFile($fileIdentifier)) {
return true;
}
throw new NotImplementedException(sprintf('Method %s::%s() is not implemented', __CLASS__, __METHOD__), 1519045391);
}
/**
* Creates a (cryptographic) hash for a file.
*
* @param string $fileIdentifier
* @param string $hashAlgorithm The hash algorithm to use
* @return string
* @throws \RuntimeException
* @throws \InvalidArgumentException
*/
public function hash($fileIdentifier, $hashAlgorithm)
{
if (!in_array($hashAlgorithm, ['sha1', 'md5'], true)) {
throw new \InvalidArgumentException('Hash algorithm "' . $hashAlgorithm . '" is not supported.', 1519131571);
}
switch ($hashAlgorithm) {
case 'sha1':
return sha1($fileIdentifier);
break;
case 'md5':
return md5($fileIdentifier);
break;
default:
throw new \RuntimeException('Hash algorithm ' . $hashAlgorithm . ' is not implemented.', 1519131572);
}
}
/**
* @param string $fileIdentifier
* @param string $targetFolderIdentifier
* @param string $newFileName
* @return string|void
* @throws NotImplementedException
*/
public function moveFileWithinStorage($fileIdentifier, $targetFolderIdentifier, $newFileName)
{
throw new NotImplementedException(sprintf('Method %s::%s() is not implemented', __CLASS__, __METHOD__), 1519045392);
}
/**
* @param string $sourceFolderIdentifier
* @param string $targetFolderIdentifier
* @param string $newFolderName
* @return array|void
* @throws NotImplementedException
*/
public function moveFolderWithinStorage($sourceFolderIdentifier, $targetFolderIdentifier, $newFolderName)
{
throw new NotImplementedException(sprintf('Method %s::%s() is not implemented', __CLASS__, __METHOD__), 1519045393);
}
/**
* @param string $sourceFolderIdentifier
* @param string $targetFolderIdentifier
* @param string $newFolderName
* @return bool|void
* @throws NotImplementedException
*/
public function copyFolderWithinStorage($sourceFolderIdentifier, $targetFolderIdentifier, $newFolderName)
{
throw new NotImplementedException(sprintf('Method %s::%s() is not implemented', __CLASS__, __METHOD__), 1519045394);
}
/**
* @param string $fileIdentifier
* @return string
* @throws Exception\FileDoesNotExistException
*/
public function getFileContents($fileIdentifier)
{
try {
$downloadLocation = $this->getAssetBankManager()->getMediaDownloadLocation($fileIdentifier)->wait();
return file_get_contents($downloadLocation['s3_file']);
} catch (\Exception $exception) {
throw new Exception\FileDoesNotExistException(
sprintf('Requested file "%s" coudn\'t be found', $fileIdentifier),
1519115242,
$exception
);
}
}
/**
* @param string $fileIdentifier
* @param string $contents
* @return int|void
* @throws NotImplementedException
*/
public function setFileContents($fileIdentifier, $contents)
{
throw new NotImplementedException(sprintf('Method %s::%s() is not implemented', __CLASS__, __METHOD__), 1519045395);
}
/**
* @param string $fileName
* @param string $folderIdentifier
* @return bool
*/
public function fileExistsInFolder($fileName, $folderIdentifier)
{
if ($folderIdentifier !== $this->rootFolder) {
return false;
}
// @todo: find a file by name instead of identifier
return false;
}
/**
* @param string $folderName
* @param string $folderIdentifier
* @return bool
*/
public function folderExistsInFolder($folderName, $folderIdentifier)
{
// Currently we don't know the concept of folders within Bynder and for now always return false
return false;
}
public function getFileForLocalProcessing($fileIdentifier, $writable = true)
{
return $this->saveFileToTemporaryPath($fileIdentifier);
}
/**
* @param string $identifier
* @return array
*/
public function getPermissions($identifier)
{
return [
'r' => $identifier === $this->rootFolder || $this->fileExists($identifier),
'w' => false
];
}
/**
* Directly output the contents of the file to the output
* buffer. Should not take care of header files or flushing
* buffer before. Will be taken care of by the Storage.
*
* @param string $identifier
* @throws Exception\FileDoesNotExistException
*/
public function dumpFileContents($identifier)
{
try {
$downloadLocation = $this->getAssetBankManager()->getMediaDownloadLocation($identifier)->wait();
readfile($downloadLocation['s3_file'], 0);
} catch (\Exception $exception) {
throw new Exception\FileDoesNotExistException(
sprintf('Requested file "%s" coudn\'t be found', $identifier),
1519115242,
$exception
);
}
}
/**
* @param string $folderIdentifier
* @param string $identifier
* @return bool
*/
public function isWithin($folderIdentifier, $identifier)
{
if ($folderIdentifier === $this->rootFolder) {
return true;
} else {
return false;
}
}
/**
* @param string $fileIdentifier
* @param array $propertiesToExtract
* @return array
* @throws Exception\FileDoesNotExistException
*/
public function getFileInfoByIdentifier($fileIdentifier, array $propertiesToExtract = [])
{
if (preg_match('/^processed_([0-9A-Z\-]{35})_([a-z]+)/', $fileIdentifier, $matches)) {
$fileIdentifier = $matches[1];
}
try {
$mediaInfo = $this->getBynderService()->getMediaInfo($fileIdentifier);
} catch (\Exception $exception) {
throw new Exception\FileDoesNotExistException(
sprintf('Requested file "%s" coudn\'t be found', $fileIdentifier),
1519115242,
$exception
);
}
return $this->extractFileInformation($mediaInfo, $propertiesToExtract);
}
/**
* @param string $folderIdentifier
* @return array
*/
public function getFolderInfoByIdentifier($folderIdentifier)
{
return [
'identifier' => $folderIdentifier,
'name' => 'Bynder',
'mtime' => 0,
'ctime' => 0,
'storage' => $this->storageUid
];
}
/**
* @param string $fileName
* @param string $folderIdentifier
* @return string
*/
public function getFileInFolder($fileName, $folderIdentifier)
{
return '';
}
/**
* @param string $folderIdentifier
* @param int $start
* @param int $numberOfItems
* @param bool $recursive
* @param array $filenameFilterCallbacks
* @param string $sort
* @param bool $sortRev
* @return array
*/
public function getFilesInFolder($folderIdentifier, $start = 0, $numberOfItems = 0, $recursive = false, array $filenameFilterCallbacks = [], $sort = '', $sortRev = false)
{
return [];
}
/**
* @param string $folderName
* @param string $folderIdentifier
* @return string
*/
public function getFolderInFolder($folderName, $folderIdentifier)
{
return '';
}
/**
* @param string $folderIdentifier
* @param int $start
* @param int $numberOfItems
* @param bool $recursive
* @param array $folderNameFilterCallbacks
* @param string $sort
* @param bool $sortRev
* @return array
*/
public function getFoldersInFolder($folderIdentifier, $start = 0, $numberOfItems = 0, $recursive = false, array $folderNameFilterCallbacks = [], $sort = '', $sortRev = false)
{
return [];
}
/**
* @param string $folderIdentifier
* @param bool $recursive
* @param array $filenameFilterCallbacks
* @return int
*/
public function countFilesInFolder($folderIdentifier, $recursive = false, array $filenameFilterCallbacks = [])
{
return 0;
}
/**
* @param string $folderIdentifier
* @param bool $recursive
* @param array $folderNameFilterCallbacks
* @return int
*/
public function countFoldersInFolder($folderIdentifier, $recursive = false, array $folderNameFilterCallbacks = [])
{
return 0;
}
/**
* @param string $fileIdentifier
* @return bool
*/
protected function isProcessedFile(string $fileIdentifier): bool
{
return (bool)preg_match('/^processed_([0-9A-Z\-]{35})_([a-z]+)/', $fileIdentifier);
}
/**
* @return AssetBankManager
* @throws \InvalidArgumentException
*/
protected function getAssetBankManager(): AssetBankManager
{
if ($this->assetBankManager === null) {
$this->assetBankManager = $this->getBynderService()
->getBynderApi()
->getAssetBankManager();
}
return $this->assetBankManager;
}
/**
* @return BynderService
* @throws \InvalidArgumentException
*/
protected function getBynderService(): BynderService
{
if ($this->bynderService === null) {
$this->bynderService = GeneralUtility::makeInstance(BynderService::class);
}
return $this->bynderService;
}
/**
* Extracts information about a file from the filesystem.
*
* @param array $mediaInfo as returned from getAssetBankManager()->getMediaInfo()
* @param array $propertiesToExtract array of properties which should be returned, if empty all will be extracted
* @return array
*/
protected function extractFileInformation(array $mediaInfo, array $propertiesToExtract = []): array
{
if (empty($propertiesToExtract)) {
$propertiesToExtract = [
'size',
'atime',
'mtime',
'ctime',
'mimetype',
'name',
'extension',
'identifier',
'identifier_hash',
'storage',
'folder_hash'
];
}
$fileInformation = [];
foreach ($propertiesToExtract as $property) {
$fileInformation[$property] = $this->getSpecificFileInformation($mediaInfo, $property);
}
return $fileInformation;
}
/**
* Extracts a specific FileInformation from the FileSystems.
*
* @param array $mediaInfo
* @param string $property
*
* @return bool|int|string
* @throws \InvalidArgumentException
*/
protected function getSpecificFileInformation($mediaInfo, $property)
{
switch ($property) {
case 'size':
return $mediaInfo['fileSize'];
case 'atime':
return strtotime($mediaInfo['dateModified']);
case 'mtime':
return strtotime($mediaInfo['dateModified']);
case 'ctime':
return strtotime($mediaInfo['dateCreated']);
case 'name':
return $mediaInfo['name'] . '.' . $mediaInfo['extension'][0];
case 'mimetype':
// @todo: find beter way to determine mimetype
return $mediaInfo['type'] . '/' . $mediaInfo['extension'][0];
case 'identifier':
return $mediaInfo['id'];
case 'extension':
return $mediaInfo['extension'][0];
case 'storage':
return $this->storageUid;
case 'identifier_hash':
return $this->hashIdentifier($mediaInfo['id']);
case 'folder_hash':
return $this->hashIdentifier('');
// Metadata
case 'title':
return $mediaInfo['name'];
case 'description':
return $mediaInfo['description'];
case 'width':
return $mediaInfo['width'];
case 'height':
return $mediaInfo['height'];
case 'copyright':
return $mediaInfo['copyright'];
case 'keywords':
return implode(', ', $mediaInfo['tags'] ?? []);
default:
throw new \InvalidArgumentException(sprintf('The information "%s" is not available.', $property), 1519130380);
}
}
/**
* Save a file to a temporary path and returns that path.
*
* @param string $fileIdentifier
* @return string The temporary path
* @throws \RuntimeException
* @throws Exception\FileDoesNotExistException
*/
protected function saveFileToTemporaryPath($fileIdentifier): string
{
$temporaryPath = $this->getTemporaryPathForFile($fileIdentifier);
$result = file_put_contents($temporaryPath, $this->getFileContents($fileIdentifier));
if ($result === false) {
throw new \RuntimeException(
'Copying file "' . $fileIdentifier . '" to temporary path "' . $temporaryPath . '" failed.',
1519208427
);
}
return $temporaryPath;
}
/**
* Returns a temporary path for a given file, including the file extension.
*
* @param string $fileIdentifier
* @return string
* @throws Exception\FileDoesNotExistException
*/
protected function getTemporaryPathForFile($fileIdentifier): string
{
list($fileExtension) = $this->getFileInfoByIdentifier($fileIdentifier, ['extension']);
$tempFile = GeneralUtility::tempnam('fal-tempfile-', '.' . $fileExtension);
return self::$tempFiles[] = $tempFile;
}
/**
* Cleanup temp files that a still present
*/
public function __destruct()
{
foreach (self::$tempFiles as $tempFile) {
GeneralUtility::unlink_tempfile($tempFile);
}
}
}