Passed
Push — master ( de702b...3e9331 )
by Pauli
02:18
created

AmpacheController::getCover()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 10
nc 4
nop 2
dl 0
loc 15
ccs 0
cts 10
cp 0
crap 12
rs 9.9332
c 1
b 0
f 0
1
<?php
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, 2014
12
 * @copyright Pauli Järvinen 2017 - 2020
13
 */
14
15
namespace OCA\Music\Controller;
16
17
use \OCP\AppFramework\Controller;
0 ignored issues
show
Bug introduced by
The type OCP\AppFramework\Controller was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
use \OCP\AppFramework\Http\JSONResponse;
0 ignored issues
show
Bug introduced by
The type OCP\AppFramework\Http\JSONResponse was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
use \OCP\IRequest;
0 ignored issues
show
Bug introduced by
The type OCP\IRequest was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
20
use \OCP\IURLGenerator;
0 ignored issues
show
Bug introduced by
The type OCP\IURLGenerator was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
21
22
use \OCA\Music\AppFramework\BusinessLayer\BusinessLayer;
23
use \OCA\Music\AppFramework\BusinessLayer\BusinessLayerException;
24
use \OCA\Music\AppFramework\Core\Logger;
25
use \OCA\Music\Middleware\AmpacheException;
26
27
use \OCA\Music\BusinessLayer\AlbumBusinessLayer;
28
use \OCA\Music\BusinessLayer\ArtistBusinessLayer;
29
use \OCA\Music\BusinessLayer\GenreBusinessLayer;
30
use \OCA\Music\BusinessLayer\Library;
31
use \OCA\Music\BusinessLayer\PlaylistBusinessLayer;
32
use \OCA\Music\BusinessLayer\TrackBusinessLayer;
33
34
use \OCA\Music\Db\Album;
35
use \OCA\Music\Db\AmpacheUserMapper;
36
use \OCA\Music\Db\AmpacheSession;
37
use \OCA\Music\Db\AmpacheSessionMapper;
38
use \OCA\Music\Db\Artist;
39
use \OCA\Music\Db\SortBy;
40
41
use \OCA\Music\Http\ErrorResponse;
42
use \OCA\Music\Http\FileResponse;
43
use \OCA\Music\Http\XMLResponse;
44
45
use \OCA\Music\Utility\AmpacheUser;
46
use \OCA\Music\Utility\CoverHelper;
47
use \OCA\Music\Utility\Util;
48
49
class AmpacheController extends Controller {
50
	private $ampacheUserMapper;
51
	private $ampacheSessionMapper;
52
	private $albumBusinessLayer;
53
	private $artistBusinessLayer;
54
	private $genreBusinessLayer;
55
	private $playlistBusinessLayer;
56
	private $trackBusinessLayer;
57
	private $library;
58
	private $ampacheUser;
59
	private $urlGenerator;
60
	private $rootFolder;
61
	private $l10n;
62
	private $coverHelper;
63
	private $logger;
64
	private $jsonMode;
65
66
	const SESSION_EXPIRY_TIME = 6000;
67
	const ALL_TRACKS_PLAYLIST_ID = 10000000;
68
	const API_VERSION = 350001;
69
70
	public function __construct($appname,
71
								IRequest $request,
72
								$l10n,
73
								IURLGenerator $urlGenerator,
74
								AmpacheUserMapper $ampacheUserMapper,
75
								AmpacheSessionMapper $ampacheSessionMapper,
76
								AlbumBusinessLayer $albumBusinessLayer,
77
								ArtistBusinessLayer $artistBusinessLayer,
78
								GenreBusinessLayer $genreBusinessLayer,
79
								PlaylistBusinessLayer $playlistBusinessLayer,
80
								TrackBusinessLayer $trackBusinessLayer,
81
								Library $library,
82
								AmpacheUser $ampacheUser,
83
								$rootFolder,
84
								CoverHelper $coverHelper,
85
								Logger $logger) {
86
		parent::__construct($appname, $request);
87
88
		$this->ampacheUserMapper = $ampacheUserMapper;
89
		$this->ampacheSessionMapper = $ampacheSessionMapper;
90
		$this->albumBusinessLayer = $albumBusinessLayer;
91
		$this->artistBusinessLayer = $artistBusinessLayer;
92
		$this->genreBusinessLayer = $genreBusinessLayer;
93
		$this->playlistBusinessLayer = $playlistBusinessLayer;
94
		$this->trackBusinessLayer = $trackBusinessLayer;
95
		$this->library = $library;
96
		$this->urlGenerator = $urlGenerator;
97
		$this->l10n = $l10n;
98
99
		// used to share user info with middleware
100
		$this->ampacheUser = $ampacheUser;
101
102
		// used to deliver actual media file
103
		$this->rootFolder = $rootFolder;
104
105
		$this->coverHelper = $coverHelper;
106
		$this->logger = $logger;
107
	}
108
109
	public function setJsonMode($useJsonMode) {
110
		$this->jsonMode = $useJsonMode;
111
	}
112
113
	public function ampacheResponse($content) {
114
		if ($this->jsonMode) {
115
			return new JSONResponse($content);
116
		} else {
117
			return new XMLResponse(['root' => $content], ['id', 'count']);
118
		}
119
	}
120
121
	/**
122
	 * @NoAdminRequired
123
	 * @PublicPage
124
	 * @NoCSRFRequired
125
	 */
126
	public function xmlApi($action, $user, $timestamp, $auth, $filter, $exact, $limit, $offset) {
127
		// differentation between xmlApi and jsonApi is made already by the middleware
128
		return $this->dispatch($action, $user, $timestamp, $auth, $filter, $exact, $limit, $offset);
129
	}
130
131
	/**
132
	 * @NoAdminRequired
133
	 * @PublicPage
134
	 * @NoCSRFRequired
135
	 */
136
	public function jsonApi($action, $user, $timestamp, $auth, $filter, $exact, $limit, $offset) {
137
		// differentation between xmlApi and jsonApi is made already by the middleware
138
		return $this->dispatch($action, $user, $timestamp, $auth, $filter, $exact, $limit, $offset);
139
	}
140
141
	protected function dispatch($action, $user, $timestamp, $auth, $filter, $exact, $limit, $offset) {
142
		$this->logger->log("Ampache action '$action' requested", 'debug');
143
144
		$limit = self::validateLimitOrOffset($limit);
145
		$offset = self::validateLimitOrOffset($offset);
146
147
		switch ($action) {
148
			case 'handshake':
149
				return $this->handshake($user, $timestamp, $auth);
150
			case 'ping':
151
				return $this->ping($auth);
152
			case 'artists':
153
				return $this->artists($filter, $exact, $limit, $offset, $auth);
154
			case 'artist':
155
				return $this->artist($filter, $auth);
156
			case 'artist_albums':
157
				return $this->artist_albums($filter, $auth);
158
			case 'album_songs':
159
				return $this->album_songs($filter, $auth);
160
			case 'albums':
161
				return $this->albums($filter, $exact, $limit, $offset, $auth);
162
			case 'album':
163
				return $this->album($filter, $auth);
164
			case 'artist_songs':
165
				return $this->artist_songs($filter, $auth);
166
			case 'songs':
167
				return $this->songs($filter, $exact, $limit, $offset, $auth);
168
			case 'song':
169
				return $this->song($filter, $auth);
170
			case 'search_songs':
171
				return $this->search_songs($filter, $auth);
172
			case 'playlists':
173
				return $this->playlists($filter, $exact, $limit, $offset);
174
			case 'playlist':
175
				return $this->playlist($filter);
176
			case 'playlist_songs':
177
				return $this->playlist_songs($filter, $limit, $offset, $auth);
178
			case 'tags':
179
				return $this->tags($filter, $exact, $limit, $offset);
180
			case 'tag':
181
				return $this->tag($filter);
182
			case 'tag_artists':
183
				return $this->tag_artists($filter, $limit, $offset, $auth);
184
			case 'tag_albums':
185
				return $this->tag_albums($filter, $limit, $offset, $auth);
186
			case 'tag_songs':
187
				return $this->tag_songs($filter, $limit, $offset, $auth);
188
189
			# non Ampache API actions
190
			case '_play':
191
				return $this->_play($filter);
192
			case '_get_album_cover':
193
				return $this->_get_album_cover($filter);
194
			case '_get_artist_cover':
195
				return $this->_get_artist_cover($filter);
196
		}
197
198
		$this->logger->log("Unsupported Ampache action '$action' requested", 'warn');
199
		throw new AmpacheException('Action not supported', 405);
200
	}
201
202
	/***********************
203
	 * Ampahce API methods *
204
	 ***********************/
205
206
	protected function handshake($user, $timestamp, $auth) {
207
		$currentTime = \time();
208
		$expiryDate = $currentTime + self::SESSION_EXPIRY_TIME;
209
210
		$this->checkHandshakeTimestamp($timestamp, $currentTime);
211
		$this->checkHandshakeAuthentication($user, $timestamp, $auth);
212
		$token = $this->startNewSession($user, $expiryDate);
213
214
		$currentTimeFormated = \date('c', $currentTime);
215
		$expiryDateFormated = \date('c', $expiryDate);
216
217
		return $this->ampacheResponse([
218
			'auth' => $token,
219
			'version' => self::API_VERSION,
220
			'update' => $currentTimeFormated,
221
			'add' => $currentTimeFormated,
222
			'clean' => $currentTimeFormated,
223
			'songs' => $this->trackBusinessLayer->count($user),
224
			'artists' => $this->artistBusinessLayer->count($user),
225
			'albums' => $this->albumBusinessLayer->count($user),
226
			'playlists' => $this->playlistBusinessLayer->count($user) + 1, // +1 for "All tracks"
227
			'session_expire' => $expiryDateFormated,
228
			'tags' => $this->genreBusinessLayer->count($user),
229
			'videos' => 0
230
		]);
231
	}
232
233
	protected function ping($auth) {
234
		if ($auth !== null && $auth !== '') {
235
			$this->ampacheSessionMapper->extend($auth, \time() + self::SESSION_EXPIRY_TIME);
236
		}
237
238
		return $this->ampacheResponse([
239
			'version' => self::API_VERSION
240
		]);
241
	}
242
243
	protected function artists($filter, $exact, $limit, $offset, $auth) {
244
		$artists = $this->findEntities($this->artistBusinessLayer, $filter, $exact, $limit, $offset);
245
		return $this->renderArtists($artists, $auth);
246
	}
247
248
	protected function artist($artistId, $auth) {
249
		$userId = $this->ampacheUser->getUserId();
250
		$artist = $this->artistBusinessLayer->find($artistId, $userId);
251
		return $this->renderArtists([$artist], $auth);
252
	}
253
254
	protected function artist_albums($artistId, $auth) {
255
		$userId = $this->ampacheUser->getUserId();
256
		$albums = $this->albumBusinessLayer->findAllByArtist($artistId, $userId);
257
		return $this->renderAlbums($albums, $auth);
258
	}
259
260
	protected function artist_songs($artistId, $auth) {
261
		$userId = $this->ampacheUser->getUserId();
262
		$artist = $this->artistBusinessLayer->find($artistId, $userId);
263
		$tracks = $this->trackBusinessLayer->findAllByArtist($artistId, $userId);
264
		$this->injectArtistAndAlbum($tracks, $artist);
265
		return $this->renderSongs($tracks, $auth);
266
	}
267
268
	protected function album_songs($albumId, $auth) {
269
		$userId = $this->ampacheUser->getUserId();
270
271
		$album = $this->albumBusinessLayer->find($albumId, $userId);
272
		$album->setAlbumArtist($this->artistBusinessLayer->find($album->getAlbumArtistId(), $userId));
273
274
		$tracks = $this->trackBusinessLayer->findAllByAlbum($albumId, $userId);
275
		$this->injectArtistAndAlbum($tracks, null, $album);
276
277
		return $this->renderSongs($tracks, $auth);
278
	}
279
280
	protected function song($trackId, $auth) {
281
		$userId = $this->ampacheUser->getUserId();
282
		$track = $this->trackBusinessLayer->find($trackId, $userId);
283
		$trackInArray = [$track];
284
		$this->injectArtistAndAlbum($trackInArray);
285
		return $this->renderSongs($trackInArray, $auth);
286
	}
287
288
	protected function songs($filter, $exact, $limit, $offset, $auth) {
289
290
		// optimized handling for fetching the whole library
291
		// note: the ordering of the songs differs between these two cases
292
		if (empty($filter) && !$limit && !$offset) {
293
			$tracks = $this->getAllTracks();
294
		}
295
		// general case
296
		else {
297
			$tracks = $this->findEntities($this->trackBusinessLayer, $filter, $exact, $limit, $offset);
298
			$this->injectArtistAndAlbum($tracks);
299
		}
300
301
		return $this->renderSongs($tracks, $auth);
302
	}
303
304
	protected function search_songs($filter, $auth) {
305
		$userId = $this->ampacheUser->getUserId();
306
		$tracks = $this->trackBusinessLayer->findAllByNameRecursive($filter, $userId);
307
		$this->injectArtistAndAlbum($tracks);
308
		return $this->renderSongs($tracks, $auth);
309
	}
310
311
	protected function albums($filter, $exact, $limit, $offset, $auth) {
312
		$albums = $this->findEntities($this->albumBusinessLayer, $filter, $exact, $limit, $offset);
313
		return $this->renderAlbums($albums, $auth);
314
	}
315
316
	protected function album($albumId, $auth) {
317
		$userId = $this->ampacheUser->getUserId();
318
		$album = $this->albumBusinessLayer->find($albumId, $userId);
319
		return $this->renderAlbums([$album], $auth);
320
	}
321
322
	protected function playlists($filter, $exact, $limit, $offset) {
323
		$userId = $this->ampacheUser->getUserId();
324
		$playlists = $this->findEntities($this->playlistBusinessLayer, $filter, $exact, $limit, $offset);
325
326
		// append "All tracks" if not searching by name, and it is not off-limit
327
		if (empty($filter) && ($limit === null || \count($playlists) < $limit)) {
328
			$playlists[] = new AmpacheController_AllTracksPlaylist($userId, $this->trackBusinessLayer, $this->l10n);
329
		}
330
331
		return $this->renderPlaylists($playlists);
332
	}
333
334
	protected function playlist($listId) {
335
		$userId = $this->ampacheUser->getUserId();
336
		if ($listId == self::ALL_TRACKS_PLAYLIST_ID) {
337
			$playlist = new AmpacheController_AllTracksPlaylist($userId, $this->trackBusinessLayer, $this->l10n);
338
		} else {
339
			$playlist = $this->playlistBusinessLayer->find($listId, $userId);
340
		}
341
		return $this->renderPlaylists([$playlist]);
342
	}
343
344
	protected function playlist_songs($listId, $limit, $offset, $auth) {
345
		if ($listId == self::ALL_TRACKS_PLAYLIST_ID) {
346
			$playlistTracks = $this->getAllTracks();
347
			$playlistTracks = \array_slice($playlistTracks, $offset, $limit);
348
		}
349
		else {
350
			$userId = $this->ampacheUser->getUserId();
351
			$playlistTracks = $this->playlistBusinessLayer->getPlaylistTracks($listId, $userId, $limit, $offset);
352
			$this->injectArtistAndAlbum($playlistTracks);
353
		}
354
		return $this->renderSongs($playlistTracks, $auth);
355
	}
356
357
	protected function tags($filter, $exact, $limit, $offset) {
358
		$userId = $this->ampacheUser->getUserId();
359
		// TODO: $filter, $exact
360
		$genres = $this->genreBusinessLayer->findAllWithCounts($userId, $limit, $offset);
361
		return $this->renderTags($genres);
362
	}
363
364
	protected function tag($tagId) {
365
		$userId = $this->ampacheUser->getUserId();
366
		$genre = $this->genreBusinessLayer->find($tagId, $userId);
367
		return $this->renderTags([$genre]);
368
	}
369
370
	protected function tag_artists($genreId, $limit, $offset, $auth) {
371
		$userId = $this->ampacheUser->getUserId();
372
		$artists = $this->artistBusinessLayer->findAllByGenre($genreId, $userId, $limit, $offset);
373
		return $this->renderArtists($artists, $auth);
374
	}
375
376
	protected function tag_albums($genreId, $limit, $offset, $auth) {
377
		$userId = $this->ampacheUser->getUserId();
378
		$albums = $this->albumBusinessLayer->findAllByGenre($genreId, $userId, $limit, $offset);
379
		return $this->renderAlbums($albums, $auth);
380
	}
381
382
	protected function tag_songs($genreId, $limit, $offset, $auth) {
383
		$userId = $this->ampacheUser->getUserId();
384
		$tracks = $this->trackBusinessLayer->findAllByGenre($genreId, $userId, $limit, $offset);
385
		$this->injectArtistAndAlbum($tracks, $artist);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $artist seems to be never defined.
Loading history...
386
		return $this->renderSongs($tracks, $auth);
387
	}
388
389
	/***************************************************************
390
	 * API methods which are not part of the Ampache specification *
391
	 ***************************************************************/
392
	protected function _play($trackId) {
393
		$userId = $this->ampacheUser->getUserId();
394
395
		try {
396
			$track = $this->trackBusinessLayer->find($trackId, $userId);
397
		} catch (BusinessLayerException $e) {
398
			return new ErrorResponse(Http::STATUS_NOT_FOUND, $e->getMessage());
0 ignored issues
show
Bug introduced by
The type OCA\Music\Controller\Http was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
399
		}
400
401
		$files = $this->rootFolder->getUserFolder($userId)->getById($track->getFileId());
402
403
		if (\count($files) === 1) {
404
			return new FileResponse($files[0]);
405
		} else {
406
			return new ErrorResponse(Http::STATUS_NOT_FOUND);
407
		}
408
	}
409
410
	protected function _get_album_cover($albumId) {
411
		return $this->getCover($albumId, $this->albumBusinessLayer);
412
	}
413
414
	protected function _get_artist_cover($artistId) {
415
		return $this->getCover($artistId, $this->artistBusinessLayer);
416
	}
417
418
419
	/********************
420
	 * Helper functions *
421
	 ********************/
422
423
	private function getCover($entityId, BusinessLayer $businessLayer) {
424
		$userId = $this->ampacheUser->getUserId();
425
		$userFolder = $this->rootFolder->getUserFolder($userId);
426
		$entity = $businessLayer->find($entityId, $userId);
427
428
		try {
429
			$coverData = $this->coverHelper->getCover($entity, $userId, $userFolder);
430
			if ($coverData !== null) {
431
				return new FileResponse($coverData);
432
			}
433
		} catch (BusinessLayerException $e) {
434
			return new ErrorResponse(Http::STATUS_NOT_FOUND, 'entity not found');
435
		}
436
437
		return new ErrorResponse(Http::STATUS_NOT_FOUND, 'entity has no cover');
438
	}
439
440
	private function checkHandshakeTimestamp($timestamp, $currentTime) {
441
		$providedTime = \intval($timestamp);
442
443
		if ($providedTime === 0) {
444
			throw new AmpacheException('Invalid Login - cannot parse time', 401);
445
		}
446
		if ($providedTime < ($currentTime - self::SESSION_EXPIRY_TIME)) {
447
			throw new AmpacheException('Invalid Login - session is outdated', 401);
448
		}
449
		// Allow the timestamp to be at maximum 10 minutes in the future. The client may use its
450
		// own system clock to generate the timestamp and that may differ from the server's time.
451
		if ($providedTime > $currentTime + 600) {
452
			throw new AmpacheException('Invalid Login - timestamp is in future', 401);
453
		}
454
	}
455
456
	private function checkHandshakeAuthentication($user, $timestamp, $auth) {
457
		$hashes = $this->ampacheUserMapper->getPasswordHashes($user);
458
459
		foreach ($hashes as $hash) {
460
			$expectedHash = \hash('sha256', $timestamp . $hash);
461
462
			if ($expectedHash === $auth) {
463
				return;
464
			}
465
		}
466
467
		throw new AmpacheException('Invalid Login - passphrase does not match', 401);
468
	}
469
470
	private function startNewSession($user, $expiryDate) {
471
		// this can cause collision, but it's just a temporary token
472
		$token = \md5(\uniqid(\rand(), true));
473
474
		// create new session
475
		$session = new AmpacheSession();
476
		$session->setUserId($user);
477
		$session->setToken($token);
478
		$session->setExpiry($expiryDate);
479
480
		// save session
481
		$this->ampacheSessionMapper->insert($session);
482
483
		return $token;
484
	}
485
486
	private function findEntities(BusinessLayer $businessLayer, $filter, $exact, $limit=null, $offset=null) {
487
		$userId = $this->ampacheUser->getUserId();
488
489
		if ($filter) {
490
			$fuzzy = !((boolean) $exact);
491
			return $businessLayer->findAllByName($filter, $userId, $fuzzy, $limit, $offset);
492
		} else {
493
			return $businessLayer->findAll($userId, SortBy::Name, $limit, $offset);
494
		}
495
	}
496
497
	/**
498
	 * Getting all tracks with this helper is more efficient than with `findEntities`
499
	 * followed by `injectArtistAndAlbum`. This is because, under the hood, the albums
500
	 * and artists are fetched with a single DB query instead of fetching each separately.
501
	 * 
502
	 * The result set is ordered first by artist and then by song title.
503
	 */
504
	private function getAllTracks() {
505
		$userId = $this->ampacheUser->getUserId();
506
		$tracks = $this->library->getTracksAlbumsAndArtists($userId)['tracks'];
507
		\usort($tracks, ['\OCA\Music\Db\Track', 'compareArtistAndTitle']);
508
		foreach ($tracks as $index => &$track) {
509
			$track->setNumberOnPlaylist($index + 1);
510
		}
511
		return $tracks;
512
	}
513
514
	private function createAmpacheActionUrl($action, $filter, $auth) {
515
		$api = $this->jsonMode ? 'music.ampache.jsonApi' : 'music.ampache.xmlApi';
516
		return $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute($api))
517
				. "?action=$action&filter=$filter&auth=$auth";
518
	}
519
520
	private function createCoverUrl($entity, $auth) {
521
		if ($entity instanceof Album) {
522
			$type = 'album';
523
		} elseif ($entity instanceof Artist) {
524
			$type = 'artist';
525
		} else {
526
			throw new AmpacheException('unexpeted entity type for cover image', 500);
527
		}
528
529
		if ($entity->getCoverFileId()) {
530
			return $this->createAmpacheActionUrl("_get_{$type}_cover", $entity->getId(), $auth);
531
		} else {
532
			return '';
533
		}
534
	}
535
536
	/**
537
	 * Any non-integer values and integer value 0 are converted to null to
538
	 * indicate "no limit" or "no offset".
539
	 * @param string $value
540
	 * @return integer|null
541
	 */
542
	private static function validateLimitOrOffset($value) {
543
		if (\ctype_digit(\strval($value)) && $value !== 0) {
544
			return \intval($value);
545
		} else {
546
			return null;
547
		}
548
	}
549
550
	private function renderArtists($artists, $auth) {
551
		$userId = $this->ampacheUser->getUserId();
552
		$genreMap = Util::createIdLookupTable($this->genreBusinessLayer->findAll($userId));
553
554
		return $this->ampacheResponse([
555
			'total_count' => \count($artists),
556
			'artist' => \array_map(function($artist) use ($userId, $genreMap, $auth) {
557
				return [
558
					'id' => $artist->getId(),
559
					'name' => $artist->getNameString($this->l10n),
560
					'albums' => $this->albumBusinessLayer->countByArtist($artist->getId()),
561
					'songs' => $this->trackBusinessLayer->countByArtist($artist->getId()),
562
					'art' => $this->createCoverUrl($artist, $auth),
563
					'rating' => 0,
564
					'preciserating' => 0,
565
					'tag' => \array_map(function($genreId) use ($genreMap) {
566
						return [
567
							'id' => $genreId,
568
							'value' => $genreMap[$genreId]->getNameString($this->l10n),
569
							'count' => 1
570
						];
571
					}, $this->trackBusinessLayer->getGenresByArtistId($artist->getId(), $userId))
572
				];
573
			}, $artists)
574
		]);
575
	}
576
577
	private function renderAlbums($albums, $auth) {
578
		$userId = $this->ampacheUser->getUserId();
579
580
		$genreMap = Util::createIdLookupTable($this->genreBusinessLayer->findAll($userId));
581
582
		return $this->ampacheResponse([
583
			'total_count' => \count($albums),
584
			'album' => \array_map(function($album) use ($userId, $auth, $genreMap) {
585
				$artist = $this->artistBusinessLayer->find($album->getAlbumArtistId(), $userId);
586
				return [
587
					'id' => $album->getId(),
588
					'name' => $album->getNameString($this->l10n),
589
					'artist' => [
590
						'id' => $artist->getId(),
591
						'value' => $artist->getNameString($this->l10n)
592
					],
593
					'tracks' => $this->trackBusinessLayer->countByAlbum($album->getId()),
594
					'rating' => 0,
595
					'year' => $album->yearToAPI(),
596
					'art' => $this->createCoverUrl($album, $auth),
597
					'preciserating' => 0,
598
					'tag' => \array_map(function($genreId) use ($genreMap) {
599
						return [
600
							'id' => $genreId,
601
							'value' => $genreMap[$genreId]->getNameString($this->l10n),
602
							'count' => 1
603
						];
604
					}, $album->getGenres())
605
				];
606
			}, $albums)
607
		]);
608
	}
609
610
	private function injectArtistAndAlbum(&$tracks, $commonArtist=null, $commonAlbum=null) {
611
		$userId = $this->ampacheUser->getUserId();
612
613
		foreach ($tracks as &$track) {
614
			$artist = $commonArtist ?: $this->artistBusinessLayer->find($track->getArtistId(), $userId);
615
			$track->setArtist($artist);
616
617
			if (!empty($commonAlbum)) {
618
				$track->setAlbum($commonAlbum);
619
			} else {
620
				$album = $this->albumBusinessLayer->find($track->getAlbumId(), $userId);
621
				$album->setAlbumArtist($this->artistBusinessLayer->find($album->getAlbumArtistId(), $userId));
622
				$track->setAlbum($album);
623
			}
624
		}
625
	}
626
627
	private function renderSongs($tracks, $auth) {
628
		$userId = $this->ampacheUser->getUserId();
629
		$genreMap = Util::createIdLookupTable($this->genreBusinessLayer->findAll($userId));
630
631
		return $this->ampacheResponse([
632
			'total_count' => \count($tracks),
633
			'song' => \array_map(function($track) use ($auth, $genreMap) {
634
				$artist = $track->getArtist();
635
				$album = $track->getAlbum();
636
				$albumArtist = $album->getAlbumArtist();
637
638
				$result = [
639
					'id' => $track->getId(),
640
					'title' => $track->getTitle(),
641
					'artist' => [
642
						'id' => $artist->getId(),
643
						'value' => $artist->getNameString($this->l10n)
644
					],
645
					'albumartist' => [
646
						'id' => $albumArtist->getId(),
647
						'value' => $albumArtist->getNameString($this->l10n)
648
					],
649
					'album' => [
650
						'id' => $album->getId(),
651
						'value' => $album->getNameString($this->l10n)
652
					],
653
					'url' => $this->createAmpacheActionUrl('_play', $track->getId(), $auth),
654
					'time' => $track->getLength(),
655
					'year' => $track->getYear(),
656
					'track' => $track->getAdjustedTrackNumber(),
657
					'bitrate' => $track->getBitrate(),
658
					'mime' => $track->getMimetype(),
659
					'size' => $track->getSize(),
660
					'art' => $this->createCoverUrl($album, $auth),
661
					'rating' => 0,
662
					'preciserating' => 0,
663
				];
664
665
				$genreId = $track->getGenreId();
666
				if ($genreId !== null) {
667
					$result['tag'] = [
668
						'id' => $genreId,
669
						'value' => $genreMap[$genreId]->getNameString($this->l10n),
670
						'count' => 1
671
					];
672
				}
673
				return $result;
674
			}, $tracks)
675
		]);
676
	}
677
678
	private function renderPlaylists($playlists) {
679
		return $this->ampacheResponse([
680
			'total_count' => [\count($playlists)],
681
			'playlist' => \array_map(function($playlist) {
682
				return [
683
					'id' => $playlist->getId(),
684
					'name' => $playlist->getName(),
685
					'owner' => $this->ampacheUser->getUserId(),
686
					'items' => $playlist->getTrackCount(),
687
					'type' => 'Private'
688
				];
689
			}, $playlists)
690
		]);
691
	}
692
693
	private function renderTags($genres) {
694
		return $this->ampacheResponse([
695
			'total_count' => [\count($genres)],
696
			'tag' => \array_map(function($genre) {
697
				return [
698
					'id' => $genre->getId(),
699
					'name' => $genre->getNameString($this->l10n),
700
					'albums' => $genre->getAlbumCount(),
701
					'artists' => $genre->getArtistCount(),
702
					'songs' => $genre->getTrackCount(),
703
					'videos' => 0,
704
					'playlists' => 0,
705
					'stream' => 0
706
				];
707
			}, $genres)
708
		]);
709
	}
710
711
}
712
713
/**
714
 * Adapter class which acts like the Playlist class for the purpose of 
715
 * AmpacheController::renderPlaylists but contains all the track of the user. 
716
 */
717
class AmpacheController_AllTracksPlaylist {
718
719
	private $user;
720
	private $trackBusinessLayer;
721
	private $l10n;
722
723
	public function __construct($user, $trackBusinessLayer, $l10n) {
724
		$this->user = $user;
725
		$this->trackBusinessLayer = $trackBusinessLayer;
726
		$this->l10n = $l10n;
727
	}
728
729
	public function getId() {
730
		return AmpacheController::ALL_TRACKS_PLAYLIST_ID;
731
	}
732
733
	public function getName() {
734
		return $this->l10n->t('All tracks');
735
	}
736
737
	public function getTrackCount() {
738
		return $this->trackBusinessLayer->count($this->user);
739
	}
740
}
741