source: Klonkt/src/services/AudioEmbedService.js@ 3e86f1c

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

feat: on-brand media embeds via the real player APIs

Replaces bare platform iframes with on-brand cards, powered by the
official JS APIs so play/pause/progress are in our own hands:

  • YouTube (IFrame Player API) + SoundCloud (Widget API): fully custom controls, native chrome hidden.
  • Spotify (iFrame API): our frame around it + controls (their player UI remains; restyling not possible without Premium+OAuth).
  • Shared PlaybackRegistry: mutual exclusion -- only 1 thing plays at a time (incl. the site audio player). Replaces the focus/blur heuristic with real play events (blur stays as fallback for iframe-only embeds).
  • Progressive enhancement: if an ad-blocker blocks the platform API, falls back seamlessly to the bare platform iframe (autoplay). The resting-state card is our brand for everyone.

AudioEmbedService now renders a placeholder div (data-embed-*) for YT/SC/
Spotify instead of an iframe; embed-player.js builds the card client-side.
CSP scriptSrc extended with the player API hosts.

Adversarial review (workflow) -> 6 bugs fixed: HTMX swap leak (poll timers/
adapters -> MutationObserver teardown + adapter.destroy()), javascript: URL XSS
(scheme guard in detectProvider + safeHref client-side), Spotify ended
misdetection (no more reset-to-0), ytId/server regex on exact 11, blur scope
limited to .folio-embed.

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

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