Passed
Pull Request — master (#752)
by
unknown
02:07
created

ApiController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 35
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 17
nc 1
nop 18
dl 0
loc 35
ccs 18
cts 18
cp 1
crap 1
rs 9.7
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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 - 2019
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;
0 ignored issues
show
Bug introduced by
The type OCP\AppFramework\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...
19
use \OCP\AppFramework\Http\DataDisplayResponse;
0 ignored issues
show
Bug introduced by
The type OCP\AppFramework\Http\DataDisplayResponse 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\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...
21
use \OCP\AppFramework\Http\RedirectResponse;
0 ignored issues
show
Bug introduced by
The type OCP\AppFramework\Http\RedirectResponse 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...
22
use \OCP\Files\Folder;
0 ignored issues
show
Bug introduced by
The type OCP\Files\Folder 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...
23
use \OCP\IL10N;
0 ignored issues
show
Bug introduced by
The type OCP\IL10N 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...
24
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...
25
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...
26
27
use \OCA\Music\AppFramework\Core\Logger;
28
use \OCA\Music\BusinessLayer\AlbumBusinessLayer;
29
use \OCA\Music\BusinessLayer\ArtistBusinessLayer;
30
use \OCA\Music\BusinessLayer\TrackBusinessLayer;
31
use \OCA\Music\BusinessLayer\PlaylistBusinessLayer;
32
use \OCA\Music\BusinessLayer\BookmarkBusinessLayer;
33
use \OCA\Music\Db\Album;
34
use \OCA\Music\Db\Artist;
35
use \OCA\Music\Db\Maintenance;
36
use \OCA\Music\Db\Track;
37
use \OCA\Music\Http\ErrorResponse;
38
use \OCA\Music\Http\FileResponse;
39
use \OCA\Music\Utility\CollectionHelper;
40
use \OCA\Music\Utility\CoverHelper;
41
use \OCA\Music\Utility\DetailsHelper;
42
use \OCA\Music\Utility\Scanner;
43
use OCA\Music\BusinessLayer\GenreBusinessLayer;
44
45
class ApiController extends Controller {
46
47
	/** @var IL10N */
48
	private $l10n;
49
	/** @var TrackBusinessLayer */
50
	private $trackBusinessLayer;
51
	/** @var ArtistBusinessLayer */
52
	private $artistBusinessLayer;
53
	/** @var AlbumBusinessLayer */
54
	private $albumBusinessLayer;
55
        /** @var PlaylistBusinessLayer */
56
        private $playlistBusinessLayer;
57
        /** @var BookmarkBusinessLayer */
58
        private $bookmarkBusinessLayer;
59
	/** @var GenreBusinessLayer */
60
	private $genreBusinessLayer;
61
	/** @var Scanner */
62
	private $scanner;
63
	/** @var CollectionHelper */
64
	private $collectionHelper;
65
	/** @var CoverHelper */
66
	private $coverHelper;
67
	/** @var DetailsHelper */
68
	private $detailsHelper;
69
	/** @var Maintenance */
70
	private $maintenance;
71
	/** @var string */
72
	private $userId;
73
	/** @var IURLGenerator */
74 16
	private $urlGenerator;
75
	/** @var Folder */
76
	private $userFolder;
77
	/** @var Logger */
78
	private $logger;
79
80
	public function __construct($appname,
81
								IRequest $request,
82
								IURLGenerator $urlGenerator,
83
								TrackBusinessLayer $trackbusinesslayer,
84
								ArtistBusinessLayer $artistbusinesslayer,
85
								AlbumBusinessLayer $albumbusinesslayer,
86
                PlaylistBusinessLayer $playlistbusinesslayer,
87
                BookmarkBusinessLayer $bookmarkbusinesslayer,
88
								GenreBusinessLayer $genreBusinessLayer,
89
								Scanner $scanner,
90 16
								CollectionHelper $collectionHelper,
91 16
								CoverHelper $coverHelper,
92 16
								DetailsHelper $detailsHelper,
93 16
								Maintenance $maintenance,
94 16
								$userId,
95 16
								IL10N $l10n,
96 16
								Folder $userFolder,
97 16
								Logger $logger) {
98 16
		parent::__construct($appname, $request);
99 16
		$this->l10n = $l10n;
100 16
		$this->trackBusinessLayer = $trackbusinesslayer;
101 16
		$this->artistBusinessLayer = $artistbusinesslayer;
102 16
		$this->albumBusinessLayer = $albumbusinesslayer;
103 16
                $this->playlistBusinessLayer = $playlistbusinesslayer;
104 16
                $this->bookmarkBusinessLayer = $bookmarkbusinesslayer;
105 16
		$this->genreBusinessLayer = $genreBusinessLayer;
106
		$this->scanner = $scanner;
107
		$this->collectionHelper = $collectionHelper;
108
		$this->coverHelper = $coverHelper;
109
		$this->detailsHelper = $detailsHelper;
110
		$this->maintenance = $maintenance;
111
		$this->userId = $userId;
112 5
		$this->urlGenerator = $urlGenerator;
113 5
		$this->userFolder = $userFolder;
114
		$this->logger = $logger;
115 5
	}
116
117
	/**
118
	 * Extracts the id from an unique slug (id-slug)
119
	 * @param string $slug the slug
120
	 * @return integer the id
121
	 */
122
	protected static function getIdFromSlug($slug) {
123
		$split = \explode('-', $slug, 2);
124
125
		return (int)$split[0];
126
	}
127
128
	/**
129
	 * @NoAdminRequired
130
	 * @NoCSRFRequired
131
	 */
132
	public function prepareCollection() {
133
		$hash = $this->collectionHelper->getCachedJsonHash();
134
		if ($hash === null) {
135
			// build the collection but ignore the data for now
136
			$this->collectionHelper->getJson();
137
			$hash = $this->collectionHelper->getCachedJsonHash();
138
		}
139
		return new JSONResponse(['hash' => $hash]);
140
	}
141
142
	/**
143
	 * @NoAdminRequired
144
	 * @NoCSRFRequired
145
	 */
146
	public function collection() {
147
148
		$collectionJson = $this->collectionHelper->getJson();
149
		$response = new DataDisplayResponse($collectionJson);
150
		$response->addHeader('Content-Type', 'application/json; charset=utf-8');
151
152
		// Instruct the client to cache the result in case it requested the collection with
153
		// the correct hash. The hash could be incorrect if the collection would have changed
154
		// between calls to prepareCollection() and colletion().
155
		$requestHash = $this->request->getParam('hash');
156
		$actualHash = $this->collectionHelper->getCachedJsonHash();
157
		if (!empty($actualHash) && $requestHash === $actualHash) {
158
			self::setClientCaching($response, 90); // cache for 3 months
159
		}
160
161
		return $response;
162
	}
163
164
	/**
165
	 * @NoAdminRequired
166
	 * @NoCSRFRequired
167
	 */
168
	public function folders() {
169
		$folders = $this->trackBusinessLayer->findAllFolders($this->userId, $this->userFolder);
170
		return new JSONResponse($folders);
171
	}
172
173
	/**
174
	 * @NoAdminRequired
175
	 * @NoCSRFRequired
176
	 */
177
	public function genres() {
178
		$genres = $this->genreBusinessLayer->findAllWithTrackIds($this->userId);
179
		$unscanned =  $this->trackBusinessLayer->findFilesWithoutScannedGenre($this->userId);
180 3
		return new JSONResponse([
181 3
			'genres' => \array_map(function($g) {return $g->toApi();}, $genres),
182 3
			'unscanned' => $unscanned
183
		]);
184 3
	}
185
186
	/**
187 3
	 * @NoAdminRequired
188 3
	 * @NoCSRFRequired
189
	 */
190 3
	public function artists($fulltree, $albums) {
191
		$fulltree = \filter_var($fulltree, FILTER_VALIDATE_BOOLEAN);
192
		$includeAlbums = \filter_var($albums, FILTER_VALIDATE_BOOLEAN);
193
		/** @var Artist[] $artists */
194
		$artists = $this->artistBusinessLayer->findAll($this->userId);
195
196
		$artists = \array_map(function($a) use ($fulltree, $includeAlbums) {
197 2
			return $this->artistToApi($a, $includeAlbums || $fulltree, $fulltree);
198 2
		}, $artists);
199 2
200
		return new JSONResponse($artists);
201 2
	}
202 2
203 2
	/**
204
	 * @NoAdminRequired
205
	 * @NoCSRFRequired
206
	 */
207
	public function artist($artistIdOrSlug, $fulltree) {
208
		$fulltree = \filter_var($fulltree, FILTER_VALIDATE_BOOLEAN);
209
		$artistId = $this->getIdFromSlug($artistIdOrSlug);
210
		/** @var Artist $artist */
211
		$artist = $this->artistBusinessLayer->find($artistId, $this->userId);
212
		$artist = $this->artistToApi($artist, $fulltree, $fulltree);
213 5
		return new JSONResponse($artist);
214 5
	}
215 5
216 3
	/**
217 3
	 * Return given artist in Shia API format
218
	 * @param Artist $artist
219
	 * @param boolean $includeAlbums
220 3
	 * @param boolean $includeTracks (ignored if $includeAlbums==false)
221 3
	 * @return array
222
	 */
223 5
	private function artistToApi($artist, $includeAlbums, $includeTracks) {
224
		$artistInApi = $artist->toAPI($this->urlGenerator, $this->l10n);
225
		if ($includeAlbums) {
226
			$artistId = $artist->getId();
227
			$albums = $this->albumBusinessLayer->findAllByArtist($artistId, $this->userId);
228
229
			$artistInApi['albums'] = \array_map(function($a) use ($includeTracks) {
230 2
				return $this->albumToApi($a, $includeTracks, false);
231 2
			}, $albums);
232 2
		}
233
		return $artistInApi;
234
	}
235 2
236
	/**
237
	 * @NoAdminRequired
238
	 * @NoCSRFRequired
239 2
	 */
240 2
	public function albums($artist, $fulltree) {
241
		$fulltree = \filter_var($fulltree, FILTER_VALIDATE_BOOLEAN);
242 2
		if ($artist) {
243
			$albums = $this->albumBusinessLayer->findAllByArtist($artist, $this->userId);
244
		} else {
245
			$albums = $this->albumBusinessLayer->findAll($this->userId);
246
		}
247
248
		$albums = \array_map(function($a) use ($fulltree) {
249 2
			return $this->albumToApi($a, $fulltree, $fulltree);
250 2
		}, $albums);
251 2
252 2
		return new JSONResponse($albums);
253 2
	}
254 2
255
	/**
256
	 * @NoAdminRequired
257
	 * @NoCSRFRequired
258
	 */
259
	public function album($albumIdOrSlug, $fulltree) {
260
		$fulltree = \filter_var($fulltree, FILTER_VALIDATE_BOOLEAN);
261
		$albumId = $this->getIdFromSlug($albumIdOrSlug);
262
		$album = $this->albumBusinessLayer->find($albumId, $this->userId);
263
		$album = $this->albumToApi($album, $fulltree, $fulltree);
264 7
		return new JSONResponse($album);
265 7
	}
266
267 7
	/**
268 4
	 * Return given album in the Shiva API format
269 4
	 * @param Album $album
270
	 * @param boolean $includeTracks
271 4
	 * @param boolean $includeAlbums
272 4
	 * @return array
273
	 */
274
	private function albumToApi($album, $includeTracks, $includeArtists) {
275 7
		$albumInApi = $album->toAPI($this->urlGenerator, $this->l10n);
276 2
277 2
		if ($includeTracks) {
278 2
			$albumId = $album->getId();
279 2
			$tracks = $this->trackBusinessLayer->findAllByAlbum($albumId, $this->userId);
280 2
			$albumInApi['tracks'] = \array_map(function($t) {
281
				return $t->toAPI($this->urlGenerator);
282
			}, $tracks);
283 7
		}
284
285
		if ($includeArtists) {
286
			$artistIds = $album->getArtistIds();
287
			$artists = $this->artistBusinessLayer->findById($artistIds, $this->userId);
288
			$albumInApi['artists'] = \array_map(function($a) {
289
				return $a->toAPI($this->urlGenerator, $this->l10n);
290 4
			}, $artists);
291 4
		}
292 4
293 1
		return $albumInApi;
294 3
	}
295 1
296
	/**
297 2
	 * @NoAdminRequired
298
	 * @NoCSRFRequired
299 4
	 */
300 4
	public function tracks($artist, $album, $fulltree) {
301 4
		$fulltree = \filter_var($fulltree, FILTER_VALIDATE_BOOLEAN);
302 4
		if ($artist) {
303 4
			$tracks = $this->trackBusinessLayer->findAllByArtist($artist, $this->userId);
304
		} elseif ($album) {
305 1
			$tracks = $this->trackBusinessLayer->findAllByAlbum($album, $this->userId);
306 1
		} else {
307 1
			$tracks = $this->trackBusinessLayer->findAll($this->userId);
308 4
		}
309
		foreach ($tracks as &$track) {
310
			$artistId = $track->getArtistId();
311 4
			$albumId = $track->getAlbumId();
312
			$track = $track->toAPI($this->urlGenerator);
313
			if ($fulltree) {
314
				/** @var Artist $artist */
315
				$artist = $this->artistBusinessLayer->find($artistId, $this->userId);
316
				$track['artist'] = $artist->toAPI($this->urlGenerator, $this->l10n);
317
				$album = $this->albumBusinessLayer->find($albumId, $this->userId);
318 1
				$track['album'] = $album->toAPI($this->urlGenerator, $this->l10n);
319 1
			}
320
		}
321 1
		return new JSONResponse($tracks);
322 1
	}
323
324
	/**
325
	 * @NoAdminRequired
326
	 * @NoCSRFRequired
327
	 */
328
	public function track($trackIdOrSlug) {
329 1
		$trackId = $this->getIdFromSlug($trackIdOrSlug);
330 1
		/** @var Track $track */
331 1
		$track = $this->trackBusinessLayer->find($trackId, $this->userId);
332 1
		return new JSONResponse($track->toAPI($this->urlGenerator));
333 1
	}
334 1
335
	/**
336
	 * @NoAdminRequired
337
	 * @NoCSRFRequired
338
	 */
339
	public function trackByFileId($fileId) {
340
		$track = $this->trackBusinessLayer->findByFileId($fileId, $this->userId);
341
		if ($track !== null) {
342
			$track->setAlbum($this->albumBusinessLayer->find($track->getAlbumId(), $this->userId));
343
			$track->setArtist($this->artistBusinessLayer->find($track->getArtistId(), $this->userId));
344
			return new JSONResponse($track->toCollection($this->l10n));
345
		} else {
346
			return new ErrorResponse(Http::STATUS_NOT_FOUND);
347
		}
348
	}
349
350
	/**
351
	 * @NoAdminRequired
352
	 * @NoCSRFRequired
353
	 */
354
	public function getScanState() {
355
		return new JSONResponse([
356
			'unscannedFiles' => $this->scanner->getUnscannedMusicFileIds($this->userId),
357
			'scannedCount' => $this->trackBusinessLayer->count($this->userId)
358
		]);
359
	}
360
361
	/**
362
	 * @NoAdminRequired
363
	 * @UseSession to keep the session reserved while execution in progress
364
	 */
365
	public function scan($files, $finalize) {
366
		// extract the parameters
367
		$fileIds = \array_map('intval', \explode(',', $files));
368
		$finalize = \filter_var($finalize, FILTER_VALIDATE_BOOLEAN);
369
370
		$filesScanned = $this->scanner->scanFiles($this->userId, $this->userFolder, $fileIds);
371
372
		$coversUpdated = false;
373
		if ($finalize) {
374
			$coversUpdated = $this->scanner->findCovers($this->userId);
375
			$totalCount = $this->trackBusinessLayer->count($this->userId);
376
			$this->logger->log("Scanning finished, user $this->userId has $totalCount scanned tracks in total", 'info');
377
		}
378
379
		return new JSONResponse([
380
			'filesScanned' => $filesScanned,
381
			'coversUpdated' => $coversUpdated
382
		]);
383
	}
384
385
	/**
386
	 * @NoAdminRequired
387
	 * @UseSession to keep the session reserved while execution in progress
388
	 */
389
	public function resetScanned() {
390
		$this->maintenance->resetDb($this->userId);
391
		return new JSONResponse(['success' => true]);
392
	}
393
394
	/**
395
	 * @NoAdminRequired
396
	 * @NoCSRFRequired
397
	 */
398
	public function download($fileId) {
399
		$track = $this->trackBusinessLayer->findByFileId($fileId, $this->userId);
400
		if ($track === null) {
401
			return new ErrorResponse(Http::STATUS_NOT_FOUND, 'track not found');
402
		}
403
404
		$nodes = $this->userFolder->getById($track->getFileId());
405
		if (\count($nodes) > 0) {
406
			// get the first valid node
407
			$node = $nodes[0];
408
409
			$mime = $node->getMimeType();
410
			$content = $node->getContent();
411
			return new FileResponse(['mimetype' => $mime, 'content' => $content]);
412
		}
413
414
		return new ErrorResponse(Http::STATUS_NOT_FOUND, 'file not found');
415
	}
416
417
	/**
418
	 * @NoAdminRequired
419
	 * @NoCSRFRequired
420
	 */
421
	public function filePath($fileId) {
422
		$nodes = $this->userFolder->getById($fileId);
423
		if (\count($nodes) == 0) {
424
			return new ErrorResponse(Http::STATUS_NOT_FOUND);
425
		} else {
426
			$node = $nodes[0];
427
			$path = $this->userFolder->getRelativePath($node->getPath());
428
			// URL encode each part of the file path
429
			$path = \join('/', \array_map('rawurlencode', \explode('/', $path)));
430
			return new JSONResponse(['path' => $path]);
431
		}
432
	}
433
434
	/**
435
	 * @NoAdminRequired
436
	 * @NoCSRFRequired
437
	 */
438
	public function fileInfo($fileId) {
439
		$info = $this->scanner->getFileInfo($fileId, $this->userId, $this->userFolder);
440
		if ($info) {
441
			return new JSONResponse($info);
442
		} else {
443
			return new ErrorResponse(Http::STATUS_NOT_FOUND);
444
		}
445
	}
446
447
	/**
448
	 * @NoAdminRequired
449
	 * @NoCSRFRequired
450
	 */
451
	public function fileDetails($fileId) {
452
		$details = $this->detailsHelper->getDetails($fileId, $this->userFolder);
453
		if ($details) {
454
			return new JSONResponse($details);
455
		} else {
456
			return new ErrorResponse(Http::STATUS_NOT_FOUND);
457
		}
458
	}
459
460
	/**
461
	 * @NoAdminRequired
462
	 * @NoCSRFRequired
463
	 */
464
	public function cover($albumIdOrSlug) {
465
		$albumId = $this->getIdFromSlug($albumIdOrSlug);
466
		$coverAndHash = $this->coverHelper->getCoverAndHash($albumId, $this->userId, $this->userFolder);
467
468
		if ($coverAndHash['hash'] !== null) {
469
			// Cover is in cache. Return a redirection response so that the client
470
			// will fetch the content through a cacheable route.
471
			$link = $this->urlGenerator->linkToRoute('music.api.cachedCover', ['hash' => $coverAndHash['hash']]);
472
			return new RedirectResponse($link);
473
		} else if ($coverAndHash['data'] !== null) {
474
			return new FileResponse($coverAndHash['data']);
475
		} else {
476
			return new ErrorResponse(Http::STATUS_NOT_FOUND);
477
		}
478
	}
479
480
	/**
481
	 * @NoAdminRequired
482
	 * @NoCSRFRequired
483
	 */
484
	public function cachedCover($hash) {
485
		$coverData = $this->coverHelper->getCoverFromCache($hash, $this->userId);
486
487
		if ($coverData !== null) {
488
			$response =  new FileResponse($coverData);
489
			// instruct also the client-side to cache the result, this is safe
490
			// as the resource URI contains the image hash
491
			self::setClientCaching($response);
492
			return $response;
493
		} else {
494
			return new ErrorResponse(Http::STATUS_NOT_FOUND);
495
		}
496
	}
497
498
  /**
499
   * get playqueue
500
   *
501
   * @NoAdminRequired
502
   * @NoCSRFRequired
503
   */
504
  public function getPlayQueue() {
505
    $retVal = [];
506
507
		try {
508
      $playqueueBookmark = $this->bookmarkBusinessLayer->findPlayQueueBookmark($this->userId);
509
      if ($playqueueBookmark !== null) {
510
        $retVal['current'] = $playqueueBookmark->getTrackId();
511
        $retVal['position'] = $playqueueBookmark->getPosition();
512
        $retVal['changed'] = $playqueueBookmark->getComment();
513
      }
514
515
      $playqueue = $this->playlistBusinessLayer->findPlayQueue($this->userId);
516
      if ($playqueue !== null) {
0 ignored issues
show
introduced by
The condition $playqueue !== null is always true.
Loading history...
517
        $retVal['trackIds'] = $playqueue->getTrackIdsAsArray();
518
      }
519
		} catch (BusinessLayerException $ex) {
0 ignored issues
show
Bug introduced by
The type OCA\Music\Controller\BusinessLayerException 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...
520
			return new ErrorResponse(Http::STATUS_NOT_FOUND, $ex->getMessage());
521
		}
522
523
		return new JSONResponse($retVal);
524
  }
525
526
  /**
527
   * save playqueue
528
   *
529
   * @NoAdminRequired
530
   * @NoCSRFRequired
531
   */
532
	public function savePlayQueue($position, $currentTrackId, $trackIds) {
533
		try {
534
      // save position and current track if avialable (means that all tracks in queue don't have to be passed in every time)
535
      if (($position !== null) && ($currentTrackId !== null)) {
536
        $this->bookmarkBusinessLayer->createPlayQueueBookmark($this->userId, $currentTrackId, $position);
537
      }
538
539
      // save tracks in queue
540
      if ($trackIds !== null) {
541
        $this->playlistBusinessLayer->createPlayQueueWithTracks($this->userId, $trackIds);
542
      }
543
		} catch (BusinessLayerException $ex) {
544
			return new ErrorResponse(Http::STATUS_NOT_FOUND, $ex->getMessage());
545
		}
546
547
		return new JSONResponse([ 'success' => true ]);
548
  }
549
550
	private static function setClientCaching(&$httpResponse, $days=365) {
551
		$httpResponse->cacheFor($days * 24 * 60 * 60);
552
		$httpResponse->addHeader('Pragma', 'cache');
553
	}
554
}
555