Passed
Push — master ( 49d479...df34b5 )
by Pauli
02:10
created

AmpacheController::indexIsWithinOffsetAndLimit()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 2
c 1
b 0
f 0
nc 3
nop 3
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 12
rs 10
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(self::prepareResultForJsonApi($content));
116
		} else {
117
			return new XMLResponse(['root' => $content], ['id', 'count', 'code']);
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
		$allTracksIndex = $this->playlistBusinessLayer->count($userId);
328
		if (empty($filter) && self::indexIsWithinOffsetAndLimit($allTracksIndex, $offset, $limit)) {
329
			$playlists[] = new AmpacheController_AllTracksPlaylist($userId, $this->trackBusinessLayer, $this->l10n);
330
		}
331
332
		return $this->renderPlaylists($playlists);
333
	}
334
335
	protected function playlist($listId) {
336
		$userId = $this->ampacheUser->getUserId();
337
		if ($listId == self::ALL_TRACKS_PLAYLIST_ID) {
338
			$playlist = new AmpacheController_AllTracksPlaylist($userId, $this->trackBusinessLayer, $this->l10n);
339
		} else {
340
			$playlist = $this->playlistBusinessLayer->find($listId, $userId);
341
		}
342
		return $this->renderPlaylists([$playlist]);
343
	}
344
345
	protected function playlist_songs($listId, $limit, $offset, $auth) {
346
		if ($listId == self::ALL_TRACKS_PLAYLIST_ID) {
347
			$playlistTracks = $this->getAllTracks();
348
			$playlistTracks = \array_slice($playlistTracks, $offset, $limit);
349
		}
350
		else {
351
			$userId = $this->ampacheUser->getUserId();
352
			$playlistTracks = $this->playlistBusinessLayer->getPlaylistTracks($listId, $userId, $limit, $offset);
353
			$this->injectArtistAndAlbum($playlistTracks);
354
		}
355
		return $this->renderSongs($playlistTracks, $auth);
356
	}
357
358
	protected function tags($filter, $exact, $limit, $offset) {
359
		$genres = $this->findEntities($this->genreBusinessLayer, $filter, $exact, $limit, $offset);
360
		return $this->renderTags($genres);
361
	}
362
363
	protected function tag($tagId) {
364
		$userId = $this->ampacheUser->getUserId();
365
		$genre = $this->genreBusinessLayer->find($tagId, $userId);
366
		return $this->renderTags([$genre]);
367
	}
368
369
	protected function tag_artists($genreId, $limit, $offset, $auth) {
370
		$userId = $this->ampacheUser->getUserId();
371
		$artists = $this->artistBusinessLayer->findAllByGenre($genreId, $userId, $limit, $offset);
372
		return $this->renderArtists($artists, $auth);
373
	}
374
375
	protected function tag_albums($genreId, $limit, $offset, $auth) {
376
		$userId = $this->ampacheUser->getUserId();
377
		$albums = $this->albumBusinessLayer->findAllByGenre($genreId, $userId, $limit, $offset);
378
		return $this->renderAlbums($albums, $auth);
379
	}
380
381
	protected function tag_songs($genreId, $limit, $offset, $auth) {
382
		$userId = $this->ampacheUser->getUserId();
383
		$tracks = $this->trackBusinessLayer->findAllByGenre($genreId, $userId, $limit, $offset);
384
		$this->injectArtistAndAlbum($tracks, $artist);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $artist seems to be never defined.
Loading history...
385
		return $this->renderSongs($tracks, $auth);
386
	}
387
388
	/***************************************************************
389
	 * API methods which are not part of the Ampache specification *
390
	 ***************************************************************/
391
	protected function _play($trackId) {
392
		$userId = $this->ampacheUser->getUserId();
393
394
		try {
395
			$track = $this->trackBusinessLayer->find($trackId, $userId);
396
		} catch (BusinessLayerException $e) {
397
			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...
398
		}
399
400
		$files = $this->rootFolder->getUserFolder($userId)->getById($track->getFileId());
401
402
		if (\count($files) === 1) {
403
			return new FileResponse($files[0]);
404
		} else {
405
			return new ErrorResponse(Http::STATUS_NOT_FOUND);
406
		}
407
	}
408
409
	protected function _get_album_cover($albumId) {
410
		return $this->getCover($albumId, $this->albumBusinessLayer);
411
	}
412
413
	protected function _get_artist_cover($artistId) {
414
		return $this->getCover($artistId, $this->artistBusinessLayer);
415
	}
416
417
418
	/********************
419
	 * Helper functions *
420
	 ********************/
421
422
	private function getCover($entityId, BusinessLayer $businessLayer) {
423
		$userId = $this->ampacheUser->getUserId();
424
		$userFolder = $this->rootFolder->getUserFolder($userId);
425
		$entity = $businessLayer->find($entityId, $userId);
426
427
		try {
428
			$coverData = $this->coverHelper->getCover($entity, $userId, $userFolder);
429
			if ($coverData !== null) {
430
				return new FileResponse($coverData);
431
			}
432
		} catch (BusinessLayerException $e) {
433
			return new ErrorResponse(Http::STATUS_NOT_FOUND, 'entity not found');
434
		}
435
436
		return new ErrorResponse(Http::STATUS_NOT_FOUND, 'entity has no cover');
437
	}
438
439
	private function checkHandshakeTimestamp($timestamp, $currentTime) {
440
		$providedTime = \intval($timestamp);
441
442
		if ($providedTime === 0) {
443
			throw new AmpacheException('Invalid Login - cannot parse time', 401);
444
		}
445
		if ($providedTime < ($currentTime - self::SESSION_EXPIRY_TIME)) {
446
			throw new AmpacheException('Invalid Login - session is outdated', 401);
447
		}
448
		// Allow the timestamp to be at maximum 10 minutes in the future. The client may use its
449
		// own system clock to generate the timestamp and that may differ from the server's time.
450
		if ($providedTime > $currentTime + 600) {
451
			throw new AmpacheException('Invalid Login - timestamp is in future', 401);
452
		}
453
	}
454
455
	private function checkHandshakeAuthentication($user, $timestamp, $auth) {
456
		$hashes = $this->ampacheUserMapper->getPasswordHashes($user);
457
458
		foreach ($hashes as $hash) {
459
			$expectedHash = \hash('sha256', $timestamp . $hash);
460
461
			if ($expectedHash === $auth) {
462
				return;
463
			}
464
		}
465
466
		throw new AmpacheException('Invalid Login - passphrase does not match', 401);
467
	}
468
469
	private function startNewSession($user, $expiryDate) {
470
		// this can cause collision, but it's just a temporary token
471
		$token = \md5(\uniqid(\rand(), true));
472
473
		// create new session
474
		$session = new AmpacheSession();
475
		$session->setUserId($user);
476
		$session->setToken($token);
477
		$session->setExpiry($expiryDate);
478
479
		// save session
480
		$this->ampacheSessionMapper->insert($session);
481
482
		return $token;
483
	}
484
485
	private function findEntities(BusinessLayer $businessLayer, $filter, $exact, $limit=null, $offset=null) {
486
		$userId = $this->ampacheUser->getUserId();
487
488
		if ($filter) {
489
			$fuzzy = !((boolean) $exact);
490
			return $businessLayer->findAllByName($filter, $userId, $fuzzy, $limit, $offset);
491
		} else {
492
			return $businessLayer->findAll($userId, SortBy::Name, $limit, $offset);
493
		}
494
	}
495
496
	/**
497
	 * Getting all tracks with this helper is more efficient than with `findEntities`
498
	 * followed by `injectArtistAndAlbum`. This is because, under the hood, the albums
499
	 * and artists are fetched with a single DB query instead of fetching each separately.
500
	 * 
501
	 * The result set is ordered first by artist and then by song title.
502
	 */
503
	private function getAllTracks() {
504
		$userId = $this->ampacheUser->getUserId();
505
		$tracks = $this->library->getTracksAlbumsAndArtists($userId)['tracks'];
506
		\usort($tracks, ['\OCA\Music\Db\Track', 'compareArtistAndTitle']);
507
		foreach ($tracks as $index => &$track) {
508
			$track->setNumberOnPlaylist($index + 1);
509
		}
510
		return $tracks;
511
	}
512
513
	private function createAmpacheActionUrl($action, $filter, $auth) {
514
		$api = $this->jsonMode ? 'music.ampache.jsonApi' : 'music.ampache.xmlApi';
515
		return $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute($api))
516
				. "?action=$action&filter=$filter&auth=$auth";
517
	}
518
519
	private function createCoverUrl($entity, $auth) {
520
		if ($entity instanceof Album) {
521
			$type = 'album';
522
		} elseif ($entity instanceof Artist) {
523
			$type = 'artist';
524
		} else {
525
			throw new AmpacheException('unexpeted entity type for cover image', 500);
526
		}
527
528
		if ($entity->getCoverFileId()) {
529
			return $this->createAmpacheActionUrl("_get_{$type}_cover", $entity->getId(), $auth);
530
		} else {
531
			return '';
532
		}
533
	}
534
535
	/**
536
	 * Any non-integer values and integer value 0 are converted to null to
537
	 * indicate "no limit" or "no offset".
538
	 * @param string $value
539
	 * @return integer|null
540
	 */
541
	private static function validateLimitOrOffset($value) {
542
		if (\ctype_digit(\strval($value)) && $value !== 0) {
543
			return \intval($value);
544
		} else {
545
			return null;
546
		}
547
	}
548
549
	/**
550
	 * @param int $index
551
	 * @param int|null $offset
552
	 * @param int|null $limit
553
	 * @return boolean
554
	 */
555
	private static function indexIsWithinOffsetAndLimit($index, $offset, $limit) {
556
		$offset = \intval($offset); // missing offset is interpreted as 0-offset
557
		return ($limit === null) || ($index >= $offset && $index < $offset + $limit);
558
	}
559
560
	private function renderArtists($artists, $auth) {
561
		$userId = $this->ampacheUser->getUserId();
562
		$genreMap = Util::createIdLookupTable($this->genreBusinessLayer->findAll($userId));
563
564
		return $this->ampacheResponse([
565
			'artist' => \array_map(function($artist) use ($userId, $genreMap, $auth) {
566
				return [
567
					'id' => (string)$artist->getId(),
568
					'name' => $artist->getNameString($this->l10n),
569
					'albums' => $this->albumBusinessLayer->countByArtist($artist->getId()),
570
					'songs' => $this->trackBusinessLayer->countByArtist($artist->getId()),
571
					'art' => $this->createCoverUrl($artist, $auth),
572
					'rating' => 0,
573
					'preciserating' => 0,
574
					'tag' => \array_map(function($genreId) use ($genreMap) {
575
						return [
576
							'id' => (string)$genreId,
577
							'value' => $genreMap[$genreId]->getNameString($this->l10n),
578
							'count' => 1
579
						];
580
					}, $this->trackBusinessLayer->getGenresByArtistId($artist->getId(), $userId))
581
				];
582
			}, $artists)
583
		]);
584
	}
585
586
	private function renderAlbums($albums, $auth) {
587
		$userId = $this->ampacheUser->getUserId();
588
589
		$genreMap = Util::createIdLookupTable($this->genreBusinessLayer->findAll($userId));
590
591
		return $this->ampacheResponse([
592
			'album' => \array_map(function($album) use ($userId, $auth, $genreMap) {
593
				$artist = $this->artistBusinessLayer->find($album->getAlbumArtistId(), $userId);
594
				return [
595
					'id' => (string)$album->getId(),
596
					'name' => $album->getNameString($this->l10n),
597
					'artist' => [
598
						'id' => (string)$artist->getId(),
599
						'value' => $artist->getNameString($this->l10n)
600
					],
601
					'tracks' => $this->trackBusinessLayer->countByAlbum($album->getId()),
602
					'rating' => 0,
603
					'year' => $album->yearToAPI(),
604
					'art' => $this->createCoverUrl($album, $auth),
605
					'preciserating' => 0,
606
					'tag' => \array_map(function($genreId) use ($genreMap) {
607
						return [
608
							'id' => (string)$genreId,
609
							'value' => $genreMap[$genreId]->getNameString($this->l10n),
610
							'count' => 1
611
						];
612
					}, $album->getGenres())
613
				];
614
			}, $albums)
615
		]);
616
	}
617
618
	private function injectArtistAndAlbum(&$tracks, $commonArtist=null, $commonAlbum=null) {
619
		$userId = $this->ampacheUser->getUserId();
620
621
		foreach ($tracks as &$track) {
622
			$artist = $commonArtist ?: $this->artistBusinessLayer->find($track->getArtistId(), $userId);
623
			$track->setArtist($artist);
624
625
			if (!empty($commonAlbum)) {
626
				$track->setAlbum($commonAlbum);
627
			} else {
628
				$album = $this->albumBusinessLayer->find($track->getAlbumId(), $userId);
629
				$album->setAlbumArtist($this->artistBusinessLayer->find($album->getAlbumArtistId(), $userId));
630
				$track->setAlbum($album);
631
			}
632
		}
633
	}
634
635
	private function renderSongs($tracks, $auth) {
636
		$userId = $this->ampacheUser->getUserId();
637
		$genreMap = Util::createIdLookupTable($this->genreBusinessLayer->findAll($userId));
638
639
		return $this->ampacheResponse([
640
			'song' => \array_map(function($track) use ($auth, $genreMap) {
641
				$artist = $track->getArtist();
642
				$album = $track->getAlbum();
643
				$albumArtist = $album->getAlbumArtist();
644
645
				$result = [
646
					'id' => (string)$track->getId(),
647
					'title' => $track->getTitle(),
648
					'artist' => [
649
						'id' => (string)$artist->getId(),
650
						'value' => $artist->getNameString($this->l10n)
651
					],
652
					'albumartist' => [
653
						'id' => (string)$albumArtist->getId(),
654
						'value' => $albumArtist->getNameString($this->l10n)
655
					],
656
					'album' => [
657
						'id' => (string)$album->getId(),
658
						'value' => $album->getNameString($this->l10n)
659
					],
660
					'url' => $this->createAmpacheActionUrl('_play', $track->getId(), $auth),
661
					'time' => $track->getLength(),
662
					'year' => $track->getYear(),
663
					'track' => $track->getAdjustedTrackNumber(),
664
					'bitrate' => $track->getBitrate(),
665
					'mime' => $track->getMimetype(),
666
					'size' => $track->getSize(),
667
					'art' => $this->createCoverUrl($album, $auth),
668
					'rating' => 0,
669
					'preciserating' => 0,
670
				];
671
672
				$genreId = $track->getGenreId();
673
				if ($genreId !== null) {
674
					$result['tag'] = [[
675
						'id' => (string)$genreId,
676
						'value' => $genreMap[$genreId]->getNameString($this->l10n),
677
						'count' => 1
678
					]];
679
				}
680
				return $result;
681
			}, $tracks)
682
		]);
683
	}
684
685
	private function renderPlaylists($playlists) {
686
		return $this->ampacheResponse([
687
			'playlist' => \array_map(function($playlist) {
688
				return [
689
					'id' => (string)$playlist->getId(),
690
					'name' => $playlist->getName(),
691
					'owner' => $this->ampacheUser->getUserId(),
692
					'items' => $playlist->getTrackCount(),
693
					'type' => 'Private'
694
				];
695
			}, $playlists)
696
		]);
697
	}
698
699
	private function renderTags($genres) {
700
		return $this->ampacheResponse([
701
			'tag' => \array_map(function($genre) {
702
				return [
703
					'id' => (string)$genre->getId(),
704
					'name' => $genre->getNameString($this->l10n),
705
					'albums' => $genre->getAlbumCount(),
706
					'artists' => $genre->getArtistCount(),
707
					'songs' => $genre->getTrackCount(),
708
					'videos' => 0,
709
					'playlists' => 0,
710
					'stream' => 0
711
				];
712
			}, $genres)
713
		]);
714
	}
715
716
	/**
717
	 * Array is considered to be "indexed" if its first element has numerical key.
718
	 * Empty array is considered to be "indexed".
719
	 * @param array $array
720
	 */
721
	private static function arrayIsIndexed(array $array) {
722
		reset($array);
723
		return empty($array) || \is_int(key($array));
724
	}
725
726
	/**
727
	 * The JSON API has some asymmetries with the JSON API. This function makes the needed
728
	 * translations for the result content before it is converted into JSON. 
729
	 * @param array $content
730
	 * @return array
731
	 */
732
	private static function prepareResultForJsonApi($content) {
733
		// In all responses returning an array of library entities, the root node is anonymous.
734
		// Unwrap the outermost array if it is an associative array with a single array-type value.
735
		if (\count($content) === 1 && !self::arrayIsIndexed($content)
736
				&& \is_array(\current($content)) && self::arrayIsIndexed(\current($content))) {
737
			$content = \array_pop($content);
738
		}
739
740
		// The key 'value' has a special meaning on XML responses, as it makes the corresponding value
741
		// to be treated as text content of the parent element. In the JSON API, these are mostly
742
		// substituted with property 'name', but error responses use the property 'message', instead.
743
		if (\array_key_exists('error', $content)) {
744
			$content = Util::convertArrayKeys($content, ['value' => 'message']);
745
		} else {
746
			$content = Util::convertArrayKeys($content, ['value' => 'name']);
747
		}
748
		return $content;
749
	}
750
}
751
752
/**
753
 * Adapter class which acts like the Playlist class for the purpose of 
754
 * AmpacheController::renderPlaylists but contains all the track of the user. 
755
 */
756
class AmpacheController_AllTracksPlaylist {
757
758
	private $user;
759
	private $trackBusinessLayer;
760
	private $l10n;
761
762
	public function __construct($user, $trackBusinessLayer, $l10n) {
763
		$this->user = $user;
764
		$this->trackBusinessLayer = $trackBusinessLayer;
765
		$this->l10n = $l10n;
766
	}
767
768
	public function getId() {
769
		return AmpacheController::ALL_TRACKS_PLAYLIST_ID;
770
	}
771
772
	public function getName() {
773
		return $this->l10n->t('All tracks');
774
	}
775
776
	public function getTrackCount() {
777
		return $this->trackBusinessLayer->count($this->user);
778
	}
779
}
780