source: Klonkt/src/services/AudioEmbedService.js@ 183875b

main
Last change on this file since 183875b was 183875b, checked in by roboburr <roboburr@…>, 3 months ago

feat(audio): per-track "open in" Spotify/YouTube/SoundCloud links

New per-track fields link_spotify/link_youtube/link_soundcloud (audio_tracks),
editable in the track editor (https + correct host validated). Shown as small
brand icons per track row in standalone track embeds, albums and playlists —
click opens the track on that service (new tab). buster audio.css?v=8.

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

  • Property mode set to 100644
File size: 25.7 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"-iconen (brand-gekleurd 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 // Kleine "open in"-links voor een track (Spotify/YouTube/SoundCloud). De hrefs
22 // zijn server-side al gevalideerd (alleen https + juiste host). Geeft '' als er
23 // geen links zijn. Wordt naast de play-knop gezet (buiten de knop → geen
24 // conflict met afspelen).
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 // Alleen http(s)-URL's embedden. De provider-regexes hieronder zijn NIET
43 // verankerd, dus zonder deze check zou bv. `javascript:alert(1)//youtu.be/x`
44 // matchen en als embed-URL belanden (stored XSS via een [[embed:...]]-
45 // shortcode — die tekst gaat niet langs de HTML-sanitizer omdat 'ie in een
46 // text-node zit). De scheme-guard sluit javascript:/data:/vbscript: enz. uit.
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 altijd exact 11 tekens (lijnt uit met de client-side
71 // ytId() in embed-player.js, die ook {11} verwacht).
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 static generateIframe(provider, config) {
87 switch (provider) {
88 // Eigen custom-spelers (client-side via embed-player.js + de echte
89 // platform-API's). We renderen een placeholder met data-attributen i.p.v.
90 // het kale platform-iframe, zodat de embed in ÓNZE huisstijl verschijnt.
91 case 'youtube':
92 return this.embedPlaceholder('youtube', config.id, 'video',
93 config.url || `https://youtu.be/${config.id}`);
94 case 'soundcloud':
95 return this.embedPlaceholder('soundcloud', config.url, 'track', config.url);
96 case 'spotify':
97 return this.embedPlaceholder('spotify', `spotify:${config.type}:${config.id}`,
98 config.type, config.url || `https://open.spotify.com/${config.type}/${config.id}`);
99 // Geen JS-API (Bandcamp/Apple) of niet-prioritair (Vimeo): blijven een
100 // iframe; mutual-exclusion loopt voor deze via de blur-fallback.
101 case 'bandcamp':
102 return this.bandcampIframe(config);
103 case 'applemusic':
104 return this.applemusicIframe(config);
105 case 'vimeo':
106 return this.vimeoIframe(config);
107 default:
108 return null;
109 }
110 }
111
112 /**
113 * Placeholder voor een eigen custom-speler. embed-player.js pikt
114 * .folio-embed[data-embed-provider] op en bouwt de kaart + speler client-side.
115 * ALLE waarden via escape() — post.content_html wordt ongeescaped uitgevoerd.
116 */
117 static embedPlaceholder(provider, ref, type, url) {
118 const attrs = [
119 `data-embed-provider="${this.escape(provider)}"`,
120 `data-embed-ref="${this.escape(ref)}"`,
121 type ? `data-embed-type="${this.escape(type)}"` : '',
122 `data-embed-url="${this.escape(url)}"`,
123 ].filter(Boolean).join(' ');
124 return `<div class="folio-embed folio-embed--${this.escape(provider)} pcms-embed pcms-embed-card pcms-embed-loading" ${attrs}></div>`;
125 }
126
127 static spotifyIframe({ type, id }) {
128 const src = `https://open.spotify.com/embed/${type}/${id}`;
129 return `
130 <figure class="folio-embed folio-embed--spotify">
131 <iframe src="${this.escape(src)}"
132 style="width:100%;height:152px;border:0;"
133 loading="lazy"
134 allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
135 title="Spotify ${type}"></iframe>
136 </figure>
137 `.trim();
138 }
139
140 static bandcampIframe({ url }) {
141 const encodedUrl = encodeURIComponent(url);
142 const src = `https://bandcamp.com/EmbeddedPlayer/url=${encodedUrl}/size=large/bgcol=faf8f3/linkcol=c2410c/tracklist=false/transparent=true/`;
143 return `
144 <figure class="folio-embed folio-embed--bandcamp">
145 <iframe src="${this.escape(src)}"
146 style="width:100%;height:470px;border:0;"
147 loading="lazy"
148 allow="encrypted-media"
149 title="Bandcamp player"></iframe>
150 </figure>
151 `.trim();
152 }
153
154 static soundcloudIframe({ url }) {
155 const params = {
156 url: url,
157 color: '#ff5500',
158 auto_play: 'false',
159 hide_related: 'true',
160 show_comments: 'false',
161 show_user: 'true',
162 show_reposts: 'false',
163 show_teaser: 'false',
164 visual: 'true'
165 };
166 const query = new URLSearchParams(params).toString();
167 const src = `https://w.soundcloud.com/player/?${query}`;
168 return `
169 <figure class="folio-embed folio-embed--soundcloud">
170 <iframe src="${this.escape(src)}"
171 style="width:100%;height:300px;border:0;"
172 loading="lazy"
173 allow="autoplay; clipboard-write; encrypted-media"
174 title="SoundCloud player"></iframe>
175 </figure>
176 `.trim();
177 }
178
179 static applemusicIframe({ url }) {
180 const match = url.match(/music\.apple\.com\/([a-z]{2}\/(?:album|playlist|song)\/[^/?#]+\/[0-9]+)/i);
181 if (!match) return null;
182 const src = `https://embed.music.apple.com/${match[1]}`;
183 return `
184 <figure class="folio-embed folio-embed--applemusic">
185 <iframe src="${this.escape(src)}"
186 style="width:100%;height:175px;border:0;overflow:hidden;border-radius:8px;"
187 loading="lazy"
188 allow="autoplay; clipboard-write; encrypted-media"
189 title="Apple Music"></iframe>
190 </figure>
191 `.trim();
192 }
193
194 static youtubeIframe({ id }) {
195 const src = `https://www.youtube-nocookie.com/embed/${id}`;
196 return `
197 <figure class="folio-embed folio-embed--youtube">
198 <iframe src="${this.escape(src)}"
199 style="aspect-ratio:16/9;width:100%;height:auto;border:0;"
200 loading="lazy"
201 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
202 allowfullscreen
203 title="YouTube video"></iframe>
204 </figure>
205 `.trim();
206 }
207
208 static vimeoIframe({ id }) {
209 const src = `https://player.vimeo.com/video/${id}`;
210 return `
211 <figure class="folio-embed folio-embed--vimeo">
212 <iframe src="${this.escape(src)}"
213 style="aspect-ratio:16/9;width:100%;height:auto;border:0;"
214 loading="lazy"
215 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
216 allowfullscreen
217 title="Vimeo video"></iframe>
218 </figure>
219 `.trim();
220 }
221
222 /**
223 * Auto-embed: Scan paragraphs containing only a URL.
224 * Handles two markdown-rendered shapes:
225 * <p>https://url</p> (bare URL — when GFM auto-link is off)
226 * <p><a href="https://url">https://url</a></p> (marked GFM auto-link — what we get)
227 * Either way → <figure class="folio-embed">...
228 */
229 static autoembed(html) {
230 if (!html) return html;
231 return html.replace(
232 /<p>\s*(?:<a\b[^>]*?\shref="([^"]+)"[^>]*>[^<]*<\/a>|(https?:\/\/[^\s<>"']+))\s*<\/p>/gi,
233 (match, hrefUrl, bareUrl) => {
234 const url = hrefUrl || bareUrl;
235 const detected = this.detectProvider(url);
236 if (detected) {
237 const iframe = this.generateIframe(detected.provider, detected);
238 return iframe || match;
239 }
240 return match;
241 }
242 );
243 }
244
245 /**
246 * Replace [[embed:<url>]] shortcodes met de platform-iframe (YouTube, Spotify,
247 * SoundCloud, Apple Music, Bandcamp, Vimeo). De editor-knop voegt deze
248 * shortcode in; losse URL-regels embedden ook automatisch via autoembed().
249 * Niet-ondersteunde/ongeldige URLs krijgen een nette inline-melding.
250 */
251 static embedMediaShortcodes(html) {
252 if (!html) return html;
253 return html.replace(/\[\[embed:([^\]]+)\]\]/gi, (match, rawUrl) => {
254 const url = rawUrl.trim().replace(/&amp;/g, '&');
255 const detected = this.detectProvider(url);
256 if (!detected) {
257 return `<div class="post-embed-missing"><em>Embed: niet-ondersteunde of ongeldige URL.</em></div>`;
258 }
259 return this.generateIframe(detected.provider, detected) || match;
260 });
261 }
262
263 /**
264 * Replace [[track:<id>]] shortcodes with v9-style player markup.
265 * Caller passes a lookup function (id) -> { id, title, artist, url, cover }
266 * where url is already a signed /audio/stream/... URL. Unknown ids → left as-is.
267 */
268 static embedTrackShortcodes(html, trackLookup) {
269 if (!html || typeof trackLookup !== 'function') return html;
270 return html.replace(/\[\[track:([A-Za-z0-9_-]+)\]\]/g, (match, id) => {
271 const t = trackLookup(id);
272 if (!t || !t.url) return match;
273 const trackJson = JSON.stringify({
274 id,
275 url: t.url,
276 title: t.title || 'Untitled',
277 artist: t.artist || '',
278 cover: t.cover || '',
279 credit: t.credit || '',
280 license: t.license || '',
281 });
282 const titleH = this.escape(t.title || 'Untitled');
283 const artistH = this.escape(t.artist || '');
284 const urlH = this.escape(t.url);
285 // Zichtbare eigenaar/licentie-regel onder de track.
286 const creditBits = [this.escape(t.credit || ''), this.escape(t.license || '')].filter(Boolean).join(' · ');
287 const dataAttr = trackJson
288 .replace(/&/g, '&amp;').replace(/'/g, '&#39;').replace(/</g, '&lt;');
289 // id="track-<id>" = anker zodat de mini-speler hierheen kan scrollen.
290 return `<div class="post-audio-track" id="track-${id}" data-pcms-track-id="${id}" data-pcms-track-url="${urlH}" data-pcms-track='${dataAttr}'>
291 <button type="button" class="pat-play" aria-label="Play ${titleH}">
292 <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 4l12 8-12 8z"/></svg>
293 </button>
294 <div class="pat-info">
295 <div class="pat-title">${titleH}</div>
296 ${artistH ? `<div class="pat-artist">${artistH}</div>` : ''}
297 ${creditBits ? `<div class="pat-credit">${creditBits}</div>` : ''}
298 </div>
299 ${this.openInLinks(t)}
300</div>`;
301 });
302 }
303
304 /**
305 * Replace [[album:<name>]] shortcodes with a v9-style album block.
306 * Caller passes a lookup function (name) -> { title, artist, cover, tracks: [{url,title,artist,cover}, ...] }
307 * Tracks must already have signed URLs. Unknown albums → left as-is.
308 * The wrapper carries the full album JSON so audio-player.js can queue it
309 * when any track or the album play button is clicked.
310 */
311 static embedAlbumShortcodes(html, albumLookup) {
312 if (!html || typeof albumLookup !== 'function') return html;
313 return html.replace(/\[\[album:([^\]]+)\]\]/g, (match, rawName) => {
314 const name = rawName.trim();
315 const album = albumLookup(name);
316 if (!album || !album.tracks || !album.tracks.length) return match;
317
318 // Stable DOM id for this rendering — used as data-pcms-album-id on tracks
319 const albumDomId = 'album-' + Math.random().toString(36).slice(2, 10);
320 const albumJson = JSON.stringify(album.tracks)
321 .replace(/&/g, '&amp;').replace(/'/g, '&#39;').replace(/</g, '&lt;');
322 const titleH = this.escape(album.title || name);
323 const artistH = this.escape(album.artist || '');
324 const coverH = album.cover ? this.escape(album.cover) : '';
325
326 const trackItems = album.tracks.map((t, i) => {
327 const tTitle = this.escape(t.title || ('Track ' + (i + 1)));
328 const tArtist = this.escape(t.artist || '');
329 const tUrl = this.escape(t.url);
330 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}">
331 <button type="button" class="pat-play" aria-label="Play ${tTitle}">
332 <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 4l12 8-12 8z"/></svg>
333 </button>
334 <div class="pat-info">
335 <span class="pat-track-num">${i + 1}.</span>
336 <div class="pat-title">${tTitle}</div>
337 ${tArtist && tArtist !== artistH ? `<div class="pat-artist">${tArtist}</div>` : ''}
338 </div>
339 ${this.openInLinks(t)}
340 </li>`;
341 }).join('\n');
342
343 return `<div class="post-album" id="${albumDomId}" data-pcms-album='${albumJson}' data-pcms-album-title="${titleH}">
344 <div class="post-album-header">
345 <button type="button" class="post-album-cover-btn" data-pcms-album-id="${albumDomId}" aria-label="Play album ${titleH}">
346 ${coverH
347 ? `<img src="${coverH}" alt="" class="post-album-cover-img">`
348 : `<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>`}
349 <span class="post-album-play-overlay" aria-hidden="true">
350 <svg viewBox="0 0 24 24" fill="currentColor"><path d="M8 4l12 8-12 8z"/></svg>
351 </span>
352 </button>
353 <div class="post-album-info">
354 <h3 class="post-album-title">${titleH}</h3>
355 ${artistH ? `<p class="post-album-artist">${artistH}</p>` : ''}
356 <p class="post-album-count">${album.tracks.length} track${album.tracks.length === 1 ? '' : 's'}</p>
357 </div>
358 </div>
359 <ol class="post-album-tracks">
360${trackItems}
361 </ol>
362</div>`;
363 });
364 }
365
366 /**
367 * Replace [[playlist:<id>]] shortcodes with a v9-style album block.
368 * Caller passes a lookup function (id) -> hydrated playlist object from
369 * PlaylistService.get(), or null. Unknown playlists render an inline
370 * "niet gevonden" placeholder so the post still validates as HTML.
371 *
372 * Shape returned by lookup:
373 * { id, title, artist, year, cover, kind, tracks: [{url,title,artist,cover,duration}, ...] }
374 *
375 * `kind` is honored:
376 * - 'album' → ordered list with track numbers
377 * - 'playlist' → list with per-track cover thumbnails (mixtape feel)
378 *
379 * opts: { isAdmin: boolean } — when true, an edit/delete action overlay
380 * is rendered top-right of each card. The handlers are wired up in
381 * audio-player.js via event delegation on data-pcms-playlist-delete.
382 */
383 static embedPlaylistShortcodes(html, playlistLookup, opts = {}) {
384 if (!html || typeof playlistLookup !== 'function') return html;
385 const isAdmin = !!opts.isAdmin;
386 return html.replace(/\[\[playlist:([a-z0-9][a-z0-9-]*)\]\]/gi, (match, rawId) => {
387 const id = rawId.toLowerCase();
388 const pl = playlistLookup(id);
389
390 if (!pl) {
391 return `<div class="post-playlist-missing"><em>Playlist "${this.escape(id)}" niet gevonden.</em></div>`;
392 }
393 if (!pl.tracks || !pl.tracks.length) {
394 return `<div class="post-playlist-empty"><em>Playlist "${this.escape(pl.title)}" heeft geen beschikbare tracks.</em></div>`;
395 }
396
397 const albumDomId = 'album-' + id;
398 const kind = (pl.kind === 'playlist') ? 'playlist' : 'album';
399 const kindLabel = kind === 'playlist' ? '📃 Playlist' : '💿 Album';
400 const titleH = this.escape(pl.title || 'Naamloos');
401 const artistH = this.escape(pl.artist || '');
402 const coverH = pl.cover ? this.escape(pl.cover) : '';
403
404 // Audio-player.js reads data-pcms-album for queue. Same shape as
405 // embedAlbumShortcodes — keep both in sync.
406 const tracksData = pl.tracks.map(t => ({
407 id: t.id,
408 url: t.url,
409 title: t.title,
410 artist: t.artist || pl.artist || '',
411 cover: t.cover || pl.cover || '',
412 }));
413 const albumJson = JSON.stringify(tracksData)
414 .replace(/&/g, '&amp;').replace(/'/g, '&#39;').replace(/</g, '&lt;');
415
416 // Total duration for the meta line
417 const totalSec = pl.tracks.reduce((s, t) => s + (t.duration || 0), 0);
418 const metaParts = [];
419 if (pl.year) metaParts.push(String(pl.year));
420 metaParts.push(pl.tracks.length + (pl.tracks.length === 1 ? ' track' : ' tracks'));
421 if (totalSec > 0) {
422 const h = Math.floor(totalSec / 3600);
423 const m = Math.floor((totalSec % 3600) / 60);
424 if (h > 0) metaParts.push(`${h}h ${m}m`);
425 else metaParts.push(`${Math.max(1, m)} min`);
426 }
427 const metaLine = this.escape(metaParts.join(' · '));
428 const firstUrl = this.escape(pl.tracks[0].url);
429
430 // Track items — playlist-kind shows per-track cover thumbs, album-kind shows numbers
431 const trackItems = pl.tracks.map((t, i) => {
432 const tTitleH = this.escape(t.title || ('Track ' + (i + 1)));
433 const tArtistH = this.escape(t.artist || '');
434 const tUrl = this.escape(t.url);
435 const showArtist = tArtistH && tArtistH !== artistH;
436
437 // Duration cell — render even when 0 for consistent column layout
438 const durHtml = t.duration > 0
439 ? `<span class="pat-duration">${Math.floor(t.duration / 60)}:${String(t.duration % 60).padStart(2, '0')}</span>`
440 : `<span class="pat-duration pat-duration-empty">—:—</span>`;
441
442 // Leader cell — number for albums, cover thumb for playlists
443 const leader = (kind === 'playlist' && t.cover)
444 ? `<span class="pat-cover" style="background-image:url(${this.escape(t.cover)})" aria-hidden="true"></span>`
445 : `<span class="pat-num">${i + 1}</span>`;
446
447 const trackBase = String(t.url).split('?')[0];
448 return ` <li class="post-album-track-compact"${t.id ? ` id="track-${t.id}" data-pcms-track-id="${t.id}"` : ''}>
449 <button type="button" class="pat-row"
450 data-pcms-track-url="${tUrl}"
451 data-pcms-album-id="${albumDomId}"
452 data-pcms-track-base="${this.escape(trackBase)}"
453 aria-label="Speel ${tTitleH}">
454 ${leader}
455 <span class="pat-meta">
456 <span class="pat-title">${tTitleH}</span>
457 ${showArtist ? `<span class="pat-artist">${tArtistH}</span>` : ''}
458 </span>
459 ${durHtml}
460 </button>
461 ${this.openInLinks(t)}
462 </li>`;
463 }).join('\n');
464
465 return `<div class="post-album" id="${albumDomId}"
466 data-pcms-album='${albumJson}'
467 data-pcms-album-title="${titleH}"
468 data-pcms-album-kind="${kind}"
469 data-pcms-playlist-id="${this.escape(id)}">
470${isAdmin ? ` <div class="post-album-actions" role="group" aria-label="Playlist beheren">
471 <a class="post-album-action" href="/admin/playlists?edit=${this.escape(id)}" title="Bewerk playlist" aria-label="Bewerk playlist">
472 <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>
473 </a>
474 <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">
475 <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>
476 </button>
477 </div>
478` : ''} <div class="post-album-header">
479 <button type="button" class="post-album-cover-btn"
480 data-pcms-track-url="${firstUrl}"
481 data-pcms-album-id="${albumDomId}"
482 aria-label="Speel ${kind === 'playlist' ? 'playlist' : 'album'}">
483 ${coverH
484 ? `<span class="post-album-cover" style="background-image:url('${coverH}')"></span>`
485 : `<span class="post-album-cover post-album-cover-empty">
486 <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>
487 </span>`}
488 <span class="post-album-cover-play" aria-hidden="true">
489 <svg viewBox="0 0 24 24"><path d="M8 4l12 8-12 8z" fill="currentColor"/></svg>
490 </span>
491 </button>
492 <div class="post-album-info">
493 <p class="post-album-label">${kindLabel}</p>
494 <h3 class="post-album-title">${titleH}</h3>
495 ${artistH ? `<p class="post-album-artist">${artistH}</p>` : ''}
496 <p class="post-album-meta">${metaLine}</p>
497 </div>
498 </div>
499 <ol class="post-album-tracks post-album-tracks-compact" data-album-kind="${kind}">
500${trackItems}
501 </ol>
502</div>`;
503 });
504 }
505
506 /**
507 * Human-readable label for a provider slug. Used by external-link buttons.
508 */
509 static platformLabel(provider) {
510 return ({
511 spotify: 'Spotify',
512 bandcamp: 'Bandcamp',
513 soundcloud: 'SoundCloud',
514 applemusic: 'Apple Music',
515 youtube: 'YouTube',
516 vimeo: 'Vimeo',
517 tidal: 'Tidal',
518 deezer: 'Deezer',
519 mixcloud: 'Mixcloud',
520 })[provider] || 'External link';
521 }
522
523 /**
524 * Detect platform from URL purely by hostname (covers more services than
525 * detectProvider, which is embed-focused). Used for [[link:url]] rendering.
526 */
527 static detectLinkPlatform(url) {
528 try {
529 const host = new URL(url).hostname.toLowerCase();
530 if (host.includes('open.spotify.com') || host === 'spotify.com') return 'spotify';
531 if (host.includes('bandcamp.com')) return 'bandcamp';
532 if (host.includes('soundcloud.com')) return 'soundcloud';
533 if (host.includes('music.apple.com') || host.includes('itunes.apple.com')) return 'applemusic';
534 if (host.includes('youtube.com') || host.includes('youtu.be') || host.includes('music.youtube.com')) return 'youtube';
535 if (host.includes('vimeo.com')) return 'vimeo';
536 if (host.includes('tidal.com')) return 'tidal';
537 if (host.includes('deezer.com')) return 'deezer';
538 if (host.includes('mixcloud.com')) return 'mixcloud';
539 return 'other';
540 } catch (e) {
541 return null;
542 }
543 }
544
545 /**
546 * Replace [[link:url]] or [[link:url|Custom Label]] shortcodes with a
547 * branded "Open in <Platform>" anchor (no iframe). Opens in new tab.
548 * Per Robin's v9: "Externe link, klik = open platform (target _blank)".
549 */
550 static embedExternalLinkShortcodes(html) {
551 if (!html) return html;
552 return html.replace(/\[\[link:([^\]|]+)(?:\|([^\]]+))?\]\]/g, (match, rawUrl, customLabel) => {
553 const url = rawUrl.trim();
554 if (!/^https?:\/\//i.test(url)) return match;
555 const platform = this.detectLinkPlatform(url) || 'other';
556 const label = (customLabel || '').trim();
557 const platformLabel = this.platformLabel(platform);
558 const buttonText = label || `Open in ${platformLabel}`;
559 const urlH = this.escape(url);
560 const textH = this.escape(buttonText);
561 return `<a class="post-audio-external post-audio-external--${platform}" href="${urlH}" target="_blank" rel="noopener noreferrer" data-platform="${platform}">
562 <span class="pae-icon" aria-hidden="true">▶</span>
563 <span class="pae-text">${textH}</span>
564 <span class="pae-arrow" aria-hidden="true">↗</span>
565</a>`;
566 });
567 }
568
569 static escape(str) {
570 return str
571 .replace(/&/g, '&amp;')
572 .replace(/</g, '&lt;')
573 .replace(/>/g, '&gt;')
574 .replace(/"/g, '&quot;')
575 .replace(/'/g, '&#39;');
576 }
577}
578
579export default AudioEmbedService;
Note: See TracBrowser for help on using the repository browser.