Passed
Push — master ( 8fb3d8...e6f5c5 )
by Pauli
12:47
created

TrackBusinessLayer::findAllDirty()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
1
<?php declare(strict_types=1);
2
3
/**
4
 * ownCloud - Music app
5
 *
6
 * This file is licensed under the Affero General Public License version 3 or
7
 * later. See the COPYING file.
8
 *
9
 * @author Morris Jobke <[email protected]>
10
 * @author Pauli Järvinen <[email protected]>
11
 * @copyright Morris Jobke 2013
12
 * @copyright Pauli Järvinen 2016 - 2021
13
 */
14
15
namespace OCA\Music\BusinessLayer;
16
17
use OCA\Music\AppFramework\BusinessLayer\BusinessLayer;
18
use OCA\Music\AppFramework\BusinessLayer\BusinessLayerException;
19
use OCA\Music\AppFramework\Core\Logger;
20
21
use OCA\Music\Db\TrackMapper;
22
use OCA\Music\Db\Track;
23
24
use OCA\Music\Utility\Util;
25
26
use OCP\AppFramework\Db\DoesNotExistException;
27
use OCP\Files\Folder;
28
29
/**
30
 * Base class functions with the actually used inherited types to help IDE and Scrutinizer:
31
 * @method Track find(int $trackId, string $userId)
32
 * @method Track[] findAll(string $userId, int $sortBy=SortBy::None, int $limit=null, int $offset=null)
33
 * @method Track[] findAllByName(string $name, string $userId, bool $fuzzy=false, int $limit=null, int $offset=null)
34
 * @phpstan-extends BusinessLayer<Track>
35
 */
36
class TrackBusinessLayer extends BusinessLayer {
37
	protected $mapper; // eclipse the definition from the base class, to help IDE and Scrutinizer to know the actual type
38
	private $logger;
39
40
	public function __construct(TrackMapper $trackMapper, Logger $logger) {
41
		parent::__construct($trackMapper);
42
		$this->mapper = $trackMapper;
43
		$this->logger = $logger;
44
	}
45
46
	/**
47
	 * Returns all tracks filtered by artist (both album and track artists are considered)
48
	 * @return Track[]
49
	 */
50
	public function findAllByArtist(int $artistId, string $userId, ?int $limit=null, ?int $offset=null) : array {
51
		return $this->mapper->findAllByArtist($artistId, $userId, $limit, $offset);
52
	}
53
54
	/**
55
	 * Returns all tracks filtered by album. Optionally, filter also by the performing artist.
56
	 * @return Track[]
57
	 */
58
	public function findAllByAlbum(int $albumId, string $userId, ?int $artistId=null, ?int $limit=null, ?int $offset=null) : array {
59
		return $this->mapper->findAllByAlbum($albumId, $userId, $artistId, $limit, $offset);
60
	}
61
62
	/**
63
	 * Returns all tracks filtered by parent folder
64
	 * @return Track[]
65
	 */
66
	public function findAllByFolder(int $folderId, string $userId, ?int $limit=null, ?int $offset=null) : array {
67
		return $this->mapper->findAllByFolder($folderId, $userId, $limit, $offset);
68
	}
69
70
	/**
71
	 * Returns all tracks filtered by genre
72
	 * @return Track[]
73
	 */
74
	public function findAllByGenre(int $genreId, string $userId, ?int $limit=null, ?int $offset=null) : array {
75
		return $this->mapper->findAllByGenre($genreId, $userId, $limit, $offset);
76
	}
77
78
	/**
79
	 * Returns all tracks filtered by name (of track/album/artist)
80
	 * @param string $name the name of the track/album/artist
81
	 * @param string $userId the name of the user
82
	 * @return Track[]
83
	 */
84
	public function findAllByNameRecursive(string $name, string $userId, ?int $limit=null, ?int $offset=null) : array {
85
		$name = \trim($name);
86
		return $this->mapper->findAllByNameRecursive($name, $userId, $limit, $offset);
87
	}
88
89
	/**
90
	 * Returns all tracks specified by name and/or artist name
91
	 * @return Track[] Tracks matching the criteria
92
	 */
93
	public function findAllByNameAndArtistName(?string $name, ?string $artistName, string $userId) : array {
94
		if ($name !== null) {
95
			$name = \trim($name);
96
		}
97
		if ($artistName !== null) {
98
			$artistName = \trim($artistName);
99
		}
100
101
		return $this->mapper->findAllByNameAndArtistName($name, $artistName, /*fuzzy=*/false, $userId);
102
	}
103
104
	/**
105
	 * Returns all tracks where the 'modified' time in the file system (actually in the cloud's file cache)
106
	 * is later than the 'updated' field of the entity in the database.
107
	 * @return Track[]
108
	 */
109
	public function findAllDirty(string $userId) : array {
110
		$tracks = $this->findAll($userId);
111
		return \array_filter($tracks, function (Track $track) {
112
			$dbModTime = new \DateTime($track->getUpdated());
113
			return ($dbModTime->getTimestamp() < $track->getFileModTime());
114
		});
115
	}
116
117
	/**
118
	 * Find most frequently played tracks
119
	 * @return Track[]
120
	 */
121
	public function findFrequentPlay(string $userId, ?int $limit=null, ?int $offset=null) : array {
122
		return $this->mapper->findFrequentPlay($userId, $limit, $offset);
123
	}
124
125
	/**
126
	 * Find most recently played tracks
127
	 * @return Track[]
128
	 */
129
	public function findRecentPlay(string $userId, ?int $limit=null, ?int $offset=null) : array {
130
		return $this->mapper->findRecentPlay($userId, $limit, $offset);
131
	}
132
133
	/**
134
	 * Find least recently played tracks
135
	 * @return Track[]
136
	 */
137
	public function findNotRecentPlay(string $userId, ?int $limit=null, ?int $offset=null) : array {
138
		return $this->mapper->findNotRecentPlay($userId, $limit, $offset);
139
	}
140
141
	/**
142
	 * Returns the track for a file id
143
	 * @return Track|null
144
	 */
145
	public function findByFileId(int $fileId, string $userId) : ?Track {
146
		try {
147
			return $this->mapper->findByFileId($fileId, $userId);
148
		} catch (DoesNotExistException $e) {
149
			return null;
150
		}
151
	}
152
153
	/**
154
	 * Returns file IDs of all indexed tracks of the user
155
	 * @return int[]
156
	 */
157
	public function findAllFileIds(string $userId) : array {
158
		return $this->mapper->findAllFileIds($userId);
159
	}
160
161
	/**
162
	 * Returns all folders of the user containing indexed tracks, along with the contained track IDs
163
	 * @return array of entries like {id: int, name: string, path: string, parent: ?int, trackIds: int[]}
164
	 */
165
	public function findAllFolders(string $userId, Folder $musicFolder) : array {
166
		// All tracks of the user, grouped by their parent folders. Some of the parent folders
167
		// may be owned by other users and are invisible to this user (in case of shared files).
168
		$tracksByFolder = $this->mapper->findTrackAndFolderIds($userId);
169
170
		// Get the folder names and paths for ordinary local folders directly from the DB.
171
		// This is significantly more efficient than using the Files API because we need to
172
		// run only single DB query instead of one per folder.
173
		$folderNamesAndParents = $this->mapper->findNodeNamesAndParents(
174
				\array_keys($tracksByFolder), $musicFolder->getStorage()->getId());
175
176
		// root folder has to be handled as a special case because shared files from
177
		// many folders may be shown to this user mapped under the root folder
178
		$rootFolderTracks = [];
179
180
		// Build the final results. Use the previously fetched data for the ordinary
181
		// local folders and query the data through the Files API for the more special cases.
182
		$result = [];
183
		foreach ($tracksByFolder as $folderId => $trackIds) {
184
			$entry = self::getFolderEntry($folderNamesAndParents, $folderId, $trackIds, $musicFolder);
185
186
			if ($entry) {
187
				$result[] = $entry;
188
			} else {
189
				$rootFolderTracks = \array_merge($rootFolderTracks, $trackIds);
190
			}
191
		}
192
193
		// add the library root folder
194
		$result[] = [
195
			'name' => '',
196
			'parent' => null,
197
			'trackIds' => $rootFolderTracks,
198
			'id' => $musicFolder->getId()
199
		];
200
201
		// add the intermediate folders which do not directly contain any tracks
202
		$this->recursivelyAddMissingParentFolders($result, $result, $musicFolder);
203
204
		return $result;
205
	}
206
207
	private function recursivelyAddMissingParentFolders(array $foldersToProcess, array &$alreadyFoundFolders, Folder $musicFolder) : void {
208
209
		$parentIds = \array_unique(\array_column($foldersToProcess, 'parent'));
210
		$parentIds = Util::arrayDiff($parentIds, \array_column($alreadyFoundFolders, 'id'));
211
		$parentInfo = $this->mapper->findNodeNamesAndParents($parentIds, $musicFolder->getStorage()->getId());
212
213
		$newParents = [];
214
		foreach ($parentIds as $parentId) {
215
			if ($parentId !== null) {
216
				$newParents[] =  self::getFolderEntry($parentInfo, $parentId, [], $musicFolder);
217
			}
218
		}
219
220
		$alreadyFoundFolders = \array_merge($alreadyFoundFolders, $newParents);
221
222
		if (\count($newParents)) {
223
			$this->recursivelyAddMissingParentFolders($newParents, $alreadyFoundFolders, $musicFolder);
224
		}
225
	}
226
227
	private static function getFolderEntry(array $folderNamesAndParents, int $folderId, array $trackIds, Folder $musicFolder) : ?array {
228
		if (isset($folderNamesAndParents[$folderId])) {
229
			// normal folder within the user home storage
230
			$entry = $folderNamesAndParents[$folderId];
231
			// special handling for the root folder
232
			if ($folderId === $musicFolder->getId()) {
233
				$entry = null;
234
			}
235
		} else {
236
			// shared folder or parent folder of a shared file or an externally mounted folder
237
			$folderNode = $musicFolder->getById($folderId)[0] ?? null;
238
			if ($folderNode === null) {
239
				// other user's folder with files shared with this user (mapped under root)
240
				$entry = null;
241
			} else {
242
				$entry = [
243
					'name' => $folderNode->getName(),
244
					'parent' => $folderNode->getParent()->getId()
245
				];
246
			}
247
		}
248
249
		if ($entry) {
250
			$entry['trackIds'] = $trackIds;
251
			$entry['id'] = $folderId;
252
253
			if ($entry['id'] == $musicFolder->getId()) {
254
				// the library root should be reported without a parent folder as that parent does not belong to the library
255
				$entry['parent'] = null;
256
			}
257
		}
258
259
		return $entry;
260
	}
261
262
	/**
263
	 * Returns all genre IDs associated with the given artist
264
	 * @return int[]
265
	 */
266
	public function getGenresByArtistId(int $artistId, string $userId) : array {
267
		return $this->mapper->getGenresByArtistId($artistId, $userId);
268
	}
269
270
	/**
271
	 * Returns file IDs of the tracks which do not have genre scanned. This is not the same
272
	 * thing as unknown genre, which is stored as empty string and means that the genre has
273
	 * been scanned but was not found from the track metadata.
274
	 * @return int[]
275
	 */
276
	public function findFilesWithoutScannedGenre(string $userId) : array {
277
		return $this->mapper->findFilesWithoutScannedGenre($userId);
278
	}
279
280
	public function countByArtist(int $artistId) : int {
281
		return $this->mapper->countByArtist($artistId);
282
	}
283
284
	public function countByAlbum(int $albumId) : int {
285
		return $this->mapper->countByAlbum($albumId);
286
	}
287
288
	/**
289
	 * @return integer Duration in seconds
290
	 */
291
	public function totalDurationOfAlbum(int $albumId) : int {
292
		return $this->mapper->totalDurationOfAlbum($albumId);
293
	}
294
295
	/**
296
	 * Update "last played" timestamp and increment the total play count of the track.
297
	 */
298
	public function recordTrackPlayed(int $trackId, string $userId, ?\DateTime $timeOfPlay = null) : void {
299
		$timeOfPlay = $timeOfPlay ?? new \DateTime();
300
301
		if (!$this->mapper->recordTrackPlayed($trackId, $userId, $timeOfPlay)) {
302
			throw new BusinessLayerException("Track with ID $trackId was not found");
303
		}
304
	}
305
306
	/**
307
	 * Adds a track if it does not exist already or updates an existing track
308
	 * @param string $title the title of the track
309
	 * @param int|null $number the number of the track
310
	 * @param int|null $discNumber the number of the disc
311
	 * @param int|null $year the year of the release
312
	 * @param int $genreId the genre id of the track
313
	 * @param int $artistId the artist id of the track
314
	 * @param int $albumId the album id of the track
315
	 * @param int $fileId the file id of the track
316
	 * @param string $mimetype the mimetype of the track
317
	 * @param string $userId the name of the user
318
	 * @param int $length track length in seconds
319
	 * @param int $bitrate track bitrate in bits (not kbits)
320
	 * @return Track The added/updated track
321
	 */
322
	public function addOrUpdateTrack(
323
			$title, $number, $discNumber, $year, $genreId, $artistId, $albumId,
324
			$fileId, $mimetype, $userId, $length=null, $bitrate=null) {
325
		$track = new Track();
326
		$track->setTitle(Util::truncate($title, 256)); // some DB setups can't truncate automatically to column max size
327
		$track->setNumber($number);
328
		$track->setDisk($discNumber);
329
		$track->setYear($year);
330
		$track->setGenreId($genreId);
331
		$track->setArtistId($artistId);
332
		$track->setAlbumId($albumId);
333
		$track->setFileId($fileId);
334
		$track->setMimetype($mimetype);
335
		$track->setUserId($userId);
336
		$track->setLength($length);
337
		$track->setBitrate($bitrate);
338
		return $this->mapper->insertOrUpdate($track);
339
	}
340
341
	/**
342
	 * Deletes a track
343
	 * @param int[] $fileIds file IDs of the tracks to delete
344
	 * @param string[]|null $userIds the target users; if omitted, the tracks matching the
345
	 *                      $fileIds are deleted from all users
346
	 * @return array|false  False is returned if no such track was found; otherwise array of six arrays
347
	 *         (named 'deletedTracks', 'remainingAlbums', 'remainingArtists', 'obsoleteAlbums',
348
	 *         'obsoleteArtists', and 'affectedUsers'). These contain the track, album, artist, and
349
	 *         user IDs of the deleted tracks. The 'obsolete' entities are such which no longer
350
	 *         have any tracks while 'remaining' entities have some left.
351
	 */
352
	public function deleteTracks(array $fileIds, ?array $userIds=null) {
353
		$tracks = ($userIds !== null)
354
			? $this->mapper->findByFileIds($fileIds, $userIds)
355
			: $this->mapper->findAllByFileIds($fileIds);
356
357
		if (\count($tracks) === 0) {
358
			$result = false;
359
		} else {
360
			// delete all the matching tracks
361
			$trackIds = Util::extractIds($tracks);
362
			$this->deleteById($trackIds);
363
364
			// find all distinct albums, artists, and users of the deleted tracks
365
			$artists = [];
366
			$albums = [];
367
			$users = [];
368
			foreach ($tracks as $track) {
369
				$artists[$track->getArtistId()] = 1;
370
				$albums[$track->getAlbumId()] = 1;
371
				$users[$track->getUserId()] = 1;
372
			}
373
			$artists = \array_keys($artists);
374
			$albums = \array_keys($albums);
375
			$users = \array_keys($users);
376
377
			// categorize each artist as 'remaining' or 'obsolete'
378
			$remainingArtists = [];
379
			$obsoleteArtists = [];
380
			foreach ($artists as $artistId) {
381
				if ($this->mapper->countByArtist($artistId) === 0) {
382
					$obsoleteArtists[] = $artistId;
383
				} else {
384
					$remainingArtists[] = $artistId;
385
				}
386
			}
387
388
			// categorize each album as 'remaining' or 'obsolete'
389
			$remainingAlbums = [];
390
			$obsoleteAlbums = [];
391
			foreach ($albums as $albumId) {
392
				if ($this->mapper->countByAlbum($albumId) === 0) {
393
					$obsoleteAlbums[] = $albumId;
394
				} else {
395
					$remainingAlbums[] = $albumId;
396
				}
397
			}
398
399
			$result = [
400
				'deletedTracks'    => $trackIds,
401
				'remainingAlbums'  => $remainingAlbums,
402
				'remainingArtists' => $remainingArtists,
403
				'obsoleteAlbums'   => $obsoleteAlbums,
404
				'obsoleteArtists'  => $obsoleteArtists,
405
				'affectedUsers'    => $users
406
			];
407
		}
408
409
		return $result;
410
	}
411
}
412