source: Klonkt/src/services/AudioEmbedService.js@ a85f539

main
Last change on this file since a85f539 was a85f539, checked in by Robin <roboburr@…>, 8 weeks ago

Fix: bare .webm/.mp4/.mp3 URLs render a native player

autoembed() and [[embed:]] now detect direct media-file URLs and emit a
<video>/<audio> element (was: left as a plain link). Sanitizer allows
video/audio/source with a tight attr + http(s)-scheme allowlist so
hand-authored and federated-in players survive. detectProvider() is left
untouched so the timeline/cover callers that switch on provider slugs are
unaffected.

Co-Authored-By: Claude Opus 4.8 <noreply@…>

  • Property mode set to 100644
File size: 29.9 KB
Line 
1/**
2 * AudioEmbedService — Parse URLs and return embed HTML
3 * Supports: Spotify, Bandcamp, SoundCloud, Apple Music, YouTube, Vimeo
4 *
5 * Usage in post content:
6 * <p>https://open.spotify.com/track/123abc</p>
7 * →
8 * <figure class="folio-embed folio-embed--spotify">
9 * <iframe src="..."></iframe>
10 * </figure>
11 */
12
13// "Open in" icons (brand-colored via CSS .pat-link--).
14const OPEN_IN_SVG = {
15 spotify: '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2a10 10 0 100 20 10 10 0 000-20zm4.6 14.42a.62.62 0 01-.86.21c-2.35-1.44-5.3-1.76-8.79-.96a.62.62 0 11-.28-1.21c3.8-.87 7.07-.5 9.71 1.11.3.18.39.57.22.85zm1.23-2.73a.78.78 0 01-1.07.26c-2.69-1.66-6.79-2.14-9.97-1.17a.78.78 0 11-.45-1.49c3.63-1.1 8.15-.56 11.24 1.33.36.22.48.7.25 1.07zm.1-2.85C14.66 8.95 9.4 8.78 6.3 9.72a.93.93 0 11-.54-1.79c3.56-1.08 9.37-.87 13.07 1.33a.94.94 0 01-.96 1.61z"/></svg>',
16 youtube: '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M23 7.1a3 3 0 00-2.1-2.12C19.04 4.5 12 4.5 12 4.5s-7.04 0-8.9.48A3 3 0 001 7.1 31.2 31.2 0 00.5 12 31.2 31.2 0 001 16.9a3 3 0 002.1 2.12c1.86.48 8.9.48 8.9.48s7.04 0 8.9-.48A3 3 0 0023 16.9 31.2 31.2 0 0023.5 12 31.2 31.2 0 0023 7.1zM9.75 15.5v-7l6 3.5-6 3.5z"/></svg>',
17 soundcloud: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M4 14v4M7.5 11v7M11 9v9"/><path d="M14.5 9.5V18h4a3 3 0 100-6 4 4 0 00-4-2.5z"/></svg>',
18};
19
20class AudioEmbedService {
21 // Small "open in" links for a track (Spotify/YouTube/SoundCloud). The hrefs
22 // are already validated server-side (https + correct host only). Returns ''
23 // when no links exist. Placed next to the play button (outside the button →
24 // no conflict with playback).
25 static openInLinks(t) {
26 if (!t) return '';
27 const out = [];
28 const add = (url, key, label) => {
29 if (!url) return;
30 out.push(`<a class="pat-link pat-link--${key}" href="${this.escape(url)}" target="_blank" rel="noopener noreferrer" title="Open in ${label}" aria-label="Open in ${label}">${OPEN_IN_SVG[key]}</a>`);
31 };
32 add(t.link_spotify, 'spotify', 'Spotify');
33 add(t.link_youtube, 'youtube', 'YouTube');
34 add(t.link_soundcloud, 'soundcloud', 'SoundCloud');
35 return out.length ? `<span class="pat-links">${out.join('')}</span>` : '';
36 }
37
38 static detectProvider(url) {
39 if (!url || typeof url !== 'string') return null;
40 url = url.trim();
41
42 // Only embed http(s) URLs. The provider regexes below are NOT anchored,
43 // so without this check e.g. `javascript:alert(1)//youtu.be/x` would match
44 // and land as an embed URL (stored XSS via an [[embed:...]] shortcode —
45 // that text never passes through the HTML sanitizer because it lives in a
46 // text node). The scheme guard excludes javascript:/data:/vbscript: etc.
47 if (!/^https?:\/\//i.test(url)) return null;
48
49 // Spotify
50 if (/open\.spotify\.com\/(track|album|playlist|episode|show)\/([A-Za-z0-9]+)/i.test(url)) {
51 const match = url.match(/\/(track|album|playlist|episode|show)\/([A-Za-z0-9]+)/i);
52 return { provider: 'spotify', type: match[1], id: match[2], url };
53 }
54
55 // Bandcamp
56 if (/bandcamp\.com\/(track|album)/i.test(url)) {
57 return { provider: 'bandcamp', url };
58 }
59
60 // SoundCloud
61 if (/soundcloud\.com/i.test(url)) {
62 return { provider: 'soundcloud', url };
63 }
64
65 // Apple Music
66 if (/music\.apple\.com\/([a-z]{2})\/(?:album|playlist|song)\//i.test(url)) {
67 return { provider: 'applemusic', url };
68 }
69
70 // YouTube — video id is always exactly 11 characters (aligns with the client-side
71 // ytId() in embed-player.js, which also expects {11}).
72 if (/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/|youtube\.com\/live\/)([A-Za-z0-9_-]{11})/i.test(url)) {
73 const match = url.match(/(?:v=|youtu\.be\/|embed\/|shorts\/|live\/)([A-Za-z0-9_-]{11})/i);
74 return { provider: 'youtube', id: match[1], url };
75 }
76
77 // Vimeo
78 if (/vimeo\.com\/(?:video\/)?(\d+)/i.test(url)) {
79 const match = url.match(/\d+/);
80 return { provider: 'vimeo', id: match[0], url };
81 }
82
83 return null;
84 }
85
86 // Direct media files (video/audio) hosted anywhere → a native <video>/<audio>
87 // player. Kept OUT of detectProvider() on purpose: the timeline/cover callers
88 // switch on provider slugs (youtube/spotify/…) and a bare file has none, so
89 // overloading detectProvider would suppress e.g. a PeerTube fallback. Only
90 // autoembed() and [[embed:…]] use this.
91 static MEDIA_FILE_EXT = {
92 video: ['mp4', 'webm', 'm4v', 'mov', 'ogv'],
93 audio: ['mp3', 'ogg', 'oga', 'wav', 'm4a', 'flac', 'opus', 'aac'],
94 };
95
96 static detectMediaFile(url) {
97 if (!url || typeof url !== 'string') return null;
98 if (!/^https?:\/\//i.test(url)) return null;
99 let pathname;
100 try { pathname = new URL(url).pathname.toLowerCase(); } catch { return null; }
101 const ext = (pathname.match(/\.([a-z0-9]+)$/) || [])[1];
102 if (!ext) return null;
103 if (this.MEDIA_FILE_EXT.video.includes(ext)) return { kind: 'video', url };
104 if (this.MEDIA_FILE_EXT.audio.includes(ext)) return { kind: 'audio', url };
105 return null;
106 }
107
108 static mediaFileEmbed(url) {
109 const m = this.detectMediaFile(url);
110 if (!m) return null;
111 const src = this.escape(m.url);
112 if (m.kind === 'video') {
113 return `<figure class="folio-embed folio-embed--video"><video src="${src}" controls preload="metadata" playsinline></video></figure>`;
114 }
115 return `<figure class="folio-embed folio-embed--audio"><audio src="${src}" controls preload="metadata"></audio></figure>`;
116 }
117
118 static generateIframe(provider, config) {
119 switch (provider) {
120 // Custom players (client-side via embed-player.js + the real platform APIs).
121 // We render a placeholder with data attributes instead of the bare platform
122 // iframe, so the embed appears in OUR brand style.
123 case 'youtube':
124 return this.embedPlaceholder('youtube', config.id, 'video',
125 config.url || `https://youtu.be/${config.id}`);
126 case 'soundcloud':
127 return this.embedPlaceholder('soundcloud', config.url, 'track', config.url);
128 case 'spotify':
129 return this.embedPlaceholder('spotify', `spotify:${config.type}:${config.id}`,
130 config.type, config.url || `https://open.spotify.com/${config.type}/${config.id}`);
131 // No JS API (Bandcamp/Apple) or low priority (Vimeo): remain as iframes;
132 // mutual exclusion for these runs via the blur fallback.
133 case 'bandcamp':
134 return this.bandcampIframe(config);
135 case 'applemusic':
136 return this.applemusicIframe(config);
137 case 'vimeo':
138 return this.vimeoIframe(config);
139 default:
140 return null;
141 }
142 }
143
144 /**
145 * Placeholder for a custom player. embed-player.js picks up
146 * .folio-embed[data-embed-provider] and builds the card + player client-side.
147 * ALL values go through escape() — post.content_html is executed unescaped.
148 */
149 static embedPlaceholder(provider, ref, type, url) {
150 const attrs = [
151 `data-embed-provider="${this.escape(provider)}"`,
152 `data-embed-ref="${this.escape(ref)}"`,
153 type ? `data-embed-type="${this.escape(type)}"` : '',
154 `data-embed-url="${this.escape(url)}"`,
155 ].filter(Boolean).join(' ');
156 return `<div class="folio-embed folio-embed--${this.escape(provider)} pcms-embed pcms-embed-card pcms-embed-loading" ${attrs}></div>`;
157 }
158
159 static spotifyIframe({ type, id }) {
160 const src = `https://open.spotify.com/embed/${type}/${id}`;
161 return `
162 <figure class="folio-embed folio-embed--spotify">
163 <iframe src="${this.escape(src)}"
164 style="width:100%;height:152px;border:0;"
165 loading="lazy"
166 allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
167 title="Spotify ${type}"></iframe>
168 </figure>
169 `.trim();
170 }
171
172 static bandcampIframe({ url }) {
173 const encodedUrl = encodeURIComponent(url);
174 const src = `https://bandcamp.com/EmbeddedPlayer/url=${encodedUrl}/size=large/bgcol=faf8f3/linkcol=c2410c/tracklist=false/transparent=true/`;
175 return `
176 <figure class="folio-embed folio-embed--bandcamp">
177 <iframe src="${this.escape(src)}"
178 style="width:100%;height:470px;border:0;"
179 loading="lazy"
180 allow="encrypted-media"
181 title="Bandcamp player"></iframe>
182 </figure>
183 `.trim();
184 }
185
186 static soundcloudIframe({ url }) {
187 const params = {
188 url: url,
189 color: '#ff5500',
190 auto_play: 'false',
191 hide_related: 'true',
192 show_comments: 'false',
193 show_user: 'true',
194 show_reposts: 'false',
195 show_teaser: 'false',
196 visual: 'true'
197 };
198 const query = new URLSearchParams(params).toString();
199 const src = `https://w.soundcloud.com/player/?${query}`;
200 return `
201 <figure class="folio-embed folio-embed--soundcloud">
202 <iframe src="${this.escape(src)}"
203 style="width:100%;height:300px;border:0;"
204 loading="lazy"
205 allow="autoplay; clipboard-write; encrypted-media"
206 title="SoundCloud player"></iframe>
207 </figure>
208 `.trim();
209 }
210
211 static applemusicIframe({ url }) {
212 const match = url.match(/music\.apple\.com\/([a-z]{2}\/(?:album|playlist|song)\/[^/?#]+\/[0-9]+)/i);
213 if (!match) return null;
214 const src = `https://embed.music.apple.com/${match[1]}`;
215 return `
216 <figure class="folio-embed folio-embed--applemusic">
217 <iframe src="${this.escape(src)}"
218 style="width:100%;height:175px;border:0;overflow:hidden;border-radius:8px;"
219 loading="lazy"
220 allow="autoplay; clipboard-write; encrypted-media"
221 title="Apple Music"></iframe>
222 </figure>
223 `.trim();
224 }
225
226 static youtubeIframe({ id }) {
227 const src = `https://www.youtube-nocookie.com/embed/${id}`;
228 return `
229 <figure class="folio-embed folio-embed--youtube">
230 <iframe src="${this.escape(src)}"
231 style="aspect-ratio:16/9;width:100%;height:auto;border:0;"
232 loading="lazy"
233 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
234 allowfullscreen
235 title="YouTube video"></iframe>
236 </figure>
237 `.trim();
238 }
239
240 static vimeoIframe({ id }) {
241 const src = `https://player.vimeo.com/video/${id}`;
242 return `
243 <figure class="folio-embed folio-embed--vimeo">
244 <iframe src="${this.escape(src)}"
245 style="aspect-ratio:16/9;width:100%;height:auto;border:0;"
246 loading="lazy"
247 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
248 allowfullscreen
249 title="Vimeo video"></iframe>
250 </figure>
251 `.trim();
252 }
253
254 /**
255 * Auto-embed: Scan paragraphs containing only a URL.
256 * Handles two markdown-rendered shapes:
257 * <p>https://url</p> (bare URL — when GFM auto-link is off)
258 * <p><a href="https://url">https://url</a></p> (marked GFM auto-link — what we get)
259 * Either way → <figure class="folio-embed">...
260 */
261 static autoembed(html) {
262 if (!html) return html;
263 return html.replace(
264 /<p>\s*(?:<a\b[^>]*?\shref="([^"]+)"[^>]*>[^<]*<\/a>|(https?:\/\/[^\s<>"']+))\s*<\/p>/gi,
265 (match, hrefUrl, bareUrl) => {
266 const url = hrefUrl || bareUrl;
267 const detected = this.detectProvider(url);
268 if (detected) {
269 const iframe = this.generateIframe(detected.provider, detected);
270 return iframe || match;
271 }
272 // Bare media file (…/clip.webm, …/song.mp3) → native player.
273 const media = this.mediaFileEmbed(url);
274 if (media) return media;
275 return match;
276 }
277 );
278 }
279
280 /**
281 * Replace [[embed:<url>]] shortcodes with the platform iframe (YouTube, Spotify,
282 * SoundCloud, Apple Music, Bandcamp, Vimeo). The editor button inserts this
283 * shortcode; bare URL lines also embed automatically via autoembed().
284 * Unsupported/invalid URLs get a clean inline notice.
285 */
286 static embedMediaShortcodes(html) {
287 if (!html) return html;
288 return html.replace(/\[\[embed:([^\]]+)\]\]/gi, (match, rawUrl) => {
289 const url = rawUrl.trim().replace(/&amp;/g, '&');
290 const detected = this.detectProvider(url);
291 if (!detected) {
292 // Bare media file (…/clip.webm, …/song.mp3) → native player.
293 const media = this.mediaFileEmbed(url);
294 if (media) return media;
295 return `<div class="post-embed-missing"><em>Embed: niet-ondersteunde of ongeldige URL.</em></div>`;
296 }
297 return this.generateIframe(detected.provider, detected) || match;
298 });
299 }
300
301 /**
302 * Replace [[track:<id>]] shortcodes with v9-style player markup.
303 * Caller passes a lookup function (id) -> { id, title, artist, url, cover }
304 * where url is already a signed /audio/stream/... URL. Unknown ids → left as-is.
305 */
306 static embedTrackShortcodes(html, trackLookup) {
307 if (!html || typeof trackLookup !== 'function') return html;
308 return html.replace(/\[\[track:([A-Za-z0-9_-]+)\]\]/g, (match, id) => {
309 const t = trackLookup(id);
310 if (!t) return match;
311 const titleH0 = this.escape(t.title || 'Untitled');
312 const artistH0 = this.escape(t.artist || '');
313 const creditBits0 = [this.escape(t.credit || ''), this.escape(t.license || '')].filter(Boolean).join(' · ');
314 // Link-only track (no audio file): no play button, but info + open-in links.
315 if (!t.url) {
316 const coverH0 = this.escape(t.cover || '');
317 const leader0 = coverH0
318 ? `<span class="pat-noplay pat-noplay--cover" style="background-image:url('${coverH0}')" aria-hidden="true"></span>`
319 : `<span class="pat-noplay" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg></span>`;
320 return `<div class="post-audio-track post-audio-track--static" id="track-${id}">
321 ${leader0}
322 <div class="pat-info">
323 <div class="pat-title">${titleH0}</div>
324 ${artistH0 ? `<div class="pat-artist">${artistH0}</div>` : ''}
325 ${creditBits0 ? `<div class="pat-credit">${creditBits0}</div>` : ''}
326 </div>
327 ${this.openInLinks(t)}
328</div>`;
329 }
330 const trackJson = JSON.stringify({
331 id,
332 url: t.url,
333 title: t.title || 'Untitled',
334 artist: t.artist || '',
335 cover: t.cover || '',
336 credit: t.credit || '',
337 license: t.license || '',
338 });
339 const titleH = this.escape(t.title || 'Untitled');
340 const artistH = this.escape(t.artist || '');
341 const urlH = this.escape(t.url);
342 // Visible owner/license line below the track.
343 const creditBits = [this.escape(t.credit || ''), this.escape(t.license || '')].filter(Boolean).join(' · ');
344 const dataAttr = trackJson
345 .replace(/&/g, '&amp;').replace(/'/g, '&#39;').replace(/</g, '&lt;');
346 // id="track-<id>" = anchor so the mini-player can scroll to this element.
347 return `<div class="post-audio-track" id="track-${id}" data-pcms-track-id="${id}" data-pcms-track-url="${urlH}" data-pcms-track='${dataAttr}'>
348 <button type="button" class="pat-play" aria-label="Play ${titleH}">
349 <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 4l12 8-12 8z"/></svg>
350 </button>
351 <div class="pat-info">
352 <div class="pat-title">${titleH}</div>
353 ${artistH ? `<div class="pat-artist">${artistH}</div>` : ''}
354 ${creditBits ? `<div class="pat-credit">${creditBits}</div>` : ''}
355 </div>
356 ${this.openInLinks(t)}
357</div>`;
358 });
359 }
360
361 /**
362 * Replace [[album:<name>]] shortcodes with a v9-style album block.
363 * Caller passes a lookup function (name) -> { title, artist, cover, tracks: [{url,title,artist,cover}, ...] }
364 * Tracks must already have signed URLs. Unknown albums → left as-is.
365 * The wrapper carries the full album JSON so audio-player.js can queue it
366 * when any track or the album play button is clicked.
367 */
368 static embedAlbumShortcodes(html, albumLookup) {
369 if (!html || typeof albumLookup !== 'function') return html;
370 return html.replace(/\[\[album:([^\]]+)\]\]/g, (match, rawName) => {
371 const name = rawName.trim();
372 const album = albumLookup(name);
373 if (!album || !album.tracks || !album.tracks.length) return match;
374
375 // Stable DOM id for this rendering — used as data-pcms-album-id on tracks
376 const albumDomId = 'album-' + Math.random().toString(36).slice(2, 10);
377 // Only playable tracks (with url) in the queue; link-only tracks appear
378 // in the list but not in the playback JSON.
379 const albumJson = JSON.stringify(album.tracks.filter((t) => t.url))
380 .replace(/&/g, '&amp;').replace(/'/g, '&#39;').replace(/</g, '&lt;');
381 const titleH = this.escape(album.title || name);
382 const artistH = this.escape(album.artist || '');
383 const coverH = album.cover ? this.escape(album.cover) : '';
384
385 const trackItems = album.tracks.map((t, i) => {
386 const tTitle = this.escape(t.title || ('Track ' + (i + 1)));
387 const tArtist = this.escape(t.artist || '');
388 // Link-only track: no play button, but track number + info + open-in links.
389 if (!t.url) {
390 return ` <li class="post-audio-track post-audio-track--static"${t.id ? ` id="track-${t.id}"` : ''}>
391 <span class="pat-track-num">${i + 1}.</span>
392 <div class="pat-info">
393 <div class="pat-title">${tTitle}</div>
394 ${tArtist && tArtist !== artistH ? `<div class="pat-artist">${tArtist}</div>` : ''}
395 </div>
396 ${this.openInLinks(t)}
397 </li>`;
398 }
399 const tUrl = this.escape(t.url);
400 return ` <li class="post-audio-track"${t.id ? ` id="track-${t.id}" data-pcms-track-id="${t.id}"` : ''} data-pcms-track-url="${tUrl}" data-pcms-album-id="${albumDomId}">
401 <button type="button" class="pat-play" aria-label="Play ${tTitle}">
402 <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 4l12 8-12 8z"/></svg>
403 </button>
404 <div class="pat-info">
405 <span class="pat-track-num">${i + 1}.</span>
406 <div class="pat-title">${tTitle}</div>
407 ${tArtist && tArtist !== artistH ? `<div class="pat-artist">${tArtist}</div>` : ''}
408 </div>
409 ${this.openInLinks(t)}
410 </li>`;
411 }).join('\n');
412
413 return `<div class="post-album" id="${albumDomId}" data-pcms-album='${albumJson}' data-pcms-album-title="${titleH}">
414 <div class="post-album-header">
415 <button type="button" class="post-album-cover-btn" data-pcms-album-id="${albumDomId}" aria-label="Play album ${titleH}">
416 ${coverH
417 ? `<img src="${coverH}" alt="" class="post-album-cover-img">`
418 : `<svg class="post-album-cover-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M9 17V5l12-2v12"/><circle cx="6" cy="17" r="3"/><circle cx="18" cy="15" r="3"/></svg>`}
419 <span class="post-album-play-overlay" aria-hidden="true">
420 <svg viewBox="0 0 24 24" fill="currentColor"><path d="M8 4l12 8-12 8z"/></svg>
421 </span>
422 </button>
423 <div class="post-album-info">
424 <h3 class="post-album-title">${titleH}</h3>
425 ${artistH ? `<p class="post-album-artist">${artistH}</p>` : ''}
426 <p class="post-album-count">${album.tracks.length} track${album.tracks.length === 1 ? '' : 's'}</p>
427 </div>
428 </div>
429 <ol class="post-album-tracks">
430${trackItems}
431 </ol>
432</div>`;
433 });
434 }
435
436 /**
437 * Replace [[playlist:<id>]] shortcodes with a v9-style album block.
438 * Caller passes a lookup function (id) -> hydrated playlist object from
439 * PlaylistService.get(), or null. Unknown playlists render an inline
440 * "niet gevonden" placeholder so the post still validates as HTML.
441 *
442 * Shape returned by lookup:
443 * { id, title, artist, year, cover, kind, tracks: [{url,title,artist,cover,duration}, ...] }
444 *
445 * `kind` is honored:
446 * - 'album' → ordered list with track numbers
447 * - 'playlist' → list with per-track cover thumbnails (mixtape feel)
448 *
449 * opts: { isAdmin: boolean } — when true, an edit/delete action overlay
450 * is rendered top-right of each card. The handlers are wired up in
451 * audio-player.js via event delegation on data-pcms-playlist-delete.
452 */
453 static embedPlaylistShortcodes(html, playlistLookup, opts = {}) {
454 if (!html || typeof playlistLookup !== 'function') return html;
455 const isAdmin = !!opts.isAdmin;
456 return html.replace(/\[\[playlist:([a-z0-9][a-z0-9-]*)\]\]/gi, (match, rawId) => {
457 const id = rawId.toLowerCase();
458 const pl = playlistLookup(id);
459
460 if (!pl) {
461 return `<div class="post-playlist-missing"><em>Playlist "${this.escape(id)}" niet gevonden.</em></div>`;
462 }
463 if (!pl.tracks || !pl.tracks.length) {
464 return `<div class="post-playlist-empty"><em>Playlist "${this.escape(pl.title)}" heeft geen beschikbare tracks.</em></div>`;
465 }
466
467 const albumDomId = 'album-' + id;
468 const kind = (pl.kind === 'playlist') ? 'playlist' : 'album';
469 const kindLabel = kind === 'playlist' ? '📃 Playlist' : '💿 Album';
470 const titleH = this.escape(pl.title || 'Naamloos');
471 const artistH = this.escape(pl.artist || '');
472 const coverH = pl.cover ? this.escape(pl.cover) : '';
473
474 // Audio-player.js reads data-pcms-album for queue. Same shape as
475 // embedAlbumShortcodes — keep both in sync.
476 // Only playable tracks in the queue; link-only tracks appear in the list
477 // but not in the playback JSON.
478 const tracksData = pl.tracks.filter(t => t.url).map(t => ({
479 id: t.id,
480 url: t.url,
481 title: t.title,
482 artist: t.artist || pl.artist || '',
483 cover: t.cover || pl.cover || '',
484 }));
485 const albumJson = JSON.stringify(tracksData)
486 .replace(/&/g, '&amp;').replace(/'/g, '&#39;').replace(/</g, '&lt;');
487
488 // Total duration for the meta line
489 const totalSec = pl.tracks.reduce((s, t) => s + (t.duration || 0), 0);
490 const metaParts = [];
491 if (pl.year) metaParts.push(String(pl.year));
492 metaParts.push(pl.tracks.length + (pl.tracks.length === 1 ? ' track' : ' tracks'));
493 if (totalSec > 0) {
494 const h = Math.floor(totalSec / 3600);
495 const m = Math.floor((totalSec % 3600) / 60);
496 if (h > 0) metaParts.push(`${h}h ${m}m`);
497 else metaParts.push(`${Math.max(1, m)} min`);
498 }
499 const metaLine = this.escape(metaParts.join(' · '));
500 const firstUrl = this.escape((pl.tracks.find(t => t.url) || {}).url || '');
501
502 // Track items — playlist-kind shows per-track cover thumbs, album-kind shows numbers
503 const trackItems = pl.tracks.map((t, i) => {
504 const tTitleH = this.escape(t.title || ('Track ' + (i + 1)));
505 const tArtistH = this.escape(t.artist || '');
506 const tUrl = this.escape(t.url);
507 const showArtist = tArtistH && tArtistH !== artistH;
508
509 // Duration cell — render even when 0 for consistent column layout
510 const durHtml = t.duration > 0
511 ? `<span class="pat-duration">${Math.floor(t.duration / 60)}:${String(t.duration % 60).padStart(2, '0')}</span>`
512 : `<span class="pat-duration pat-duration-empty">—:—</span>`;
513
514 // Leader cell — number for albums, cover thumb for playlists
515 const leader = (kind === 'playlist' && t.cover)
516 ? `<span class="pat-cover" style="background-image:url(${this.escape(t.cover)})" aria-hidden="true"></span>`
517 : `<span class="pat-num">${i + 1}</span>`;
518
519 // Link-only track: no clickable play row (static div), but open-in links.
520 if (!t.url) {
521 return ` <li class="post-album-track-compact post-album-track-compact--static"${t.id ? ` id="track-${t.id}"` : ''}>
522 <div class="pat-row pat-static">
523 ${leader}
524 <span class="pat-meta">
525 <span class="pat-title">${tTitleH}</span>
526 ${showArtist ? `<span class="pat-artist">${tArtistH}</span>` : ''}
527 </span>
528 ${durHtml}
529 </div>
530 ${this.openInLinks(t)}
531 </li>`;
532 }
533 const trackBase = String(t.url).split('?')[0];
534 return ` <li class="post-album-track-compact"${t.id ? ` id="track-${t.id}" data-pcms-track-id="${t.id}"` : ''}>
535 <button type="button" class="pat-row"
536 data-pcms-track-url="${tUrl}"
537 data-pcms-album-id="${albumDomId}"
538 data-pcms-track-base="${this.escape(trackBase)}"
539 aria-label="Speel ${tTitleH}">
540 ${leader}
541 <span class="pat-meta">
542 <span class="pat-title">${tTitleH}</span>
543 ${showArtist ? `<span class="pat-artist">${tArtistH}</span>` : ''}
544 </span>
545 ${durHtml}
546 </button>
547 ${this.openInLinks(t)}
548 </li>`;
549 }).join('\n');
550
551 return `<div class="post-album" id="${albumDomId}"
552 data-pcms-album='${albumJson}'
553 data-pcms-album-title="${titleH}"
554 data-pcms-album-kind="${kind}"
555 data-pcms-playlist-id="${this.escape(id)}">
556${isAdmin ? ` <div class="post-album-actions" role="group" aria-label="Playlist beheren">
557 <a class="post-album-action" href="/admin/playlists?edit=${this.escape(id)}" title="Bewerk playlist" aria-label="Bewerk playlist">
558 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>
559 </a>
560 <button type="button" class="post-album-action is-danger" data-pcms-playlist-delete="${this.escape(id)}" data-pcms-playlist-title="${titleH}" title="Verwijder playlist" aria-label="Verwijder playlist">
561 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/><path d="M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"/></svg>
562 </button>
563 </div>
564` : ''} <div class="post-album-header">
565 <button type="button" class="post-album-cover-btn"
566 data-pcms-track-url="${firstUrl}"
567 data-pcms-album-id="${albumDomId}"
568 aria-label="Speel ${kind === 'playlist' ? 'playlist' : 'album'}">
569 ${coverH
570 ? `<span class="post-album-cover" style="background-image:url('${coverH}')"></span>`
571 : `<span class="post-album-cover post-album-cover-empty">
572 <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 17V5l12-2v12"/><circle cx="6" cy="17" r="3" fill="currentColor"/><circle cx="18" cy="15" r="3" fill="currentColor"/></svg>
573 </span>`}
574 <span class="post-album-cover-play" aria-hidden="true">
575 <svg viewBox="0 0 24 24"><path d="M8 4l12 8-12 8z" fill="currentColor"/></svg>
576 </span>
577 </button>
578 <div class="post-album-info">
579 <p class="post-album-label">${kindLabel}</p>
580 <h3 class="post-album-title">${titleH}</h3>
581 ${artistH ? `<p class="post-album-artist">${artistH}</p>` : ''}
582 <p class="post-album-meta">${metaLine}</p>
583 </div>
584 </div>
585 <ol class="post-album-tracks post-album-tracks-compact" data-album-kind="${kind}">
586${trackItems}
587 </ol>
588</div>`;
589 });
590 }
591
592 /**
593 * Human-readable label for a provider slug. Used by external-link buttons.
594 */
595 static platformLabel(provider) {
596 return ({
597 spotify: 'Spotify',
598 bandcamp: 'Bandcamp',
599 soundcloud: 'SoundCloud',
600 applemusic: 'Apple Music',
601 youtube: 'YouTube',
602 vimeo: 'Vimeo',
603 tidal: 'Tidal',
604 deezer: 'Deezer',
605 mixcloud: 'Mixcloud',
606 })[provider] || 'External link';
607 }
608
609 /**
610 * Detect platform from URL purely by hostname (covers more services than
611 * detectProvider, which is embed-focused). Used for [[link:url]] rendering.
612 */
613 static detectLinkPlatform(url) {
614 try {
615 const host = new URL(url).hostname.toLowerCase();
616 if (host.includes('open.spotify.com') || host === 'spotify.com') return 'spotify';
617 if (host.includes('bandcamp.com')) return 'bandcamp';
618 if (host.includes('soundcloud.com')) return 'soundcloud';
619 if (host.includes('music.apple.com') || host.includes('itunes.apple.com')) return 'applemusic';
620 if (host.includes('youtube.com') || host.includes('youtu.be') || host.includes('music.youtube.com')) return 'youtube';
621 if (host.includes('vimeo.com')) return 'vimeo';
622 if (host.includes('tidal.com')) return 'tidal';
623 if (host.includes('deezer.com')) return 'deezer';
624 if (host.includes('mixcloud.com')) return 'mixcloud';
625 return 'other';
626 } catch (e) {
627 return null;
628 }
629 }
630
631 /**
632 * Replace [[link:url]] or [[link:url|Custom Label]] shortcodes with a
633 * branded "Open in <Platform>" anchor (no iframe). Opens in new tab.
634 * Per Robin's v9: "External link, click = open platform (target _blank)".
635 */
636 static embedExternalLinkShortcodes(html) {
637 if (!html) return html;
638 return html.replace(/\[\[link:([^\]|]+)(?:\|([^\]]+))?\]\]/g, (match, rawUrl, customLabel) => {
639 const url = rawUrl.trim();
640 if (!/^https?:\/\//i.test(url)) return match;
641 const platform = this.detectLinkPlatform(url) || 'other';
642 const label = (customLabel || '').trim();
643 const platformLabel = this.platformLabel(platform);
644 const buttonText = label || `Open in ${platformLabel}`;
645 const urlH = this.escape(url);
646 const textH = this.escape(buttonText);
647 return `<a class="post-audio-external post-audio-external--${platform}" href="${urlH}" target="_blank" rel="noopener noreferrer" data-platform="${platform}">
648 <span class="pae-icon" aria-hidden="true">▶</span>
649 <span class="pae-text">${textH}</span>
650 <span class="pae-arrow" aria-hidden="true">↗</span>
651</a>`;
652 });
653 }
654
655 static escape(str) {
656 return str
657 .replace(/&/g, '&amp;')
658 .replace(/</g, '&lt;')
659 .replace(/>/g, '&gt;')
660 .replace(/"/g, '&quot;')
661 .replace(/'/g, '&#39;');
662 }
663}
664
665export default AudioEmbedService;
Note: See TracBrowser for help on using the repository browser.