Passed
Push — master ( f27996...767f60 )
by Pauli
01:52
created

AmpacheController::goodbye()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 2
rs 10
c 0
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\Random;
48
use \OCA\Music\Utility\Util;
49
50
class AmpacheController extends Controller {
51
	private $ampacheUserMapper;
52
	private $ampacheSessionMapper;
53
	private $albumBusinessLayer;
54
	private $artistBusinessLayer;
55
	private $genreBusinessLayer;
56
	private $playlistBusinessLayer;
57
	private $trackBusinessLayer;
58
	private $library;
59
	private $ampacheUser;
60
	private $urlGenerator;
61
	private $rootFolder;
62
	private $l10n;
63
	private $coverHelper;
64
	private $random;
65
	private $logger;
66
	private $jsonMode;
67
68
	const SESSION_EXPIRY_TIME = 6000;
69
	const ALL_TRACKS_PLAYLIST_ID = 10000000;
70
	const API_VERSION = 400001;
71
	const API_MIN_COMPATIBLE_VERSION = 350001;
72
73
	public function __construct($appname,
74
								IRequest $request,
75
								$l10n,
76
								IURLGenerator $urlGenerator,
77
								AmpacheUserMapper $ampacheUserMapper,
78
								AmpacheSessionMapper $ampacheSessionMapper,
79
								AlbumBusinessLayer $albumBusinessLayer,
80
								ArtistBusinessLayer $artistBusinessLayer,
81
								GenreBusinessLayer $genreBusinessLayer,
82
								PlaylistBusinessLayer $playlistBusinessLayer,
83
								TrackBusinessLayer $trackBusinessLayer,
84
								Library $library,
85
								AmpacheUser $ampacheUser,
86
								$rootFolder,
87
								CoverHelper $coverHelper,
88
								Random $random,
89
								Logger $logger) {
90
		parent::__construct($appname, $request);
91
92
		$this->ampacheUserMapper = $ampacheUserMapper;
93
		$this->ampacheSessionMapper = $ampacheSessionMapper;
94
		$this->albumBusinessLayer = $albumBusinessLayer;
95
		$this->artistBusinessLayer = $artistBusinessLayer;
96
		$this->genreBusinessLayer = $genreBusinessLayer;
97
		$this->playlistBusinessLayer = $playlistBusinessLayer;
98
		$this->trackBusinessLayer = $trackBusinessLayer;
99
		$this->library = $library;
100
		$this->urlGenerator = $urlGenerator;
101
		$this->l10n = $l10n;
102
103
		// used to share user info with middleware
104
		$this->ampacheUser = $ampacheUser;
105
106
		// used to deliver actual media file
107
		$this->rootFolder = $rootFolder;
108
109
		$this->coverHelper = $coverHelper;
110
		$this->random = $random;
111
		$this->logger = $logger;
112
	}
113
114
	public function setJsonMode($useJsonMode) {
115
		$this->jsonMode = $useJsonMode;
116
	}
117
118
	public function ampacheResponse($content) {
119
		if ($this->jsonMode) {
120
			return new JSONResponse(self::prepareResultForJsonApi($content));
121
		} else {
122
			return new XMLResponse(self::prepareResultForXmlApi($content), ['id', 'index', 'count', 'code']);
123
		}
124
	}
125
126
	/**
127
	 * @NoAdminRequired
128
	 * @PublicPage
129
	 * @NoCSRFRequired
130
	 */
131
	public function xmlApi($action, $user, $timestamp, $auth, $filter, $exact, $limit, $offset, $id) {
132
		// differentation between xmlApi and jsonApi is made already by the middleware
133
		return $this->dispatch($action, $user, $timestamp, $auth, $filter, $exact, $limit, $offset, $id);
134
	}
135
136
	/**
137
	 * @NoAdminRequired
138
	 * @PublicPage
139
	 * @NoCSRFRequired
140
	 */
141
	public function jsonApi($action, $user, $timestamp, $auth, $filter, $exact, $limit, $offset, $id) {
142
		// differentation between xmlApi and jsonApi is made already by the middleware
143
		return $this->dispatch($action, $user, $timestamp, $auth, $filter, $exact, $limit, $offset, $id);
144
	}
145
146
	protected function dispatch($action, $user, $timestamp, $auth, $filter, $exact, $limit, $offset, $id) {
147
		$this->logger->log("Ampache action '$action' requested", 'debug');
148
149
		$limit = self::validateLimitOrOffset($limit);
150
		$offset = self::validateLimitOrOffset($offset);
151
152
		switch ($action) {
153
			case 'handshake':
154
				return $this->handshake($user, $timestamp, $auth);
155
			case 'goodbye':
156
				return $this->goodbye($auth);
157
			case 'ping':
158
				return $this->ping($auth);
159
			case 'get_indexes':
160
				return $this->get_indexes($filter, $limit, $offset);
161
			case 'stats':
162
				return $this->stats($limit, $offset, $auth);
163
			case 'artists':
164
				return $this->artists($filter, $exact, $limit, $offset, $auth);
165
			case 'artist':
166
				return $this->artist($filter, $auth);
167
			case 'artist_albums':
168
				return $this->artist_albums($filter, $auth);
169
			case 'album_songs':
170
				return $this->album_songs($filter, $auth);
171
			case 'albums':
172
				return $this->albums($filter, $exact, $limit, $offset, $auth);
173
			case 'album':
174
				return $this->album($filter, $auth);
175
			case 'artist_songs':
176
				return $this->artist_songs($filter, $auth);
177
			case 'songs':
178
				return $this->songs($filter, $exact, $limit, $offset, $auth);
179
			case 'song':
180
				return $this->song($filter, $auth);
181
			case 'search_songs':
182
				return $this->search_songs($filter, $auth);
183
			case 'playlists':
184
				return $this->playlists($filter, $exact, $limit, $offset);
185
			case 'playlist':
186
				return $this->playlist($filter);
187
			case 'playlist_songs':
188
				return $this->playlist_songs($filter, $limit, $offset, $auth);
189
			case 'playlist_generate':
190
				return $this->playlist_generate($filter, $limit, $offset, $auth);
191
			case 'tags':
192
				return $this->tags($filter, $exact, $limit, $offset);
193
			case 'tag':
194
				return $this->tag($filter);
195
			case 'tag_artists':
196
				return $this->tag_artists($filter, $limit, $offset, $auth);
197
			case 'tag_albums':
198
				return $this->tag_albums($filter, $limit, $offset, $auth);
199
			case 'tag_songs':
200
				return $this->tag_songs($filter, $limit, $offset, $auth);
201
			case 'flag':
202
				return $this->flag();
203
			case 'download':
204
				return $this->download($id); // args 'type' and 'format' not supported
205
			case 'stream':
206
				return $this->stream($id, $offset); // args 'type', 'bitrate', 'format', and 'length' not supported
207
208
			# non Ampache API actions
209
			case '_get_album_cover':
210
				return $this->_get_album_cover($id);
211
			case '_get_artist_cover':
212
				return $this->_get_artist_cover($id);
213
		}
214
215
		$this->logger->log("Unsupported Ampache action '$action' requested", 'warn');
216
		throw new AmpacheException('Action not supported', 405);
217
	}
218
219
	/***********************
220
	 * Ampahce API methods *
221
	 ***********************/
222
223
	protected function handshake($user, $timestamp, $auth) {
224
		$currentTime = \time();
225
		$expiryDate = $currentTime + self::SESSION_EXPIRY_TIME;
226
227
		$this->checkHandshakeTimestamp($timestamp, $currentTime);
228
		$this->checkHandshakeAuthentication($user, $timestamp, $auth);
229
		$token = $this->startNewSession($user, $expiryDate);
230
231
		$currentTimeFormated = \date('c', $currentTime);
232
		$expiryDateFormated = \date('c', $expiryDate);
233
234
		return $this->ampacheResponse([
235
			'auth' => $token,
236
			'api' => self::API_VERSION,
237
			'update' => $currentTimeFormated,
238
			'add' => $currentTimeFormated,
239
			'clean' => $currentTimeFormated,
240
			'songs' => $this->trackBusinessLayer->count($user),
241
			'artists' => $this->artistBusinessLayer->count($user),
242
			'albums' => $this->albumBusinessLayer->count($user),
243
			'playlists' => $this->playlistBusinessLayer->count($user) + 1, // +1 for "All tracks"
244
			'session_expire' => $expiryDateFormated,
245
			'tags' => $this->genreBusinessLayer->count($user),
246
			'videos' => 0,
247
			'catalogs' => 0
248
		]);
249
	}
250
251
	protected function goodbye($auth) {
252
		// getting the session should not throw as the middleware has already checked that the token is valid
253
		$session = $this->ampacheSessionMapper->findByToken($auth);
254
		$this->ampacheSessionMapper->delete($session);
255
256
		return $this->ampacheResponse(['success' => "goodbye: $auth"]);
257
	}
258
259
	protected function ping($auth) {
260
		$response = [
261
			// TODO: 'server' => Music app version,
262
			'version' => self::API_VERSION,
263
			'compatible' => self::API_MIN_COMPATIBLE_VERSION
264
		];
265
266
		if (!empty($auth)) {
267
			// getting the session should not throw as the middleware has already checked that the token is valid
268
			$session = $this->ampacheSessionMapper->findByToken($auth);
269
			$response['session_expire'] = \date('c', $session->getExpiry());
270
		}
271
272
		return $this->ampacheResponse($response);
273
	}
274
275
	protected function get_indexes($filter, $limit, $offset) {
276
		// TODO: args $add, $update
277
		$type = $this->getRequiredParam('type');
278
279
		$businessLayer = $this->getBusinessLayer($type);
280
		$entities = $this->findEntities($businessLayer, $filter, false, $limit, $offset);
281
		return $this->renderEntitiesIndex($entities, $type);
282
	}
283
284
	protected function stats($limit, $offset, $auth) {
285
		$type = $this->getRequiredParam('type');
286
		$filter = $this->getRequiredParam('filter');
287
		$userId = $this->ampacheUser->getUserId();
288
289
		if (!\in_array($type, ['song', 'album', 'artist'])) {
290
			throw new AmpacheException("Unsupported type $type", 400);
291
		}
292
		$businessLayer = $this->getBusinessLayer($type);
293
294
		switch ($filter) {
295
			case 'newest':
296
				$entities = $businessLayer->findAll($userId, SortBy::Newest, $limit, $offset);
297
				break;
298
			case 'flagged':
299
				$entities = $businessLayer->findAllStarred($userId, $limit, $offset);
300
				break;
301
			case 'random':
302
				$entities = $businessLayer->findAll($userId, SortBy::None);
303
				$indices = $this->random->getIndices(\count($entities), $offset, $limit, $userId, 'ampache_stats_'.$type);
304
				$entities = Util::arrayMultiGet($entities, $indices);
305
				break;
306
			case 'highest':		//TODO
307
			case 'frequent':	//TODO
308
			case 'recent':		//TODO
309
			case 'forgotten':	//TODO
310
			default:
311
				throw new AmpacheException("Unsupported filter $filter", 400);
312
		}
313
314
		return $this->renderEntities($entities, $type, $auth);
315
	}
316
317
	protected function artists($filter, $exact, $limit, $offset, $auth) {
318
		$artists = $this->findEntities($this->artistBusinessLayer, $filter, $exact, $limit, $offset);
319
		return $this->renderArtists($artists, $auth);
320
	}
321
322
	protected function artist($artistId, $auth) {
323
		$userId = $this->ampacheUser->getUserId();
324
		$artist = $this->artistBusinessLayer->find($artistId, $userId);
325
		return $this->renderArtists([$artist], $auth);
326
	}
327
328
	protected function artist_albums($artistId, $auth) {
329
		$userId = $this->ampacheUser->getUserId();
330
		$albums = $this->albumBusinessLayer->findAllByArtist($artistId, $userId);
331
		return $this->renderAlbums($albums, $auth);
332
	}
333
334
	protected function artist_songs($artistId, $auth) {
335
		$userId = $this->ampacheUser->getUserId();
336
		$tracks = $this->trackBusinessLayer->findAllByArtist($artistId, $userId);
337
		return $this->renderSongs($tracks, $auth);
338
	}
339
340
	protected function album_songs($albumId, $auth) {
341
		$userId = $this->ampacheUser->getUserId();
342
343
		$album = $this->albumBusinessLayer->find($albumId, $userId);
344
		$tracks = $this->trackBusinessLayer->findAllByAlbum($albumId, $userId);
345
346
		foreach ($tracks as &$track) {
347
			$track->setAlbum($album);
348
		}
349
350
		return $this->renderSongs($tracks, $auth);
351
	}
352
353
	protected function song($trackId, $auth) {
354
		$userId = $this->ampacheUser->getUserId();
355
		$track = $this->trackBusinessLayer->find($trackId, $userId);
356
		$trackInArray = [$track];
357
		return $this->renderSongs($trackInArray, $auth);
358
	}
359
360
	protected function songs($filter, $exact, $limit, $offset, $auth) {
361
362
		// optimized handling for fetching the whole library
363
		// note: the ordering of the songs differs between these two cases
364
		if (empty($filter) && !$limit && !$offset) {
365
			$tracks = $this->getAllTracks();
366
		}
367
		// general case
368
		else {
369
			$tracks = $this->findEntities($this->trackBusinessLayer, $filter, $exact, $limit, $offset);
370
		}
371
372
		return $this->renderSongs($tracks, $auth);
373
	}
374
375
	protected function search_songs($filter, $auth) {
376
		$userId = $this->ampacheUser->getUserId();
377
		$tracks = $this->trackBusinessLayer->findAllByNameRecursive($filter, $userId);
378
		return $this->renderSongs($tracks, $auth);
379
	}
380
381
	protected function albums($filter, $exact, $limit, $offset, $auth) {
382
		$albums = $this->findEntities($this->albumBusinessLayer, $filter, $exact, $limit, $offset);
383
		return $this->renderAlbums($albums, $auth);
384
	}
385
386
	protected function album($albumId, $auth) {
387
		$userId = $this->ampacheUser->getUserId();
388
		$album = $this->albumBusinessLayer->find($albumId, $userId);
389
		return $this->renderAlbums([$album], $auth);
390
	}
391
392
	protected function playlists($filter, $exact, $limit, $offset) {
393
		$userId = $this->ampacheUser->getUserId();
394
		$playlists = $this->findEntities($this->playlistBusinessLayer, $filter, $exact, $limit, $offset);
395
396
		// append "All tracks" if not searching by name, and it is not off-limit
397
		$allTracksIndex = $this->playlistBusinessLayer->count($userId);
398
		if (empty($filter) && self::indexIsWithinOffsetAndLimit($allTracksIndex, $offset, $limit)) {
399
			$playlists[] = new AmpacheController_AllTracksPlaylist($userId, $this->trackBusinessLayer, $this->l10n);
400
		}
401
402
		return $this->renderPlaylists($playlists);
403
	}
404
405
	protected function playlist($listId) {
406
		$userId = $this->ampacheUser->getUserId();
407
		if ($listId == self::ALL_TRACKS_PLAYLIST_ID) {
408
			$playlist = new AmpacheController_AllTracksPlaylist($userId, $this->trackBusinessLayer, $this->l10n);
409
		} else {
410
			$playlist = $this->playlistBusinessLayer->find($listId, $userId);
411
		}
412
		return $this->renderPlaylists([$playlist]);
413
	}
414
415
	protected function playlist_songs($listId, $limit, $offset, $auth) {
416
		if ($listId == self::ALL_TRACKS_PLAYLIST_ID) {
417
			$playlistTracks = $this->getAllTracks();
418
			$playlistTracks = \array_slice($playlistTracks, $offset, $limit);
419
		}
420
		else {
421
			$userId = $this->ampacheUser->getUserId();
422
			$playlistTracks = $this->playlistBusinessLayer->getPlaylistTracks($listId, $userId, $limit, $offset);
423
		}
424
		return $this->renderSongs($playlistTracks, $auth);
425
	}
426
427
	protected function playlist_generate($filter, $limit, $offset, $auth) {
428
		$mode = $this->request->getParam('mode', 'random');
429
		$album = $this->request->getParam('album');
430
		$artist = $this->request->getParam('artist');
431
		$flag = $this->request->getParam('flag');
432
		$format = $this->request->getParam('format', 'song');
433
434
		$tracks = $this->findEntities($this->trackBusinessLayer, $filter, false); // $limit and $offset are applied later
435
436
		// filter the found tracks according to the additional requirements
437
		if ($album !== null) {
438
			$tracks = \array_filter($tracks, function($track) use ($album) {
439
				return ($track->getAlbumId() == $album);
440
			});
441
		}
442
		if ($artist !== null) {
443
			$tracks = \array_filter($tracks, function($track) use ($artist) {
444
				return ($track->getArtistId() == $artist);
445
			});
446
		}
447
		if ($flag == 1) {
448
			$tracks = \array_filter($tracks, function($track) {
449
				return ($track->getStarred() !== null);
450
			});
451
		}
452
		// After filtering, there may be "holes" between the array indices. Reindex the array.
453
		$tracks = \array_values($tracks);
454
455
		if ($mode == 'random') {
456
			$userId = $this->ampacheUser->getUserId();
457
			$indices = $this->random->getIndices(\count($tracks), $offset, $limit, $userId, 'ampache_playlist_generate');
458
			$tracks = Util::arrayMultiGet($tracks, $indices);
459
		} else { // 'recent', 'forgotten', 'unplayed'
460
			throw new AmpacheException("Mode '$mode' is not supported", 400);
461
		}
462
463
		switch ($format) {
464
			case 'song':
465
				return $this->renderSongs($tracks, $auth);
466
			case 'index':
467
				return $this->renderSongsIndex($tracks);
468
			case 'id':
469
				return $this->renderEntityIds($tracks);
470
			default:
471
				throw new AmpacheException("Format '$format' is not supported", 400);
472
		}
473
	}
474
475
	protected function tags($filter, $exact, $limit, $offset) {
476
		$genres = $this->findEntities($this->genreBusinessLayer, $filter, $exact, $limit, $offset);
477
		return $this->renderTags($genres);
478
	}
479
480
	protected function tag($tagId) {
481
		$userId = $this->ampacheUser->getUserId();
482
		$genre = $this->genreBusinessLayer->find($tagId, $userId);
483
		return $this->renderTags([$genre]);
484
	}
485
486
	protected function tag_artists($genreId, $limit, $offset, $auth) {
487
		$userId = $this->ampacheUser->getUserId();
488
		$artists = $this->artistBusinessLayer->findAllByGenre($genreId, $userId, $limit, $offset);
489
		return $this->renderArtists($artists, $auth);
490
	}
491
492
	protected function tag_albums($genreId, $limit, $offset, $auth) {
493
		$userId = $this->ampacheUser->getUserId();
494
		$albums = $this->albumBusinessLayer->findAllByGenre($genreId, $userId, $limit, $offset);
495
		return $this->renderAlbums($albums, $auth);
496
	}
497
498
	protected function tag_songs($genreId, $limit, $offset, $auth) {
499
		$userId = $this->ampacheUser->getUserId();
500
		$tracks = $this->trackBusinessLayer->findAllByGenre($genreId, $userId, $limit, $offset);
501
		return $this->renderSongs($tracks, $auth);
502
	}
503
504
	protected function flag() {
505
		$type = $this->getRequiredParam('type');
506
		$id = $this->getRequiredParam('id');
507
		$flag = $this->getRequiredParam('flag');
508
		$flag = \filter_var($flag, FILTER_VALIDATE_BOOLEAN);
509
510
		if (!\in_array($type, ['song', 'album', 'artist'])) {
511
			throw new AmpacheException("Unsupported type $type", 400);
512
		}
513
514
		$userId = $this->ampacheUser->getUserId();
515
		$businessLayer = $this->getBusinessLayer($type);
516
		if ($flag) {
517
			$modifiedCount = $businessLayer->setStarred([$id], $userId);
518
			$message = "flag ADDED to $id";
519
		} else {
520
			$modifiedCount = $businessLayer->unsetStarred([$id], $userId);
521
			$message = "flag REMOVED from $id";
522
		}
523
524
		if ($modifiedCount > 0) {
525
			return $this->ampacheResponse(['success' => $message]);
526
		} else {
527
			throw new AmpacheException("The $type $id was not found", 400);
528
		}
529
	}
530
531
	protected function download($trackId) {
532
		$userId = $this->ampacheUser->getUserId();
533
534
		try {
535
			$track = $this->trackBusinessLayer->find($trackId, $userId);
536
		} catch (BusinessLayerException $e) {
537
			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...
538
		}
539
540
		$files = $this->rootFolder->getUserFolder($userId)->getById($track->getFileId());
541
542
		if (\count($files) === 1) {
543
			return new FileResponse($files[0]);
544
		} else {
545
			return new ErrorResponse(Http::STATUS_NOT_FOUND);
546
		}
547
	}
548
549
	protected function stream($trackId, $offset) {
550
		// This is just a dummy implementation. We don't support transcoding or streaming
551
		// from a time offset.
552
		// All the other unsupported arguments are just ignored, but a request with an offset
553
		// is responded with an error. This is becuase the client would probably work in an
554
		// unexpected way if it thinks it's streaming from offset but actually it is streaming
555
		// from the beginning of the file. Returning an error gives the client a chance to fallback
556
		// to other methods of seeking.
557
		if ($offset !== null) {
558
			throw new AmpacheException('Streaming with time offset is not supported', 400);
559
		}
560
561
		return $this->download($trackId);
562
	}
563
564
	/***************************************************************
565
	 * API methods which are not part of the Ampache specification *
566
	 ***************************************************************/
567
	protected function _get_album_cover($albumId) {
568
		return $this->getCover($albumId, $this->albumBusinessLayer);
569
	}
570
571
	protected function _get_artist_cover($artistId) {
572
		return $this->getCover($artistId, $this->artistBusinessLayer);
573
	}
574
575
576
	/********************
577
	 * Helper functions *
578
	 ********************/
579
580
	private function getBusinessLayer($type) {
581
		switch ($type) {
582
			case 'song':		return $this->trackBusinessLayer;
583
			case 'album':		return $this->albumBusinessLayer;
584
			case 'artist':		return $this->artistBusinessLayer;
585
			case 'playlist':	return $this->playlistBusinessLayer;
586
			case 'tag':			return $this->genreBusinessLayer;
587
			default:			throw new AmpacheException("Unsupported type $type", 400);
588
		}
589
	}
590
591
	private function renderEntities($entities, $type, $auth) {
592
		switch ($type) {
593
			case 'song':		return $this->renderSongs($entities, $auth);
594
			case 'album':		return $this->renderAlbums($entities, $auth);
595
			case 'artist':		return $this->renderArtists($entities, $auth);
596
			case 'playlist':	return $this->renderPlaylists($entities);
597
			case 'tag':			return $this->renderTags($entities);
598
			default:			throw new AmpacheException("Unsupported type $type", 400);
599
		}
600
	}
601
602
	private function renderEntitiesIndex($entities, $type) {
603
		switch ($type) {
604
			case 'song':		return $this->renderSongsIndex($entities);
605
			case 'album':		return $this->renderAlbumsIndex($entities);
606
			case 'artist':		return $this->renderArtistsIndex($entities);
607
			case 'playlist':	return $this->renderPlaylistsIndex($entities);
608
			default:			throw new AmpacheException("Unsupported type $type", 400);
609
		}
610
	}
611
612
	private function getCover($entityId, BusinessLayer $businessLayer) {
613
		$userId = $this->ampacheUser->getUserId();
614
		$userFolder = $this->rootFolder->getUserFolder($userId);
615
		$entity = $businessLayer->find($entityId, $userId);
616
617
		try {
618
			$coverData = $this->coverHelper->getCover($entity, $userId, $userFolder);
619
			if ($coverData !== null) {
620
				return new FileResponse($coverData);
621
			}
622
		} catch (BusinessLayerException $e) {
623
			return new ErrorResponse(Http::STATUS_NOT_FOUND, 'entity not found');
624
		}
625
626
		return new ErrorResponse(Http::STATUS_NOT_FOUND, 'entity has no cover');
627
	}
628
629
	private function checkHandshakeTimestamp($timestamp, $currentTime) {
630
		$providedTime = \intval($timestamp);
631
632
		if ($providedTime === 0) {
633
			throw new AmpacheException('Invalid Login - cannot parse time', 401);
634
		}
635
		if ($providedTime < ($currentTime - self::SESSION_EXPIRY_TIME)) {
636
			throw new AmpacheException('Invalid Login - session is outdated', 401);
637
		}
638
		// Allow the timestamp to be at maximum 10 minutes in the future. The client may use its
639
		// own system clock to generate the timestamp and that may differ from the server's time.
640
		if ($providedTime > $currentTime + 600) {
641
			throw new AmpacheException('Invalid Login - timestamp is in future', 401);
642
		}
643
	}
644
645
	private function checkHandshakeAuthentication($user, $timestamp, $auth) {
646
		$hashes = $this->ampacheUserMapper->getPasswordHashes($user);
647
648
		foreach ($hashes as $hash) {
649
			$expectedHash = \hash('sha256', $timestamp . $hash);
650
651
			if ($expectedHash === $auth) {
652
				return;
653
			}
654
		}
655
656
		throw new AmpacheException('Invalid Login - passphrase does not match', 401);
657
	}
658
659
	private function startNewSession($user, $expiryDate) {
660
		// this can cause collision, but it's just a temporary token
661
		$token = \md5(\uniqid(\rand(), true));
662
663
		// create new session
664
		$session = new AmpacheSession();
665
		$session->setUserId($user);
666
		$session->setToken($token);
667
		$session->setExpiry($expiryDate);
668
669
		// save session
670
		$this->ampacheSessionMapper->insert($session);
671
672
		return $token;
673
	}
674
675
	private function findEntities(BusinessLayer $businessLayer, $filter, $exact, $limit=null, $offset=null) {
676
		$userId = $this->ampacheUser->getUserId();
677
678
		if ($filter) {
679
			$fuzzy = !((boolean) $exact);
680
			return $businessLayer->findAllByName($filter, $userId, $fuzzy, $limit, $offset);
681
		} else {
682
			return $businessLayer->findAll($userId, SortBy::Name, $limit, $offset);
683
		}
684
	}
685
686
	/**
687
	 * Getting all tracks with this helper is more efficient than with `findEntities`
688
	 * followed by a call to `albumBusinessLayer->find(...)` on each track.
689
	 * This is because, under the hood, the albums are fetched with a single DB query
690
	 * instead of fetching each separately.
691
	 *
692
	 * The result set is ordered first by artist and then by song title.
693
	 */
694
	private function getAllTracks() {
695
		$userId = $this->ampacheUser->getUserId();
696
		$tracks = $this->library->getTracksAlbumsAndArtists($userId)['tracks'];
697
		\usort($tracks, ['\OCA\Music\Db\Track', 'compareArtistAndTitle']);
698
		foreach ($tracks as $index => &$track) {
699
			$track->setNumberOnPlaylist($index + 1);
700
		}
701
		return $tracks;
702
	}
703
704
	private function createAmpacheActionUrl($action, $id, $auth) {
705
		$api = $this->jsonMode ? 'music.ampache.jsonApi' : 'music.ampache.xmlApi';
706
		return $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute($api))
707
				. "?action=$action&id=$id&auth=$auth";
708
	}
709
710
	private function createCoverUrl($entity, $auth) {
711
		if ($entity instanceof Album) {
712
			$type = 'album';
713
		} elseif ($entity instanceof Artist) {
714
			$type = 'artist';
715
		} else {
716
			throw new AmpacheException('unexpeted entity type for cover image', 500);
717
		}
718
719
		if ($entity->getCoverFileId()) {
720
			return $this->createAmpacheActionUrl("_get_{$type}_cover", $entity->getId(), $auth);
721
		} else {
722
			return '';
723
		}
724
	}
725
726
	/**
727
	 * Any non-integer values and integer value 0 are converted to null to
728
	 * indicate "no limit" or "no offset".
729
	 * @param string $value
730
	 * @return integer|null
731
	 */
732
	private static function validateLimitOrOffset($value) {
733
		if (\ctype_digit(\strval($value)) && $value !== 0) {
734
			return \intval($value);
735
		} else {
736
			return null;
737
		}
738
	}
739
740
	/**
741
	 * @param int $index
742
	 * @param int|null $offset
743
	 * @param int|null $limit
744
	 * @return boolean
745
	 */
746
	private static function indexIsWithinOffsetAndLimit($index, $offset, $limit) {
747
		$offset = \intval($offset); // missing offset is interpreted as 0-offset
748
		return ($limit === null) || ($index >= $offset && $index < $offset + $limit);
749
	}
750
751
	private function renderArtists($artists, $auth) {
752
		$userId = $this->ampacheUser->getUserId();
753
		$genreMap = Util::createIdLookupTable($this->genreBusinessLayer->findAll($userId));
754
755
		return $this->ampacheResponse([
756
			'artist' => \array_map(function($artist) use ($userId, $genreMap, $auth) {
757
				return [
758
					'id' => (string)$artist->getId(),
759
					'name' => $artist->getNameString($this->l10n),
760
					'albums' => $this->albumBusinessLayer->countByArtist($artist->getId()),
761
					'songs' => $this->trackBusinessLayer->countByArtist($artist->getId()),
762
					'art' => $this->createCoverUrl($artist, $auth),
763
					'rating' => 0,
764
					'preciserating' => 0,
765
					'tag' => \array_map(function($genreId) use ($genreMap) {
766
						return [
767
							'id' => (string)$genreId,
768
							'value' => $genreMap[$genreId]->getNameString($this->l10n),
769
							'count' => 1
770
						];
771
					}, $this->trackBusinessLayer->getGenresByArtistId($artist->getId(), $userId))
772
				];
773
			}, $artists)
774
		]);
775
	}
776
777
	private function renderAlbums($albums, $auth) {
778
		$userId = $this->ampacheUser->getUserId();
779
780
		$genreMap = Util::createIdLookupTable($this->genreBusinessLayer->findAll($userId));
781
782
		return $this->ampacheResponse([
783
			'album' => \array_map(function($album) use ($auth, $genreMap) {
784
				return [
785
					'id' => (string)$album->getId(),
786
					'name' => $album->getNameString($this->l10n),
787
					'artist' => [
788
						'id' => (string)$album->getAlbumArtistId(),
789
						'value' => $album->getAlbumArtistNameString($this->l10n)
790
					],
791
					'tracks' => $this->trackBusinessLayer->countByAlbum($album->getId()),
792
					'rating' => 0,
793
					'year' => $album->yearToAPI(),
794
					'art' => $this->createCoverUrl($album, $auth),
795
					'preciserating' => 0,
796
					'tag' => \array_map(function($genreId) use ($genreMap) {
797
						return [
798
							'id' => (string)$genreId,
799
							'value' => $genreMap[$genreId]->getNameString($this->l10n),
800
							'count' => 1
801
						];
802
					}, $album->getGenres())
803
				];
804
			}, $albums)
805
		]);
806
	}
807
808
	private function renderSongs($tracks, $auth) {
809
		return $this->ampacheResponse([
810
			'song' => \array_map(function($track) use ($auth) {
811
				$album = $track->getAlbum()
812
						?: $this->albumBusinessLayer->find($track->getAlbumId(), $this->ampacheUser->getUserId());
813
814
				$result = [
815
					'id' => (string)$track->getId(),
816
					'title' => $track->getTitle(),
817
					'name' => $track->getTitle(),
818
					'artist' => [
819
						'id' => (string)$track->getArtistId(),
820
						'value' => $track->getArtistNameString($this->l10n)
821
					],
822
					'albumartist' => [
823
						'id' => (string)$album->getAlbumArtistId(),
824
						'value' => $album->getAlbumArtistNameString($this->l10n)
825
					],
826
					'album' => [
827
						'id' => (string)$album->getId(),
828
						'value' => $album->getNameString($this->l10n)
829
					],
830
					'url' => $this->createAmpacheActionUrl('download', $track->getId(), $auth),
831
					'time' => $track->getLength(),
832
					'year' => $track->getYear(),
833
					'track' => $track->getAdjustedTrackNumber(),
834
					'bitrate' => $track->getBitrate(),
835
					'mime' => $track->getMimetype(),
836
					'size' => $track->getSize(),
837
					'art' => $this->createCoverUrl($album, $auth),
838
					'rating' => 0,
839
					'preciserating' => 0,
840
				];
841
842
				$genreId = $track->getGenreId();
843
				if ($genreId !== null) {
844
					$result['tag'] = [[
845
						'id' => (string)$genreId,
846
						'value' => $track->getGenreNameString($this->l10n),
847
						'count' => 1
848
					]];
849
				}
850
				return $result;
851
			}, $tracks)
852
		]);
853
	}
854
855
	private function renderPlaylists($playlists) {
856
		return $this->ampacheResponse([
857
			'playlist' => \array_map(function($playlist) {
858
				return [
859
					'id' => (string)$playlist->getId(),
860
					'name' => $playlist->getName(),
861
					'owner' => $this->ampacheUser->getUserId(),
862
					'items' => $playlist->getTrackCount(),
863
					'type' => 'Private'
864
				];
865
			}, $playlists)
866
		]);
867
	}
868
869
	private function renderTags($genres) {
870
		return $this->ampacheResponse([
871
			'tag' => \array_map(function($genre) {
872
				return [
873
					'id' => (string)$genre->getId(),
874
					'name' => $genre->getNameString($this->l10n),
875
					'albums' => $genre->getAlbumCount(),
876
					'artists' => $genre->getArtistCount(),
877
					'songs' => $genre->getTrackCount(),
878
					'videos' => 0,
879
					'playlists' => 0,
880
					'stream' => 0
881
				];
882
			}, $genres)
883
		]);
884
	}
885
886
	private function renderSongsIndex($tracks) {
887
		return $this->ampacheResponse([
888
			'song' => \array_map(function($track) {
889
				return [
890
					'id' => (string)$track->getId(),
891
					'title' => $track->getTitle(),
892
					'name' => $track->getTitle(),
893
					'artist' => [
894
						'id' => (string)$track->getArtistId(),
895
						'value' => $track->getArtistNameString($this->l10n)
896
					],
897
					'album' => [
898
						'id' => (string)$track->getAlbumId(),
899
						'value' => $track->getAlbumNameString($this->l10n)
900
					]
901
				];
902
			}, $tracks)
903
		]);
904
	}
905
906
	private function renderAlbumsIndex($albums) {
907
		return $this->ampacheResponse([
908
			'album' => \array_map(function($album) {
909
				return [
910
					'id' => (string)$album->getId(),
911
					'name' => $album->getNameString($this->l10n),
912
					'artist' => [
913
						'id' => (string)$album->getAlbumArtistId(),
914
						'value' => $album->getAlbumArtistNameString($this->l10n)
915
					]
916
				];
917
			}, $albums)
918
		]);
919
	}
920
921
	private function renderArtistsIndex($artists) {
922
		return $this->ampacheResponse([
923
			'artist' => \array_map(function($artist) {
924
				$userId = $this->ampacheUser->getUserId();
925
				$albums = $this->albumBusinessLayer->findAllByArtist($artist->getId(), $userId);
926
927
				return [
928
					'id' => (string)$artist->getId(),
929
					'name' => $artist->getNameString($this->l10n),
930
					'album' => \array_map(function($album) {
931
						return [
932
							'id' => (string)$album->getId(),
933
							'value' => $album->getNameString($this->l10n)
934
						];
935
					}, $albums)
936
				];
937
			}, $artists)
938
		]);
939
	}
940
941
	private function renderPlaylistsIndex($playlists) {
942
		return $this->ampacheResponse([
943
			'playlist' => \array_map(function($playlist) {
944
				return [
945
					'id' => (string)$playlist->getId(),
946
					'name' => $playlist->getName(),
947
					'playlisttrack' => $playlist->getTrackIdsAsArray()
948
				];
949
			}, $playlists)
950
		]);
951
	}
952
953
	private function renderEntityIds($entities) {
954
		return $this->ampacheResponse(['id' => Util::extractIds($entities)]);
955
	}
956
957
	/**
958
	 * Array is considered to be "indexed" if its first element has numerical key.
959
	 * Empty array is considered to be "indexed".
960
	 * @param array $array
961
	 */
962
	private static function arrayIsIndexed(array $array) {
963
		reset($array);
964
		return empty($array) || \is_int(key($array));
965
	}
966
967
	/**
968
	 * The JSON API has some asymmetries with the XML API. This function makes the needed
969
	 * translations for the result content before it is converted into JSON. 
970
	 * @param array $content
971
	 * @return array
972
	 */
973
	private static function prepareResultForJsonApi($content) {
974
		// In all responses returning an array of library entities, the root node is anonymous.
975
		// Unwrap the outermost array if it is an associative array with a single array-type value.
976
		if (\count($content) === 1 && !self::arrayIsIndexed($content)
977
				&& \is_array(\current($content)) && self::arrayIsIndexed(\current($content))) {
978
			$content = \array_pop($content);
979
		}
980
981
		// The key 'value' has a special meaning on XML responses, as it makes the corresponding value
982
		// to be treated as text content of the parent element. In the JSON API, these are mostly
983
		// substituted with property 'name', but error responses use the property 'message', instead.
984
		if (\array_key_exists('error', $content)) {
985
			$content = Util::convertArrayKeys($content, ['value' => 'message']);
986
		} else {
987
			$content = Util::convertArrayKeys($content, ['value' => 'name']);
988
		}
989
		return $content;
990
	}
991
992
	/**
993
	 * The XML API has some asymmetries with the JSON API. This function makes the needed
994
	 * translations for the result content before it is converted into XML. 
995
	 * @param array $content
996
	 * @return array
997
	 */
998
	private static function prepareResultForXmlApi($content) {
999
		\reset($content);
1000
		$firstKey = \key($content);
1001
1002
		// all 'entity list' kind of responses shall have the (deprecated) total_count element
1003
		if ($firstKey == 'song' || $firstKey == 'album' || $firstKey == 'artist'
1004
				|| $firstKey == 'playlist' || $firstKey == 'tag') {
1005
			$content = ['total_count' => \count($content[$firstKey])] + $content;
1006
		}
1007
1008
		// for some bizarre reason, the 'id' arrays have 'index' attributes in the XML format
1009
		if ($firstKey == 'id') {
1010
			$content['id'] = \array_map(function($id, $index) {
1011
				return ['index' => $index, 'value' => $id];
1012
			}, $content['id'], \array_keys($content['id']));
1013
		}
1014
1015
		return ['root' => $content];
1016
	}
1017
1018
	private function getRequiredParam($paramName) {
1019
		$param = $this->request->getParam($paramName);
1020
1021
		if ($param === null) {
1022
			throw new AmpacheException("Required parameter '$paramName' missing", 400);
1023
		}
1024
1025
		return $param;
1026
	}
1027
}
1028
1029
/**
1030
 * Adapter class which acts like the Playlist class for the purpose of 
1031
 * AmpacheController::renderPlaylists but contains all the track of the user. 
1032
 */
1033
class AmpacheController_AllTracksPlaylist {
1034
1035
	private $user;
1036
	private $trackBusinessLayer;
1037
	private $l10n;
1038
1039
	public function __construct($user, $trackBusinessLayer, $l10n) {
1040
		$this->user = $user;
1041
		$this->trackBusinessLayer = $trackBusinessLayer;
1042
		$this->l10n = $l10n;
1043
	}
1044
1045
	public function getId() {
1046
		return AmpacheController::ALL_TRACKS_PLAYLIST_ID;
1047
	}
1048
1049
	public function getName() {
1050
		return $this->l10n->t('All tracks');
1051
	}
1052
1053
	public function getTrackCount() {
1054
		return $this->trackBusinessLayer->count($this->user);
1055
	}
1056
}
1057