Passed
Push — master ( 5b26e7...7c69c7 )
by Pauli
01:47
created

AmpacheController::arrayIsIndexed()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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