Skip to content

Commit 36963f2

Browse files
committed
Improvements to use Kirby's content API for output in the snippet.
1 parent 8fb8c31 commit 36963f2

File tree

4 files changed

+83
-35
lines changed

4 files changed

+83
-35
lines changed

classes/MusicKit.php

Lines changed: 50 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Scottboms\MusicKit\Utils;
88
use Kirby\Http\Response;
99
use Kirby\Http\Remote;
10+
use Kirby\Cms\Content;
1011

1112
class MusicKit
1213
{
@@ -403,64 +404,92 @@ public static function albumDetails(string $albumId, string $language = 'en-US')
403404
* server-side helper for front-end snippet
404405
* fetches recently played using shared token, caches response,
405406
* and normalize to a render-friendly array
407+
*
406408
* @return Array
407409
*/
408-
public static function recentForFrontend(int $limit = 12, string $language = 'en-US', int $cacheTtl = 120): array
410+
public static function recentForFrontend(
411+
int $limit = 12,
412+
string $language = 'en-US',
413+
int $cacheTtl = 120,
414+
bool $asContent = true): array
409415
{
410416
$cache = kirby()->cache('scottboms.applemusic');
411417
$cacheKey = 'am:recent:site:' . md5(json_encode([$limit, $language]));
418+
419+
// try cache (always arrays)
412420
if ($cacheTtl > 0 && ($cached = $cache->get($cacheKey))) {
413-
return $cached;
421+
return static::toContentPayload($cached);
414422
}
415423

424+
// need a shared (site-level) Music-User-Token
416425
$mut = Auth::readAnyToken();
417426
if (!$mut) {
418427
$payload = ['items' => [], 'error' => 'Missing shared Music-User-Token (site)'];
419428
if ($cacheTtl > 0) $cache->set($cacheKey, $payload, $cacheTtl);
420-
return $payload;
429+
return static::toContentPayload($payload);
421430
}
422431

432+
// dev token + fetch from api
423433
$opts = static::opts();
424434
$dev = Auth::devToken($opts);
425-
$resp = static::appleGet(
426-
'/v1/me/recent/played/tracks?limit=' . $limit . '&l=' . rawurlencode($language),
427-
$dev,
428-
$mut
429-
);
430-
$json = json_decode($resp->body() ?? 'null', true);
431-
432-
if (!is_array($json) || $resp->code() >= 400) {
435+
436+
$path = '/v1/me/recent/played/tracks?limit=' . (int)$limit . '&l=' . rawurlencode($language);
437+
$res = static::appleGet($path, $dev, $mut);
438+
$json = json_decode($res->body() ?? 'null', true);
439+
440+
if (!is_array($json) || !isset($json['data'])) {
433441
$payload = ['items' => [], 'error' => 'Apple Music API error'];
434442
if ($cacheTtl > 0) $cache->set($cacheKey, $payload, $cacheTtl);
435-
return $payload;
443+
return static::toContentPayload($payload);
436444
}
437445

438-
// normalize for rendering
446+
// normalize items to cache-friendly arrays
439447
$items = array_map(function ($i) {
440448
$a = $i['attributes'] ?? [];
441449
$img = null;
450+
442451
if (!empty($a['artwork']['url'])) {
443452
$img = str_replace(['{w}', '{h}'], [240, 240], $a['artwork']['url']);
444453
}
445454

446-
// convert millis -> mm:ss
447-
$duration = $a['durationInMillis'] ?? null;
448-
$songLength = Utils::format_mmss($duration);
455+
$id = $i['id'] ?? null;
456+
$url = $a['url'] ?? null;
457+
458+
// if the id starts with i., clear the url (internal ids)
459+
if (is_string($id) && str_starts_with($id, 'i.')) {
460+
$url = null;
461+
}
449462

450463
return [
451-
'id' => $i['id'] ?? null,
464+
'id' => $id,
452465
'name' => $a['name'] ?? '',
453466
'artist' => $a['artistName'] ?? '',
454467
'album' => $a['albumName'] ?? '',
455-
'duration' => $songLength,
456-
'releaseDate' => $a['releaseDate'] ?? null,
457-
'url' => $a['url'] ?? null,
468+
'duration' => Utils::format_mmss($a['durationInMillis'] ?? null),
469+
'releaseDate' => $a['releaseDate'] ?? null, // ISO 8601 (use ->toDate() in templates)
470+
'url' => $url,
458471
'image' => $img,
459472
];
460473
}, $json['data'] ?? []);
461474

462475
$payload = ['items' => $items, 'error' => null];
463-
if ($cacheTtl > 0) $cache->set($cacheKey, $payload, $cacheTtl);
476+
477+
// cache arrays
478+
if ($cacheTtl > 0) {
479+
$cache->set($cacheKey, $payload, $cacheTtl);
480+
}
481+
482+
return static::toContentPayload($payload);
483+
}
484+
485+
486+
/**
487+
* convert ['items' => [array...]] to ['items' => [Content...]]
488+
* @return Array
489+
*/
490+
protected static function toContentPayload(array $payload): array
491+
{
492+
$payload['items'] = array_map(fn ($i) => new Content($i), $payload['items'] ?? []);
464493
return $payload;
465494
}
466495

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.5',
162+
'version' => '2.3.6',
163163
'homepage' => 'https://github.com/scottboms/kirby-applemusic',
164164
'license' => 'MIT',
165165
'authors' => [[ 'name' => 'Scott Boms' ]],

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "scottboms/applemusic",
33
"description": "Apple Music Embed",
44
"author": "Scott Boms <[email protected]>",
5-
"version": "2.3.5",
5+
"version": "2.3.6",
66
"type": "kirby-plugin",
77
"license": "MIT",
88
"scripts": {

snippets/recently-played.php

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
$cacheTtl = (int)($cacheTtl ?? 120);
88

99
$result = MusicKit::recentForFrontend($limit, $language, $cacheTtl);
10+
1011
$items = $result['items'];
1112
$error = $result['error'];
1213
?>
@@ -20,19 +21,37 @@
2021
<p class="am-empty">No items.</p>
2122
<?php else: ?>
2223
<ul class="am-grid">
23-
<?php foreach ($items as $t): ?>
24+
<?php foreach ($items as $song): ?>
2425
<li class="am-card">
25-
<a<?= $t['url'] ? ' href="' . html($t['url']) . '" target="_blank" rel="noopener"' : '' ?>>
26-
<?php if ($t['image']): ?>
27-
<figure>
28-
<img src="<?= html($t['image']) ?>" alt="<?= html($t['name']) ?>" loading="lazy">
29-
</figure>
30-
<?php endif; ?>
31-
<span class="am-title"><?= html($t['name']) ?></span>
32-
<span class="am-subtitle"><?= html($t['album']) ?></span>
33-
<span class="am-sub"><?= html($t['artist']) ?></span>
34-
<span class="am-sub"><?= html($t['duration']) ?></span>
35-
</a>
26+
<?php if ($song->url()->isNotEmpty()): ?>
27+
<a href="<?= $song->url() ?>" target="_blank" rel="noopener">
28+
<?php endif ?>
29+
30+
<?php if ($song->image()->isNotEmpty()): ?>
31+
<figure>
32+
<img src="<?= $song->image() ?>" alt="<?= $song->name() ?>" loading="lazy">
33+
</figure>
34+
<?php endif ?>
35+
36+
<?php if ($song->name()->isNotEmpty()): ?>
37+
<span class="am-title"><?= $song->name() ?></span>
38+
<?php endif ?>
39+
40+
<?php if ($song->album()->isNotEmpty()): ?>
41+
<span class="am-subtitle"><?= $song->album() ?></span>
42+
<?php endif ?>
43+
44+
<?php if ($song->artist()->isNotEmpty()): ?>
45+
<span class="am-sub"><?= $song->artist() ?></span>
46+
<?php endif ?>
47+
48+
<?php if ($song->duration()->isNotEmpty()): ?>
49+
<span class="am-sub"><?= $song->duration() ?></span>
50+
<?php endif ?>
51+
52+
<?php if ($song->url()->isNotEmpty()): ?>
53+
</a>
54+
<?php endif ?>
3655
</li>
3756
<?php endforeach; ?>
3857
</ul>

0 commit comments

Comments
 (0)