Skip to content

Commit b5db5a7

Browse files
committed
Some light code cleanup and refactoring.
1 parent a3317d1 commit b5db5a7

File tree

6 files changed

+175
-94
lines changed

6 files changed

+175
-94
lines changed

classes/Auth.php

Lines changed: 88 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@
1010

1111
class Auth
1212
{
13+
/**
14+
* musickit config status
15+
* @return Array
16+
*/
1317
public static function musickit_config_status(): array
1418
{
1519
$opts = [
@@ -20,7 +24,11 @@ public static function musickit_config_status(): array
2024
return self::configStatus($opts);
2125
}
2226

23-
// config status check
27+
28+
/**
29+
* config status
30+
* @return Array
31+
*/
2432
public static function configStatus(array $opts): array
2533
{
2634
$missing = [];
@@ -51,13 +59,22 @@ public static function configStatus(array $opts): array
5159
];
5260
}
5361

54-
// configuration status convenience wrapper
62+
63+
/**
64+
* configuration status convenience wrapper
65+
* @return Boolean
66+
*/
5567
public static function isConfigured(array $opts): bool
5668
{
5769
return static::configStatus($opts)['ok'] === true;
5870
}
5971

60-
// validate required apple keys in options; return response on error, null on success
72+
73+
/**
74+
* validate required apple keys in options
75+
* return response on error, null on success
76+
* @return Json
77+
*/
6178
public static function validateOptions(array $opts): ?Response
6279
{
6380
$status = static::configStatus($opts);
@@ -72,14 +89,22 @@ public static function validateOptions(array $opts): ?Response
7289
], 400);
7390
}
7491

75-
// minutes to keep cached user token (default: 30 days)
92+
93+
/**
94+
* minutes to keep cached user token (default: 30 days)
95+
* @return Integer
96+
*/
7697
public static function tokenCacheTtl(): int
7798
{
7899
$minutes = (int) option('scottboms.applemusic.tokenCacheTtlMinutes', 60 * 24 * 30);
79100
return max(1, $minutes);
80101
}
81102

82-
// set domain host for cache
103+
104+
/**
105+
* set domain host for cache
106+
* @return String
107+
*/
83108
private static function domainFolder(): string
84109
{
85110
// use kirby request host if available
@@ -97,7 +122,11 @@ private static function domainFolder(): string
97122
return preg_replace('~[^a-z0-9\.\-]+~', '-', $host);
98123
}
99124

100-
// path to persist the per-user music-user-token
125+
126+
/**
127+
* path to persist the per-user music-user-token
128+
* @return String
129+
*/
101130
public static function tokenPath(?string $userId = null): string
102131
{
103132
$uid = $userId ?? (kirby()->user()?->id() ?? 'site');
@@ -106,7 +135,11 @@ public static function tokenPath(?string $userId = null): string
106135
return $root . '/' . $dom . '/scottboms/applemusic/' . $uid . '.json';
107136
}
108137

109-
// store the music-user-token
138+
139+
/**
140+
* store the music-user-token
141+
* @return Boolean
142+
*/
110143
public static function storeToken(string $token, ?string $userId = null): bool
111144
{
112145
$path = static::tokenPath($userId);
@@ -125,7 +158,11 @@ public static function storeToken(string $token, ?string $userId = null): bool
125158
return $ok;
126159
}
127160

128-
// read the music-user-token (cache -> file fallback)
161+
162+
/**
163+
* read the music-user-token (cache -> file fallback)
164+
* @return String
165+
*/
129166
public static function readToken(?string $userId = null): ?string
130167
{
131168
$uid = $userId ?? (kirby()->user()?->id() ?? 'site');
@@ -149,7 +186,11 @@ public static function readToken(?string $userId = null): ?string
149186
return null;
150187
}
151188

152-
// delete cached token
189+
190+
/**
191+
* delete cached token
192+
* @return Boolean
193+
*/
153194
public static function deleteToken(?string $userId = null): bool
154195
{
155196
$uid = $userId ?? (kirby()->user()?->id() ?? 'site');
@@ -160,7 +201,12 @@ public static function deleteToken(?string $userId = null): bool
160201
return F::exists($path) ? F::remove($path) : true;
161202
}
162203

163-
// mint a developer jwt (throws on invalid inputs)
204+
205+
/**
206+
* mint a developer jwt (throws on invalid inputs)
207+
* uses jwt library
208+
* @return String
209+
*/
164210
public static function mintDevToken(array $opts): string
165211
{
166212
$now = \time();
@@ -172,7 +218,11 @@ public static function mintDevToken(array $opts): string
172218
return JWT::encode($payload, $opts['privateKey'], 'ES256', $opts['keyId']);
173219
}
174220

175-
// cached developer token (mint if absent)
221+
222+
/**
223+
* cached developer token (mint if absent)
224+
* @return String
225+
*/
176226
public static function devToken(array $opts): string
177227
{
178228
// scoped by credentials and domain to avoid collisions
@@ -197,7 +247,11 @@ public static function devToken(array $opts): string
197247
return $jwt;
198248
}
199249

200-
// refresh token
250+
251+
/**
252+
* refresh dev token
253+
* @return String
254+
*/
201255
public static function refreshDevToken(array $opts): string
202256
{
203257
$team = (string)($opts['teamId'] ?? 'noteam');
@@ -209,7 +263,10 @@ public static function refreshDevToken(array $opts): string
209263
return static::devToken($opts);
210264
}
211265

212-
// optional cors for dev-token endpoint
266+
/**
267+
* cors for dev-token endpoint
268+
* @return Array
269+
*/
213270
public static function devTokenCorsHeaders(?string $origin, array $allowedOrigins): array
214271
{
215272
$headers = ['Content-Type' => 'application/json'];
@@ -220,7 +277,11 @@ public static function devTokenCorsHeaders(?string $origin, array $allowedOrigin
220277
return $headers;
221278
}
222279

223-
// user must be logged into the panel
280+
281+
/**
282+
* user must be logged into the panel
283+
* @return String
284+
*/
224285
public static function ensurePanelUser()
225286
{
226287
if (!$user = kirby()->user()) {
@@ -229,7 +290,11 @@ public static function ensurePanelUser()
229290
return $user;
230291
}
231292

232-
// must have stored music-user-token
293+
294+
/**
295+
* must have stored music-user-token
296+
* @return String
297+
*/
233298
public static function ensureUserToken(string $userId)
234299
{
235300
$mut = static::readToken($userId);
@@ -239,10 +304,13 @@ public static function ensureUserToken(string $userId)
239304
return $mut;
240305
}
241306

307+
242308
/**
243309
* render the apple music auth page
244-
* $sf can be 'auto' or a storefront code (e.g. 'us'); will be html-escaped.
245-
* $appName/$appBuild are injected as json for MusicKit.configure({ app: { name, build } }).
310+
* $sf can be 'auto' or a storefront code (eg. 'us')
311+
* will be html-escaped.
312+
* $appName/$appBuild are injected as json for MusicKit.configure({ app: { name, build } })
313+
* @return Json
246314
*/
247315
public static function renderAuthPage(string $sf, string $appName, string $appBuild): Response
248316
{
@@ -267,13 +335,15 @@ public static function renderAuthPage(string $sf, string $appName, string $appBu
267335
return new Response(trim($html), 'text/html');
268336
}
269337

338+
270339
/**
271340
* return any saved music-user-token
272341
* priority: configured default user id -> first token file found
342+
* @return String
273343
*/
274344
public static function readAnyToken(): ?string
275345
{
276-
// return valid token
346+
// return a valid token
277347
$dir = \dirname(static::tokenPath('any'));
278348
if (!Dir::exists($dir)) {
279349
return null;

classes/MusicKit.php

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ public static function recentlyPlayedTracks(array $opts, array $params = [], ?st
121121

122122
/**
123123
* get user storefront
124+
* @return String
124125
*/
125126
public static function storefront(array $opts, string $language = 'en-US'): Response
126127
{
@@ -140,9 +141,11 @@ public static function storefront(array $opts, string $language = 'en-US'): Resp
140141
]);
141142
}
142143

144+
143145
/**
144-
* recently played tracks
146+
* get recently played tracks
145147
* keeps existing recentlyPlayedTracks() logic, normalizes the return to response
148+
* @return Array
146149
*/
147150
public static function recentlyPlayed(array $opts, array $params = []): Response
148151
{
@@ -238,11 +241,15 @@ public static function songDetails(string $songId, string $language = 'en-US'):
238241
'previewUrl' => $a['previews'][0]['url'] ?? null,
239242
'duration' => $duration,
240243
'image' => $img,
241-
'raw' => $body, // optional: full response payload
244+
//'raw' => $body, // optional: full response payload
242245
], 200);
243246
}
244247

245-
// get individual album details
248+
249+
/**
250+
* get individual album details
251+
* @return Array
252+
*/
246253
public static function albumDetails(string $albumId, string $language = 'en-US'): Response
247254
{
248255
$opts = static::opts();
@@ -365,16 +372,17 @@ public static function albumDetails(string $albumId, string $language = 'en-US')
365372
'trackCount' => $a['trackCount'],
366373
'totalDuration' => $totalDuration,
367374
'tracks' => $tracks,
368-
//'raw' => $body, // optional: full response payload
375+
//'raw' => $body, // optional: full response payload
369376
], 200);
370377
}
371378

379+
372380
/**
373-
* server-side helper for front-end:
374-
* fetches recently played for the shared token, cache it,
381+
* server-side helper for front-end snippet
382+
* fetches recently played using shared token, caches response,
375383
* and normalize to a render-friendly array
376384
*
377-
* @return Array {items: list<array{id?:string,name:string,artist:string,url:string|null,image:string|null}>, error:?string}
385+
* @return Array
378386
*/
379387
public static function recentForFrontend(int $limit = 12, string $language = 'en-US', int $cacheTtl = 120): array
380388
{
@@ -414,21 +422,16 @@ public static function recentForFrontend(int $limit = 12, string $language = 'en
414422
$img = str_replace(['{w}', '{h}'], [240, 240], $a['artwork']['url']);
415423
}
416424

417-
// convert millis -> MM:SS
418-
$duration = null;
419-
if (isset($a['durationInMillis'])) {
420-
$seconds = (int) floor($a['durationInMillis'] / 1000);
421-
$minutes = floor($seconds / 60);
422-
$secs = $seconds % 60;
423-
$duration = sprintf('%d:%02d', $minutes, $secs);
424-
}
425+
// convert millis -> mm:ss
426+
$duration = $a['durationInMillis'] ?? null;
427+
$songLength = Utils::format_mmss($duration);
425428

426429
return [
427430
'id' => $i['id'] ?? null,
428431
'name' => $a['name'] ?? '',
429432
'artist' => $a['artistName'] ?? '',
430433
'album' => $a['albumName'] ?? '',
431-
'duration' => $duration ?? null,
434+
'duration' => $songLength,
432435
'releaseDate' => $a['releaseDate'] ?? null,
433436
'url' => $a['url'] ?? null,
434437
'image' => $img,

index.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@
159159
],
160160

161161
'info' => [
162-
'version' => '2.3.1',
162+
'version' => '2.3.2',
163163
'homepage' => 'https://github.com/scottboms/kirby-applemusic',
164164
'license' => 'MIT',
165165
'authors' => [[ 'name' => 'Scott Boms' ]],

0 commit comments

Comments
 (0)