forked from owncloud/music
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscanner.php
729 lines (629 loc) · 25.1 KB
/
scanner.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
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
<?php
/**
* ownCloud - Music app
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Morris Jobke <[email protected]>
* @author Pauli Järvinen <[email protected]>
* @copyright Morris Jobke 2013, 2014
* @copyright Pauli Järvinen 2016 - 2020
*/
namespace OCA\Music\Utility;
use OC\Hooks\PublicEmitter;
use \OCP\Files\File;
use \OCP\Files\Folder;
use \OCP\Files\IRootFolder;
use \OCA\Music\AppFramework\Core\Logger;
use \OCA\Music\BusinessLayer\ArtistBusinessLayer;
use \OCA\Music\BusinessLayer\AlbumBusinessLayer;
use \OCA\Music\BusinessLayer\GenreBusinessLayer;
use \OCA\Music\BusinessLayer\PlaylistBusinessLayer;
use \OCA\Music\BusinessLayer\TrackBusinessLayer;
use \OCA\Music\Db\Cache;
use \OCA\Music\Db\Maintenance;
use Symfony\Component\Console\Output\OutputInterface;
class Scanner extends PublicEmitter {
private $extractor;
private $artistBusinessLayer;
private $albumBusinessLayer;
private $trackBusinessLayer;
private $playlistBusinessLayer;
private $genreBusinessLayer;
private $cache;
private $coverHelper;
private $logger;
private $maintenance;
private $userMusicFolder;
private $rootFolder;
public function __construct(Extractor $extractor,
ArtistBusinessLayer $artistBusinessLayer,
AlbumBusinessLayer $albumBusinessLayer,
TrackBusinessLayer $trackBusinessLayer,
PlaylistBusinessLayer $playlistBusinessLayer,
GenreBusinessLayer $genreBusinessLayer,
Cache $cache,
CoverHelper $coverHelper,
Logger $logger,
Maintenance $maintenance,
UserMusicFolder $userMusicFolder,
IRootFolder $rootFolder) {
$this->extractor = $extractor;
$this->artistBusinessLayer = $artistBusinessLayer;
$this->albumBusinessLayer = $albumBusinessLayer;
$this->trackBusinessLayer = $trackBusinessLayer;
$this->playlistBusinessLayer = $playlistBusinessLayer;
$this->genreBusinessLayer = $genreBusinessLayer;
$this->cache = $cache;
$this->coverHelper = $coverHelper;
$this->logger = $logger;
$this->maintenance = $maintenance;
$this->userMusicFolder = $userMusicFolder;
$this->rootFolder = $rootFolder;
// Trying to enable stream support
if (\ini_get('allow_url_fopen') !== '1') {
$this->logger->log('allow_url_fopen is disabled. It is strongly advised to enable it in your php.ini', 'warn');
@\ini_set('allow_url_fopen', '1');
}
}
/**
* Gets called by 'post_write' (file creation, file update) and 'post_share' hooks
* @param \OCP\Files\File $file the file
* @param string $userId
* @param \OCP\Files\Folder $userHome
* @param string|null $filePath Deduced from $file if not given
*/
public function update($file, $userId, $userHome, $filePath = null) {
if ($filePath === null) {
$filePath = $file->getPath();
}
// debug logging
$this->logger->log("update - $filePath", 'debug');
if (!($file instanceof File) || !$userId || !($userHome instanceof Folder)) {
$this->logger->log('Invalid arguments given to Scanner.update - file='.\get_class($file).
", userId=$userId, userHome=".\get_class($userHome), 'warn');
return;
}
// skip files that aren't inside the user specified path
if (!$this->pathIsUnderMusicFolder($filePath, $userId)) {
$this->logger->log("skipped - file is outside of specified music folder", 'debug');
return;
}
$mimetype = $file->getMimeType();
// debug logging
$this->logger->log("update - mimetype $mimetype", 'debug');
if (Util::startsWith($mimetype, 'image')) {
$this->updateImage($file, $userId);
} elseif (Util::startsWith($mimetype, 'audio') && !self::isPlaylistMime($mimetype)) {
$this->updateAudio($file, $userId, $userHome, $filePath, $mimetype);
}
}
private static function isPlaylistMime($mime) {
return $mime == 'audio/mpegurl' || $mime == 'audio/x-scpls';
}
private function pathIsUnderMusicFolder($filePath, $userId) {
$musicFolder = $this->userMusicFolder->getFolder($userId);
$musicPath = $musicFolder->getPath();
return Util::startsWith($filePath, $musicPath);
}
private function updateImage($file, $userId) {
$coverFileId = $file->getId();
$parentFolderId = $file->getParent()->getId();
if ($this->albumBusinessLayer->updateFolderCover($coverFileId, $parentFolderId)) {
$this->logger->log('updateImage - the image was set as cover for some album(s)', 'debug');
$this->cache->remove($userId, 'collection');
}
if ($artistId = $this->artistBusinessLayer->updateCover($file, $userId)) {
$this->logger->log("updateImage - the image was set as cover for the artist $artistId", 'debug');
$this->coverHelper->removeArtistCoverFromCache($artistId, $userId);
}
}
private function updateAudio($file, $userId, $userHome, $filePath, $mimetype) {
if (\ini_get('allow_url_fopen')) {
$this->emit('\OCA\Music\Utility\Scanner', 'update', [$filePath]);
$meta = $this->extractMetadata($file, $userHome, $filePath);
$fileId = $file->getId();
// add/update artist and get artist entity
$artist = $this->artistBusinessLayer->addOrUpdateArtist($meta['artist'], $userId);
$artistId = $artist->getId();
// add/update albumArtist and get artist entity
$albumArtist = $this->artistBusinessLayer->addOrUpdateArtist($meta['albumArtist'], $userId);
$albumArtistId = $albumArtist->getId();
// add/update album and get album entity
$album = $this->albumBusinessLayer->addOrUpdateAlbum(
$meta['album'], $albumArtistId, $userId);
$albumId = $album->getId();
// add/update genre and get genre entity
$genre = $this->genreBusinessLayer->addOrUpdateGenre($meta['genre'], $userId);
// add/update track and get track entity
$track = $this->trackBusinessLayer->addOrUpdateTrack(
$meta['title'], $meta['trackNumber'], $meta['discNumber'], $meta['year'], $genre->getId(),
$artistId, $albumId, $fileId, $mimetype, $userId, $meta['length'], $meta['bitrate']);
// if present, use the embedded album art as cover for the respective album
if ($meta['picture'] != null) {
$this->albumBusinessLayer->setCover($fileId, $albumId);
$this->coverHelper->removeAlbumCoverFromCache($albumId, $userId);
}
// if this file is an existing file which previously was used as cover for an album but now
// the file no longer contains any embedded album art
elseif ($this->albumBusinessLayer->albumCoverIsOneOfFiles($albumId, [$fileId])) {
$this->albumBusinessLayer->removeCovers([$fileId]);
$this->findEmbeddedCoverForAlbum($albumId, $userId, $userHome);
$this->coverHelper->removeAlbumCoverFromCache($albumId, $userId);
}
// invalidate the cache as the music collection was changed
$this->cache->remove($userId, 'collection');
// debug logging
$this->logger->log('imported entities - ' .
"artist: $artistId, albumArtist: $albumArtistId, album: $albumId, track: {$track->getId()}",
'debug');
}
}
private function extractMetadata($file, $userHome, $filePath) {
$fieldsFromFileName = self::parseFileName($file->getName());
$fileInfo = $this->extractor->extract($file);
$meta = [];
// Track artist and album artist
$meta['artist'] = ExtractorGetID3::getTag($fileInfo, 'artist');
$meta['albumArtist'] = ExtractorGetID3::getFirstOfTags($fileInfo, ['band', 'albumartist', 'album artist', 'album_artist']);
// use artist and albumArtist as fallbacks for each other
if (self::isNullOrEmpty($meta['albumArtist'])) {
$meta['albumArtist'] = $meta['artist'];
}
if (self::isNullOrEmpty($meta['artist'])) {
$meta['artist'] = $meta['albumArtist'];
}
// set 'Unknown Artist' in case neither artist nor albumArtist was found
if (self::isNullOrEmpty($meta['artist'])) {
$meta['artist'] = null;
$meta['albumArtist'] = null;
}
// title
$meta['title'] = ExtractorGetID3::getTag($fileInfo, 'title');
if (self::isNullOrEmpty($meta['title'])) {
$meta['title'] = $fieldsFromFileName['title'];
}
// album
$meta['album'] = ExtractorGetID3::getTag($fileInfo, 'album');
if (self::isNullOrEmpty($meta['album'])) {
// album name not set in fileinfo, use parent folder name as album name unless it is the root folder
$dirPath = \dirname($filePath);
if ($userHome->getPath() === $dirPath) {
$meta['album'] = null;
} else {
$meta['album'] = \basename($dirPath);
}
}
// track number
$meta['trackNumber'] = ExtractorGetID3::getFirstOfTags($fileInfo, ['track_number', 'tracknumber', 'track'],
$fieldsFromFileName['track_number']);
$meta['trackNumber'] = self::normalizeOrdinal($meta['trackNumber']);
// disc number
$meta['discNumber'] = ExtractorGetID3::getFirstOfTags($fileInfo, ['disc_number', 'discnumber', 'part_of_a_set'], '1');
$meta['discNumber'] = self::normalizeOrdinal($meta['discNumber']);
// year
$meta['year'] = ExtractorGetID3::getFirstOfTags($fileInfo, ['year', 'date', 'creation_date']);
$meta['year'] = self::normalizeYear($meta['year']);
$meta['genre'] = ExtractorGetID3::getTag($fileInfo, 'genre') ?: ''; // empty string used for "scanned but unknown"
$meta['picture'] = ExtractorGetID3::getTag($fileInfo, 'picture', true);
if (\array_key_exists('playtime_seconds', $fileInfo)) {
$meta['length'] = \ceil($fileInfo['playtime_seconds']);
} else {
$meta['length'] = null;
}
if (\array_key_exists('audio', $fileInfo) && \array_key_exists('bitrate', $fileInfo['audio'])) {
$meta['bitrate'] = $fileInfo['audio']['bitrate'];
} else {
$meta['bitrate'] = null;
}
return $meta;
}
/**
* @param string[] $affectedUsers
* @param int[] $affectedAlbums
*/
private function invalidateCacheOnDelete($affectedUsers, $affectedAlbums, $affectedArtists) {
// Delete may be for one file or for a folder containing thousands of albums.
// If loads of albums got affected, then ditch the whole cache of the affected
// users because removing the cached covers one-by-one could delay the delete
// operation significantly.
$albumCount = \count($affectedAlbums);
$artistCount = \count($affectedArtists);
$userCount = \count($affectedUsers);
if ($albumCount + $artistCount > 100) {
$this->logger->log("Delete operation affected $albumCount albums and $artistCount artists. " .
"Invalidate the whole cache of all affected users ($userCount).", 'debug');
foreach ($affectedUsers as $user) {
$this->cache->remove($user);
}
}
else {
// remove the cached covers
if ($artistCount > 0) {
$this->logger->log("Remove covers of $artistCount artist(s) from the cache (if present)", 'debug');
foreach ($affectedArtists as $artistId) {
$this->coverHelper->removeArtistCoverFromCache($artistId, null);
}
}
if ($albumCount > 0) {
$this->logger->log("Remove covers of $albumCount album(s) from the cache (if present)", 'debug');
foreach ($affectedAlbums as $albumId) {
$this->coverHelper->removeAlbumCoverFromCache($albumId, null);
}
// remove the cached collection if any album covers were removed
foreach ($affectedUsers as $user) {
$this->cache->remove($user, 'collection');
}
}
}
}
/**
* @param int[] $fileIds
* @param string[]|null $userIds
* @return boolean true if anything was removed
*/
private function deleteAudio($fileIds, $userIds=null) {
$this->logger->log('deleteAudio - '. \implode(', ', $fileIds), 'debug');
$this->emit('\OCA\Music\Utility\Scanner', 'delete', [$fileIds, $userIds]);
$result = $this->trackBusinessLayer->deleteTracks($fileIds, $userIds);
if ($result) { // one or more tracks were removed
// remove obsolete artists and albums, and track references in playlists
$this->albumBusinessLayer->deleteById($result['obsoleteAlbums']);
$this->artistBusinessLayer->deleteById($result['obsoleteArtists']);
$this->playlistBusinessLayer->removeTracksFromAllLists($result['deletedTracks']);
// check if a removed track was used as embedded cover art file for a remaining album
foreach ($result['remainingAlbums'] as $albumId) {
if ($this->albumBusinessLayer->albumCoverIsOneOfFiles($albumId, $fileIds)) {
$this->albumBusinessLayer->setCover(null, $albumId);
$this->findEmbeddedCoverForAlbum($albumId);
$this->coverHelper->removeAlbumCoverFromCache($albumId, null);
}
}
$this->invalidateCacheOnDelete(
$result['affectedUsers'], $result['obsoleteAlbums'], $result['obsoleteArtists']);
$this->logger->log('removed entities - ' . \json_encode($result), 'debug');
}
return $result !== false;
}
/**
* @param int[] $fileIds
* @param string[]|null $userIds
* @return boolean true if anything was removed
*/
private function deleteImage($fileIds, $userIds=null) {
$this->logger->log('deleteImage - '. \implode(', ', $fileIds), 'debug');
$affectedAlbums = $this->albumBusinessLayer->removeCovers($fileIds, $userIds);
$affectedArtists = $this->artistBusinessLayer->removeCovers($fileIds, $userIds);
$affectedUsers = \array_merge(
Util::extractUserIds($affectedAlbums),
Util::extractUserIds($affectedArtists)
);
$affectedUsers = \array_unique($affectedUsers);
$this->invalidateCacheOnDelete(
$affectedUsers, Util::extractIds($affectedAlbums), Util::extractIds($affectedArtists));
return (\count($affectedAlbums) + \count($affectedArtists) > 0);
}
/**
* Gets called by 'unshare' hook and 'delete' hook
*
* @param int $fileId ID of the deleted files
* @param string[]|null $userIds the IDs of the users to remove the file from; if omitted,
* the file is removed from all users (ie. owner and sharees)
*/
public function delete($fileId, $userIds=null) {
if (!$this->deleteAudio([$fileId], $userIds) && !$this->deleteImage([$fileId], $userIds)) {
$this->logger->log("deleted file $fileId was not an indexed " .
'audio file or a cover image', 'debug');
}
}
/**
* Remove all audio files and cover images in the given folder from the database.
* This gets called when a folder is deleted or unshared from the user.
*
* @param \OCP\Files\Folder $folder
* @param string[]|null $userIds the IDs of the users to remove the folder from; if omitted,
* the folder is removed from all users (ie. owner and sharees)
*/
public function deleteFolder($folder, $userIds=null) {
$audioFiles = $folder->searchByMime('audio');
if (\count($audioFiles) > 0) {
$this->deleteAudio(Util::extractIds($audioFiles), $userIds);
}
// NOTE: When a folder is removed, we don't need to check for any image
// files in the folder. This is because those images could be potentially
// used as covers only on the audio files of the same folder and those
// were already removed above.
}
/**
* search for music files by mimetype inside user specified library path
* (which defaults to user home dir)
*
* @return \OCP\Files\File[]
*/
private function getMusicFiles($userId) {
try {
$folder = $this->userMusicFolder->getFolder($userId);
} catch (\OCP\Files\NotFoundException $e) {
return [];
}
// Search files with mime 'audio/*' but filter out the playlist files
$files = $folder->searchByMime('audio');
return array_filter($files, function ($f) {
return !self::isPlaylistMime($f->getMimeType());
});
}
/**
* search for image files by mimetype inside user specified library path
* (which defaults to user home dir)
*
* @return \OCP\Files\File[]
*/
private function getImageFiles($userId) {
try {
$folder = $this->userMusicFolder->getFolder($userId);
} catch (\OCP\Files\NotFoundException $e) {
return [];
}
return $folder->searchByMime('image');
}
private function getScannedFileIds($userId) {
return $this->trackBusinessLayer->findAllFileIds($userId);
}
public function getAllMusicFileIds($userId) {
$musicFiles = $this->getMusicFiles($userId);
return Util::extractIds($musicFiles);
}
public function getUnscannedMusicFileIds($userId) {
$scannedIds = $this->getScannedFileIds($userId);
$allIds = $this->getAllMusicFileIds($userId);
$unscannedIds = Util::arrayDiff($allIds, $scannedIds);
$count = \count($unscannedIds);
if ($count) {
$this->logger->log("Found $count unscanned music files for user $userId", 'info');
} else {
$this->logger->log("No unscanned music files for user $userId", 'debug');
}
return $unscannedIds;
}
public function scanFiles($userId, $userHome, $fileIds, OutputInterface $debugOutput = null) {
$count = \count($fileIds);
$this->logger->log("Scanning $count files of user $userId", 'debug');
// back up the execution time limit
$executionTime = \intval(\ini_get('max_execution_time'));
// set execution time limit to unlimited
\set_time_limit(0);
$count = 0;
foreach ($fileIds as $fileId) {
$fileNodes = $userHome->getById($fileId);
if (\count($fileNodes) > 0) {
$file = $fileNodes[0];
$memBefore = $debugOutput ? \memory_get_usage(true) : 0;
$this->update($file, $userId, $userHome);
if ($debugOutput) {
$memAfter = \memory_get_usage(true);
$memDelta = $memAfter - $memBefore;
$fmtMemAfter = Util::formatFileSize($memAfter);
$fmtMemDelta = Util::formatFileSize($memDelta);
$path = $file->getPath();
$debugOutput->writeln("\e[1m $count \e[0m $fmtMemAfter \e[1m $memDelta \e[0m ($fmtMemDelta) $path");
}
$count++;
} else {
$this->logger->log("File with id $fileId not found for user $userId", 'warn');
}
}
// reset execution time limit
\set_time_limit($executionTime);
return $count;
}
/**
* Check the availability of all the indexed audio files of the user. Remove
* from the index any which are not available.
* @param string $userId
* @param Folder $userHome
* @return Number of removed files
*/
public function removeUnavailableFiles($userId, $userHome) {
$indexedFiles = $this->getScannedFileIds($userId);
$unavailableFiles = [];
foreach ($indexedFiles as $fileId) {
$fileNodes = $userHome->getById($fileId);
if (empty($fileNodes)) {
$this->logger->log("File $fileId is not available for user $userId, removing", 'info');
$unavailableFiles[] = $fileId;
}
}
$count = \count($unavailableFiles);
if ($count > 0) {
$this->deleteAudio($unavailableFiles, [$userId]);
}
return $count;
}
/**
* Remove all such audio files from the collection which do not reside
* under the configured music path.
* @param string $userId
*/
private function removeFilesNotUnderMusicFolder($userId) {
$indexedFiles = $this->getScannedFileIds($userId);
$validFiles = Util::extractIds($this->getMusicFiles($userId));
$filesToRemove = Util::arrayDiff($indexedFiles, $validFiles);
if (\count($filesToRemove)) {
$this->deleteAudio($filesToRemove, [$userId]);
}
}
/**
* Parse and get basic info about a file. The file does not have to be indexed in the database.
* @param string $fileId
* @param string $userId
* @param Folder $userFolder
* $return array|null
*/
public function getFileInfo($fileId, $userId, $userFolder) {
$info = $this->getIndexedFileInfo($fileId, $userId, $userFolder)
?: $this->getUnindexedFileInfo($fileId, $userId, $userFolder);
// base64-encode and wrap the cover image if available
if ($info !== null && $info['cover'] !== null) {
$mime = $info['cover']['mimetype'];
$content = $info['cover']['content'];
$info['cover'] = 'data:' . $mime. ';base64,' . \base64_encode($content);
}
return $info;
}
private function getIndexedFileInfo($fileId, $userId, $userFolder) {
$track = $this->trackBusinessLayer->findByFileId($fileId, $userId);
if ($track !== null) {
$artist = $this->artistBusinessLayer->find($track->getArtistId(), $userId);
$album = $this->albumBusinessLayer->find($track->getAlbumId(), $userId);
return [
'title' => $track->getTitle(),
'artist' => $artist->getName(),
'cover' => $this->coverHelper->getCover($album, $userId, $userFolder),
'in_library' => true
];
}
return null;
}
private function getUnindexedFileInfo($fileId, $userId, $userFolder) {
$fileNodes = $userFolder->getById($fileId);
if (\count($fileNodes) > 0) {
$file = $fileNodes[0];
$metadata = $this->extractMetadata($file, $userFolder, $file->getPath());
$cover = $metadata['picture'];
if ($cover != null) {
$cover = [
'mimetype' => $cover['image_mime'],
'content' => $this->coverHelper->scaleDownAndCrop($cover['data'], 200)
];
}
return [
'title' => $metadata['title'],
'artist' => $metadata['artist'],
'cover' => $cover,
'in_library' => $this->pathIsUnderMusicFolder($file->getPath(), $userId)
];
}
return null;
}
/**
* Update music path
*
* @param string $oldPath
* @param string $newPath
* @param string $userId
*/
public function updatePath($oldPath, $newPath, $userId) {
$this->logger->log("Changing music collection path of user $userId from $oldPath to $newPath", 'info');
$userHome = $this->resolveUserFolder($userId);
try {
$oldFolder = Util::getFolderFromRelativePath($userHome, $oldPath);
$newFolder = Util::getFolderFromRelativePath($userHome, $newPath);
if ($newFolder->getPath() === $oldFolder->getPath()) {
$this->logger->log('New collection path is the same as the old path, nothing to do', 'debug');
} elseif ($newFolder->isSubNode($oldFolder)) {
$this->logger->log('New collection path is (grand) parent of old path, previous content is still valid', 'debug');
} elseif ($oldFolder->isSubNode($newFolder)) {
$this->logger->log('Old collection path is (grand) parent of new path, checking the validity of previous content', 'debug');
$this->removeFilesNotUnderMusicFolder($userId);
} else {
$this->logger->log('Old and new collection paths are unrelated, erasing the previous collection content', 'debug');
$this->maintenance->resetDb($userId);
}
}
catch (\OCP\Files\NotFoundException $e) {
$this->logger->log('One of the paths was invalid, erasing the previous collection content', 'warn');
$this->maintenance->resetDb($userId);
}
}
/**
* Find external cover images for albums which do not yet have one.
* Target either one user or all users.
* @param string|null $userId
* @return bool true if any albums were updated; false otherwise
*/
public function findAlbumCovers($userId = null) {
$affectedUsers = $this->albumBusinessLayer->findCovers($userId);
// scratch the cache for those users whose music collection was touched
foreach ($affectedUsers as $user) {
$this->cache->remove($user, 'collection');
$this->logger->log('album cover(s) were found for user '. $user, 'debug');
}
return !empty($affectedUsers);
}
/**
* Find external cover images for albums which do not yet have one.
* Target either one user or all users.
* @param string|null $userId
* @return bool true if any albums were updated; false otherwise
*/
public function findArtistCovers($userId) {
$allImages = $this->getImageFiles($userId);
return $this->artistBusinessLayer->updateCovers($allImages, $userId);
}
public function resolveUserFolder($userId) {
return $this->rootFolder->getUserFolder($userId);
}
private static function isNullOrEmpty($string) {
return $string === null || $string === '';
}
private static function normalizeOrdinal($ordinal) {
// convert format '1/10' to '1'
$tmp = \explode('/', $ordinal);
$ordinal = $tmp[0];
// check for numeric values - cast them to int and verify it's a natural number above 0
if (\is_numeric($ordinal) && ((int)$ordinal) > 0) {
$ordinal = (int)$ordinal;
} else {
$ordinal = null;
}
return $ordinal;
}
private static function parseFileName($fileName) {
// If the file name starts e.g like "12. something" or "12 - something", the
// preceeding number is extracted as track number. Everything after the optional
// track number + delimiters part but before the file extension is extracted as title.
// The file extension consists of a '.' followed by 1-4 "word characters".
if (\preg_match('/^((\d+)\s*[.-]\s+)?(.+)\.(\w{1,4})$/', $fileName, $matches) === 1) {
return ['track_number' => $matches[2], 'title' => $matches[3]];
} else {
return ['track_number' => null, 'title' => $fileName];
}
}
private static function normalizeYear($date) {
if (\ctype_digit($date)) {
return (int)$date; // the date is a valid year as-is
} elseif (\preg_match('/^(\d\d\d\d)-\d\d-\d\d.*/', $date, $matches) === 1) {
return (int)$matches[1]; // year from ISO-formatted date yyyy-mm-dd
} else {
return null;
}
}
/**
* Loop through the tracks of an album and set the first track containing embedded cover art
* as cover file for the album
* @param int $albumId
* @param string|null $userId name of user, deducted from $albumId if omitted
* @param Folder|null $userFolder home folder of user, deducted from $userId if omitted
*/
private function findEmbeddedCoverForAlbum($albumId, $userId=null, $userFolder=null) {
if ($userId === null) {
$userId = $this->albumBusinessLayer->findAlbumOwner($albumId);
}
if ($userFolder === null) {
$userFolder = $this->resolveUserFolder($userId);
}
$tracks = $this->trackBusinessLayer->findAllByAlbum($albumId, $userId);
foreach ($tracks as $track) {
$nodes = $userFolder->getById($track->getFileId());
if (\count($nodes) > 0) {
// parse the first valid node and check if it contains embedded cover art
$image = $this->extractor->parseEmbeddedCoverArt($nodes[0]);
if ($image != null) {
$this->albumBusinessLayer->setCover($track->getFileId(), $albumId);
break;
}
}
}
}
}