Post

↻ ◁ || ▷ ↺ Musique - Générateur de playlist

↻ ◁ || ▷ ↺ Musique - Générateur de playlist

Web - Générateur playlist musical

Toutes les opérations sont effectuées sur le serveur cwwk (192.168.0.205)

“Playlists uniquement avec dossier absolu pour les applis de type Subsonic”
Ce code exporte des chemins absolus issus de music-path :
/sharenfs/multimedia/Music/musicyan/.../fichier.mp3

Dossier travail: /sharenfs/rnmkcy/web-music-playlist

Python venv + flask + uwsgi

1
2
3
4
5
6
7
8
# Créer le dossier projet
mkdir -p /sharenfs/rnmkcy/web-music-playlist
chown -R $USER:$USER /sharenfs/rnmkcy/web-music-playlist
cd /sharenfs/rnmkcy/web-music-playlist
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip wheel
pip install flask uwsgi

Écrire app.py (export .m3u avec chemins absolus)

Créer app.py dans /sharenfs/rnmkcy/web-music-playlist/ :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
import os
from pathlib import Path

from flask import Flask, request, Response, render_template_string, abort, jsonify

app = Flask(__name__)

MUSIC_ROOT = Path(os.environ.get("MUSIC_ROOT", "/sharenfs/multimedia/Music/musicyan")).resolve()

# index : { artist: { album_or_None: [ {name, rel}...] } }
def build_index():
    index = {}
    if not MUSIC_ROOT.exists():
        return index

    mp3_exts = {".mp3"}

    def is_mp3(p: Path) -> bool:
        return p.is_file() and p.suffix.lower() in mp3_exts

    for artist_dir in sorted([p for p in MUSIC_ROOT.iterdir() if p.is_dir()]):
        artist = artist_dir.name
        index.setdefault(artist, {})

        # cas : mp3 directement dans /Artist/
        direct = []
        for f in sorted([p for p in artist_dir.iterdir() if is_mp3(p)]):
            rel = f.relative_to(MUSIC_ROOT).as_posix()
            direct.append({"name": f.stem, "rel": rel})
        if direct:
            index[artist]["~direct"] = direct

        # cas : /Artist/Album/*.mp3
        for album_dir in sorted([p for p in artist_dir.iterdir() if p.is_dir()]):
            album = album_dir.name
            tracks = []
            for f in sorted([p for p in album_dir.iterdir() if is_mp3(p)]):
                rel = f.relative_to(MUSIC_ROOT).as_posix()
                tracks.append({"name": f.stem, "rel": rel})
            if tracks:
                index[artist][album] = tracks

    return index


INDEX = build_index()

def make_m3u_from_rels(rels, title="Playlist"):
    lines = ["#EXTM3U"]
    # IMPORTANT : chemins absolus serveur, comme tu as constaté que ça marche
    for rel in rels:
        abs_path = (MUSIC_ROOT / rel).resolve()
        lines.append(str(abs_path))
    return "\n".join(lines) + "\n"

@app.route("/api/index")
def api_index():
    # rescan simple à la volée (sinon mets en cache + option)
    global INDEX
    INDEX = build_index()
    return jsonify(INDEX)

@app.route("/export", methods=["POST"])
def export():
    global INDEX
    if not INDEX:
        INDEX = build_index()

    title = (request.form.get("title") or "Playlist").strip()[:120] or "Playlist"
    rels = request.form.getlist("track")

    # filtrage par sécurité
    valid = set()
    for _, albums in INDEX.items():
        for _, tracks in albums.items():
            for t in tracks:
                valid.add(t["rel"])

    chosen = [r for r in rels if r in valid]
    if not chosen:
        abort(400, "Aucun morceau sélectionné")

    m3u = make_m3u_from_rels(chosen, title=title)

    filename = title.replace('"', "").replace("/", "_").replace("\\", "_") + ".m3u"
    headers = {
        "Content-Type": "audio/x-mpegurl; charset=utf-8",
        "Content-Disposition": f'attachment; filename="{filename}"'
    }
    return Response(m3u, headers=headers)

@app.route("/")
def ui():
    return render_template_string("""
<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>Playlist globale (.m3u)</title>
<style>
  :root{
    --pad: 16px;
    --gap: 16px;
    --radius: 8px;

    --bg: #ffffff;
    --text: #111111;
    --muted: #666666;
    --box-border: #dddddd;
    --box-bg: #ffffff;
    --btn-bg: #fafafa;
    --btn-border: #cccccc;
    --input-border: #cccccc;
  }

  /* Sombre par défaut */
  html[data-theme="dark"]{
    --bg: #0f1115;
    --text: #e8eaf0;
    --muted: #a0a4b3;
    --box-border: #2a2f3a;
    --box-bg: #141824;
    --btn-bg: #1a2130;
    --btn-border: #323a4c;
    --input-border: #323a4c;
  }

  * { box-sizing: border-box; }

  html, body { height: 100%; }

  body {
    font-family: sans-serif;
    margin: var(--pad);
    color: var(--text);
    background: var(--bg);
  }

  h2 { margin-top: 0; }

  .grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: var(--gap);
    align-items: start;
  }

  @media (max-width: 820px){
    body { margin: 12px; }
    .grid { grid-template-columns: 1fr; }
  }

  .box {
    border: 1px solid var(--box-border);
    padding: 12px;
    border-radius: var(--radius);
    background: var(--box-bg);
  }

  input[type="search"] {
    width: 100%;
    padding: 10px 10px;
    border-radius: 6px;
    border: 1px solid var(--input-border);
    background: transparent;
    color: var(--text);
    outline: none;
  }
  input[type="search"]::placeholder { color: var(--muted); }

  .muted { color: var(--muted); font-size: 12px; }

  button {
    padding: 10px 14px;
    cursor: pointer;
    margin-right: 8px;
    margin-bottom: 8px;
    border-radius: 6px;
    border: 1px solid var(--btn-border);
    background: var(--btn-bg);
    color: var(--text);
  }

  .actions{
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
  }

  .topbar{
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 10px;
  }

  .themeBtn{
    margin: 0;
    white-space: nowrap;
  }

  ul { list-style: none; padding-left: 0; margin: 10px 0 0 0; }
  li { margin: 6px 0; }

  .track { display: flex; align-items: center; gap: 8px; }

  .track label {
    cursor: pointer;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 100%;
  }

  #selection-panel {
    max-height: 180px;
    overflow: auto;
    font-size: 13px;
    line-height: 1.4;
  }

  .spacer { height: 16px; }
</style>
</head>
<body>
  <div class="topbar">
    <h2 style="margin:0;">Playlist globale (.m3u)</h2>
    <button id="themeToggle" class="themeBtn" type="button">Clair</button>
  </div>

  <div class="grid">
    <div class="box">
      <b>Recherche</b>
      <div class="spacer" style="height:8px"></div>
      <input id="q" type="search" placeholder="ex: Paranoid, Thunderstruck..."/>
      <div class="spacer" style="height:10px"></div>
      <div class="muted">Coche/décoche puis “Exporter .m3u”.</div>
    </div>

    <div class="box">
      <b>Sélection</b>
      <div class="spacer" style="height:8px"></div>
      <div class="muted" id="count">0 morceaux</div>
      <div class="spacer" style="height:12px"></div>

      <div class="actions">
        <button onclick="exportM3U()">Exporter .m3u</button>
        <button onclick="toggleAll(true)">Tout cocher</button>
        <button onclick="toggleAll(false)">Tout décocher</button>
      </div>
    </div>
  </div>

  <div class="spacer"></div>

  <div class="box">
    <b>Vue sur la sélection</b>
    <div class="spacer" style="height:8px"></div>
    <div class="muted"><span id="selection-count">0</span> morceaux cochés</div>
    <div class="spacer" style="height:10px"></div>
    <div id="selection-panel" style="max-height:180px; overflow:auto; font-size:13px; line-height:1.4;">
      <div id="selection-list"></div>
    </div>
  </div>

  <div class="spacer"></div>
  <div id="content" class="box"></div>

<script>
let INDEX = null;
let collapsed = {}; // "artist|album" ; album peut être "~direct"
let lastQuery = "";
// --- thème sombre/claire
(function(){
  // sombre par défaut
  const saved = localStorage.getItem("theme");
  const theme = saved || "dark";
  document.documentElement.setAttribute("data-theme", theme);

  const btn = document.getElementById("themeToggle");
  const label = () => {
    const t = document.documentElement.getAttribute("data-theme");
    btn.textContent = (t === "dark") ? "Clair" : "Sombre";
  };

  label();

  btn.addEventListener("click", () => {
    const cur = document.documentElement.getAttribute("data-theme");
    const next = (cur === "dark") ? "light" : "dark";
    document.documentElement.setAttribute("data-theme", next);
    localStorage.setItem("theme", next);
    label();
  });
})();

// --- helpers
function keyFor(artist, album){ return artist + "|" + album; }

function ensureCollapsedIndex(index){
  collapsed = {};
  for (const artist of Object.keys(index).sort()){
    collapsed[keyFor(artist, "__artist__")] = true;
    const albums = index[artist] || {};
    for (const album of Object.keys(albums).sort()){
      collapsed[keyFor(artist, album)] = true;
    }
  }
}

function allTrackRels(index){
  const rels = [];
  for (const artist of Object.keys(index)){
    const albums = index[artist] || {};
    for (const album of Object.keys(albums)){
      const tracks = albums[album] || [];
      for (const t of tracks) rels.push(t.rel);
    }
  }
  return rels;
}

function getSelectedRels(){
  const selected = new Set();
  document.querySelectorAll('input[type="checkbox"][name="track"]:checked').forEach(cb => selected.add(cb.value));
  return selected;
}

function setSelectedRelsToAll(on){
  const rels = allTrackRels(INDEX);
  const selected = new Set();
  if (on) rels.forEach(r => selected.add(r));

  const checkboxes = document.querySelectorAll('input[type="checkbox"][name="track"]');
  checkboxes.forEach(cb => cb.checked = selected.has(cb.value));

  renderSelectionView();
  updateCount();
}

function updateCount(){
  const count = document.querySelectorAll('input[type="checkbox"][name="track"]:checked').length;
  document.getElementById("count").textContent = count + " morceaux";
}

function renderSelectionView(){
  const panel = document.getElementById("selection-panel");
  if (!panel) return;

  const selected = getSelectedRels();
  const relToTrack = new Map();
  for (const artist of Object.keys(INDEX)){
    const albums = INDEX[artist] || {};
    for (const album of Object.keys(albums)){
      const tracks = albums[album] || [];
      for (const t of tracks){
        relToTrack.set(t.rel, { artist, album, name: t.name });
      }
    }
  }

  const arr = Array.from(selected).map(rel => {
    const meta = relToTrack.get(rel) || { artist:"?", album:"?", name:rel };
    const albumLabel = (meta.album === "~direct") ? "(morceaux directs)" : meta.album;
    return meta.artist + " / " + albumLabel + "" + meta.name;
  }).sort();

  document.getElementById("selection-count").textContent = arr.length;

  const list = document.getElementById("selection-list");
  list.innerHTML = "";
  if (arr.length === 0){
    const li = document.createElement("div");
    li.style.color = "#666";
    li.textContent = "Rien sélectionné.";
    list.appendChild(li);
    return;
  }

  const maxItems = 200;
  const slice = arr.slice(0, maxItems);
  slice.forEach(txt => {
    const div = document.createElement("div");
    div.textContent = txt;
    list.appendChild(div);
  });

  if (arr.length > maxItems){
    const more = document.createElement("div");
    more.style.color = "#666";
    more.textContent = "… et " + (arr.length - maxItems) + " autres";
    list.appendChild(more);
  }
}

function bindCount(){
  document.querySelectorAll('input[type="checkbox"][name="track"]').forEach(cb => {
    cb.onchange = () => { updateCount(); renderSelectionView(); };
  });
}

// --- render
function render(index, q=""){
  lastQuery = q;
  const content = document.getElementById("content");
  content.innerHTML = "";

  const prevSelected = getSelectedRels();

  const artists = Object.keys(index).sort();
  for (const artist of artists){
    const albums = index[artist] || {};

    const artistReduced = !!collapsed[keyFor(artist, "__artist__")];

    const artistBox = document.createElement("div");
    artistBox.style.marginBottom = "14px";

    const artistHeader = document.createElement("div");
    artistHeader.style.display = "flex";
    artistHeader.style.alignItems = "center";
    artistHeader.style.gap = "8px";

    const artistToggle = document.createElement("button");
    artistToggle.textContent = (artistReduced ? "+" : "");
    artistToggle.onclick = () => {
      collapsed[keyFor(artist, "__artist__")] = !collapsed[keyFor(artist, "__artist__")];
      render(INDEX, document.getElementById("q").value.toLowerCase() || "");
    };

    const artistTitle = document.createElement("div");
    artistTitle.innerHTML = "<b>" + artist + "</b>";

    artistHeader.appendChild(artistToggle);
    artistHeader.appendChild(artistTitle);
    artistBox.appendChild(artistHeader);

    let any = false;

    const searching = !!q;

    for (const album of Object.keys(albums).sort()){
      const tracks = albums[album] || [];

      const visible = tracks.filter(t => {
        if (!q) return true;
        const hay = (artist + " " + (album === "~direct" ? "" : album) + " " + t.name).toLowerCase();
        return hay.includes(q);
      });
      if (visible.length === 0) continue;

      any = true;

      if (artistReduced && !searching) continue;

      const collapsedAlbum = !!collapsed[keyFor(artist, album)];

      const albumWrapper = document.createElement("div");

      const albumHeader = document.createElement("div");
      albumHeader.style.display = "flex";
      albumHeader.style.alignItems = "center";
      albumHeader.style.gap = "8px";
      albumHeader.style.marginTop = "8px";

      const albumToggle = document.createElement("button");
      albumToggle.textContent = (collapsedAlbum ? "+" : "");
      albumToggle.onclick = () => {
        collapsed[keyFor(artist, album)] = !collapsed[keyFor(artist, album)];
        render(INDEX, document.getElementById("q").value.toLowerCase() || "");
      };

      const albumTitle = document.createElement("div");
      albumTitle.className = "muted";
      albumTitle.textContent = (album === "~direct") ? "(morceaux directs)" : album;

      albumHeader.appendChild(albumToggle);
      albumHeader.appendChild(albumTitle);
      albumWrapper.appendChild(albumHeader);

      if (!collapsedAlbum || searching){
        const ul = document.createElement("ul");
        for (const t of visible){
          const li = document.createElement("li");
          li.className = "track";

          const cb = document.createElement("input");
          cb.type = "checkbox";
          cb.checked = prevSelected.has(t.rel);
          cb.name = "track";
          cb.value = t.rel;

          const label = document.createElement("label");
          label.textContent = t.name;

          li.appendChild(cb);
          li.appendChild(label);
          ul.appendChild(li);
        }
        albumWrapper.appendChild(ul);
      }

      artistBox.appendChild(albumWrapper);
    }

    if (any) content.appendChild(artistBox);
  }

  bindCount();
  updateCount();
  renderSelectionView();
}

function toggleAll(on){
  setSelectedRelsToAll(on);
}

// --- export
async function exportM3U(){
  let rels = Array.from(getSelectedRels());
  if (rels.length === 0){ alert("Aucun morceau sélectionné."); return; }

  for (let i = rels.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [rels[i], rels[j]] = [rels[j], rels[i]];
  }

  const title = prompt("Nom de la playlist :", "Playlist") || "Playlist";
  const form = new URLSearchParams();
  form.append("title", title);
  rels.forEach(r => form.append("track", r));

  const res = await fetch("/export", {
    method: "POST",
    headers: {"Content-Type": "application/x-www-form-urlencoded"},
    body: form.toString()
  });

  if (!res.ok){ alert("Erreur export: " + res.status); return; }

  const blob = await res.blob();
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;

  const safeName = (title).replace(/[^a-zA-Z0-9_-]+/g, "_");
  a.download = safeName + ".m3u";
  document.body.appendChild(a);
  a.click();
  a.remove();
  URL.revokeObjectURL(url);
}

// recherche
document.getElementById("q").addEventListener("input", (e) => {
  const qq = (e.target.value || "").toLowerCase();
  render(INDEX, qq);
});

// init
(async function init(){
  const res = await fetch("/api/index");
  INDEX = await res.json();

  ensureCollapsedIndex(INDEX);
  render(INDEX, "");
})();
</script>

</body>
</html>
""")

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5100, debug=False)

Vérification syntaxe et indentation

une commande pour vérifier si aucune erreur de syntaxe ou indentation

1
2
3
4
5
# Si pas le prompt (.venv) yick@alder:/sharenfs/rnmkcy/web-music-playlist$
cd /sharenfs/rnmkcy/web-music-playlist
source .venv/bin/activate
# vérification syntaxe
python -m py_compile app.py # Ne renvoie rien -> OK

Lancer manuellement pour test

1
2
3
source /sharenfs/rnmkcy/web-music-playlist/.venv/bin/activate
cd /sharenfs/rnmkcy/web-music-playlist
python app.py

Si tout est ok

1
2
3
4
5
  * Serving Flask app 'app'
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5100
Press CTRL+C to quit

Tester :

  • http://127.0.0.1:5100

uwsgi.ini

/sharenfs/rnmkcy/web-music-playlist/uwsgi.ini

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[uwsgi]
chdir = /sharenfs/rnmkcy/web-music-playlist
module = app:app

master = true
processes = 1
threads = 2
vacuum = true
die-on-term = true

socket = /run/uwsgi/playlist-web.sock
chmod-socket = 660

uid = 1000
gid = 1000

disable-logging = false

Ce modèle correspond aux configurations uWSGI standards avec socket UNIX, permissions et mode daemonisé pour nginx

Mettre en service systemd (recommandé)

Créer /etc/systemd/system/web-music-playlist.service :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[Unit]
Description=Flask playlist generator
After=network.target

[Service]
Type=notify
User=yick
Group=yick
WorkingDirectory=/sharenfs/rnmkcy/web-music-playlist
RuntimeDirectory=uwsgi
RuntimeDirectoryMode=0755
Environment="PATH=/sharenfs/rnmkcy/web-music-playlist/venv/bin"
ExecStart=/sharenfs/rnmkcy/web-music-playlist/venv/bin/uwsgi --ini /sharenfs/rnmkcy/web-music-playlist/uwsgi.ini
Restart=always
KillSignal=SIGQUIT
TimeoutStartSec=30

[Install]
WantedBy=multi-user.target

Puis :

1
2
3
4
sudo systemctl daemon-reload
sudo systemctl enable --now web-music-playlist
sudo systemctl status web-music-playlist --no-pager
sudo journalctl -u web-music-playlist -f --no-pager

Nginx (vhost)

exposition /music/ + reverse proxy Flask)
Créer /etc/nginx/conf.d/playlist.rnmkcy.eu.conf :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name playlist.rnmkcy.eu;

    include /etc/nginx/conf.d/ssl-modern.inc;

    location /music/ {
        alias /sharenfs/multimedia/Music/musicyan/;
        autoindex off;
        add_header Cache-Control "public, max-age=31536000";
    }

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/run/uwsgi/playlist-web.sock;
        uwsgi_read_timeout 120s;
        uwsgi_connect_timeout 30s;
    }
}

Vérifier puis reload :

1
2
sudo nginx -t
sudo systemctl reload nginx

Lien :

Cet article est sous licence CC BY 4.0 par l'auteur.