source: Klonkt/src/services/AudioEmbedService.js@ 46f23fd

main
Last change on this file since 46f23fd was 7bc636b, checked in by Robin <robin@…>, 4 months ago

Initial commit — PrutFolio v1 source (pulled from Hetzner /srv/prutfolio)

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