source: Klonkt/src/views/pages/admin-audio.ejs@ f2eacca

main
Last change on this file since f2eacca was f2eacca, checked in by roboburr <roboburr@…>, 2 months ago

feat(music): per-track "share on the fediverse" — federate the file as a native AS2 Audio attachment

A per-track opt-in (default off) so an OPEN track's audio file is federated as a real AS2 Audio
attachment and served ungated → it plays inline in EVERY fediverse client, incl. the official
Mastodon apps (which only play native media, not external player cards). Gated tracks (default)
keep the file hidden + web-player-only. This is the spec-canonical way to federate audio; the
gated path stays the deliberate anti-steal choice.

  • src/config/database.js — audio_tracks.fedi_open column (default 0)
  • src/routes/audio.js — /audio/stream serves fedi_open tracks ungated so remote servers can fetch them
  • src/services/ActivityPubService.js (buildNote) — fedi_open tracks → AS2 Audio attachments (the file URL)
  • src/routes/admin-audio.js — POST /:id/fedi-open toggle (god-only) + fedi_open in the track query
  • src/views/pages/admin-audio.ejs — per-track share toggle next to the download toggle
  • src/services/i18n.js — aaud.fedi_on/off labels (nl/en/de)

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

  • Property mode set to 100644
File size: 37.6 KB
Line 
1<div class="container ax-page">
2
3 <p><a href="/admin" class="btn">&larr; Beheer</a></p>
4 <header class="ax-header">
5 <div>
6 <h1><%= t('aaud.title') %></h1>
7 <p class="ax-tagline"><%= t('aaud.tagline_pre') %> <code>[[track:&lt;id&gt;]]</code> <%= t('aaud.tagline_post') %></p>
8 </div>
9 </header>
10
11 <% if (success) { %><div class="ax-flash ax-flash-ok"><%= success %></div><% } %>
12 <% if (error) { %><div class="ax-flash ax-flash-err"><%= error %></div><% } %>
13
14 <%# ── UPLOAD ──────────────────────────────────────────────── %>
15 <section class="ax-card">
16 <div class="ax-card-title"><%= t('aaud.upload') %></div>
17
18 <%# Bulk drag-drop zone. Multiple files at once, transcoded sequentially.
19 Title is auto-derived from each filename. Artist/album/cover are
20 SHARED across the batch (set once, applied to every track) — same
21 pattern as iTunes/Plex bulk-add. %>
22 <div class="ax-form">
23
24 <%# Shared metadata fields (apply to ALL files in the batch). %>
25 <div class="ax-row ax-row-2">
26 <label class="ax-field">
27 <span><%= t('aaud.artist') %> <small><%= t('aaud.applied_all') %></small></span>
28 <input type="text" id="batch-artist" placeholder="<%= t('aaud.optional') %>">
29 </label>
30 <label class="ax-field">
31 <span><%= t('aaud.album') %> <small><%= t('aaud.applied_all') %></small></span>
32 <input type="text" id="batch-album" placeholder="<%= t('aaud.optional') %>">
33 </label>
34 </div>
35 <label class="ax-field ax-file">
36 <span><%= t('aaud.cover') %> <small><%= t('aaud.cover_hint') %></small></span>
37 <span class="ax-file-control">
38 <span class="ax-btn ax-btn-secondary ax-file-btn">🖼 <%= t('aaud.choose_cover') %></span>
39 <span class="ax-file-name" data-empty><%= t('aaud.no_file') %></span>
40 <input type="file" id="batch-cover" accept="image/jpeg,image/png,image/webp,image/gif">
41 </span>
42 </label>
43
44 <%# The drop-zone itself. Click anywhere to open file picker. %>
45 <label class="ax-dropzone" id="audio-dropzone" tabindex="0">
46 <span class="ax-dropzone-icon">🎵</span>
47 <strong class="ax-dropzone-title"><%= t('aaud.drag_here') %></strong>
48 <span class="ax-dropzone-sub"><%= t('aaud.or_click') %><br><small>mp3, m4a, ogg, opus, flac · max <%= maxBytesMb %> MB · wav max <%= maxWavMb %> MB</small></span>
49 <input type="file" id="audio-files" accept="audio/*" multiple>
50 </label>
51
52 <%# Per-file progress list. Populated by JS as files are queued. %>
53 <ul class="ax-upload-queue" id="upload-queue" hidden></ul>
54
55 <div class="ax-form-actions" id="upload-actions" hidden>
56 <button type="button" class="ax-btn ax-btn-primary" id="start-upload-btn">⬆ <%= t('aaud.start_upload') %></button>
57 <button type="button" class="ax-btn" id="clear-queue-btn"><%= t('aaud.clear_list') %></button>
58 </div>
59 </div>
60 </section>
61
62 <%# ── TRACK LIST ─────────────────────────────────────────── %>
63 <section class="ax-card">
64 <div class="ax-card-title" style="display:flex;align-items:center;gap:.5rem">
65 <%= t('aaud.tracks') %> <span class="ax-count"><%= tracks.length %></span>
66 <button type="button" class="ax-btn ax-btn-secondary" id="add-link-track-btn"
67 style="margin-left:auto;font-size:.85rem" title="<%= t('aaud.add_link_track_title') %>">
68 + <%= t('aaud.add_link_track') %>
69 </button>
70 </div>
71
72 <% if (!tracks.length) { %>
73 <div class="ax-empty">
74 <div class="ax-empty-icon">♫</div>
75 <p><%= t('aaud.no_tracks') %></p>
76 </div>
77 <% } else { %>
78 <%
79 // Pre-fetch loop labels — `t` is shadowed by the loop var below.
80 var _aaudUntitled = t('aaud.untitled');
81 var _aaudPlay = t('aaud.play');
82 var _aaudEdit = t('aaud.edit');
83 var _aaudDlOn = t('aaud.dl_on');
84 var _aaudDlOff = t('aaud.dl_off');
85 var _aaudFediOn = t('aaud.fedi_on');
86 var _aaudFediOff = t('aaud.fedi_off');
87 var _aaudDelete = t('aaud.delete');
88 var _aaudCopy = t('aaud.copy_click');
89 var _aaudDelConfirm = t('aaud.delete_confirm');
90 %>
91 <ul class="ax-list">
92 <% tracks.forEach(function(t) { %>
93 <li class="ax-track" data-track-id="<%= t.id %>">
94 <% if (t.cover_url) { %>
95 <img class="ax-track-cover" src="<%= t.cover_url %>" alt="" data-cover-thumb>
96 <% } else { %>
97 <span class="ax-track-cover ax-track-cover-empty" data-cover-thumb>♫</span>
98 <% } %>
99
100 <div class="ax-track-meta">
101 <div class="ax-track-title" data-cell="title"><%= t.title || _aaudUntitled %></div>
102 <div class="ax-track-sub">
103 <span data-cell="artist"><%= t.artist || '—' %></span>
104 <% if (t.album) { %><span class="ax-track-sep">·</span><span data-cell="album"><%= t.album %></span><% } else { %><span data-cell="album" hidden></span><% } %>
105 <span class="ax-track-sep">·</span><span><%= t.size ? Math.round(t.size/1024) + ' KB' : '—' %></span>
106 </div>
107 <code class="ax-embed" data-copy="[[track:<%= t.id %>]]" title="<%= _aaudCopy %>">[[track:<%= t.id %>]]</code>
108 </div>
109
110 <div class="ax-track-actions">
111 <% if (t.stream_url) { %>
112 <button type="button" class="ax-icon-btn ax-track-play"
113 data-stream-url="<%= t.stream_url %>"
114 data-track-id="<%= t.id %>"
115 aria-label="<%= _aaudPlay %>" title="<%= _aaudPlay %>">
116 <span class="ax-track-play-icon" aria-hidden="true">▶</span>
117 </button>
118 <% } %>
119 <button type="button" class="ax-icon-btn" data-track-edit data-id="<%= t.id %>" aria-label="<%= _aaudEdit %>" title="<%= _aaudEdit %>">✎</button>
120 <% if (typeof premiumUnlocked === 'undefined' || premiumUnlocked) { %>
121 <button type="button" class="ax-icon-btn" data-track-dl data-id="<%= t.id %>" data-on="<%= t.downloadable ? '1' : '0' %>"
122 aria-label="<%= t.downloadable ? _aaudDlOn : _aaudDlOff %>" title="<%= t.downloadable ? _aaudDlOn : _aaudDlOff %>"
123 style="<%= t.downloadable ? 'color:var(--accent,#6b8f71)' : 'opacity:.5' %>">⬇</button>
124 <% } %>
125 <form action="/admin/audio/<%= t.id %>/fedi-open" method="post" class="ax-track-fedi" style="display:inline">
126 <button type="submit" class="ax-icon-btn"
127 aria-label="<%= t.fedi_open ? _aaudFediOn : _aaudFediOff %>" title="<%= t.fedi_open ? _aaudFediOn : _aaudFediOff %>"
128 style="<%= t.fedi_open ? 'color:var(--accent,#6b8f71)' : 'opacity:.5' %>">🌐</button>
129 </form>
130 <form action="/admin/audio/<%= t.id %>/delete" method="post" data-confirm="<%= _aaudDelConfirm %>" class="ax-track-delete">
131 <button type="submit" class="ax-icon-btn ax-icon-btn-danger" aria-label="<%= _aaudDelete %>" title="<%= _aaudDelete %>">🗑</button>
132 </form>
133 </div>
134 </li>
135 <% }); %>
136 </ul>
137 <% } %>
138 </section>
139
140 <% if ((typeof premiumUnlocked === 'undefined' || premiumUnlocked) && typeof embedUrl !== 'undefined') { %>
141 <section class="ax-section" style="margin-top:1.5rem">
142 <h2 style="margin:0 0 .4rem">🔊 <%= t('aaud.embed_player') %></h2>
143 <p style="opacity:.75;font-size:.9rem;margin:0 0 .6rem"><%= t('aaud.embed_hint') %></p>
144 <textarea readonly rows="3" data-selectall style="width:100%;font-family:monospace;font-size:12px;padding:10px;border-radius:8px;border:1px solid var(--rule);background:var(--paper-2);color:inherit;">&lt;iframe src="<%= embedUrl %>" width="100%" height="420" frameborder="0" loading="lazy" style="border-radius:12px"&gt;&lt;/iframe&gt;</textarea>
145 <p style="margin:.6rem 0 0"><a class="btn" href="<%= embedUrl %>" target="_blank">▶ <%= t('aaud.preview_player') %></a></p>
146 </section>
147 <% } %>
148
149</div>
150
151<style>
152/* ─── Page wrapper ──────────────────────────────────────────────── */
153.ax-page {
154 max-width: 880px;
155 margin: 1.5rem auto 4rem;
156 padding: 0 1rem;
157}
158.ax-header {
159 display: flex; align-items: flex-start; gap: 0.75rem;
160 margin-bottom: 1.5rem;
161}
162.ax-header h1 {
163 font-family: var(--font-display, serif);
164 font-size: 1.75rem;
165 margin: 0 0 0.25rem;
166}
167.ax-tagline {
168 color: var(--ink-muted, var(--ink-soft));
169 margin: 0;
170 font-size: 0.9rem;
171 line-height: 1.5;
172}
173.ax-tagline code {
174 background: var(--paper-2);
175 padding: 0.1em 0.4em;
176 border-radius: 4px;
177 font-size: 0.9em;
178}
179.ax-back {
180 display: inline-flex; align-items: center; justify-content: center;
181 width: 40px; height: 40px;
182 border: 1px solid var(--rule);
183 border-radius: 8px;
184 background: var(--paper);
185 color: var(--ink);
186 text-decoration: none;
187 font-size: 1.1rem;
188 flex-shrink: 0;
189 transition: border-color 120ms;
190}
191.ax-back:hover { border-color: var(--accent); }
192
193/* ─── Flash messages ───────────────────────────────────────────── */
194.ax-flash {
195 padding: 0.75rem 1rem;
196 border-radius: 8px;
197 margin-bottom: 1rem;
198 font-size: 0.9rem;
199}
200.ax-flash-ok { background: rgba(40,160,90,.15); color: #2a9d5e; border: 1px solid rgba(40,160,90,.3); }
201.ax-flash-err { background: rgba(200,60,60,.15); color: #c33; border: 1px solid rgba(200,60,60,.3); }
202
203/* ─── Card sections ────────────────────────────────────────────── */
204.ax-card {
205 background: var(--paper);
206 border: 1px solid var(--rule);
207 border-radius: 12px;
208 padding: 1.25rem;
209 margin-bottom: 1rem;
210}
211.ax-card-title {
212 font-family: var(--font-display, serif);
213 font-size: 1.15rem;
214 font-weight: 600;
215 margin-bottom: 1rem;
216 display: flex; align-items: baseline; gap: 0.5rem;
217}
218.ax-count {
219 font-family: var(--font-ui, system-ui);
220 font-size: 0.8rem;
221 color: var(--ink-muted, var(--ink-soft));
222 background: var(--paper-2);
223 padding: 0.1em 0.55em;
224 border-radius: 999px;
225 font-weight: 500;
226}
227
228/* ─── Form fields ──────────────────────────────────────────────── */
229.ax-form {
230 display: flex; flex-direction: column;
231 gap: 0.85rem;
232}
233.ax-row {
234 display: grid; gap: 0.85rem;
235}
236.ax-row-2 { grid-template-columns: 1fr 1fr; }
237@media (max-width: 600px) {
238 .ax-row-2 { grid-template-columns: 1fr; }
239}
240.ax-field {
241 display: flex; flex-direction: column;
242 gap: 0.35rem;
243 min-width: 0;
244}
245.ax-field > span {
246 font-size: 0.8rem;
247 font-weight: 600;
248 color: var(--ink-soft);
249 display: flex; align-items: baseline; gap: 0.4rem;
250 flex-wrap: wrap;
251}
252.ax-field > span small {
253 font-weight: 400; color: var(--ink-muted);
254 font-size: 0.95em;
255}
256.ax-field input[type="text"],
257.ax-field input[type="url"],
258.ax-field input[type="email"],
259.ax-field select,
260.ax-field textarea {
261 width: 100%;
262 box-sizing: border-box;
263 padding: 0.6rem 0.75rem;
264 border: 1px solid var(--rule);
265 border-radius: 6px;
266 background: var(--paper-2);
267 color: var(--ink);
268 font-family: var(--font-ui, system-ui), sans-serif;
269 font-size: 0.95rem;
270 -webkit-appearance: none; appearance: none;
271 transition: border-color 120ms;
272}
273.ax-field input:focus,
274.ax-field select:focus,
275.ax-field textarea:focus {
276 outline: 2px solid var(--accent);
277 outline-offset: -1px;
278 border-color: var(--accent);
279}
280
281/* ─── File inputs (custom-styled wrapper) ─────────────────────── */
282.ax-file-control {
283 display: flex; align-items: center; gap: 0.5rem;
284 flex-wrap: wrap;
285 position: relative;
286 min-height: 40px;
287}
288.ax-file-control input[type="file"] {
289 position: absolute; inset: 0;
290 opacity: 0; cursor: pointer;
291 z-index: 2;
292}
293.ax-file-btn {
294 pointer-events: none; /* let clicks pass through to the file input */
295}
296.ax-file-name {
297 font-size: 0.85rem;
298 color: var(--ink);
299 word-break: break-all;
300 flex: 1;
301 min-width: 0;
302}
303.ax-file-name[data-empty] { color: var(--ink-muted, var(--ink-soft)); }
304
305.ax-form-actions {
306 display: flex; gap: 0.5rem;
307 margin-top: 0.25rem;
308}
309.ax-form-actions[hidden] { display: none; }
310
311/* ─── Buttons ──────────────────────────────────────────────────── */
312.ax-btn {
313 display: inline-flex; align-items: center; justify-content: center; gap: 0.4rem;
314 padding: 0.55rem 1rem;
315 border: 1px solid var(--rule);
316 background: var(--paper-2);
317 color: var(--ink);
318 font-family: var(--font-ui, system-ui), sans-serif;
319 font-size: 0.9rem; font-weight: 500;
320 text-decoration: none;
321 border-radius: 6px;
322 cursor: pointer;
323 min-height: 40px;
324 transition: background 120ms, border-color 120ms;
325 -webkit-tap-highlight-color: transparent;
326}
327.ax-btn:hover { border-color: var(--accent); }
328.ax-btn-secondary { background: var(--paper-2); }
329.ax-btn-primary {
330 background: var(--accent); color: white;
331 border-color: var(--accent);
332}
333.ax-btn-primary:hover { opacity: 0.92; border-color: var(--accent); }
334
335/* Tiny icon-only button for row actions */
336.ax-icon-btn {
337 display: inline-flex; align-items: center; justify-content: center;
338 width: 40px; height: 40px;
339 border: 1px solid var(--rule);
340 background: var(--paper-2);
341 color: var(--ink);
342 border-radius: 8px;
343 cursor: pointer;
344 font-size: 1rem;
345 transition: background 120ms, border-color 120ms, color 120ms;
346}
347.ax-icon-btn:hover { border-color: var(--accent); }
348.ax-icon-btn-danger:hover { color: #dc2626; border-color: #dc2626; }
349
350.ax-track-play.is-playing {
351 border-color: var(--accent);
352 color: var(--accent);
353 background: color-mix(in srgb, var(--accent) 12%, var(--paper-2));
354}
355.ax-track-play-icon { font-size: 0.85rem; line-height: 1; }
356
357/* ─── Empty state ──────────────────────────────────────────────── */
358.ax-empty {
359 text-align: center;
360 padding: 2rem 1rem;
361 color: var(--ink-muted, var(--ink-soft));
362}
363.ax-empty-icon {
364 font-size: 2.5rem;
365 font-family: var(--font-display, serif);
366 color: var(--ink-soft);
367 opacity: 0.4;
368 margin-bottom: 0.5rem;
369}
370.ax-empty p { margin: 0; }
371
372/* ─── Track list (card per row) ────────────────────────────────── */
373.ax-list {
374 list-style: none; padding: 0; margin: 0;
375 display: flex; flex-direction: column;
376 gap: 0.6rem;
377}
378.ax-track {
379 display: grid;
380 grid-template-columns: 56px 1fr auto;
381 gap: 0.85rem;
382 align-items: center;
383 padding: 0.75rem;
384 background: var(--paper-2);
385 border: 1px solid var(--rule);
386 border-radius: 10px;
387 transition: border-color 120ms;
388}
389.ax-track:hover { border-color: var(--accent); }
390.ax-track-cover {
391 width: 56px; height: 56px;
392 border-radius: 6px;
393 object-fit: cover;
394 background: var(--paper);
395 display: flex; align-items: center; justify-content: center;
396 font-family: var(--font-display, serif);
397 font-size: 1.5rem;
398 color: var(--accent);
399 flex-shrink: 0;
400}
401.ax-track-cover-empty { /* span variant */ }
402.ax-track-meta {
403 min-width: 0; /* allow text-overflow on long titles */
404 display: flex; flex-direction: column; gap: 0.2rem;
405}
406.ax-track-title {
407 font-weight: 600;
408 font-size: 0.95rem;
409 color: var(--ink);
410 overflow: hidden;
411 text-overflow: ellipsis;
412 white-space: nowrap;
413}
414.ax-track-sub {
415 font-size: 0.8rem;
416 color: var(--ink-muted, var(--ink-soft));
417 display: flex; flex-wrap: wrap; gap: 0.3rem; align-items: center;
418}
419.ax-track-sep { opacity: 0.5; }
420.ax-embed {
421 display: inline-block;
422 background: var(--paper);
423 padding: 0.15rem 0.5rem;
424 border-radius: 4px;
425 font-family: var(--font-mono, ui-monospace, monospace);
426 font-size: 0.75rem;
427 color: var(--ink-soft);
428 cursor: pointer;
429 user-select: all;
430 margin-top: 0.15rem;
431 word-break: break-all;
432 align-self: flex-start;
433 transition: background 120ms;
434}
435.ax-embed:hover { background: var(--rule); }
436.ax-embed.is-copied { background: rgba(40,160,90,0.2); color: #2a9d5e; }
437
438.ax-track-actions {
439 display: flex; gap: 0.4rem;
440 flex-shrink: 0;
441}
442.ax-track-delete { display: inline; }
443
444/* ─── Mobile tweaks ───────────────────────────────────────────── */
445@media (max-width: 480px) {
446 .ax-track {
447 grid-template-columns: 48px 1fr;
448 grid-template-areas: "cover meta" "actions actions";
449 gap: 0.6rem;
450 }
451 .ax-track-cover { grid-area: cover; width: 48px; height: 48px; }
452 .ax-track-meta { grid-area: meta; }
453 .ax-track-actions {
454 grid-area: actions;
455 justify-content: flex-end;
456 border-top: 1px solid var(--rule);
457 padding-top: 0.5rem;
458 margin-top: 0.25rem;
459 }
460}
461
462/* ─── Bulk drop-zone ──────────────────────────────────────────── */
463.ax-dropzone {
464 display: flex; flex-direction: column; align-items: center; justify-content: center;
465 gap: 0.4rem;
466 padding: 2rem 1rem;
467 border: 2px dashed var(--rule);
468 border-radius: 12px;
469 background: var(--paper-2);
470 cursor: pointer;
471 text-align: center;
472 transition: border-color 150ms, background 150ms;
473 position: relative;
474 min-height: 160px;
475}
476.ax-dropzone:hover,
477.ax-dropzone:focus-within {
478 border-color: var(--accent);
479}
480.ax-dropzone.is-dragover {
481 border-color: var(--accent);
482 background: color-mix(in srgb, var(--accent) 8%, var(--paper-2));
483}
484.ax-dropzone input[type="file"] {
485 /* Cover the whole dropzone but invisible — clicks bubble through to it. */
486 position: absolute; inset: 0;
487 opacity: 0;
488 cursor: pointer;
489}
490.ax-dropzone-icon {
491 font-size: 2rem;
492 opacity: 0.5;
493 line-height: 1;
494}
495.ax-dropzone-title {
496 font-size: 1rem;
497 font-weight: 600;
498 color: var(--ink);
499}
500.ax-dropzone-sub {
501 font-size: 0.85rem;
502 color: var(--ink-muted, var(--ink-soft));
503 line-height: 1.4;
504}
505.ax-dropzone-sub small {
506 font-size: 0.75rem;
507 opacity: 0.8;
508}
509
510/* ─── Upload queue ────────────────────────────────────────────── */
511.ax-upload-queue {
512 list-style: none;
513 padding: 0; margin: 0.75rem 0 0;
514 display: flex; flex-direction: column;
515 gap: 0.4rem;
516}
517.ax-queue-item {
518 display: grid;
519 grid-template-columns: 1fr auto;
520 gap: 0.75rem;
521 align-items: center;
522 padding: 0.6rem 0.85rem;
523 background: var(--paper);
524 border: 1px solid var(--rule);
525 border-radius: 8px;
526 font-size: 0.875rem;
527 transition: border-color 150ms, opacity 150ms;
528}
529.ax-queue-item--active {
530 border-color: var(--accent);
531}
532.ax-queue-item--done {
533 border-color: rgba(40,160,90,0.4);
534 opacity: 0.85;
535}
536.ax-queue-item--error {
537 border-color: rgba(220,60,60,0.5);
538}
539.ax-queue-name {
540 font-weight: 500;
541 color: var(--ink);
542 overflow: hidden;
543 text-overflow: ellipsis;
544 white-space: nowrap;
545 min-width: 0;
546}
547.ax-queue-size {
548 font-size: 0.75rem;
549 color: var(--ink-muted, var(--ink-soft));
550 margin-left: 0.5rem;
551}
552.ax-queue-status {
553 font-size: 0.75rem;
554 font-weight: 500;
555 padding: 0.15em 0.6em;
556 border-radius: 999px;
557 background: var(--paper-2);
558 color: var(--ink-soft);
559 white-space: nowrap;
560 flex-shrink: 0;
561}
562.ax-queue-status--queued { color: var(--ink-muted, var(--ink-soft)); }
563.ax-queue-status--uploading,
564.ax-queue-status--transcoding {
565 color: var(--accent);
566 background: color-mix(in srgb, var(--accent) 10%, var(--paper-2));
567}
568.ax-queue-status--done {
569 color: #2a9d5e;
570 background: rgba(40,160,90,0.12);
571}
572.ax-queue-status--error {
573 color: #dc2626;
574 background: rgba(220,60,60,0.12);
575}
576</style>
577
578<%# Track editor modal (exposes window.openTrackEditor) %>
579<%- include('../partials/track-editor', { csrfToken: (typeof csrfToken !== 'undefined' ? csrfToken : '') }) %>
580
581<script>
582(function() {
583
584 // ── Live filename display for custom file inputs ──────────────
585 document.querySelectorAll('.ax-file-control input[type="file"]').forEach(input => {
586 const nameEl = input.parentElement.querySelector('.ax-file-name');
587 if (!nameEl) return;
588 input.addEventListener('change', () => {
589 if (input.files && input.files[0]) {
590 nameEl.textContent = input.files[0].name;
591 nameEl.removeAttribute('data-empty');
592 } else {
593 nameEl.textContent = '<%= t('aaud.no_file') %>';
594 nameEl.setAttribute('data-empty', '');
595 }
596 });
597 });
598
599 // ── Inline track preview (routed through the global mini-player) ──
600 // Each .ax-track-play button is a thin wrapper around the global
601 // window.pcmsAudioPlayer.setQueue([...]) call. Visual state (▶ / ⏸ /
602 // .is-playing) is synced from the player's own audio element so it
603 // stays accurate even when the user uses the mini-player's controls.
604 (function setupTrackPreview() {
605 const buttons = document.querySelectorAll('.ax-track-play');
606 if (!buttons.length) return;
607
608 function setIcon(btn, playing) {
609 const icon = btn.querySelector('.ax-track-play-icon');
610 if (icon) icon.textContent = playing ? '⏸' : '▶';
611 btn.classList.toggle('is-playing', playing);
612 btn.setAttribute('aria-label', playing ? '<%= t('aaud.pause') %>' : '<%= t('aaud.play') %>');
613 }
614
615 // Resync ALL preview buttons against the current audio element state.
616 // Called on every play/pause/ended event so admins always see the right
617 // icon — including the case where they hit pause on the mini-player
618 // bar instead of the row's button.
619 function resyncAll() {
620 const audio = document.getElementById('audio-element');
621 const player = window.pcmsAudioPlayer;
622 const playing = audio && !audio.paused && !audio.ended;
623 // audio.src is now a blob: URL (Spotify-style playback), so compare
624 // against the player's logical track URL, not the element src.
625 const cur = player && player.currentTrack();
626 const curUrl = cur ? cur.url : '';
627 buttons.forEach(b => {
628 const isThisOne = playing && curUrl === b.dataset.streamUrl;
629 setIcon(b, isThisOne);
630 });
631 }
632
633 buttons.forEach(btn => {
634 btn.addEventListener('click', e => {
635 e.preventDefault();
636 const player = window.pcmsAudioPlayer;
637 if (!player) {
638 console.warn('[admin-audio] miniplayer not available');
639 return;
640 }
641 const url = btn.dataset.streamUrl;
642 if (!url) return;
643
644 // Build track metadata from the row's DOM so the mini-player shows
645 // useful info (title/artist/album/cover) without an extra API call.
646 const row = btn.closest('.ax-track');
647 const titleEl = row && row.querySelector('[data-cell="title"]');
648 const artistEl = row && row.querySelector('[data-cell="artist"]');
649 const albumEl = row && row.querySelector('[data-cell="album"]');
650 const coverImg = row && row.querySelector('img[data-cover-thumb]');
651 const track = {
652 url,
653 title: titleEl ? titleEl.textContent.trim() : 'Track',
654 artist: artistEl ? artistEl.textContent.trim() : '',
655 album: albumEl ? albumEl.textContent.trim() : '',
656 cover: coverImg ? coverImg.src : '',
657 };
658
659 // If this exact track is already current, toggle pause/play instead
660 // of restarting from zero. Compare logical URLs (audio.src is a blob:).
661 const cur = player.currentTrack();
662 if (cur && cur.url === url) {
663 if (player.isPlaying()) player.pause();
664 else player.play();
665 return;
666 }
667
668 player.setQueue([track], 0);
669 });
670 });
671
672 // Hook the global audio element's events to keep the row buttons synced.
673 // We attach lazily after the player has built its DOM. The script in
674 // shell.ejs runs at page-load so #audio-element exists by the time
675 // this IIFE fires (script tag is below the body content).
676 const audio = document.getElementById('audio-element');
677 if (audio) {
678 ['play', 'pause', 'ended', 'loadstart', 'emptied'].forEach(ev => {
679 audio.addEventListener(ev, resyncAll);
680 });
681 // Initial state on page load (e.g. user navigated back while a track
682 // was already playing — buttons should reflect that).
683 resyncAll();
684 }
685 })();
686
687
688 // ── Bulk upload (drag-drop + sequential transcoding) ─────────
689 // Files dropped or picked are queued (not uploaded immediately) so the
690 // user can review the list, set shared metadata, then hit "Start upload".
691 // The loop POSTs one file at a time to /admin/audio/upload with
692 // Accept: application/json so the server returns structured per-file
693 // results instead of redirecting.
694 const dropzone = document.getElementById('audio-dropzone');
695 const fileInput = document.getElementById('audio-files');
696 const queueEl = document.getElementById('upload-queue');
697 const actionsEl = document.getElementById('upload-actions');
698 const startBtn = document.getElementById('start-upload-btn');
699 const clearBtn = document.getElementById('clear-queue-btn');
700 const artistInput= document.getElementById('batch-artist');
701 const albumInput = document.getElementById('batch-album');
702 const coverInput = document.getElementById('batch-cover');
703
704 /** @type {Array<{file: File, el: HTMLElement, status: string}>} */
705 const queue = [];
706
707 function fmtBytes(n) {
708 if (n < 1024) return n + ' B';
709 if (n < 1024 * 1024) return (n / 1024).toFixed(0) + ' KB';
710 return (n / 1024 / 1024).toFixed(1) + ' MB';
711 }
712
713 function setItemStatus(item, status, label) {
714 const labels = {
715 queued: '<%= t('aaud.st_queued') %>',
716 uploading: '<%= t('aaud.st_uploading') %>',
717 transcoding: '<%= t('aaud.st_transcoding') %>',
718 done: '✓ <%= t('aaud.st_done') %>',
719 error: '✗ <%= t('aaud.st_error') %>',
720 };
721 item.status = status;
722 const badge = item.el.querySelector('.ax-queue-status');
723 badge.className = 'ax-queue-status ax-queue-status--' + status;
724 badge.textContent = label || labels[status] || status;
725 // Restyle the row
726 item.el.classList.remove(
727 'ax-queue-item--active', 'ax-queue-item--done', 'ax-queue-item--error'
728 );
729 if (status === 'uploading' || status === 'transcoding') item.el.classList.add('ax-queue-item--active');
730 else if (status === 'done') item.el.classList.add('ax-queue-item--done');
731 else if (status === 'error') item.el.classList.add('ax-queue-item--error');
732 }
733
734 function addFiles(files) {
735 let added = 0;
736 for (const file of files) {
737 if (!file.type.startsWith('audio/') &&
738 !/\.(mp3|m4a|ogg|opus|flac|wav|webm|aac|oga|mp4)$/i.test(file.name)) {
739 // Silently skip non-audio drops; keeps the UX uncluttered.
740 continue;
741 }
742 const li = document.createElement('li');
743 li.className = 'ax-queue-item';
744 li.innerHTML =
745 '<div class="ax-queue-name"></div>' +
746 '<span class="ax-queue-status ax-queue-status--queued"><%= t('aaud.st_queued') %></span>';
747 // Use textContent to avoid HTML-injection if a filename contains markup.
748 li.querySelector('.ax-queue-name').textContent = file.name;
749 // Append size hint inline
750 const size = document.createElement('span');
751 size.className = 'ax-queue-size';
752 size.textContent = fmtBytes(file.size);
753 li.querySelector('.ax-queue-name').appendChild(size);
754 queueEl.appendChild(li);
755 queue.push({ file, el: li, status: 'queued' });
756 added++;
757 }
758 if (added) {
759 queueEl.hidden = false;
760 actionsEl.hidden = false;
761 }
762 }
763
764 // ── Drop-zone events ─────────────────────────────────────────
765 // Page-level guard: a dropped file outside the zone would otherwise
766 // make the browser navigate to it (e.g. opening the audio inline), which
767 // discards typed metadata. We swallow drops anywhere unless the dropzone
768 // explicitly handles them.
769 ['dragover', 'drop'].forEach(ev => {
770 window.addEventListener(ev, e => {
771 // Allow drops INSIDE the dropzone — its own listener handles those.
772 if (dropzone.contains(e.target)) return;
773 e.preventDefault();
774 });
775 });
776
777 ['dragenter', 'dragover'].forEach(ev => {
778 dropzone.addEventListener(ev, e => {
779 e.preventDefault();
780 dropzone.classList.add('is-dragover');
781 });
782 });
783 ['dragleave', 'drop'].forEach(ev => {
784 dropzone.addEventListener(ev, e => {
785 e.preventDefault();
786 dropzone.classList.remove('is-dragover');
787 });
788 });
789 dropzone.addEventListener('drop', e => {
790 if (e.dataTransfer && e.dataTransfer.files) addFiles(e.dataTransfer.files);
791 });
792 fileInput.addEventListener('change', () => {
793 addFiles(fileInput.files);
794 // Reset so the same file can be picked again later if user wants
795 fileInput.value = '';
796 });
797
798 // ── Clear queue button ───────────────────────────────────────
799 clearBtn.addEventListener('click', () => {
800 // Only remove items that aren't currently uploading (anything queued
801 // or already finished). An in-progress upload finishes, then its row
802 // would also disappear once we re-render — but we keep it simple and
803 // just refuse to clear during an active run.
804 if (startBtn.disabled) return;
805 queue.length = 0;
806 queueEl.innerHTML = '';
807 queueEl.hidden = true;
808 actionsEl.hidden = true;
809 });
810
811 // ── Sequential upload loop ───────────────────────────────────
812 startBtn.addEventListener('click', async () => {
813 if (startBtn.disabled) return;
814 startBtn.disabled = true;
815 clearBtn.disabled = true;
816 dropzone.style.pointerEvents = 'none';
817 dropzone.style.opacity = '0.5';
818
819 const sharedArtist = artistInput.value.trim();
820 const sharedAlbum = albumInput.value.trim();
821 const sharedCover = coverInput.files && coverInput.files[0];
822
823 // Process queued items one at a time. We iterate via index so that
824 // if more files get dropped during the run they ALSO get processed
825 // (queue.push above mutates the same array we're iterating).
826 for (let i = 0; i < queue.length; i++) {
827 const item = queue[i];
828 if (item.status !== 'queued') continue;
829 try {
830 await uploadOne(item, sharedArtist, sharedAlbum, sharedCover);
831 } catch (err) {
832 console.error('upload failed for', item.file.name, err);
833 setItemStatus(item, 'error', '✗ ' + (err.message || '<%= t('aaud.failed') %>'));
834 }
835 }
836
837 startBtn.disabled = false;
838 clearBtn.disabled = false;
839 dropzone.style.pointerEvents = '';
840 dropzone.style.opacity = '';
841
842 // Reload the page so the new tracks appear in the list below.
843 // Could also fetch them and inject, but a full reload is simpler and
844 // ensures position indexes / album-grouping are correct.
845 const anyDone = queue.some(q => q.status === 'done');
846 if (anyDone) {
847 setTimeout(() => location.reload(), 700);
848 }
849 });
850
851 async function uploadOne(item, sharedArtist, sharedAlbum, sharedCover) {
852 setItemStatus(item, 'uploading');
853
854 const fd = new FormData();
855 fd.append('audio', item.file);
856 if (sharedArtist) fd.append('artist', sharedArtist);
857 if (sharedAlbum) fd.append('album', sharedAlbum);
858 if (sharedCover) fd.append('cover', sharedCover);
859 // Title is intentionally omitted — server uses filename fallback.
860
861 // We can't reliably distinguish "still uploading bytes" from
862 // "uploading done, ffmpeg running" without progress events, but the
863 // status flips to "Converteren…" once the request is past upload phase.
864 // We approximate this by waiting until the response arrives — by then
865 // both phases are complete on the server side. For a smoother feel we
866 // briefly show "transcoding" near the end of the request lifecycle.
867 const transcodeHint = setTimeout(() => {
868 if (item.status === 'uploading') setItemStatus(item, 'transcoding');
869 }, 1500);
870
871 try {
872 const res = await fetch('/admin/audio/upload', {
873 method: 'POST',
874 headers: { 'Accept': 'application/json' },
875 body: fd,
876 credentials: 'same-origin',
877 });
878 clearTimeout(transcodeHint);
879
880 // Server responds with JSON for our Accept header. If it didn't
881 // (e.g. session expired and got an HTML login page), surface that.
882 let data;
883 try { data = await res.json(); }
884 catch (_) { throw new Error('<%= t('aaud.err_unexpected') %> (' + res.status + ')'); }
885
886 if (!res.ok || !data.ok) {
887 throw new Error(data.error || ('HTTP ' + res.status));
888 }
889
890 setItemStatus(item, 'done', '✓ ' + (data.title || '<%= t('aaud.st_done') %>'));
891 } catch (err) {
892 clearTimeout(transcodeHint);
893 throw err;
894 }
895 }
896
897 // ── Click-to-copy embed codes ─────────────────────────────────
898 document.querySelectorAll('[data-copy]').forEach(el => {
899 el.addEventListener('click', async () => {
900 const text = el.dataset.copy;
901 try {
902 await navigator.clipboard.writeText(text);
903 el.classList.add('is-copied');
904 const original = el.textContent;
905 el.textContent = '✓ <%= t('aaud.copied') %>';
906 setTimeout(() => {
907 el.classList.remove('is-copied');
908 el.textContent = original;
909 }, 1200);
910 } catch (_) { /* fall through — selection still works */ }
911 });
912 });
913
914 // ── "+ Track zonder audio": maak een link-only stub + open de editor ──
915 const addLinkBtn = document.getElementById('add-link-track-btn');
916 if (addLinkBtn) {
917 addLinkBtn.addEventListener('click', async () => {
918 addLinkBtn.disabled = true;
919 try {
920 const r = await fetch('/admin/audio/create-link', {
921 method: 'POST', credentials: 'same-origin',
922 headers: { 'Content-Type': 'application/json' },
923 body: JSON.stringify({ title: '<%= t('aaud.new_track') %>' }),
924 });
925 const j = await r.json();
926 if (!r.ok || !j.ok) throw new Error(j.error || '<%= t('aaud.create_failed') %>');
927 if (typeof window.openTrackEditor !== 'function') { location.reload(); return; }
928 window.openTrackEditor({ id: j.id, onSaved: () => location.reload() });
929 } catch (err) {
930 alert('<%= t('aaud.create_failed') %>: ' + err.message);
931 } finally {
932 addLinkBtn.disabled = false;
933 }
934 });
935 }
936
937 // ── Wire all "Edit" buttons to the track-editor modal ─────────
938 // After save we patch the row in-place rather than reloading,
939 // so the user keeps their scroll position on long lists.
940 document.querySelectorAll('[data-track-edit]').forEach(btn => {
941 btn.addEventListener('click', () => {
942 if (typeof window.openTrackEditor !== 'function') {
943 alert('<%= t('aaud.editor_not_loaded') %>');
944 return;
945 }
946 const id = btn.dataset.id;
947 window.openTrackEditor({
948 id,
949 onSaved: (track) => {
950 const row = document.querySelector('li[data-track-id="' + id + '"]');
951 if (!row) return;
952 // Update visible cells
953 const titleEl = row.querySelector('[data-cell="title"]');
954 const artistEl = row.querySelector('[data-cell="artist"]');
955 const albumEl = row.querySelector('[data-cell="album"]');
956 if (titleEl) titleEl.textContent = track.title || '<%= t('aaud.untitled') %>';
957 if (artistEl) artistEl.textContent = track.artist || '—';
958 if (albumEl) {
959 albumEl.textContent = track.album || '';
960 if (track.album) albumEl.removeAttribute('hidden');
961 else albumEl.setAttribute('hidden', '');
962 }
963 // Update cover thumb (replace element if type changed)
964 const oldThumb = row.querySelector('[data-cover-thumb]');
965 if (oldThumb) {
966 const parent = oldThumb.parentElement;
967 if (track.cover_url) {
968 const img = document.createElement('img');
969 img.className = 'ax-track-cover';
970 img.src = track.cover_url;
971 img.alt = '';
972 img.dataset.coverThumb = '';
973 parent.replaceChild(img, oldThumb);
974 } else {
975 const sp = document.createElement('span');
976 sp.className = 'ax-track-cover ax-track-cover-empty';
977 sp.textContent = '♫';
978 sp.dataset.coverThumb = '';
979 parent.replaceChild(sp, oldThumb);
980 }
981 }
982 },
983 });
984 });
985 });
986
987 // Download-voor-email toggle — AJAX (geen pagina-reload meer).
988 document.querySelectorAll('[data-track-dl]').forEach(btn => {
989 btn.addEventListener('click', async () => {
990 if (btn.disabled) return;
991 const want = btn.dataset.on === '1' ? 0 : 1;
992 btn.disabled = true;
993 try {
994 const res = await fetch('/admin/audio/api/' + btn.dataset.id, {
995 method: 'POST',
996 headers: { 'Content-Type': 'application/json' },
997 body: JSON.stringify({ downloadable: !!want }),
998 });
999 if (!res.ok) throw new Error('HTTP ' + res.status);
1000 btn.dataset.on = String(want);
1001 btn.style.color = want ? 'var(--accent,#6b8f71)' : '';
1002 btn.style.opacity = want ? '1' : '.5';
1003 btn.title = want
1004 ? '<%= t('aaud.dl_on') %>'
1005 : '<%= t('aaud.dl_off') %>';
1006 } catch (e) {
1007 alert('<%= t('aaud.change_failed') %>: ' + (e.message || e));
1008 } finally {
1009 btn.disabled = false;
1010 }
1011 });
1012 });
1013})();
1014</script>
Note: See TracBrowser for help on using the repository browser.