forked from koel/koel
/
MediaSyncService.php
305 lines (267 loc) · 9.18 KB
/
MediaSyncService.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
<?php
namespace App\Services;
use App\Console\Commands\SyncMediaCommand;
use App\Events\LibraryChanged;
use App\Libraries\WatchRecord\WatchRecordInterface;
use App\Models\Album;
use App\Models\Artist;
use App\Models\Setting;
use App\Models\Song;
use App\Repositories\AlbumRepository;
use App\Repositories\ArtistRepository;
use App\Repositories\SettingRepository;
use App\Repositories\SongRepository;
use Exception;
use Psr\Log\LoggerInterface;
use SplFileInfo;
use Symfony\Component\Finder\Finder;
class MediaSyncService
{
/**
* All applicable tags in a media file that we cater for.
* Note that each isn't necessarily a valid ID3 tag name.
*
* @var array
*/
private const APPLICABLE_TAGS = [
'artist',
'album',
'title',
'length',
'track',
'disc',
'lyrics',
'cover',
'mtime',
'compilation',
];
private $mediaMetadataService;
private $songRepository;
private $helperService;
private $fileSynchronizer;
private $finder;
private $artistRepository;
private $albumRepository;
private $settingRepository;
private $logger;
public function __construct(
MediaMetadataService $mediaMetadataService,
SongRepository $songRepository,
ArtistRepository $artistRepository,
AlbumRepository $albumRepository,
SettingRepository $settingRepository,
HelperService $helperService,
FileSynchronizer $fileSynchronizer,
Finder $finder,
LoggerInterface $logger
) {
$this->mediaMetadataService = $mediaMetadataService;
$this->songRepository = $songRepository;
$this->helperService = $helperService;
$this->fileSynchronizer = $fileSynchronizer;
$this->finder = $finder;
$this->artistRepository = $artistRepository;
$this->albumRepository = $albumRepository;
$this->settingRepository = $settingRepository;
$this->logger = $logger;
}
/**
* Tags to be synced.
*
* @var array
*/
protected $tags = [];
/**
* Sync the media. Oh sync the media.
*
* @param string[] $tags The tags to sync.
* Only taken into account for existing records.
* New records will have all tags synced in regardless.
* @param bool $force Whether to force syncing even unchanged files
* @param SyncMediaCommand $syncCommand The SyncMedia command object, to log to console if executed by artisan.
*
* @throws Exception
*/
public function sync(
?string $mediaPath = null,
array $tags = [],
bool $force = false,
?SyncMediaCommand $syncCommand = null
): void {
$this->setSystemRequirements();
$this->setTags($tags);
$results = [
'success' => [],
'bad_files' => [],
'unmodified' => [],
];
$songPaths = $this->gatherFiles($mediaPath ?: Setting::get('media_path'));
if ($syncCommand) {
$syncCommand->createProgressBar(count($songPaths));
}
foreach ($songPaths as $path) {
$result = $this->fileSynchronizer->setFile($path)->sync($this->tags, $force);
switch ($result) {
case FileSynchronizer::SYNC_RESULT_SUCCESS:
$results['success'][] = $path;
break;
case FileSynchronizer::SYNC_RESULT_UNMODIFIED:
$results['unmodified'][] = $path;
break;
default:
$results['bad_files'][] = $path;
break;
}
if ($syncCommand) {
$syncCommand->advanceProgressBar();
$syncCommand->logSyncStatusToConsole($path, $result, $this->fileSynchronizer->getSyncError());
}
}
// Delete non-existing songs.
$hashes = array_map(function (string $path): string {
return $this->helperService->getFileHash($path);
}, array_merge($results['unmodified'], $results['success']));
Song::deleteWhereIDsNotIn($hashes);
// Trigger LibraryChanged, so that TidyLibrary handler is fired to, erm, tidy our library.
event(new LibraryChanged());
}
/**
* Gather all applicable files in a given directory.
*
* @param string $path The directory's full path
*
* @return SplFileInfo[]
*/
public function gatherFiles(string $path): array
{
return iterator_to_array(
$this->finder->create()
->ignoreUnreadableDirs()
->ignoreDotFiles((bool) config('koel.ignore_dot_files')) // https://github.com/phanan/koel/issues/450
->files()
->followLinks()
->name('/\.(mp3|ogg|m4a|flac)$/i')
->in($path)
);
}
/**
* Sync media using a watch record.
*
* @throws Exception
*/
public function syncByWatchRecord(WatchRecordInterface $record): void
{
$this->logger->info("New watch record received: '{$record->getPath()}'");
$record->isFile() ? $this->syncFileRecord($record) : $this->syncDirectoryRecord($record);
}
/**
* Sync a file's watch record.
*
* @throws Exception
*/
private function syncFileRecord(WatchRecordInterface $record): void
{
$path = $record->getPath();
$this->logger->info("'$path' is a file.");
// If the file has been deleted...
if ($record->isDeleted()) {
$this->handleDeletedFileRecord($path);
}
// Otherwise, it's a new or changed file. Try to sync it in.
elseif ($record->isNewOrModified()) {
$this->handleNewOrModifiedFileRecord($path);
}
}
/**
* Sync a directory's watch record.
*/
private function syncDirectoryRecord(WatchRecordInterface $record): void
{
$path = $record->getPath();
$this->logger->info("'$path' is a directory.");
if ($record->isDeleted()) {
$this->handleDeletedDirectoryRecord($path);
} elseif ($record->isNewOrModified()) {
$this->handleNewOrModifiedDirectoryRecord($path);
}
}
/**
* Construct an array of tags to be synced into the database from an input array of tags.
* If the input array is empty or contains only invalid items, we use all tags.
* Otherwise, we only use the valid items in it.
*
* @param string[] $tags
*/
public function setTags(array $tags = []): void
{
$this->tags = array_intersect($tags, self::APPLICABLE_TAGS) ?: self::APPLICABLE_TAGS;
// We always keep track of mtime.
if (!in_array('mtime', $this->tags, true)) {
$this->tags[] = 'mtime';
}
}
/**
* Tidy up the library by deleting empty albums and artists.
*
* @throws Exception
*/
public function tidy(): void
{
$inUseAlbums = $this->albumRepository->getNonEmptyAlbumIds();
$inUseAlbums[] = Album::UNKNOWN_ID;
Album::deleteWhereIDsNotIn($inUseAlbums);
$inUseArtists = $this->artistRepository->getNonEmptyArtistIds();
$inUseArtists[] = Artist::UNKNOWN_ID;
$inUseArtists[] = Artist::VARIOUS_ID;
Artist::deleteWhereIDsNotIn(array_filter($inUseArtists));
}
private function setSystemRequirements(): void
{
if (!app()->runningInConsole()) {
set_time_limit(config('koel.sync.timeout'));
}
if (config('koel.memory_limit')) {
ini_set('memory_limit', config('koel.memory_limit').'M');
}
}
/**
* @throws Exception
*/
private function handleDeletedFileRecord(string $path): void
{
if ($song = $this->songRepository->getOneByPath($path)) {
$song->delete();
$this->logger->info("$path deleted.");
event(new LibraryChanged());
} else {
$this->logger->info("$path doesn't exist in our database--skipping.");
}
}
private function handleNewOrModifiedFileRecord(string $path): void
{
$result = $this->fileSynchronizer->setFile($path)->sync($this->tags);
if ($result === FileSynchronizer::SYNC_RESULT_SUCCESS) {
$this->logger->info("Synchronized $path");
} else {
$this->logger->info("Failed to synchronized $path. Maybe an invalid file?");
}
event(new LibraryChanged());
}
private function handleDeletedDirectoryRecord(string $path): void
{
if ($count = Song::inDirectory($path)->delete()) {
$this->logger->info("Deleted $count song(s) under $path");
event(new LibraryChanged());
} else {
$this->logger->info("$path is empty--no action needed.");
}
}
private function handleNewOrModifiedDirectoryRecord(string $path): void
{
foreach ($this->gatherFiles($path) as $file) {
$this->fileSynchronizer->setFile($file)->sync($this->tags);
}
$this->logger->info("Synced all song(s) under $path");
event(new LibraryChanged());
}
}