AmpacheController::albums()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 7
dl 0
loc 12
rs 10
1
<?php declare(strict_types=1);
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 - 2026
13
 */
14
15
namespace OCA\Music\Controller;
16
17
use OCA\Music\AppFramework\BusinessLayer\BusinessLayer;
18
use OCA\Music\AppFramework\BusinessLayer\BusinessLayerException;
19
use OCA\Music\AppFramework\Core\Logger;
20
use OCA\Music\AppFramework\Utility\RequestParameterExtractor;
21
use OCA\Music\AppFramework\Utility\RequestParameterExtractorException;
22
23
use OCA\Music\BusinessLayer\AlbumBusinessLayer;
24
use OCA\Music\BusinessLayer\ArtistBusinessLayer;
25
use OCA\Music\BusinessLayer\BookmarkBusinessLayer;
26
use OCA\Music\BusinessLayer\GenreBusinessLayer;
27
use OCA\Music\BusinessLayer\Library;
28
use OCA\Music\BusinessLayer\PlaylistBusinessLayer;
29
use OCA\Music\BusinessLayer\PodcastChannelBusinessLayer;
30
use OCA\Music\BusinessLayer\PodcastEpisodeBusinessLayer;
31
use OCA\Music\BusinessLayer\RadioStationBusinessLayer;
32
use OCA\Music\BusinessLayer\TrackBusinessLayer;
33
34
use OCA\Music\Db\Album;
35
use OCA\Music\Db\AmpacheSession;
36
use OCA\Music\Db\Artist;
37
use OCA\Music\Db\BaseMapper;
38
use OCA\Music\Db\Bookmark;
39
use OCA\Music\Db\Entity;
40
use OCA\Music\Db\Genre;
41
use OCA\Music\Db\RadioStation;
42
use OCA\Music\Db\MatchMode;
43
use OCA\Music\Db\Playlist;
44
use OCA\Music\Db\PodcastChannel;
45
use OCA\Music\Db\PodcastEpisode;
46
use OCA\Music\Db\SortBy;
47
use OCA\Music\Db\Track;
48
49
use OCA\Music\Http\Attribute\AmpacheAPI;
50
use OCA\Music\Http\ErrorResponse;
51
use OCA\Music\Http\FileResponse;
52
use OCA\Music\Http\FileStreamResponse;
53
use OCA\Music\Http\RelayStreamResponse;
54
use OCA\Music\Http\XmlResponse;
55
56
use OCA\Music\Middleware\AmpacheException;
57
58
use OCA\Music\Service\AmpacheImageService;
59
use OCA\Music\Service\AmpachePreferences;
60
use OCA\Music\Service\CoverService;
61
use OCA\Music\Service\DetailsService;
62
use OCA\Music\Service\FileSystemService;
63
use OCA\Music\Service\LastfmService;
64
use OCA\Music\Service\LibrarySettings;
65
use OCA\Music\Service\PodcastService;
66
use OCA\Music\Service\Scrobbler;
67
68
use OCA\Music\Utility\AppInfo;
69
use OCA\Music\Utility\ArrayUtil;
70
use OCA\Music\Utility\Random;
71
use OCA\Music\Utility\StringUtil;
72
use OCA\Music\Utility\Util;
73
74
use OCP\AppFramework\ApiController;
75
use OCP\AppFramework\Http;
76
use OCP\AppFramework\Http\Attribute\CORS;
77
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
78
use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
79
use OCP\AppFramework\Http\Attribute\PublicPage;
80
use OCP\AppFramework\Http\JSONResponse;
81
use OCP\AppFramework\Http\RedirectResponse;
82
use OCP\AppFramework\Http\Response;
83
use OCP\IConfig;
84
use OCP\IL10N;
85
use OCP\IRequest;
86
use OCP\IURLGenerator;
87
use OCP\IUserManager;
88
89
class AmpacheController extends ApiController {
90
	private IConfig $config;
91
	private IL10N $l10n;
92
	private IURLGenerator $urlGenerator;
93
	private IUserManager $userManager;
94
	private AlbumBusinessLayer $albumBusinessLayer;
95
	private ArtistBusinessLayer $artistBusinessLayer;
96
	private BookmarkBusinessLayer $bookmarkBusinessLayer;
97
	private GenreBusinessLayer $genreBusinessLayer;
98
	private PlaylistBusinessLayer $playlistBusinessLayer;
99
	private PodcastChannelBusinessLayer $podcastChannelBusinessLayer;
100
	private PodcastEpisodeBusinessLayer $podcastEpisodeBusinessLayer;
101
	private RadioStationBusinessLayer $radioStationBusinessLayer;
102
	private TrackBusinessLayer $trackBusinessLayer;
103
	private Library $library;
104
	private PodcastService $podcastService;
105
	private AmpacheImageService $imageService;
106
	private CoverService $coverService;
107
	private DetailsService $detailsService;
108
	private FileSystemService $fileSystemService;
109
	private LastfmService $lastfmService;
110
	private LibrarySettings $librarySettings;
111
	private Random $random;
112
	private Logger $logger;
113
	private Scrobbler $scrobbler;
114
115
	private bool $jsonMode;
116
	private ?AmpacheSession $session;
117
	private array $namePrefixes;
118
119
	public const ALL_TRACKS_PLAYLIST_ID = -1;
120
	public const API4_VERSION = '4.4.0';
121
	public const API5_VERSION = '5.6.0';
122
	public const API6_VERSION = '6.7.1';
123
	public const API_MIN_COMPATIBLE_VERSION = '350001';
124
125
	public function __construct(
126
			string $appName,
127
			IRequest $request,
128
			IConfig $config,
129
			IL10N $l10n,
130
			IURLGenerator $urlGenerator,
131
			IUserManager $userManager,
132
			AlbumBusinessLayer $albumBusinessLayer,
133
			ArtistBusinessLayer $artistBusinessLayer,
134
			BookmarkBusinessLayer $bookmarkBusinessLayer,
135
			GenreBusinessLayer $genreBusinessLayer,
136
			PlaylistBusinessLayer $playlistBusinessLayer,
137
			PodcastChannelBusinessLayer $podcastChannelBusinessLayer,
138
			PodcastEpisodeBusinessLayer $podcastEpisodeBusinessLayer,
139
			RadioStationBusinessLayer $radioStationBusinessLayer,
140
			TrackBusinessLayer $trackBusinessLayer,
141
			Library $library,
142
			PodcastService $podcastService,
143
			AmpacheImageService $imageService,
144
			CoverService $coverService,
145
			DetailsService $detailsService,
146
			FileSystemService $fileSystemService,
147
			LastfmService $lastfmService,
148
			LibrarySettings $librarySettings,
149
			Random $random,
150
			Logger $logger,
151
			Scrobbler $scrobbler
152
	) {
153
		parent::__construct($appName, $request, 'POST, GET', 'Authorization, Content-Type, Accept, X-Requested-With');
154
155
		$this->config = $config;
156
		$this->l10n = $l10n;
157
		$this->urlGenerator = $urlGenerator;
158
		$this->userManager = $userManager;
159
		$this->albumBusinessLayer = $albumBusinessLayer;
160
		$this->artistBusinessLayer = $artistBusinessLayer;
161
		$this->bookmarkBusinessLayer = $bookmarkBusinessLayer;
162
		$this->genreBusinessLayer = $genreBusinessLayer;
163
		$this->playlistBusinessLayer = $playlistBusinessLayer;
164
		$this->podcastChannelBusinessLayer = $podcastChannelBusinessLayer;
165
		$this->podcastEpisodeBusinessLayer = $podcastEpisodeBusinessLayer;
166
		$this->radioStationBusinessLayer = $radioStationBusinessLayer;
167
		$this->trackBusinessLayer = $trackBusinessLayer;
168
		$this->library = $library;
169
		$this->podcastService = $podcastService;
170
		$this->imageService = $imageService;
171
		$this->coverService = $coverService;
172
		$this->detailsService = $detailsService;
173
		$this->fileSystemService = $fileSystemService;
174
		$this->lastfmService = $lastfmService;
175
		$this->librarySettings = $librarySettings;
176
		$this->random = $random;
177
		$this->logger = $logger;
178
		$this->scrobbler = $scrobbler;
179
180
		$this->jsonMode = false;
181
		$this->session = null;
182
		$this->namePrefixes = [];
183
	}
184
185
	public function setJsonMode(bool $useJsonMode) : void {
186
		$this->jsonMode = $useJsonMode;
187
	}
188
189
	public function setSession(AmpacheSession $session) : void {
190
		$this->session = $session;
191
		$this->namePrefixes = $this->librarySettings->getIgnoredArticles($session->getUserId());
192
	}
193
194
	public function ampacheResponse(array $content) : Response {
195
		if ($this->jsonMode) {
196
			return new JSONResponse($this->prepareResultForJsonApi($content));
197
		} else {
198
			return new XmlResponse($this->prepareResultForXmlApi($content), ['id', 'index', 'count', 'code', 'errorCode'], true, true, 'text');
199
		}
200
	}
201
202
	public function ampacheErrorResponse(int $code, string $message) : Response {
203
		$this->logger->debug($message);
204
205
		if ($this->apiMajorVersion() > 4) {
206
			$code = $this->mapApiV4ErrorToV5($code);
207
			$content = [
208
				'error' => [
209
					'errorCode' => (string)$code,
210
					'errorAction' => $this->request->getParam('action'),
211
					'errorType' => 'system',
212
					'errorMessage' => $message
213
				]
214
			];
215
		} else {
216
			$content = [
217
				'error' => [
218
					'code' => (string)$code,
219
					'text' => $message
220
				]
221
			];
222
		}
223
		return $this->ampacheResponse($content);
224
	}
225
226
	/** @NoSameSiteCookieRequired */
227
	#[NoAdminRequired]
228
	#[PublicPage]
229
	#[NoCSRFRequired]
230
	#[CORS]
231
	public function xmlApi(string $action) : Response {
232
		// differentiation between xmlApi and jsonApi is made already by the middleware
233
		return $this->dispatch($action);
234
	}
235
236
	/** @NoSameSiteCookieRequired */
237
	#[NoAdminRequired]
238
	#[PublicPage]
239
	#[NoCSRFRequired]
240
	#[CORS]
241
	public function jsonApi(string $action) : Response {
242
		// differentiation between xmlApi and jsonApi is made already by the middleware
243
		return $this->dispatch($action);
244
	}
245
246
	#[NoAdminRequired]
247
	#[NoCSRFRequired]
248
	public function internalApi(string $action, string|int|bool $xml='0') : Response {
249
		$this->setJsonMode(!\filter_var($xml, FILTER_VALIDATE_BOOLEAN));
250
		return $this->dispatch($action);
251
	}
252
253
	protected function dispatch(string $action) : Response {
254
		$this->logger->debug("Ampache action '$action' requested");
255
256
		// Allow calling any functions annotated to be part of the API
257
		if (\method_exists($this, $action)) {
258
			$reflection = new \ReflectionMethod($this, $action);
259
			if (!empty($reflection->getAttributes(AmpacheAPI::class))) {
260
				// custom "filter" which modifies the value of the request argument `limit`
261
				$limitFilter = function(?string $value) : int {
262
					// The value "none" is is interpreted as "no limit".
263
					// Any other non-integer values and integer value 0 are interpreted as the default limit of 5000 entries
264
					if (StringUtil::caselessEqual($value, 'none')) {
265
						$value = Util::SINT32_MAX;
266
					} else {
267
						$value = (int)$value;
268
						if ($value <= 0) {
269
							$value = 5000;
270
						}
271
					}
272
					return $value;
273
				};
274
275
				$parameterExtractor = new RequestParameterExtractor($this->request, ['limit' => $limitFilter]);
276
				try {
277
					$parameterValues = $parameterExtractor->getParametersForMethod($this, $action);
278
				} catch (RequestParameterExtractorException $ex) {
279
					throw new AmpacheException($ex->getMessage(), 400);
280
				}
281
				$response = \call_user_func_array([$this, $action], $parameterValues);
282
				// The API methods may return either a Response object or an array, which should be converted to Response
283
				if (!($response instanceof Response)) {
284
					$response = $this->ampacheResponse($response);
285
				}
286
				return $response;
287
			}
288
		}
289
290
		// No method was found for this action
291
		$this->logger->warning("Unsupported Ampache action '$action' requested");
292
		throw new AmpacheException('Action not supported', 405);
293
	}
294
295
	/***********************
296
	 * Ampache API methods *
297
	 ***********************/
298
299
	/**
300
	 * Get the handshake result. The actual user authentication and session creation logic has happened prior to calling
301
	 * this in the class AmpacheMiddleware.
302
	 */
303
	#[AmpacheAPI]
304
	protected function handshake() : array {
305
		\assert($this->session !== null);
306
		$user = $this->userId();
307
		$updateTime = \max($this->library->latestUpdateTime($user), $this->playlistBusinessLayer->latestUpdateTime($user));
308
		$addTime = \max($this->library->latestInsertTime($user), $this->playlistBusinessLayer->latestInsertTime($user));
309
		$genresKey = $this->genreKey() . 's';
310
		$playlistCount = $this->playlistBusinessLayer->count($user);
311
312
		return [
313
			'session_expire' => \date('c', $this->session->getExpiry()),
314
			'auth' => $this->session->getToken(),
315
			'api' => $this->apiVersionString(),
316
			'update' => $updateTime->format('c'),
317
			'add' => $addTime->format('c'),
318
			'clean' => \date('c', \time()), // TODO: actual time of the latest item removal
319
			'songs' => $this->trackBusinessLayer->count($user),
320
			'artists' => $this->artistBusinessLayer->count($user),
321
			'albums' => $this->albumBusinessLayer->count($user),
322
			'playlists' => $playlistCount,
323
			'searches' => 1, // "All tracks"
324
			'playlists_searches' => $playlistCount + 1,
325
			'podcasts' => $this->podcastChannelBusinessLayer->count($user),
326
			'podcast_episodes' => $this->podcastEpisodeBusinessLayer->count($user),
327
			'live_streams' => $this->radioStationBusinessLayer->count($user),
328
			$genresKey => $this->genreBusinessLayer->count($user),
329
			'videos' => 0,
330
			'catalogs' => 0,
331
			'shares' => 0,
332
			'licenses' => 0,
333
			'labels' => 0,
334
			'max_song' => $this->trackBusinessLayer->maxId($user),
335
			'max_album' => $this->albumBusinessLayer->maxId($user),
336
			'max_artist' => $this->artistBusinessLayer->maxId($user),
337
			'max_video' => null,
338
			'max_podcast' => $this->podcastChannelBusinessLayer->maxId($user),
339
			'max_podcast_episode' => $this->podcastEpisodeBusinessLayer->maxId($user),
340
			'username' => $user
341
		];
342
	}
343
344
	/**
345
	 * Get the result for the 'goodbye' command. The actual logout is handled by AmpacheMiddleware.
346
	 */
347
	#[AmpacheAPI]
348
	protected function goodbye() : array {
349
		\assert($this->session !== null);
350
		return ['success' => "goodbye: {$this->session->getToken()}"];
351
	}
352
353
	#[AmpacheAPI]
354
	protected function ping() : array {
355
		$response = [
356
			'server' => AppInfo::getFullName() . ' ' . AppInfo::getVersion(),
357
			'version' => $this->apiVersionString(),
358
			'compatible' => self::API_MIN_COMPATIBLE_VERSION
359
		];
360
361
		if ($this->session) {
362
			// in case ping is called within a valid session, the response will contain also the "handshake fields"
363
			$response += $this->handshake();
364
		}
365
366
		return $response;
367
	}
368
369
	#[AmpacheAPI]
370
	protected function get_indexes(string $type, ?string $filter, ?string $add, ?string $update, ?bool $include, int $limit, int $offset=0) : array {
371
		if ($type === 'album_artist' || $type === 'song_artist') {
372
			list($addMin, $addMax, $updateMin, $updateMax) = self::parseTimeParameters($add, $update);
373
			if ($type === 'album_artist') {
374
				$entities = $this->artistBusinessLayer->findAllHavingAlbums(
375
					$this->userId(), SortBy::Name, $limit, $offset, $filter, MatchMode::Substring, $addMin, $addMax, $updateMin, $updateMax);
376
			} else {
377
				$entities = $this->artistBusinessLayer->findAllHavingTracks(
378
					$this->userId(), SortBy::Name, $limit, $offset, $filter, MatchMode::Substring, $addMin, $addMax, $updateMin, $updateMax);
379
			}
380
			$type = 'artist';
381
		} else {
382
			$businessLayer = $this->getBusinessLayer($type);
383
			$entities = $this->findEntities($businessLayer, $filter, false, $limit, $offset, $add, $update);
384
		}
385
386
		// We support the 'include' argument only for podcasts. On the original Ampache server, also other types have support but
387
		// only 'podcast' and 'playlist' are documented to be supported and the implementation is really messy for the 'playlist'
388
		// type, with inconsistencies between XML and JSON formats and XML-structures unlike any other actions.
389
		if ($type == 'podcast' && $include) {
390
			$this->injectEpisodesToChannels($entities);
391
		}
392
393
		return $this->renderEntitiesIndex($entities, $type);
394
	}
395
396
	#[AmpacheAPI]
397
	protected function index(
398
			string $type, ?string $filter, ?string $add, ?string $update,
399
			?bool $include, int $limit, int $offset=0, bool $exact=false) : array {
400
		$userId = $this->userId();
401
		
402
		if ($type === 'album_artist' || $type === 'song_artist') {
403
			list($addMin, $addMax, $updateMin, $updateMax) = self::parseTimeParameters($add, $update);
404
			$matchMode = $exact ? MatchMode::Exact : MatchMode::Substring;
405
			if ($type === 'album_artist') {
406
				$entities = $this->artistBusinessLayer->findAllHavingAlbums(
407
					$userId, SortBy::Name, $limit, $offset, $filter, $matchMode, $addMin, $addMax, $updateMin, $updateMax);
408
			} else {
409
				$entities = $this->artistBusinessLayer->findAllHavingTracks(
410
					$userId, SortBy::Name, $limit, $offset, $filter, $matchMode, $addMin, $addMax, $updateMin, $updateMax);
411
			}
412
		} else {
413
			$businessLayer = $this->getBusinessLayer($type);
414
			$entities = $this->findEntities($businessLayer, $filter, $exact, $limit, $offset, $add, $update);
415
		}
416
417
		if ($include) {
418
			$childType = self::getChildEntityType($type);
419
			if ($childType !== null) {
420
				if ($type == 'playlist') {
421
					$idsWithChildren = [];
422
					foreach ($entities as $playlist) {
423
						\assert($playlist instanceof Playlist);
424
						$idsWithChildren[$playlist->getId()] = $playlist->getTrackIdsAsArray();
425
					}
426
				} else {
427
					$idsWithChildren = $this->getBusinessLayer($childType)->findAllIdsByParentIds($userId, ArrayUtil::extractIds($entities));
428
				}
429
				return $this->renderIdsWithChildren($idsWithChildren, $type, $childType);
430
			}
431
		}
432
433
		return $this->renderEntityIdIndex($entities, $type);
434
	}
435
436
	#[AmpacheAPI]
437
	protected function list(string $type, ?string $filter, ?string $add, ?string $update, int $limit, int $offset=0) : array {
438
		$isAlbumArtist = ($type == 'album_artist');
439
		if ($isAlbumArtist) {
440
			$type = 'artist';
441
		}
442
443
		list($addMin, $addMax, $updateMin, $updateMax) = self::parseTimeParameters($add, $update);
444
445
		$businessLayer = $this->getBusinessLayer($type);
446
		$entities = $businessLayer->findAllIdsAndNames(
447
			$this->userId(), $this->l10n, null, $limit, $offset, $addMin, $addMax, $updateMin, $updateMax, $isAlbumArtist, $filter);
448
449
		return [
450
			'list' => \array_map(
451
				fn($idAndName) => $idAndName + $this->prefixAndBaseName($idAndName['name']),
452
				$entities
453
			)
454
		];
455
	}
456
457
	#[AmpacheAPI]
458
	protected function browse(string $type, ?string $filter, ?string $add, ?string $update, int $limit, int $offset=0) : array {
459
		// note: the argument 'catalog' is disregarded in our implementation
460
		if ($type == 'root') {
461
			$catalogId = null;
462
			$childType = 'catalog';
463
			$children = [
464
				['id' => 'music', 'name' => 'music'],
465
				['id' => 'podcasts', 'name' => 'podcasts']
466
			];
467
		} else {
468
			if ($type == 'catalog') {
469
				$catalogId = null;
470
				$parentId = null;
471
472
				switch ($filter) {
473
					case 'music':
474
						$childType = 'artist';
475
						break;
476
					case 'podcasts':
477
						$childType = 'podcast';
478
						break;
479
					default:
480
						throw new AmpacheException("Filter '$filter' is not a valid catalog", 400);
481
				}
482
			} else {
483
				$catalogId = StringUtil::startsWith($type, 'podcast') ? 'podcasts' : 'music';
484
				$parentId = empty($filter) ? null : (int)$filter;
485
486
				switch ($type) {
487
					case 'podcast':
488
						$childType = 'podcast_episode';
489
						break;
490
					case 'artist':
491
						$childType = 'album';
492
						break;
493
					case 'album':
494
						$childType = 'song';
495
						break;
496
					default:
497
						throw new AmpacheException("Type '$type' is not supported", 400);
498
				}
499
			}
500
501
			$businessLayer = $this->getBusinessLayer($childType);
502
			list($addMin, $addMax, $updateMin, $updateMax) = self::parseTimeParameters($add, $update);
503
			$children = $businessLayer->findAllIdsAndNames(
504
				$this->userId(), $this->l10n, $parentId, $limit, $offset, $addMin, $addMax, $updateMin, $updateMax, true);
505
		}
506
507
		return [
508
			'catalog_id' => $catalogId,
509
			'parent_id' => $filter,
510
			'parent_type' => $type,
511
			'child_type' => $childType,
512
			'browse' => \array_map(fn($idAndName) => $idAndName + $this->prefixAndBaseName($idAndName['name']), $children)
513
		];
514
	}
515
516
	#[AmpacheAPI]
517
	protected function stats(string $type, ?string $filter, int $limit, int $offset=0) : array {
518
		$userId = $this->userId();
519
520
		// Support for API v3.x: Originally, there was no 'filter' argument and the 'type'
521
		// argument had that role. The action only supported albums in this old format.
522
		// The 'filter' argument was added and role of 'type' changed in API v4.0.
523
		if (empty($filter)) {
524
			$filter = $type;
525
			$type = 'album';
526
		}
527
528
		// Note: In addition to types specified in APIv6, we support also types 'genre' and 'live_stream'
529
		// as that's possible without extra effort. All types don't support all possible filters.
530
		$businessLayer = $this->getBusinessLayer($type);
531
532
		$getEntitiesIfSupported = function(
533
				BusinessLayer $businessLayer, string $method, string $userId,
534
				int $limit, int $offset) use ($type, $filter) {
535
			if (\method_exists($businessLayer, $method)) {
536
				return $businessLayer->$method($userId, $limit, $offset);
537
			} else {
538
				throw new AmpacheException("Filter $filter not supported for type $type", 400);
539
			}
540
		};
541
542
		switch ($filter) {
543
			case 'newest':
544
				$entities = $businessLayer->findAll($userId, SortBy::Newest, $limit, $offset);
545
				break;
546
			case 'flagged':
547
				$entities = $businessLayer->findAllStarred($userId, $limit, $offset);
548
				break;
549
			case 'random':
550
				$entities = $businessLayer->findAll($userId, SortBy::Name);
551
				$indices = $this->random->getIndices(\count($entities), $offset, $limit, $userId, 'ampache_stats_'.$type);
552
				$entities = ArrayUtil::multiGet($entities, $indices);
553
				break;
554
			case 'frequent':
555
				$entities = $getEntitiesIfSupported($businessLayer, 'findFrequentPlay', $userId, $limit, $offset);
556
				break;
557
			case 'recent':
558
				$entities = $getEntitiesIfSupported($businessLayer, 'findRecentPlay', $userId, $limit, $offset);
559
				break;
560
			case 'forgotten':
561
				$entities = $getEntitiesIfSupported($businessLayer, 'findNotRecentPlay', $userId, $limit, $offset);
562
				break;
563
			case 'highest':
564
				$entities = $businessLayer->findAllRated($userId, $limit, $offset);
565
				break;
566
			default:
567
				throw new AmpacheException("Unsupported filter $filter", 400);
568
		}
569
570
		return $this->renderEntities($entities, $type);
571
	}
572
573
	#[AmpacheAPI]
574
	protected function artists(
575
			?string $filter, ?string $add, ?string $update, int $limit, int $offset=0,
576
			bool $exact=false, bool $album_artist=false, ?string $include=null) : array {
577
		$userId = $this->userId();
578
579
		if ($album_artist) {
580
			$matchMode =  $exact ? MatchMode::Exact : MatchMode::Substring;
581
			list($addMin, $addMax, $updateMin, $updateMax) = self::parseTimeParameters($add, $update);
582
			$artists = $this->artistBusinessLayer->findAllHavingAlbums(
583
				$userId, SortBy::Name, $limit, $offset, $filter, $matchMode, $addMin, $addMax, $updateMin, $updateMax);
584
		} else {
585
			$artists = $this->findEntities($this->artistBusinessLayer, $filter, $exact, $limit, $offset, $add, $update);
586
		}
587
588
		$include = Util::explode(',', $include);
589
		if (\in_array('songs', $include)) {
590
			$this->library->injectTracksToArtists($artists, $userId);
591
		}
592
		if (\in_array('albums', $include)) {
593
			$this->library->injectAlbumsToArtists($artists, $userId);
594
		}
595
596
		return $this->renderArtists($artists);
597
	}
598
599
	#[AmpacheAPI]
600
	protected function artist(int $filter, ?string $include) : array {
601
		$userId = $this->userId();
602
		$artists = [$this->artistBusinessLayer->find($filter, $userId)];
603
604
		$include = Util::explode(',', $include);
605
		if (\in_array('songs', $include)) {
606
			$this->library->injectTracksToArtists($artists, $userId);
607
		}
608
		if (\in_array('albums', $include)) {
609
			$this->library->injectAlbumsToArtists($artists, $userId);
610
		}
611
612
		return $this->renderArtists($artists);
613
	}
614
615
	#[AmpacheAPI]
616
	protected function artist_albums(int $filter, int $limit, int $offset=0) : array {
617
		$userId = $this->userId();
618
		$albums = $this->albumBusinessLayer->findAllByArtist($filter, $userId, $limit, $offset);
619
		return $this->renderAlbums($albums);
620
	}
621
622
	#[AmpacheAPI]
623
	protected function artist_songs(int $filter, int $limit, int $offset=0, bool $top50=false) : array {
624
		$userId = $this->userId();
625
		if ($top50) {
626
			$tracks = $this->lastfmService->getTopTracks($filter, $userId, 50);
627
			$tracks = \array_slice($tracks, $offset, $limit);
628
		} else {
629
			$tracks = $this->trackBusinessLayer->findAllByArtist($filter, $userId, $limit, $offset);
630
		}
631
		return $this->renderSongs($tracks);
632
	}
633
634
	#[AmpacheAPI]
635
	protected function album_songs(int $filter, int $limit, int $offset=0) : array {
636
		$userId = $this->userId();
637
		$tracks = $this->trackBusinessLayer->findAllByAlbum($filter, $userId, null, $limit, $offset);
638
		return $this->renderSongs($tracks);
639
	}
640
641
	#[AmpacheAPI]
642
	protected function song(int $filter) : array {
643
		$userId = $this->userId();
644
		$track = $this->trackBusinessLayer->find($filter, $userId);
645
646
		// parse and include also lyrics when fetching an individual song
647
		$rootFolder = $this->librarySettings->getFolder($userId);
648
		$lyrics = $this->detailsService->getLyricsAsPlainText($track->getFileId(), $rootFolder);
649
		if ($lyrics !== null) {
650
			$lyrics = \mb_ereg_replace("\n", "<br />", $lyrics); // It's not documented but Ampache proper uses HTML line breaks for the lyrics
651
			$track->setLyrics($lyrics);
652
		}
653
654
		return $this->renderSongs([$track]);
655
	}
656
657
	#[AmpacheAPI]
658
	protected function songs(
659
			?string $filter, ?string $add, ?string $update,
660
			int $limit, int $offset=0, bool $exact=false) : array {
661
662
		$tracks = $this->findEntities($this->trackBusinessLayer, $filter, $exact, $limit, $offset, $add, $update);
663
		return $this->renderSongs($tracks);
664
	}
665
666
	#[AmpacheAPI]
667
	protected function search_songs(string $filter, int $limit, int $offset=0) : array {
668
		$userId = $this->userId();
669
		$tracks = $this->trackBusinessLayer->findAllByNameRecursive($filter, $userId, $limit, $offset);
670
		return $this->renderSongs($tracks);
671
	}
672
673
	#[AmpacheAPI]
674
	protected function albums(
675
			?string $filter, ?string $add, ?string $update, int $limit, int $offset=0,
676
			bool $exact=false, ?string $include=null) : array {
677
678
		$albums = $this->findEntities($this->albumBusinessLayer, $filter, $exact, $limit, $offset, $add, $update);
679
680
		if ($include == 'songs') {
681
			$this->library->injectTracksToAlbums($albums, $this->userId());
682
		}
683
684
		return $this->renderAlbums($albums);
685
	}
686
687
	#[AmpacheAPI]
688
	protected function album(int $filter, ?string $include) : array {
689
		$userId = $this->userId();
690
		$albums = [$this->albumBusinessLayer->find($filter, $userId)];
691
692
		if ($include == 'songs') {
693
			$this->library->injectTracksToAlbums($albums, $userId);
694
		}
695
696
		return $this->renderAlbums($albums);
697
	}
698
699
	/**
700
	 * This is a proprietary extension to the API
701
	 */
702
	#[AmpacheAPI]
703
	protected function folders(int $limit, int $offset=0) : array {
704
		$userId = $this->userId();
705
		$musicFolder = $this->librarySettings->getFolder($userId);
706
		$folders = $this->fileSystemService->findAllFolders($userId, $musicFolder);
707
708
		// disregard any (parent) folders without any direct track children
709
		$folders = \array_filter($folders, fn($folder) => \count($folder['trackIds']) > 0);
710
711
		ArrayUtil::sortByColumn($folders, 'name');
712
		$folders = \array_slice($folders, $offset, $limit);
713
714
		return [
715
			'folder' => \array_map(fn($folder) => [
716
				'id' => (string)$folder['id'],
717
				'name' => $folder['name'],
718
			], $folders)
719
		];
720
	}
721
722
	/**
723
	 * This is a proprietary extension to the API
724
	 */
725
	#[AmpacheAPI]
726
	protected function folder_songs(int $filter, int $limit, int $offset=0) : array {
727
		$userId = $this->userId();
728
		$tracks = $this->trackBusinessLayer->findAllByFolder($filter, $userId, $limit, $offset);
729
		return $this->renderSongs($tracks);
730
	}
731
732
	#[AmpacheAPI]
733
	protected function get_similar(string $type, int $filter, int $limit, int $offset=0) : array {
734
		$userId = $this->userId();
735
		if ($type == 'artist') {
736
			$entities = $this->lastfmService->getSimilarArtists($filter, $userId);
737
		} elseif ($type == 'song') {
738
			$entities = $this->lastfmService->getSimilarTracks($filter, $userId);
739
		} else {
740
			throw new AmpacheException("Type '$type' is not supported", 400);
741
		}
742
		$entities = \array_slice($entities, $offset, $limit);
743
		return $this->renderEntities($entities, $type);
744
	}
745
746
	#[AmpacheAPI]
747
	protected function playlists(
748
			?string $filter, ?string $add, ?string $update, int $limit, int $offset=0,
749
			bool $exact=false, bool $hide_search=false, bool $include=false) : array {
750
751
		$userId = $this->userId();
752
		$playlists = $this->findEntities($this->playlistBusinessLayer, $filter, $exact, $limit, $offset, $add, $update);
753
754
		// append "All tracks" if "searches" are not forbidden, and not filtering by any criteria, and it is not off-limits
755
		$allTracksIndex = $this->playlistBusinessLayer->count($userId);
756
		if (!$hide_search && empty($filter) && empty($add) && empty($update)
757
				&& self::indexIsWithinOffsetAndLimit($allTracksIndex, $offset, $limit)) {
758
			$playlists[] = $this->getAllTracksPlaylist();
759
		}
760
761
		return $this->renderPlaylists($playlists, $include);
762
	}
763
764
	#[AmpacheAPI]
765
	protected function user_playlists(
766
			?string $filter, ?string $add, ?string $update,	int $limit, int $offset=0, bool $exact=false) : array {
767
		// alias for playlists without smart lists
768
		return $this->playlists($filter, $add, $update, $limit, $offset, $exact, true);
769
	}
770
771
	#[AmpacheAPI]
772
	protected function user_smartlists() : array {
773
		// the only "smart list" currently supported is "All tracks", hence supporting any kind of filtering criteria
774
		// isn't worthwhile
775
		return $this->renderPlaylists([$this->getAllTracksPlaylist()]);
776
	}
777
778
	#[AmpacheAPI]
779
	protected function playlist(int $filter, bool $include=false) : array {
780
		$userId = $this->userId();
781
		if ($filter == self::ALL_TRACKS_PLAYLIST_ID) {
782
			$playlist = $this->getAllTracksPlaylist();
783
		} else {
784
			$playlist = $this->playlistBusinessLayer->find($filter, $userId);
785
		}
786
		return $this->renderPlaylists([$playlist], $include);
787
	}
788
789
	#[AmpacheAPI]
790
	protected function playlist_hash(int $filter) : array {
791
		if ($filter == self::ALL_TRACKS_PLAYLIST_ID) {
792
			$playlist = $this->getAllTracksPlaylist();
793
		} else {
794
			$playlist = $this->playlistBusinessLayer->find($filter, $this->userId());
795
		}
796
		return [ 'md5' => $playlist->getTrackIdsHash() ];
797
	}
798
799
	#[AmpacheAPI]
800
	protected function playlist_songs(int $filter, int $limit, int $offset=0, bool $random=false) : array {
801
		// In random mode, the pagination is handled manually after fetching the songs. Declare $rndLimit and $rndOffset
802
		// regardless of the random mode because PHPStan and Scrutinizer are not smart enough to otherwise know that they
803
		// are guaranteed to be defined in the second random block in the end of this function.
804
		$rndLimit = $limit;
805
		$rndOffset = $offset;
806
		if ($random) {
807
			$limit = null;
808
			$offset = null;
809
		}
810
811
		$userId = $this->userId();
812
		if ($filter == self::ALL_TRACKS_PLAYLIST_ID) {
813
			$tracks = $this->trackBusinessLayer->findAll($userId, SortBy::Parent, $limit, $offset);
814
			foreach ($tracks as $index => $track) {
815
				$track->setNumberOnPlaylist($index + 1);
816
			}
817
		} else {
818
			$tracks = $this->playlistBusinessLayer->getPlaylistTracks($filter, $userId, $limit, $offset);
819
		}
820
821
		if ($random) {
822
			$indices = $this->random->getIndices(\count($tracks), $rndOffset, $rndLimit, $userId, 'ampache_playlist_songs');
823
			$tracks = ArrayUtil::multiGet($tracks, $indices);
824
		}
825
826
		return $this->renderSongs($tracks);
827
	}
828
829
	#[AmpacheAPI]
830
	protected function playlist_create(string $name) : array {
831
		$playlist = $this->playlistBusinessLayer->create($name, $this->userId());
832
		return $this->renderPlaylists([$playlist]);
833
	}
834
835
	/**
836
	 * @param int $filter Playlist ID
837
	 * @param ?string $name New name for the playlist
838
	 * @param ?string $items Track IDs
839
	 * @param ?string $tracks 1-based indices of the tracks
840
	 */
841
	#[AmpacheAPI]
842
	protected function playlist_edit(int $filter, ?string $name, ?string $items, ?string $tracks) : array {
843
		$edited = false;
844
		$userId = $this->userId();
845
846
		if (!empty($name)) {
847
			$this->playlistBusinessLayer->rename($name, $filter, $userId);
848
			$edited = true;
849
		}
850
851
		$newTrackIds = \array_map('intval', Util::explode(',', $items));
852
		$newTrackOrdinals = \array_map('intval', Util::explode(',', $tracks));
853
854
		if (\count($newTrackIds) != \count($newTrackOrdinals)) {
855
			throw new AmpacheException("Arguments 'items' and 'tracks' must contain equal amount of elements", 400);
856
		} elseif (\count($newTrackIds) > 0) {
857
			$trackIds = $this->playlistBusinessLayer->getPlaylistTrackIds($filter, $userId);
858
859
			for ($i = 0, $count = \count($newTrackIds); $i < $count; ++$i) {
860
				$trackId = $newTrackIds[$i];
861
				if (!$this->trackBusinessLayer->exists($trackId, $userId)) {
862
					throw new AmpacheException("Invalid song ID $trackId", 404);
863
				}
864
				$trackIds[$newTrackOrdinals[$i]-1] = $trackId;
865
			}
866
867
			$this->playlistBusinessLayer->setTracks($trackIds, $filter, $userId);
868
			$edited = true;
869
		}
870
871
		if ($edited) {
872
			return ['success' => 'playlist changes saved'];
873
		} else {
874
			throw new AmpacheException('Nothing was changed', 400);
875
		}
876
	}
877
878
	#[AmpacheAPI]
879
	protected function playlist_delete(int $filter) : array {
880
		$this->playlistBusinessLayer->delete($filter, $this->userId());
881
		return ['success' => 'playlist deleted'];
882
	}
883
884
	#[AmpacheAPI]
885
	protected function playlist_add_song(int $filter, int $song, bool $check=false) : array {
886
		$userId = $this->userId();
887
		if (!$this->trackBusinessLayer->exists($song, $userId)) {
888
			throw new AmpacheException("Invalid song ID $song", 404);
889
		}
890
891
		$trackIds = $this->playlistBusinessLayer->getPlaylistTrackIds($filter, $userId);
892
893
		if ($check && \in_array($song, $trackIds)) {
894
			throw new AmpacheException("Can't add a duplicate item when check is enabled", 400);
895
		}
896
897
		$trackIds[] = $song;
898
		$this->playlistBusinessLayer->setTracks($trackIds, $filter, $userId);
899
		return ['success' => 'song added to playlist'];
900
	}
901
902
	#[AmpacheAPI]
903
	protected function playlist_add(int $filter, int $id, string $type) : array {
904
		$userId = $this->userId();
905
906
		if (!$this->getBusinessLayer($type)->exists($id, $userId)) {
907
			throw new AmpacheException("Invalid $type ID $id", 404);
908
		}
909
910
		$trackIds = $this->playlistBusinessLayer->getPlaylistTrackIds($filter, $userId);
911
912
		$newIds = $this->trackIdsForEntity($id, $type);
913
		$trackIds = \array_merge($trackIds, $newIds);
914
915
		$this->playlistBusinessLayer->setTracks($trackIds, $filter, $userId);
916
		return ['success' => "songs added to playlist"];
917
	}
918
919
	/**
920
	 * @param int $filter Playlist ID
921
	 * @param ?int $song Track ID
922
	 * @param ?int $track 1-based index of the track
923
	 * @param ?int $clear Value 1 erases all the songs from the playlist
924
	 */
925
	#[AmpacheAPI]
926
	protected function playlist_remove_song(int $filter, ?int $song, ?int $track, ?int $clear) : array {
927
		$userId = $this->userId();
928
		$trackIds = $this->playlistBusinessLayer->getPlaylistTrackIds($filter, $userId);
929
930
		if ($clear === 1) {
931
			$trackIds = [];
932
			$message = 'all songs removed from playlist';
933
		} elseif ($song !== null) {
934
			if (!\in_array($song, $trackIds)) {
935
				throw new AmpacheException("Song $song not found in playlist", 404);
936
			}
937
			$trackIds = ArrayUtil::diff($trackIds, [$song]);
938
			$message = 'song removed from playlist';
939
		} elseif ($track !== null) {
940
			if ($track < 1 || $track > \count($trackIds)) {
941
				throw new AmpacheException("Track ordinal $track is out of bounds", 404);
942
			}
943
			unset($trackIds[$track-1]);
944
			$message = 'song removed from playlist';
945
		} else {
946
			throw new AmpacheException("One of the arguments 'clear', 'song', 'track' is required", 400);
947
		}
948
949
		$this->playlistBusinessLayer->setTracks($trackIds, $filter, $userId);
950
		return ['success' => $message];
951
	}
952
953
	#[AmpacheAPI]
954
	protected function playlist_generate(
955
			?string $filter, ?int $album, ?int $artist, ?int $flag,
956
			int $limit, int $offset=0, string $mode='random', string $format='song') : array {
957
958
		$tracks = $this->findEntities($this->trackBusinessLayer, $filter, false); // $limit and $offset are applied later
959
960
		// filter the found tracks according to the additional requirements
961
		if ($album !== null) {
962
			$tracks = \array_filter($tracks, fn($track) => ($track->getAlbumId() == $album));
963
		}
964
		if ($artist !== null) {
965
			$tracks = \array_filter($tracks, fn($track) => ($track->getArtistId() == $artist));
966
		}
967
		if ($flag == 1) {
968
			$tracks = \array_filter($tracks, fn($track) => ($track->getStarred() !== null));
969
		}
970
		// After filtering, there may be "holes" between the array indices. Reindex the array.
971
		$tracks = \array_values($tracks);
972
973
		if ($mode == 'random') {
974
			$userId = $this->userId();
975
			$indices = $this->random->getIndices(\count($tracks), $offset, $limit, $userId, 'ampache_playlist_generate');
976
			$tracks = ArrayUtil::multiGet($tracks, $indices);
977
		} else { // 'recent', 'forgotten', 'unplayed'
978
			throw new AmpacheException("Mode '$mode' is not supported", 400);
979
		}
980
981
		switch ($format) {
982
			case 'song':
983
				return $this->renderSongs($tracks);
984
			case 'index':
985
				return $this->renderSongsIndex($tracks);
986
			case 'id':
987
				return $this->renderEntityIds($tracks);
988
			default:
989
				throw new AmpacheException("Format '$format' is not supported", 400);
990
		}
991
	}
992
993
	#[AmpacheAPI]
994
	protected function podcasts(?string $filter, ?string $include, int $limit, int $offset=0, bool $exact=false) : array {
995
		$channels = $this->findEntities($this->podcastChannelBusinessLayer, $filter, $exact, $limit, $offset);
996
997
		if ($include === 'episodes') {
998
			$this->injectEpisodesToChannels($channels);
999
		}
1000
1001
		return $this->renderPodcastChannels($channels);
1002
	}
1003
1004
	#[AmpacheAPI]
1005
	protected function podcast(int $filter, ?string $include) : array {
1006
		$userId = $this->userId();
1007
		$channel = $this->podcastChannelBusinessLayer->find($filter, $userId);
1008
1009
		if ($include === 'episodes') {
1010
			$channel->setEpisodes($this->podcastEpisodeBusinessLayer->findAllByChannel($filter, $userId));
1011
		}
1012
1013
		return $this->renderPodcastChannels([$channel]);
1014
	}
1015
1016
	#[AmpacheAPI]
1017
	protected function podcast_create(string $url) : array {
1018
		$result = $this->podcastService->subscribe($url, $this->userId());
1019
1020
		switch ($result['status']) {
1021
			case PodcastService::STATUS_OK:
1022
				return $this->renderPodcastChannels([$result['channel']]);
1023
			case PodcastService::STATUS_INVALID_URL:
1024
				throw new AmpacheException("Invalid URL $url", 400);
1025
			case PodcastService::STATUS_INVALID_RSS:
1026
				throw new AmpacheException("The document at URL $url is not a valid podcast RSS feed", 400);
1027
			case PodcastService::STATUS_ALREADY_EXISTS:
1028
				throw new AmpacheException('User already has this podcast channel subscribed', 400);
1029
			default:
1030
				throw new AmpacheException("Unexpected status code {$result['status']}", 400);
1031
		}
1032
	}
1033
1034
	#[AmpacheAPI]
1035
	protected function podcast_delete(int $filter) : array {
1036
		$status = $this->podcastService->unsubscribe($filter, $this->userId());
1037
1038
		switch ($status) {
1039
			case PodcastService::STATUS_OK:
1040
				return ['success' => 'podcast deleted'];
1041
			case PodcastService::STATUS_NOT_FOUND:
1042
				throw new AmpacheException('Channel to be deleted not found', 404);
1043
			default:
1044
				throw new AmpacheException("Unexpected status code $status", 400);
1045
		}
1046
	}
1047
1048
	#[AmpacheAPI]
1049
	protected function podcast_episodes(int $filter, int $limit, int $offset=0) : array {
1050
		$episodes = $this->podcastEpisodeBusinessLayer->findAllByChannel($filter, $this->userId(), $limit, $offset);
1051
		return $this->renderPodcastEpisodes($episodes);
1052
	}
1053
1054
	#[AmpacheAPI]
1055
	protected function podcast_episode(int $filter) : array {
1056
		$episode = $this->podcastEpisodeBusinessLayer->find($filter, $this->userId());
1057
		return $this->renderPodcastEpisodes([$episode]);
1058
	}
1059
1060
	#[AmpacheAPI]
1061
	protected function update_podcast(int $id) : array {
1062
		$result = $this->podcastService->updateChannel($id, $this->userId());
1063
1064
		switch ($result['status']) {
1065
			case PodcastService::STATUS_OK:
1066
				$message = $result['updated'] ? 'channel was updated from the source' : 'no changes found';
1067
				return ['success' => $message];
1068
			case PodcastService::STATUS_NOT_FOUND:
1069
				throw new AmpacheException('Channel to be updated not found', 404);
1070
			case PodcastService::STATUS_INVALID_URL:
1071
				throw new AmpacheException('failed to read from the channel URL', 400);
1072
			case PodcastService::STATUS_INVALID_RSS:
1073
				throw new AmpacheException('the document at the channel URL is not a valid podcast RSS feed', 400);
1074
			default:
1075
				throw new AmpacheException("Unexpected status code {$result['status']}", 400);
1076
		}
1077
	}
1078
1079
	#[AmpacheAPI]
1080
	protected function live_streams(?string $filter, int $limit, int $offset=0, bool $exact=false) : array {
1081
		$stations = $this->findEntities($this->radioStationBusinessLayer, $filter, $exact, $limit, $offset);
1082
		return $this->renderLiveStreams($stations);
1083
	}
1084
1085
	#[AmpacheAPI]
1086
	protected function live_stream(int $filter) : array {
1087
		$station = $this->radioStationBusinessLayer->find($filter, $this->userId());
1088
		return $this->renderLiveStreams([$station]);
1089
	}
1090
1091
	#[AmpacheAPI]
1092
	protected function live_stream_create(string $name, string $url, ?string $site_url) : array {
1093
		$station = $this->radioStationBusinessLayer->create($this->userId(), $name, $url, $site_url);
1094
		return $this->renderLiveStreams([$station]);
1095
	}
1096
1097
	#[AmpacheAPI]
1098
	protected function live_stream_delete(int $filter) : array {
1099
		$this->radioStationBusinessLayer->delete($filter, $this->userId());
1100
		return ['success' => "Deleted live stream: $filter"];
1101
	}
1102
1103
	#[AmpacheAPI]
1104
	protected function live_stream_edit(int $filter, ?string $name, ?string $url, ?string $site_url) : array {
1105
		$station = $this->radioStationBusinessLayer->updateStation($filter, $this->userId(), $name, $url, $site_url);
1106
		return $this->renderLiveStreams([$station]);
1107
	}
1108
1109
	#[AmpacheAPI]
1110
	protected function tags(?string $filter, int $limit, int $offset=0, bool $exact=false) : array {
1111
		$genres = $this->findEntities($this->genreBusinessLayer, $filter, $exact, $limit, $offset);
1112
		return $this->renderTags($genres);
1113
	}
1114
1115
	#[AmpacheAPI]
1116
	protected function tag(int $filter) : array {
1117
		$genre = $this->genreBusinessLayer->find($filter, $this->userId());
1118
		return $this->renderTags([$genre]);
1119
	}
1120
1121
	#[AmpacheAPI]
1122
	protected function tag_artists(int $filter, int $limit, int $offset=0) : array {
1123
		$artists = $this->artistBusinessLayer->findAllByGenre($filter, $this->userId(), $limit, $offset);
1124
		return $this->renderArtists($artists);
1125
	}
1126
1127
	#[AmpacheAPI]
1128
	protected function tag_albums(int $filter, int $limit, int $offset=0) : array {
1129
		$albums = $this->albumBusinessLayer->findAllByGenre($filter, $this->userId(), $limit, $offset);
1130
		return $this->renderAlbums($albums);
1131
	}
1132
1133
	#[AmpacheAPI]
1134
	protected function tag_songs(int $filter, int $limit, int $offset=0) : array {
1135
		$tracks = $this->trackBusinessLayer->findAllByGenre($filter, $this->userId(), $limit, $offset);
1136
		return $this->renderSongs($tracks);
1137
	}
1138
1139
	#[AmpacheAPI]
1140
	protected function genres(?string $filter, int $limit, int $offset=0, bool $exact=false) : array {
1141
		$genres = $this->findEntities($this->genreBusinessLayer, $filter, $exact, $limit, $offset);
1142
		return $this->renderGenres($genres);
1143
	}
1144
1145
	#[AmpacheAPI]
1146
	protected function genre(int $filter) : array {
1147
		$genre = $this->genreBusinessLayer->find($filter, $this->userId());
1148
		return $this->renderGenres([$genre]);
1149
	}
1150
1151
	#[AmpacheAPI]
1152
	protected function genre_artists(?int $filter, int $limit, int $offset=0) : array {
1153
		if ($filter === null) {
1154
			return $this->artists(null, null, null, $limit, $offset);
1155
		} else {
1156
			return $this->tag_artists($filter, $limit, $offset);
1157
		}
1158
	}
1159
1160
	#[AmpacheAPI]
1161
	protected function genre_albums(?int $filter, int $limit, int $offset=0) : array {
1162
		if ($filter === null) {
1163
			return $this->albums(null, null, null, $limit, $offset);
1164
		} else {
1165
			return $this->tag_albums($filter, $limit, $offset);
1166
		}
1167
	}
1168
1169
	#[AmpacheAPI]
1170
	protected function genre_songs(?int $filter, int $limit, int $offset=0) : array {
1171
		if ($filter === null) {
1172
			return $this->songs(null, null, null, $limit, $offset);
1173
		} else {
1174
			return $this->tag_songs($filter, $limit, $offset);
1175
		}
1176
	}
1177
1178
	#[AmpacheAPI]
1179
	protected function bookmarks(int $include=0) : array {
1180
		$bookmarks = $this->bookmarkBusinessLayer->findAll($this->userId());
1181
		return $this->renderBookmarks($bookmarks, $include);
1182
	}
1183
1184
	#[AmpacheAPI]
1185
	protected function bookmark(int $filter, int $include=0) : array {
1186
		$bookmark = $this->bookmarkBusinessLayer->find($filter, $this->userId());
1187
		return $this->renderBookmarks([$bookmark], $include);
1188
	}
1189
1190
	#[AmpacheAPI]
1191
	protected function get_bookmark(int $filter, string $type, int $include=0, int $all=0) : array {
1192
		// first check the validity of the entity identified by $type and $filter
1193
		$this->getBusinessLayer($type)->find($filter, $this->userId()); // throws if entity doesn't exist
1194
1195
		$entryType = self::mapBookmarkType($type);
1196
		try {
1197
			// we currently support only one bookmark per song/episode but the Ampache API doesn't have this limitation
1198
			$bookmarks = [$this->bookmarkBusinessLayer->findByEntry($entryType, $filter, $this->userId())];
1199
		} catch (BusinessLayerException $ex) {
1200
			$bookmarks = [];
1201
		}
1202
1203
		if (!$all && empty($bookmarks)) {
1204
			// It's a special case when a single bookmark is requested but there is none, in that case we
1205
			// return a completely empty response. Most other actions return an error in similar cases.
1206
			return [];
1207
		} else {
1208
			return $this->renderBookmarks($bookmarks, $include);
1209
		}
1210
	}
1211
1212
	#[AmpacheAPI]
1213
	protected function bookmark_create(int $filter, string $type, int $position, ?string $client, int $include=0) : array {
1214
		// Note: the optional argument 'date' is not supported and is disregarded
1215
		$entryType = self::mapBookmarkType($type);
1216
		$position *= 1000; // seconds to milliseconds
1217
		$bookmark = $this->bookmarkBusinessLayer->addOrUpdate($this->userId(), $entryType, $filter, $position, $client);
1218
		return $this->renderBookmarks([$bookmark], $include);
1219
	}
1220
1221
	#[AmpacheAPI]
1222
	protected function bookmark_edit(int $filter, string $type, int $position, ?string $client, int $include=0) : array {
1223
		// Note: the optional argument 'date' is not supported and is disregarded
1224
		$entryType = self::mapBookmarkType($type);
1225
		$position *= 1000; // seconds to milliseconds
1226
		$bookmark = $this->bookmarkBusinessLayer->updateByEntry($this->userId(), $entryType, $filter, $position, $client);
1227
		return $this->renderBookmarks([$bookmark], $include);
1228
	}
1229
1230
	#[AmpacheAPI]
1231
	protected function bookmark_delete(int $filter, string $type) : array {
1232
		$entryType = self::mapBookmarkType($type);
1233
		$bookmark = $this->bookmarkBusinessLayer->findByEntry($entryType, $filter, $this->userId());
1234
		$this->bookmarkBusinessLayer->delete($bookmark->getId(), $bookmark->getUserId());
1235
		return ['success' => "Deleted Bookmark: $type $filter"];
1236
	}
1237
1238
	#[AmpacheAPI]
1239
	protected function advanced_search(int $limit, int $offset=0, string $type='song', string $operator='and', bool $random=false) : array {
1240
		// get all the rule parameters as passed on the HTTP call
1241
		$rules = self::advSearchGetRuleParams($this->request->getParams());
1242
1243
		// apply some conversions on the rules
1244
		foreach ($rules as &$rule) {
1245
			$rule['rule'] = self::advSearchResolveRuleAlias($rule['rule']);
1246
			$rule['operator'] = self::advSearchInterpretOperator($rule['operator'], $rule['rule']);
1247
			$rule['input'] = self::advSearchConvertInput($rule['input'], $rule['rule']);
1248
		}
1249
1250
		// types 'album_artist' and 'song_artist' are just 'artist' searches with some extra conditions
1251
		if ($type == 'album_artist') {
1252
			$rules[] = ['rule' => 'album_count', 'operator' => '>', 'input' => '0'];
1253
			$type = 'artist';
1254
		} elseif ($type == 'song_artist') {
1255
			$rules[] = ['rule' => 'song_count', 'operator' => '>', 'input' => '0'];
1256
			$type = 'artist';
1257
		}
1258
1259
		try {
1260
			$businessLayer = $this->getBusinessLayer($type);
1261
			$userId = $this->userId();
1262
			$entities = $businessLayer->findAllAdvanced($operator, $rules, $userId, SortBy::Name, $random ? $this->random : null, $limit, $offset);
1263
		} catch (BusinessLayerException $e) {
1264
			throw new AmpacheException($e->getMessage(), 400);
1265
		}
1266
		
1267
		return $this->renderEntities($entities, $type);
1268
	}
1269
1270
	#[AmpacheAPI]
1271
	protected function search(int $limit, int $offset=0, string $type='song', string $operator='and', bool $random=false) : array {
1272
		// this is an alias
1273
		return $this->advanced_search($limit, $offset, $type, $operator, $random);
1274
	}
1275
1276
	#[AmpacheAPI]
1277
	protected function flag(string $type, int $id, bool $flag) : array {
1278
		if (!\in_array($type, ['song', 'album', 'artist', 'podcast', 'podcast_episode', 'playlist'])) {
1279
			throw new AmpacheException("Unsupported type $type", 400);
1280
		}
1281
1282
		$userId = $this->userId();
1283
		$businessLayer = $this->getBusinessLayer($type);
1284
		if ($flag) {
1285
			$modifiedCount = $businessLayer->setStarred([$id], $userId);
1286
			$message = "flag ADDED to $type $id";
1287
		} else {
1288
			$modifiedCount = $businessLayer->unsetStarred([$id], $userId);
1289
			$message = "flag REMOVED from $type $id";
1290
		}
1291
1292
		if ($modifiedCount > 0) {
1293
			return ['success' => $message];
1294
		} else {
1295
			throw new AmpacheException("The $type $id was not found", 404);
1296
		}
1297
	}
1298
1299
	#[AmpacheAPI]
1300
	protected function rate(string $type, int $id, int $rating) : array {
1301
		$rating = (int)Util::limit($rating, 0, 5);
1302
		$businessLayer = $this->getBusinessLayer($type);
1303
		try {
1304
			$businessLayer->setRating($id, $rating, $this->userId());
1305
		} catch (\BadMethodCallException $ex) {
1306
			throw new AmpacheException("Unsupported type $type", 400);
1307
		}
1308
1309
		return ['success' => "rating set to $rating for $type $id"];
1310
	}
1311
1312
	#[AmpacheAPI]
1313
	protected function record_play(int $id, ?int $date) : array {
1314
		$timeOfPlay = ($date === null) ? null : new \DateTime('@' . $date);
1315
		$this->scrobbler->recordTrackPlayed($id, $this->userId(), $timeOfPlay);
1316
		return ['success' => 'play recorded'];
1317
	}
1318
1319
	#[AmpacheAPI]
1320
	protected function scrobble(string $song, string $artist, string $album, ?int $date) : array {
1321
		// arguments songmbid, artistmbid, and albummbid not supported for now
1322
		$matching = $this->trackBusinessLayer->findAllByNameArtistOrAlbum($song, $artist, $album, $this->userId());
1323
		if (\count($matching) === 0) {
1324
			throw new AmpacheException('Song matching the criteria was not found', 404);
1325
		} else if (\count($matching) > 1) {
1326
			throw new AmpacheException('Multiple songs matched the criteria, nothing recorded', 400);
1327
		}
1328
		return $this->record_play($matching[0]->getId(), $date);
1329
	}
1330
1331
	#[AmpacheAPI]
1332
	protected function user(?string $username) : array {
1333
		$userId = $this->userId();
1334
		if (!empty($username) && \mb_strtolower($username) !== \mb_strtolower($userId)) {
1335
			throw new AmpacheException("Getting info of other users is forbidden", 403);
1336
		}
1337
		$user = $this->userManager->get($userId);
1338
1339
		return [
1340
			'id' => $user->getUID(),
1341
			'username' => $user->getUID(),
1342
			'fullname' => $user->getDisplayName(),
1343
			'auth' => '',
1344
			'email' => $user->getEMailAddress(),
1345
			'access' => 25,
1346
			'streamtoken' => null,
1347
			'fullname_public' => true,
1348
			'validation' => null,
1349
			'disabled' => !$user->isEnabled(),
1350
			'create_date' => null,
1351
			'last_seen' => null,
1352
			'website' => null,
1353
			'state' => null,
1354
			'city' => null,
1355
			'art' => $this->urlGenerator->linkToRouteAbsolute('core.avatar.getAvatar', ['userId' => $user->getUID(), 'size' => 64]),
1356
			'has_art' => ($user->getAvatarImage(64) != null)
1357
		];
1358
	}
1359
1360
	#[AmpacheAPI]
1361
	protected function user_preferences() : array {
1362
		return ['preference' => AmpachePreferences::getAll()];
1363
	}
1364
1365
	#[AmpacheAPI]
1366
	protected function user_preference(string $filter) : array {
1367
		$pref = AmpachePreferences::get($filter);
1368
		if ($pref === null) {
1369
			throw new AmpacheException("Not Found: $filter", 400);
1370
		} else {
1371
			return ['preference' => [$pref]];
1372
		}
1373
	}
1374
1375
	#[AmpacheAPI]
1376
	protected function system_preferences() : array {
1377
		return $this->user_preferences();
1378
	}
1379
1380
	#[AmpacheAPI]
1381
	protected function system_preference(string $filter) : array {
1382
		return $this->user_preference($filter);
1383
	}
1384
1385
	#[AmpacheAPI]
1386
	protected function download(int $id, string $type='song', bool $stats=false) : Response {
1387
		// request params `format` and `bitrate` are ignored
1388
1389
		// On all errors, return HTTP error codes instead of Ampache errors. When client calls this action, it awaits a binary response
1390
		// and is probably not prepared to parse any Ampache json/xml responses.
1391
		$userId = $this->userId();
1392
1393
		try {
1394
			if ($type === 'song') {
1395
				$track = $this->trackBusinessLayer->find($id, $userId);
1396
				$file = $this->librarySettings->getFolder($userId)->getById($track->getFileId())[0] ?? null;
1397
1398
				if ($file instanceof \OCP\Files\File) {
1399
					if ($stats) {
1400
						$this->record_play($id, null);
1401
					}
1402
					return new FileStreamResponse($file);
1403
				} else {
1404
					return new ErrorResponse(Http::STATUS_NOT_FOUND, "File for song $id does not exist");
1405
				}
1406
			} elseif ($type === 'podcast' || $type === 'podcast_episode') { // there's a difference between APIv4 and APIv5
1407
				$episode = $this->podcastEpisodeBusinessLayer->find($id, $userId);
1408
				$streamUrl = $episode->getStreamUrl();
1409
				if ($streamUrl === null) {
1410
					return new ErrorResponse(Http::STATUS_NOT_FOUND, "The podcast episode $id has no stream URL");
1411
				} elseif ($this->isInternalSession() && $this->config->getSystemValue('music.relay_podcast_stream', true)) {
1412
					return new RelayStreamResponse($streamUrl);
1413
				} else {
1414
					return new RedirectResponse($streamUrl);
1415
				}
1416
			} elseif ($type === 'playlist') {
1417
				$songIds = ($id === self::ALL_TRACKS_PLAYLIST_ID)
1418
					? $this->trackBusinessLayer->findAllIds($userId)
1419
					: $this->playlistBusinessLayer->find($id, $userId)->getTrackIdsAsArray();
1420
				$randomId = Random::pickItem($songIds);
1421
				if ($randomId === null) {
1422
					return new ErrorResponse(Http::STATUS_NOT_FOUND, "The playlist $id is empty");
1423
				} else {
1424
					return $this->download((int)$randomId, 'song', $stats);
1425
				}
1426
			} else {
1427
				return new ErrorResponse(Http::STATUS_UNSUPPORTED_MEDIA_TYPE, "Unsupported type '$type'");
1428
			}
1429
		} catch (BusinessLayerException $e) {
1430
			return new ErrorResponse(Http::STATUS_NOT_FOUND, $e->getMessage());
1431
		}
1432
	}
1433
1434
	#[AmpacheAPI]
1435
	protected function stream(int $id, ?int $offset, string $type='song', bool $stats=true) : Response {
1436
		// request params `bitrate`, `format`, and `length` are ignored
1437
1438
		// This is just a dummy implementation. We don't support transcoding or streaming
1439
		// from a time offset.
1440
		// All the other unsupported arguments are just ignored, but a request with an offset
1441
		// is responded with an error. This is because the client would probably work in an
1442
		// unexpected way if it thinks it's streaming from offset but actually it is streaming
1443
		// from the beginning of the file. Returning an error gives the client a chance to fallback
1444
		// to other methods of seeking.
1445
		if ($offset !== null) {
1446
			return new ErrorResponse(Http::STATUS_UNSUPPORTED_MEDIA_TYPE, 'Streaming with time offset is not supported');
1447
		}
1448
1449
		return $this->download($id, $type, $stats);
1450
	}
1451
1452
	#[AmpacheAPI]
1453
	protected function get_art(string $type, string $id, ?string $size) : Response {
1454
		if (!\in_array($type, ['song', 'album', 'artist', 'podcast', 'playlist', 'live_stream', 'user'])) {
1455
			return new ErrorResponse(Http::STATUS_UNSUPPORTED_MEDIA_TYPE, "Unsupported type $type");
1456
		}
1457
1458
		if ($size == 'original') {
1459
			$size = CoverService::DO_NOT_CROP_OR_SCALE;
1460
		} elseif ($size !== null) {
1461
			// the format should be "<width>x<height>" but we only support scaling to square shaped art
1462
			$size = (int)(\explode('x', $size)[0] ?? 0);
1463
			if ($size <= 0) {
1464
				$size = null;
1465
			}
1466
		}
1467
1468
		if ($type === 'user') {
1469
			if ($size === null || $size == CoverService::DO_NOT_CROP_OR_SCALE) {
1470
				$size = 640;
1471
			}
1472
			return new RedirectResponse($this->urlGenerator->linkToRoute('core.avatar.getAvatar', ['userId' => $id, 'size' => $size]));
1473
		} else {
1474
			$id = (int)$id;
1475
		}
1476
1477
		if ($type === 'song') {
1478
			// map song to its parent album
1479
			try {
1480
				$id = $this->trackBusinessLayer->find($id, $this->userId())->getAlbumId();
1481
				$type = 'album';
1482
			} catch (BusinessLayerException $e) {
1483
				return new ErrorResponse(Http::STATUS_NOT_FOUND, "song $id not found");
1484
			}
1485
		}
1486
1487
		return $this->getCover($id, $this->getBusinessLayer($type), $size);
1488
	}
1489
1490
	/********************
1491
	 * Helper functions *
1492
	 ********************/
1493
1494
	private function userId() : string {
1495
		// It would be an internal server logic error if the middleware would let
1496
		// an action needing the user session to be called without a valid session.
1497
		assert($this->session !== null);
1498
		return $this->session->getUserId();
1499
	}
1500
1501
	/** @phpstan-return BusinessLayer<covariant Entity> */
1502
	private function getBusinessLayer(string $type) : BusinessLayer {
1503
		switch ($type) {
1504
			case 'song':			return $this->trackBusinessLayer;
1505
			case 'album':			return $this->albumBusinessLayer;
1506
			case 'artist':			return $this->artistBusinessLayer;
1507
			case 'playlist':		return $this->playlistBusinessLayer;
1508
			case 'podcast':			return $this->podcastChannelBusinessLayer;
1509
			case 'podcast_episode':	return $this->podcastEpisodeBusinessLayer;
1510
			case 'live_stream':		return $this->radioStationBusinessLayer;
1511
			case 'tag':				return $this->genreBusinessLayer;
1512
			case 'genre':			return $this->genreBusinessLayer;
1513
			case 'bookmark':		return $this->bookmarkBusinessLayer;
1514
			default:				throw new AmpacheException("Unsupported type $type", 400);
1515
		}
1516
	}
1517
1518
	private static function getChildEntityType(string $type) : ?string {
1519
		switch ($type) {
1520
			case 'album':			return 'song';
1521
			case 'artist':			return 'album';
1522
			case 'album_artist':	return 'album';
1523
			case 'song_artist':		return 'album';
1524
			case 'playlist':		return 'song';
1525
			case 'podcast':			return 'podcast_episode';
1526
			default:				return null;
1527
		}
1528
	}
1529
1530
	private function renderEntities(array $entities, string $type) : array {
1531
		switch ($type) {
1532
			case 'song':			return $this->renderSongs($entities);
1533
			case 'album':			return $this->renderAlbums($entities);
1534
			case 'artist':			return $this->renderArtists($entities);
1535
			case 'playlist':		return $this->renderPlaylists($entities);
1536
			case 'podcast':			return $this->renderPodcastChannels($entities);
1537
			case 'podcast_episode':	return $this->renderPodcastEpisodes($entities);
1538
			case 'live_stream':		return $this->renderLiveStreams($entities);
1539
			case 'tag':				return $this->renderTags($entities);
1540
			case 'genre':			return $this->renderGenres($entities);
1541
			case 'bookmark':		return $this->renderBookmarks($entities);
1542
			default:				throw new AmpacheException("Unsupported type $type", 400);
1543
		}
1544
	}
1545
1546
	private function renderEntitiesIndex(array $entities, string $type) : array {
1547
		switch ($type) {
1548
			case 'song':			return $this->renderSongsIndex($entities);
1549
			case 'album':			return $this->renderAlbumsIndex($entities);
1550
			case 'artist':			return $this->renderArtistsIndex($entities);
1551
			case 'playlist':		return $this->renderPlaylistsIndex($entities);
1552
			case 'podcast':			return $this->renderPodcastChannelsIndex($entities);
1553
			case 'podcast_episode':	return $this->renderPodcastEpisodesIndex($entities);
1554
			case 'live_stream':		return $this->renderLiveStreamsIndex($entities);
1555
			case 'tag':				return $this->renderTags($entities); // not part of the API spec
1556
			case 'genre':			return $this->renderGenres($entities); // not part of the API spec
1557
			case 'bookmark':		return $this->renderBookmarks($entities); // not part of the API spec
1558
			default:				throw new AmpacheException("Unsupported type $type", 400);
1559
		}
1560
	}
1561
1562
	private function trackIdsForEntity(int $id, string $type) : array {
1563
		$userId = $this->userId();
1564
		switch ($type) {
1565
			case 'song':
1566
				return [$id];
1567
			case 'album':
1568
				return ArrayUtil::extractIds($this->trackBusinessLayer->findAllByAlbum($id, $userId));
1569
			case 'artist':
1570
				return ArrayUtil::extractIds($this->trackBusinessLayer->findAllByArtist($id, $userId));
1571
			case 'playlist':
1572
				return $this->playlistBusinessLayer->find($id, $userId)->getTrackIdsAsArray();
1573
			default:
1574
				throw new AmpacheException("Unsupported type $type", 400);
1575
		}
1576
	}
1577
1578
	private static function mapBookmarkType(string $ampacheType) : int {
1579
		switch ($ampacheType) {
1580
			case 'song':			return Bookmark::TYPE_TRACK;
1581
			case 'podcast_episode':	return Bookmark::TYPE_PODCAST_EPISODE;
1582
			default:				throw new AmpacheException("Unsupported type $ampacheType", 400);
1583
		}
1584
	}
1585
1586
	private static function advSearchResolveRuleAlias(string $rule) : string {
1587
		switch ($rule) {
1588
			case 'name':					return 'title';
1589
			case 'song_title':				return 'song';
1590
			case 'album_title':				return 'album';
1591
			case 'artist_title':			return 'artist';
1592
			case 'podcast_title':			return 'podcast';
1593
			case 'podcast_episode_title':	return 'podcast_episode';
1594
			case 'album_artist_title':		return 'album_artist';
1595
			case 'song_artist_title':		return 'song_artist';
1596
			case 'tag':						return 'genre';
1597
			case 'song_tag':				return 'song_genre';
1598
			case 'album_tag':				return 'album_genre';
1599
			case 'artist_tag':				return 'artist_genre';
1600
			case 'no_tag':					return 'no_genre';
1601
			default:						return $rule;
1602
		}
1603
	}
1604
1605
	private static function advSearchGetRuleParams(array $urlParams) : array {
1606
		$rules = [];
1607
1608
		// read and organize the rule parameters
1609
		foreach ($urlParams as $key => $value) {
1610
			$parts = \explode('_', $key, 3);
1611
			if ($parts[0] == 'rule' && \count($parts) > 1) {
1612
				if (\count($parts) == 2) {
1613
					$rules[$parts[1]]['rule'] = $value;
1614
				} elseif ($parts[2] == 'operator') {
1615
					$rules[$parts[1]]['operator'] = (int)$value;
1616
				} elseif ($parts[2] == 'input') {
1617
					$rules[$parts[1]]['input'] = $value;
1618
				}
1619
			}
1620
		}
1621
1622
		// validate the rule parameters
1623
		if (\count($rules) === 0) {
1624
			throw new AmpacheException('At least one rule must be given', 400);
1625
		}
1626
		foreach ($rules as $rule) {
1627
			if (\count($rule) != 3) {
1628
				throw new AmpacheException('All rules must be given as triplet "rule_N", "rule_N_operator", "rule_N_input"', 400);
1629
			}
1630
		}
1631
1632
		return $rules;
1633
	}
1634
1635
	// NOTE: alias rule names should be resolved to their base form before calling this
1636
	private static function advSearchInterpretOperator(int $rule_operator, string $rule) : string {
1637
		// Operator mapping is different for text, numeric, date, boolean, and day rules
1638
1639
		$textRules = [
1640
			'anywhere', 'title', 'song', 'album', 'artist', 'podcast', 'podcast_episode', 'album_artist', 'song_artist',
1641
			'favorite', 'favorite_album', 'favorite_artist', 'genre', 'song_genre', 'album_genre', 'artist_genre',
1642
			'playlist_name', 'type', 'file', 'mbid', 'mbid_album', 'mbid_artist', 'mbid_song'
1643
		];
1644
		// text but no support planned: 'composer', 'summary', 'placeformed', 'release_type', 'release_status', 'barcode',
1645
		// 'catalog_number', 'label', 'comment', 'lyrics', 'username', 'category'
1646
1647
		$numericRules = [
1648
			'track', 'year', 'original_year', 'myrating', 'rating', 'songrating', 'albumrating', 'artistrating',
1649
			'played_times', 'album_count', 'song_count', 'disk_count', 'time', 'bitrate'
1650
		];
1651
		// numeric but no support planned: 'yearformed', 'skipped_times', 'play_skip_ratio', 'image_height', 'image_width'
1652
1653
		$numericLimitRules = ['recent_played', 'recent_added', 'recent_updated'];
1654
1655
		$dateOrDayRules = ['added', 'updated', 'pubdate', 'last_play'];
1656
1657
		$booleanRules = [
1658
			'played', 'myplayed', 'myplayedalbum', 'myplayedartist', 'has_image', 'no_genre',
1659
			'my_flagged', 'my_flagged_album', 'my_flagged_artist'
1660
		];
1661
		// boolean but no support planned: 'smartplaylist', 'possible_duplicate', 'possible_duplicate_album'
1662
1663
		$booleanNumericRules = ['playlist', 'album_artist_id' /* own extension */];
1664
		// boolean numeric but no support planned: 'license', 'state', 'catalog'
1665
1666
		if (\in_array($rule, $textRules)) {
1667
			switch ($rule_operator) {
1668
				case 0: return 'contain';		// contains
1669
				case 1: return 'notcontain';	// does not contain;
1670
				case 2: return 'start';			// starts with
1671
				case 3: return 'end';			// ends with;
1672
				case 4: return 'is';			// is
1673
				case 5: return 'isnot';			// is not
1674
				case 6: return 'sounds';		// sounds like
1675
				case 7: return 'notsounds';		// does not sound like
1676
				case 8: return 'regexp';		// matches regex
1677
				case 9: return 'notregexp';		// does not match regex
1678
				default: throw new AmpacheException("Search operator '$rule_operator' not supported for 'text' type rules", 400);
1679
			}
1680
		} elseif (\in_array($rule, $numericRules)) {
1681
			switch ($rule_operator) {
1682
				case 0: return '>=';
1683
				case 1: return '<=';
1684
				case 2: return '=';
1685
				case 3: return '!=';
1686
				case 4: return '>';
1687
				case 5: return '<';
1688
				default: throw new AmpacheException("Search operator '$rule_operator' not supported for 'numeric' type rules", 400);
1689
			}
1690
		} elseif (\in_array($rule, $numericLimitRules)) {
1691
			return 'limit';
1692
		} elseif (\in_array($rule, $dateOrDayRules)) {
1693
			switch ($rule_operator) {
1694
				case 0: return 'before';
1695
				case 1: return 'after';
1696
				default: throw new AmpacheException("Search operator '$rule_operator' not supported for 'date' or 'day' type rules", 400);
1697
			}
1698
		} elseif (\in_array($rule, $booleanRules)) {
1699
			switch ($rule_operator) {
1700
				case 0: return 'true';
1701
				case 1: return 'false';
1702
				default: throw new AmpacheException("Search operator '$rule_operator' not supported for 'boolean' type rules", 400);
1703
			}
1704
		} elseif (\in_array($rule, $booleanNumericRules)) {
1705
			switch ($rule_operator) {
1706
				case 0: return 'equal';
1707
				case 1: return 'ne';
1708
				default: throw new AmpacheException("Search operator '$rule_operator' not supported for 'boolean numeric' type rules", 400);
1709
			}
1710
		} else {
1711
			throw new AmpacheException("Search rule '$rule' not supported", 400);
1712
		}
1713
	}
1714
1715
	private static function advSearchConvertInput(string $input, string $rule) : string {
1716
		switch ($rule) {
1717
			case 'last_play':
1718
				// days diff to ISO date
1719
				$date = new \DateTime("$input days ago");
1720
				return $date->format(BaseMapper::SQL_DATE_FORMAT);
1721
			case 'time':
1722
				// minutes to seconds
1723
				return (string)(int)((float)$input * 60);
1724
			default:
1725
				return $input;
1726
		}
1727
	}
1728
1729
	private function getAllTracksPlaylist() : Playlist {
1730
		$pl = new class extends Playlist {
1731
			public int $trackCount = 0;
1732
			public function getTrackCount() : int {
1733
				return $this->trackCount;
1734
			}
1735
		};
1736
		$pl->id = self::ALL_TRACKS_PLAYLIST_ID;
1737
		$pl->name = $this->l10n->t('All tracks');
1738
		$pl->userId = $this->userId();
1739
		$pl->updated = $this->library->latestUpdateTime($pl->userId)->format('c');
1740
		$pl->trackCount = $this->trackBusinessLayer->count($pl->userId);
1741
		$pl->setTrackIdsFromArray($this->trackBusinessLayer->findAllIds($pl->userId));
1742
		$pl->setReadOnly(true);
1743
1744
		return $pl;
1745
	}
1746
1747
	/** @phpstan-param BusinessLayer<covariant Entity> $businessLayer */
1748
	private function getCover(int $entityId, BusinessLayer $businessLayer, ?int $size) : Response {
1749
		$userId = $this->userId();
1750
		$userFolder = $this->librarySettings->getFolder($userId);
1751
1752
		try {
1753
			$entity = $businessLayer->find($entityId, $userId);
1754
			$coverData = $this->coverService->getCover($entity, $userId, $userFolder, $size);
1755
			if ($coverData !== null) {
1756
				return new FileResponse($coverData);
1757
			}
1758
		} catch (BusinessLayerException $e) {
1759
			return new ErrorResponse(Http::STATUS_NOT_FOUND, 'entity not found');
1760
		}
1761
1762
		return new ErrorResponse(Http::STATUS_NOT_FOUND, 'entity has no cover');
1763
	}
1764
1765
	private static function parseTimeParameters(?string $add=null, ?string $update=null) : array {
1766
		// It's not documented, but Ampache supports also specifying date range on `add` and `update` parameters
1767
		// by using '/' as separator. If there is no such separator, then the value is used as a lower limit.
1768
		$add = Util::explode('/', $add);
1769
		$update = Util::explode('/', $update);
1770
		$addMin = $add[0] ?? null;
1771
		$addMax = $add[1] ?? null;
1772
		$updateMin = $update[0] ?? null;
1773
		$updateMax = $update[1] ?? null;
1774
1775
		return [$addMin, $addMax, $updateMin, $updateMax];
1776
	}
1777
1778
	/** @phpstan-param BusinessLayer<covariant Entity> $businessLayer */
1779
	private function findEntities(
1780
			BusinessLayer $businessLayer, ?string $filter, bool $exact, ?int $limit=null, ?int $offset=null, ?string $add=null, ?string $update=null) : array {
1781
1782
		$userId = $this->userId();
1783
1784
		list($addMin, $addMax, $updateMin, $updateMax) = self::parseTimeParameters($add, $update);
1785
1786
		if ($filter) {
1787
			$matchMode = $exact ? MatchMode::Exact : MatchMode::Substring;
1788
			return $businessLayer->findAllByName($filter, $userId, $matchMode, $limit, $offset, $addMin, $addMax, $updateMin, $updateMax);
1789
		} else {
1790
			return $businessLayer->findAll($userId, SortBy::Name, $limit, $offset, $addMin, $addMax, $updateMin, $updateMax);
1791
		}
1792
	}
1793
1794
	/**
1795
	 * @param PodcastChannel[] $channels
1796
	 */
1797
	private function injectEpisodesToChannels(array $channels) : void {
1798
		$userId = $this->userId();
1799
		$allChannelsIncluded = (\count($channels) === $this->podcastChannelBusinessLayer->count($userId));
1800
		$this->podcastService->injectEpisodes($channels, $userId, $allChannelsIncluded);
1801
	}
1802
1803
	private function isInternalSession() : bool {
1804
		return $this->session !== null && $this->session->getToken() === 'internal';
1805
	}
1806
1807
	private function createAmpacheActionUrl(string $action, int $id, ?string $type=null) : string {
1808
		\assert($this->session !== null);
1809
		if ($this->isInternalSession()) {
1810
			$route = 'music.ampache.internalApi';
1811
			$authArg = '';
1812
		} else {
1813
			$route = $this->jsonMode ? 'music.ampache.jsonApi' : 'music.ampache.xmlApi';
1814
			$authArg = '&auth=' . $this->session->getToken();
1815
		}
1816
		return $this->urlGenerator->linkToRouteAbsolute($route)
1817
				. "?action=$action&id=$id" . $authArg
1818
				. (!empty($type) ? "&type=$type" : '');
1819
	}
1820
1821
	private function createCoverUrl(Entity $entity) : string {
1822
		if ($entity instanceof Album) {
1823
			$type = 'album';
1824
		} elseif ($entity instanceof Artist) {
1825
			$type = 'artist';
1826
		} elseif ($entity instanceof Playlist) {
1827
			$type = 'playlist';
1828
		} else {
1829
			throw new AmpacheException('unexpected entity type for cover image', 500);
1830
		}
1831
1832
		\assert($this->session !== null);
1833
		if ($this->isInternalSession()) {
1834
			// For internal clients, we don't need to create URLs with permanent but API-key-specific tokens
1835
			return $this->createAmpacheActionUrl('get_art', $entity->getId(), $type);
1836
		} else {
1837
			// Scrutinizer doesn't understand that the if-else above guarantees that getCoverFileId() may be called only on Album or Artist
1838
			if ($type === 'playlist' || $entity->/** @scrutinizer ignore-call */getCoverFileId()) {
1839
				$id = $entity->getId();
1840
				$token = $this->imageService->getToken($type, $id, $this->session->getAmpacheUserId());
1841
				return $this->urlGenerator->linkToRouteAbsolute('music.ampacheImage.image') . "?object_type=$type&object_id=$id&token=$token";
1842
			} else {
1843
				return '';
1844
			}
1845
		}
1846
	}
1847
1848
	private static function indexIsWithinOffsetAndLimit(int $index, ?int $offset, ?int $limit) : bool {
1849
		$offset = \intval($offset); // missing offset is interpreted as 0-offset
1850
		return ($limit === null) || ($index >= $offset && $index < $offset + $limit);
1851
	}
1852
1853
	private function prefixAndBaseName(?string $name) : array {
1854
		return StringUtil::splitPrefixAndBasename($name, $this->namePrefixes);
1855
	}
1856
1857
	private function renderAlbumOrArtistRef(int $id, string $name) : array {
1858
		if ($this->apiMajorVersion() > 5) {
1859
			return [
1860
				'id' => (string)$id,
1861
				'name' => $name,
1862
			] + $this->prefixAndBaseName($name);
1863
		} else {
1864
			return [
1865
				'id' => (string)$id,
1866
				'text' => $name
1867
			];
1868
		}
1869
	}
1870
1871
	/**
1872
	 * @param Artist[] $artists
1873
	 */
1874
	private function renderArtists(array $artists) : array {
1875
		$userId = $this->userId();
1876
		$genreMap = ArrayUtil::createIdLookupTable($this->genreBusinessLayer->findAll($userId));
1877
		$genreKey = $this->genreKey();
1878
		// In APIv3-4, the properties 'albums' and 'songs' were used for the album/song count in case the inclusion of the relevant
1879
		// child objects wasn't requested. APIv5+ has the dedicated properties 'albumcount' and 'songcount' for this purpose.
1880
		$oldCountApi = ($this->apiMajorVersion() < 5);
1881
1882
		return [
1883
			'artist' => \array_map(function (Artist $artist) use ($userId, $genreMap, $genreKey, $oldCountApi) {
1884
				$name = $artist->getNameString($this->l10n);
1885
				$nameParts = $this->prefixAndBaseName($name);
1886
				$albumCount = $this->albumBusinessLayer->countByAlbumArtist($artist->getId());
1887
				$songCount = $this->trackBusinessLayer->countByArtist($artist->getId());
1888
				$albums = $artist->getAlbums();
1889
				$songs = $artist->getTracks();
1890
1891
				$apiArtist = [
1892
					'id' => (string)$artist->getId(),
1893
					'name' => $name,
1894
					'prefix' => $nameParts['prefix'],
1895
					'basename' => $nameParts['basename'],
1896
					'albums' => ($albums !== null) ? $this->renderAlbums($albums) : ($oldCountApi ? $albumCount : null),
1897
					'albumcount' => $albumCount,
1898
					'songs' => ($songs !== null) ? $this->renderSongs($songs) : ($oldCountApi ? $songCount : null),
1899
					'songcount' => $songCount,
1900
					'time' => $this->trackBusinessLayer->totalDurationByArtist($artist->getId()),
1901
					'art' => $this->createCoverUrl($artist),
1902
					'has_art' => $artist->getCoverFileId() !== null,
1903
					'rating' => $artist->getRating(),
1904
					'preciserating' => $artist->getRating(),
1905
					'flag' => !empty($artist->getStarred()),
1906
					$genreKey => \array_map(fn($genreId) => [
1907
						'id' => (string)$genreId,
1908
						'text' => $genreMap[$genreId]->getNameString($this->l10n),
1909
						'count' => 1
1910
					], $this->trackBusinessLayer->getGenresByArtistId($artist->getId(), $userId))
1911
				];
1912
1913
				if ($this->jsonMode) {
1914
					// Remove an unnecessary level on the JSON API
1915
					if ($albums !== null) {
1916
						$apiArtist['albums'] = $apiArtist['albums']['album'];
1917
					}
1918
					if ($songs !== null) {
1919
						$apiArtist['songs'] = $apiArtist['songs']['song'];
1920
					}
1921
				}
1922
1923
				return $apiArtist;
1924
			}, $artists)
1925
		];
1926
	}
1927
1928
	/**
1929
	 * @param Album[] $albums
1930
	 */
1931
	private function renderAlbums(array $albums) : array {
1932
		$genreKey = $this->genreKey();
1933
		$apiMajor = $this->apiMajorVersion();
1934
		// In APIv6 JSON format, there is a new property `artists` with an array value
1935
		$includeArtists = ($this->jsonMode && $apiMajor > 5);
1936
		// In APIv3-4, the property 'tracks' was used for the song count in case the inclusion of songs wasn't requested.
1937
		// APIv5+ has the property 'songcount' for this and 'tracks' may only contain objects.
1938
		$tracksMayDenoteCount = ($apiMajor < 5);
1939
1940
		return [
1941
			'album' => \array_map(function (Album $album) use ($genreKey, $includeArtists, $tracksMayDenoteCount) {
1942
				$name = $album->getNameString($this->l10n);
1943
				$nameParts = $this->prefixAndBaseName($name);
1944
				$songCount = $this->trackBusinessLayer->countByAlbum($album->getId());
1945
				$songs = $album->getTracks();
1946
1947
				$apiAlbum = [
1948
					'id' => (string)$album->getId(),
1949
					'name' => $name,
1950
					'prefix' => $nameParts['prefix'],
1951
					'basename' => $nameParts['basename'],
1952
					'artist' => $this->renderAlbumOrArtistRef(
1953
						$album->getAlbumArtistId(),
1954
						$album->getAlbumArtistNameString($this->l10n)
1955
					),
1956
					'tracks' => ($songs !== null) ? $this->renderSongs($songs, false) : ($tracksMayDenoteCount ? $songCount : null),
1957
					'songcount' => $songCount,
1958
					'diskcount' => $album->getNumberOfDisks(),
1959
					'time' => $this->trackBusinessLayer->totalDurationOfAlbum($album->getId()),
1960
					'rating' => $album->getRating(),
1961
					'preciserating' => $album->getRating(),
1962
					'year' => $album->yearToAPI(),
1963
					'art' => $this->createCoverUrl($album),
1964
					'has_art' => $album->getCoverFileId() !== null,
1965
					'flag' => !empty($album->getStarred()),
1966
					$genreKey => \array_map(fn($genre) => [
1967
						'id' => (string)$genre->getId(),
1968
						'text' => $genre->getNameString($this->l10n),
1969
						'count' => 1
1970
					], $album->getGenres() ?? [])
1971
				];
1972
				if ($includeArtists) {
1973
					$apiAlbum['artists'] = [$apiAlbum['artist']];
1974
				}
1975
				if ($this->jsonMode && $songs !== null) {
1976
					// Remove an unnecessary level on the JSON API
1977
					$apiAlbum['tracks'] = $apiAlbum['tracks']['song'];
1978
				}
1979
1980
				return $apiAlbum;
1981
			}, $albums)
1982
		];
1983
	}
1984
1985
	/**
1986
	 * @param Track[] $tracks
1987
	 */
1988
	private function renderSongs(array $tracks, bool $injectAlbums=true) : array {
1989
		if ($injectAlbums) {
1990
			$this->albumBusinessLayer->injectAlbumsToTracks($tracks, $this->userId());
1991
		}
1992
1993
		$createPlayUrl = fn(Track $track) => $this->createAmpacheActionUrl('stream', $track->getId());
1994
		$createImageUrl = function(Track $track) : string {
1995
			$album = $track->getAlbum();
1996
			return ($album !== null && $album->getId() !== null) ? $this->createCoverUrl($album) : '';
1997
		};
1998
		$renderRef = fn(int $id, string $name) => $this->renderAlbumOrArtistRef($id, $name);
1999
		$genreKey = $this->genreKey();
2000
		// In APIv6 JSON format, there is a new property `artists` with an array value
2001
		$includeArtists = ($this->jsonMode && $this->apiMajorVersion() > 5);
2002
2003
		return [
2004
			'song' => \array_map(
2005
				fn($t) => $t->toAmpacheApi($this->l10n, $createPlayUrl, $createImageUrl, $renderRef, $genreKey, $includeArtists),
2006
				$tracks
2007
			)
2008
		];
2009
	}
2010
2011
	/**
2012
	 * @param Playlist[] $playlists
2013
	 */
2014
	private function renderPlaylists(array $playlists, bool $includeTracks=false) : array {
2015
		$createImageUrl = function(Playlist $playlist) : string {
2016
			if ($playlist->getId() === self::ALL_TRACKS_PLAYLIST_ID) {
2017
				return '';
2018
			} else {
2019
				return $this->createCoverUrl($playlist);
2020
			}
2021
		};
2022
2023
		$result = [
2024
			'playlist' => \array_map(fn($p) => $p->toAmpacheApi($createImageUrl, $includeTracks), $playlists)
2025
		];
2026
2027
		// annoyingly, the structure of the included tracks is quite different in JSON compared to XML
2028
		if ($includeTracks && $this->jsonMode) {
2029
			foreach ($result['playlist'] as &$apiPlaylist) {
2030
				$apiPlaylist['items'] = ArrayUtil::convertKeys($apiPlaylist['items']['playlisttrack'], ['text' => 'playlisttrack']);
2031
			}
2032
		}
2033
2034
		return $result;
2035
	}
2036
2037
	/**
2038
	 * @param PodcastChannel[] $channels
2039
	 */
2040
	private function renderPodcastChannels(array $channels) : array {
2041
		return [
2042
			'podcast' => \array_map(fn($c) => $c->toAmpacheApi(), $channels)
2043
		];
2044
	}
2045
2046
	/**
2047
	 * @param PodcastEpisode[] $episodes
2048
	 */
2049
	private function renderPodcastEpisodes(array $episodes) : array {
2050
		return [
2051
			'podcast_episode' => \array_map(fn($e) => $e->toAmpacheApi(
2052
				fn($episode) => $this->createAmpacheActionUrl('get_art', $episode->getChannelId(), 'podcast'),
2053
				fn($episode) => $this->createAmpacheActionUrl('stream', $episode->getId(), 'podcast_episode')
2054
			), $episodes)
2055
		];
2056
	}
2057
2058
	/**
2059
	 * @param RadioStation[] $stations
2060
	 */
2061
	private function renderLiveStreams(array $stations) : array {
2062
		$createImageUrl = fn(RadioStation $station) => $this->createAmpacheActionUrl('get_art', $station->getId(), 'live_stream');
2063
2064
		return [
2065
			'live_stream' => \array_map(fn($s) => $s->toAmpacheApi($createImageUrl), $stations)
2066
		];
2067
	}
2068
2069
	/**
2070
	 * @param Genre[] $genres
2071
	 */
2072
	private function renderTags(array $genres) : array {
2073
		return [
2074
			'tag' => \array_map(fn($g) => $g->toAmpacheApi($this->l10n), $genres)
2075
		];
2076
	}
2077
2078
	/**
2079
	 * @param Genre[] $genres
2080
	 */
2081
	private function renderGenres(array $genres) : array {
2082
		return [
2083
			'genre' => \array_map(fn($g) => $g->toAmpacheApi($this->l10n), $genres)
2084
		];
2085
	}
2086
2087
	/**
2088
	 * @param Bookmark[] $bookmarks
2089
	 */
2090
	private function renderBookmarks(array $bookmarks, int $include=0) : array {
2091
		$renderEntry = null;
2092
2093
		if ($include) {
2094
			$renderEntry = function(string $type, int $id) {
2095
				$businessLayer = $this->getBusinessLayer($type);
2096
				$entity = $businessLayer->find($id, $this->userId());
2097
				return $this->renderEntities([$entity], $type)[$type][0];
2098
			};
2099
		}
2100
2101
		return [
2102
			'bookmark' => \array_map(fn($b) => $b->toAmpacheApi($renderEntry), $bookmarks)
2103
		];
2104
	}
2105
2106
	/**
2107
	 * @param Track[] $tracks
2108
	 */
2109
	private function renderSongsIndex(array $tracks) : array {
2110
		return [
2111
			'song' => \array_map(fn($track) => [
2112
				'id' => (string)$track->getId(),
2113
				'title' => $track->getTitle(),
2114
				'name' => $track->getTitle(),
2115
				'artist' => $this->renderAlbumOrArtistRef($track->getArtistId(), $track->getArtistNameString($this->l10n)),
2116
				'album' => $this->renderAlbumOrArtistRef($track->getAlbumId(), $track->getAlbumNameString($this->l10n))
2117
			], $tracks)
2118
		];
2119
	}
2120
2121
	/**
2122
	 * @param Album[] $albums
2123
	 */
2124
	private function renderAlbumsIndex(array $albums) : array {
2125
		return [
2126
			'album' => \array_map(function ($album) {
2127
				$name = $album->getNameString($this->l10n);
2128
				$nameParts = $this->prefixAndBaseName($name);
2129
2130
				return [
2131
					'id' => (string)$album->getId(),
2132
					'name' => $name,
2133
					'prefix' => $nameParts['prefix'],
2134
					'basename' => $nameParts['basename'],
2135
					'artist' => $this->renderAlbumOrArtistRef($album->getAlbumArtistId(), $album->getAlbumArtistNameString($this->l10n))
2136
				];
2137
			}, $albums)
2138
		];
2139
	}
2140
2141
	/**
2142
	 * @param Artist[] $artists
2143
	 */
2144
	private function renderArtistsIndex(array $artists) : array {
2145
		return [
2146
			'artist' => \array_map(function ($artist) {
2147
				$userId = $this->userId();
2148
				$albums = $this->albumBusinessLayer->findAllByArtist($artist->getId(), $userId);
2149
				$name = $artist->getNameString($this->l10n);
2150
				$nameParts = $this->prefixAndBaseName($name);
2151
2152
				return [
2153
					'id' => (string)$artist->getId(),
2154
					'name' => $name,
2155
					'prefix' => $nameParts['prefix'],
2156
					'basename' => $nameParts['basename'],
2157
					'album' => \array_map(
2158
						fn($album) => $this->renderAlbumOrArtistRef($album->getId(), $album->getNameString($this->l10n)),
2159
						$albums
2160
					)
2161
				];
2162
			}, $artists)
2163
		];
2164
	}
2165
2166
	/**
2167
	 * @param Playlist[] $playlists
2168
	 */
2169
	private function renderPlaylistsIndex(array $playlists) : array {
2170
		return [
2171
			'playlist' => \array_map(fn($playlist) => [
2172
				'id' => (string)$playlist->getId(),
2173
				'name' => $playlist->getName(),
2174
				'playlisttrack' => $playlist->getTrackIdsAsArray()
2175
			], $playlists)
2176
		];
2177
	}
2178
2179
	/**
2180
	 * @param PodcastChannel[] $channels
2181
	 */
2182
	private function renderPodcastChannelsIndex(array $channels) : array {
2183
		// The v4 API spec does not give any examples of this, and the v5 example is almost identical to the v4 "normal" result
2184
		return $this->renderPodcastChannels($channels);
2185
	}
2186
2187
	/**
2188
	 * @param PodcastEpisode[] $episodes
2189
	 */
2190
	private function renderPodcastEpisodesIndex(array $episodes) : array {
2191
		// The v4 API spec does not give any examples of this, and the v5 example is almost identical to the v4 "normal" result
2192
		return $this->renderPodcastEpisodes($episodes);
2193
	}
2194
2195
	/**
2196
	 * @param RadioStation[] $stations
2197
	 */
2198
	private function renderLiveStreamsIndex(array $stations) : array {
2199
		// The API spec gives no examples of this, but testing with Ampache demo server revealed that the format is identical to the "full" format
2200
		return $this->renderLiveStreams($stations);
2201
	}
2202
2203
	/**
2204
	 * @param Entity[] $entities
2205
	 */
2206
	private function renderEntityIds(array $entities, string $key = 'id') : array {
2207
		return [$key => ArrayUtil::extractIds($entities)];
2208
	}
2209
2210
	/**
2211
	 * Render the way used by `action=index` when `include=0`
2212
	 * @param Entity[] $entities
2213
	 */
2214
	private function renderEntityIdIndex(array $entities, string $type) : array {
2215
		// the structure is quite different for JSON compared to XML
2216
		if ($this->jsonMode) {
2217
			return $this->renderEntityIds($entities, $type);
2218
		} else {
2219
			return [$type => \array_map(
2220
				fn($entity) => ['id' => $entity->getId()],
2221
				$entities
2222
			)];
2223
		}
2224
	}
2225
2226
	/**
2227
	 * Render the way used by `action=index` when `include=1`
2228
	 * @param array<int, int[]> $idsWithChildren
2229
	 */
2230
	private function renderIdsWithChildren(array $idsWithChildren, string $type, string $childType) : array {
2231
		// the structure is quite different for JSON compared to XML
2232
		if ($this->jsonMode) {
2233
			foreach ($idsWithChildren as &$children) {
2234
				$children = \array_map(fn($childId) => ['id' => $childId, 'type' => $childType], $children);
2235
			}
2236
			return [$type => $idsWithChildren];
2237
		} else {
2238
			return [$type => \array_map(fn($id, $childIds) => [
2239
				'id' => $id,
2240
				$childType => \array_map(fn($id) => ['id' => $id], $childIds)
2241
			], \array_keys($idsWithChildren), $idsWithChildren)];
2242
		}
2243
	}
2244
2245
	/**
2246
	 * Array is considered to be "indexed" if its first element has numerical key.
2247
	 * Empty array is considered to be "indexed".
2248
	 */
2249
	private static function arrayIsIndexed(array $array) : bool {
2250
		\reset($array);
2251
		return empty($array) || \is_int(\key($array));
2252
	}
2253
2254
	/**
2255
	 * The JSON API has some asymmetries with the XML API. This function makes the needed
2256
	 * translations for the result content before it is converted into JSON.
2257
	 */
2258
	private function prepareResultForJsonApi(array $content) : array {
2259
		$apiVer = $this->apiMajorVersion();
2260
2261
		// Special handling is needed for responses returning an array of library entities,
2262
		// depending on the API version. In these cases, the outermost array is of associative
2263
		// type with a single value which is a non-associative array.
2264
		if (\count($content) === 1 && !self::arrayIsIndexed($content)
2265
				&& \is_array(\current($content)) && self::arrayIsIndexed(\current($content))) {
2266
			// In API versions < 5, the root node is an anonymous array. Unwrap the outermost array.
2267
			if ($apiVer < 5) {
2268
				$content = \array_pop($content);
2269
			}
2270
			// In later versions, the root object has a named array for plural actions (like "songs", "artists").
2271
			// For singular actions (like "song", "artist"), the root object contains directly the entity properties.
2272
			else {
2273
				$action = $this->request->getParam('action');
2274
				$plural = (\substr($action, -1) === 's' || \in_array($action, ['get_similar', 'advanced_search', 'search', 'list', 'index']));
2275
2276
				// In APIv5, the action "album" is an exception, it is formatted as if it was a plural action.
2277
				// This outlier has been fixed in APIv6.
2278
				$api5albumOddity = ($apiVer === 5 && $action === 'album');
2279
2280
				// The actions "user_preference" and "system_preference" are another kind of outliers in APIv5,
2281
				// their responses are anonymous 1-item arrays. This got fixed in the APIv6.0.1
2282
				$api5preferenceOddity = ($apiVer === 5 && StringUtil::endsWith($action, 'preference'));
2283
2284
				// The action "get_bookmark" works as plural in case the argument all=1 is given
2285
				$allBookmarks = ($action === 'get_bookmark' && $this->request->getParam('all'));
2286
2287
				if ($api5preferenceOddity) {
2288
					$content = \array_pop($content);
2289
				} elseif (!($plural  || $api5albumOddity || $allBookmarks)) {
2290
					$content = \array_pop($content);
2291
					$content = \array_pop($content);
2292
				}
2293
			}
2294
		}
2295
2296
		// In API versions < 6, all boolean valued properties should be converted to 0/1.
2297
		if ($apiVer < 6) {
2298
			ArrayUtil::intCastValues($content, 'is_bool');
2299
		}
2300
2301
		// The key 'text' has a special meaning on XML responses, as it makes the corresponding value
2302
		// to be treated as text content of the parent element. In the JSON API, these are mostly
2303
		// substituted with property 'name', but error responses use the property 'message', instead.
2304
		if (\array_key_exists('error', $content)) {
2305
			$content = ArrayUtil::convertKeys($content, ['text' => 'message']);
2306
		} else {
2307
			$content = ArrayUtil::convertKeys($content, ['text' => 'name']);
2308
		}
2309
		return $content;
2310
	}
2311
2312
	/**
2313
	 * The XML API has some asymmetries with the JSON API. This function makes the needed
2314
	 * translations for the result content before it is converted into XML.
2315
	 */
2316
	private function prepareResultForXmlApi(array $content) : array {
2317
		\reset($content);
2318
		$firstKey = \key($content);
2319
2320
		// all 'entity list' kind of responses shall have the (deprecated) total_count element
2321
		if (\in_array($firstKey, ['song', 'album', 'artist', 'album_artist', 'song_artist',
2322
				'playlist', 'tag', 'genre', 'podcast', 'podcast_episode', 'live_stream'])) {
2323
			$content = ['total_count' => \count($content[$firstKey])] + $content;
2324
		}
2325
2326
		// for some bizarre reason, the 'id' arrays have 'index' attributes in the XML format
2327
		if ($firstKey == 'id') {
2328
			$content['id'] = \array_map(
2329
				fn($id, $index) => ['index' => $index, 'text' => $id],
2330
				$content['id'], \array_keys($content['id'])
2331
			);
2332
		}
2333
2334
		return ['root' => $content];
2335
	}
2336
2337
	private function genreKey() : string {
2338
		return ($this->apiMajorVersion() > 4) ? 'genre' : 'tag';
2339
	}
2340
2341
	private function requestedApiVersion() : ?string {
2342
		// During the handshake, we don't yet have a session but the requested version may be in the request args
2343
		return ($this->session !== null)
2344
			? $this->session->getApiVersion()
2345
			: $this->request->getParam('version');
2346
	}
2347
2348
	private function apiMajorVersion() : int {
2349
		$verString = $this->requestedApiVersion();
2350
		
2351
		if (\is_string($verString) && \strlen($verString)) {
2352
			$ver = (int)$verString[0];
2353
		} else {
2354
			// Default version is 6 unless otherwise defined in config.php
2355
			$ver = (int)$this->config->getSystemValue('music.ampache_api_default_ver', 6);
2356
		}
2357
2358
		// For now, we have three supported major versions. Major version 3 can be sufficiently supported
2359
		// with our "version 4" implementation.
2360
		return (int)Util::limit($ver, 4, 6);
2361
	}
2362
2363
	private function apiVersionString() : string {
2364
		switch ($this->apiMajorVersion()) {
2365
			case 4:		$ver = self::API4_VERSION; break;
2366
			case 5:		$ver = self::API5_VERSION; break;
2367
			case 6:		$ver = self::API6_VERSION; break;
2368
			default:	throw new AmpacheException('Unexpected api major version', 500);
2369
		}
2370
2371
		// Convert the version to the 6-digit legacy format if the client request used this format or there
2372
		// was no version defined by the client but the default version is 4 (Ampache introduced the new
2373
		// version number format in version 5).
2374
		$reqVersion = $this->requestedApiVersion();
2375
		if (($reqVersion !== null && \preg_match('/^\d\d\d\d\d\d$/', $reqVersion) === 1)
2376
			|| ($reqVersion === null && $ver === self::API4_VERSION))
2377
		{
2378
			$ver = \str_replace('.', '', $ver) . '000';
2379
		}
2380
	
2381
		return $ver;
2382
	}
2383
2384
	private function mapApiV4ErrorToV5(int $code) : int {
2385
		switch ($code) {
2386
			case 400:	return 4710;	// bad request
2387
			case 401:	return 4701;	// invalid handshake
2388
			case 403:	return 4703;	// access denied
2389
			case 404:	return 4704;	// not found
2390
			case 405:	return 4705;	// missing
2391
			case 412:	return 4742;	// failed access check
2392
			case 501:	return 4700;	// access control not enabled
2393
			default:	return 5000;	// unexpected (not part of the API spec)
2394
		}
2395
	}
2396
}
2397