forked from zeti1223/Local-Music-Library-Sync
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
942 lines (795 loc) · 33.1 KB
/
app.py
File metadata and controls
942 lines (795 loc) · 33.1 KB
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
import os
import sys
import json
import time
import threading
import shutil
from flask import Flask, request, render_template, redirect, url_for, flash, jsonify
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from dotenv import load_dotenv, set_key
from werkzeug.utils import secure_filename
# Load environment variables (from .env file)
load_dotenv()
# Add src to system path to import modules
sys.path.append(os.path.join(os.path.dirname(__file__), "src"))
from downloader import (
spotify_get_initial,
youtube_get_initial,
download_single,
sanitize,
read_metadata,
edit_audio_metadata,
template_decoder,
create_m3u8,
)
from threader import QueueSystem
from database import (
init_database,
add_song,
find_song,
update_song_path,
get_song_by_path,
)
app = Flask(
__name__, template_folder="public", static_folder="public", static_url_path=""
)
app.secret_key = os.getenv("SECRET_KEY", "secret_key_for_flash_messages")
# Configuration
DOWNLOAD_PATH = os.path.expanduser(os.getenv("DOWNLOAD_PATH", "~/Music"))
os.makedirs(DOWNLOAD_PATH, exist_ok=True)
AUDIO_EXTS = (".mp3", ".flac", ".m4a", ".ogg", ".wav", ".opus")
# Initialize database
init_database()
# Threading locks and state
database_update_lock = threading.Lock()
database_update_state = {
"running": False,
"total": 0,
"done": 0,
"errors": 0,
}
metadata_sync_lock = threading.Lock()
metadata_sync_state = {
"running": False,
"total": 0,
"done": 0,
"errors": 0,
"results": [], # [{file, status, message}]
}
# Start database update in background thread
def _start_database_update_thread():
"""Scan music directory and populate database with existing files."""
def run_update():
base_path = os.path.expanduser(os.getenv("DOWNLOAD_PATH", "~/Music"))
if not os.path.exists(base_path):
with database_update_lock:
database_update_state["running"] = False
return
audio_files = []
for root, dirs, files in os.walk(base_path):
for file in files:
if file.lower().endswith(AUDIO_EXTS):
full_path = os.path.join(root, file)
audio_files.append(full_path)
with database_update_lock:
database_update_state["running"] = True
database_update_state["total"] = len(audio_files)
database_update_state["done"] = 0
database_update_state["errors"] = 0
for full_path in audio_files:
try:
# Check if already in database
existing = get_song_by_path(full_path)
if existing:
with database_update_lock:
database_update_state["done"] += 1
continue
# Read metadata from file
metadata = read_metadata(full_path)
title = (metadata.get("title") or "").strip()
artist = (metadata.get("artist") or "").strip()
album = (metadata.get("album") or "").strip()
# If no metadata, try to guess from filename
if not title and not artist:
base_name = os.path.splitext(os.path.basename(full_path))[0]
if " - " in base_name:
parts = base_name.split(" - ", 1)
artist = parts[0].strip()
title = parts[1].strip()
else:
title = base_name.strip()
# Use defaults if still empty
if not title:
title = os.path.splitext(os.path.basename(full_path))[0]
if not artist:
artist = "Unknown Artist"
if not album:
album = "Unknown Album"
# Add to database
add_song(title=title, artist=artist, album=album, path=full_path)
with database_update_lock:
database_update_state["done"] += 1
except Exception as e:
print(f"Error updating database for {full_path}: {e}")
with database_update_lock:
database_update_state["errors"] += 1
database_update_state["done"] += 1
with database_update_lock:
database_update_state["running"] = False
threading.Thread(target=run_update, daemon=True).start()
# Start database update on app startup
_start_database_update_thread()
# Queue System
queue_system = QueueSystem(max_processes=int(os.getenv("MAX_PARALLEL", 1)))
download_queue = []
staging_queue = []
def _dir_template_value() -> str | None:
"""Return a usable directory template or None when not set."""
v = os.getenv("DIRECTORY_TEMPLATE")
if not v:
return None
v = str(v).strip()
if not v or v == "(Not Set)":
return None
return v
def _build_library_albums(base_path: str):
albums = []
if not os.path.exists(base_path):
return albums
for name in sorted(os.listdir(base_path)):
folder_path = os.path.join(base_path, name)
if not os.path.isdir(folder_path):
continue
tracks = []
for root, _, files in os.walk(folder_path):
for file in files:
if file.lower().endswith(AUDIO_EXTS):
rel = os.path.relpath(os.path.join(root, file), folder_path)
tracks.append(rel)
tracks.sort()
albums.append(
{
"name": name,
"has_sync": os.path.exists(os.path.join(folder_path, ".sync")),
"tracks": tracks,
}
)
return albums
def _build_library_tree(base_path: str):
"""Build a folder tree (dirs + audio files) relative to base_path."""
base_abs = os.path.abspath(base_path)
if not os.path.exists(base_abs):
return {"name": os.path.basename(base_abs), "path": "", "type": "dir", "has_sync": False, "children": []}
def walk_dir(abs_dir: str):
rel_dir = os.path.relpath(abs_dir, base_abs)
if rel_dir == ".":
rel_dir = ""
children = []
try:
entries = sorted(os.listdir(abs_dir))
except Exception:
entries = []
# Dirs first
for name in entries:
abs_p = os.path.join(abs_dir, name)
if os.path.isdir(abs_p):
children.append(walk_dir(abs_p))
# Then audio files
for name in entries:
abs_p = os.path.join(abs_dir, name)
if os.path.isfile(abs_p) and name.lower().endswith(AUDIO_EXTS):
rel_p = os.path.relpath(abs_p, base_abs)
children.append({"name": name, "path": rel_p, "type": "file"})
return {
"name": os.path.basename(abs_dir) if rel_dir else os.path.basename(base_abs),
"path": rel_dir,
"type": "dir",
"has_sync": os.path.exists(os.path.join(abs_dir, ".sync")),
"children": children,
}
return walk_dir(base_abs)
def _collect_sync_tasks(base_path: str) -> list[dict]:
"""Collect sync tasks from staging + existing .sync folders and clear staging snapshot."""
global staging_queue
tasks: list[dict] = []
now = int(time.time())
# From staging
for item in staging_queue:
if item.get("item-type") != "playlist":
continue
link = item.get("original_link")
sync_id = item.get("spotify_id") or item.get("id") or ""
folder_name = sanitize(item.get("title", "Unknown"))
tasks.append(
{
"item": item,
"folder_name": folder_name,
"sync_path": os.path.join(base_path, folder_name, ".sync"),
"sync_data": {
"timestamp": now,
"id": sync_id,
"spotify_id": item.get("spotify_id")
or (sync_id if item.get("type") == "spotify" else ""),
"collection_type": item.get("collection_type") or "",
"link": link or "",
"source": item.get("type") or "",
},
}
)
# From existing .sync folders
if os.path.exists(base_path):
for name in os.listdir(base_path):
folder_path = os.path.join(base_path, name)
sync_file = os.path.join(folder_path, ".sync")
if not (os.path.isdir(folder_path) and os.path.exists(sync_file)):
continue
try:
with open(sync_file, "r") as f:
data = json.load(f)
link = data.get("link")
if not link:
continue
item = None
if "spotify.com" in link:
item = spotify_get_initial(link)
elif "youtube.com" in link or "youtu.be" in link:
item = youtube_get_initial(link.split("&si=")[0])
if not item:
continue
if item.get("item-type") != "playlist":
continue
item["original_link"] = link
sync_id = (
item.get("spotify_id")
or item.get("id")
or data.get("spotify_id")
or data.get("id")
or ""
)
tasks.append(
{
"item": item,
"folder_name": os.path.basename(folder_path),
"sync_path": sync_file,
"sync_data": {
"timestamp": now,
"id": sync_id,
"spotify_id": item.get("spotify_id")
or (sync_id if item.get("type") == "spotify" else ""),
"collection_type": item.get("collection_type")
or data.get("collection_type")
or "",
"link": link,
"source": item.get("type") or data.get("source") or "",
},
}
)
except Exception as e:
print(f"Error syncing {name}: {e}")
# Clear staging immediately (the sync thread owns the snapshot)
staging_queue = []
return tasks
def _start_sync_thread(tasks: list[dict]) -> None:
def run_sync(collected_tasks: list[dict]):
try:
for t in collected_tasks:
item = t["item"]
download_queue.append(item)
start_download(
item,
force_collection_folder=True,
collection_folder_name=t["folder_name"],
)
# Wait until all download jobs finish, then update .sync timestamps
queue_system.wait_completion()
for t in collected_tasks:
try:
os.makedirs(os.path.dirname(t["sync_path"]), exist_ok=True)
t["sync_data"]["timestamp"] = int(time.time())
with open(t["sync_path"], "w") as f:
json.dump(t["sync_data"], f, indent=4)
except Exception as e:
print(f"Error writing sync file {t.get('sync_path')}: {e}")
except Exception as e:
print(f"Sync thread error: {e}")
threading.Thread(target=run_sync, args=(tasks,), daemon=True).start()
def _safe_join_downloads(rel_path: str) -> str:
base_path = os.path.expanduser(os.getenv("DOWNLOAD_PATH", "~/Music"))
base_abs = os.path.abspath(base_path)
safe_path = os.path.abspath(os.path.join(base_abs, rel_path))
if not safe_path.startswith(base_abs):
raise ValueError("Invalid file path")
return safe_path
def _spotify_client() -> spotipy.Spotify:
sp_id = os.getenv("SPOTIPY_CLIENT_ID")
sp_sec = os.getenv("SPOTIPY_CLIENT_SECRET")
if not sp_id or not sp_sec:
raise ValueError("Spotify token missing. Please set SPOTIPY_CLIENT_ID and SPOTIPY_CLIENT_SECRET.")
cc = SpotifyClientCredentials(client_id=sp_id, client_secret=sp_sec)
return spotipy.Spotify(client_credentials_manager=cc)
def _spotify_find_track(sp: spotipy.Spotify, title: str | None, artist: str | None):
t = (title or "").strip()
a = (artist or "").strip()
if not t and not a:
return None
# Prefer a constrained query when we can.
if t and a:
q = f'track:"{t}" artist:"{a}"'
elif t:
q = f'track:"{t}"'
else:
q = f'artist:"{a}"'
res = sp.search(q=q, type="track", limit=5)
items = (res or {}).get("tracks", {}).get("items") or []
return items[0] if items else None
def _spotify_track_to_metadata(sp: spotipy.Spotify, track: dict, artist_genre_cache: dict):
title = track.get("name") or ""
artists = [a.get("name") for a in (track.get("artists") or []) if a.get("name")]
album = (track.get("album") or {}).get("name") or ""
release = (track.get("album") or {}).get("release_date") or ""
year = release.split("-")[0] if release else ""
track_no = track.get("track_number")
genre = ""
try:
primary = (track.get("artists") or [{}])[0]
artist_id = primary.get("id")
if artist_id:
if artist_id not in artist_genre_cache:
artist_obj = sp.artist(artist_id)
artist_genre_cache[artist_id] = (artist_obj or {}).get("genres") or []
genres = artist_genre_cache.get(artist_id) or []
genre = genres[0] if genres else ""
except Exception:
genre = ""
md = {
"title": title,
"artists": artists,
"album": album,
"year": year,
}
if track_no is not None:
md["track_number"] = str(track_no)
if genre:
md["genre"] = genre
return md
def _guess_query_from_filename(rel_path: str):
base = os.path.basename(rel_path)
name, _ext = os.path.splitext(base)
# Common pattern: "Artist - Title"
if " - " in name:
a, t = name.split(" - ", 1)
return t.strip(), a.strip()
return name.strip(), ""
def _start_metadata_sync_thread(files: list[str]) -> None:
def run(files_snapshot: list[str]):
with metadata_sync_lock:
metadata_sync_state["running"] = True
metadata_sync_state["total"] = len(files_snapshot)
metadata_sync_state["done"] = 0
metadata_sync_state["errors"] = 0
metadata_sync_state["results"] = []
try:
sp = _spotify_client()
except Exception as e:
with metadata_sync_lock:
metadata_sync_state["running"] = False
metadata_sync_state["errors"] = len(files_snapshot) or 1
metadata_sync_state["results"] = [{"file": "", "status": "error", "message": str(e)}]
return
artist_genre_cache: dict = {}
for rel in files_snapshot:
status = "ok"
msg = ""
try:
safe_path = _safe_join_downloads(rel)
current = read_metadata(safe_path) or {}
title = (current.get("title") or "").strip()
artist = (current.get("artist") or "").strip()
if not title and not artist:
title, artist = _guess_query_from_filename(rel)
track = _spotify_find_track(sp, title=title, artist=artist)
if not track:
status = "not_found"
msg = f'No Spotify match found for: "{title}" / "{artist}"'
else:
md = _spotify_track_to_metadata(sp, track, artist_genre_cache)
edit_audio_metadata(safe_path, md)
msg = "Updated using Spotify metadata."
except Exception as e:
status = "error"
msg = str(e)
with metadata_sync_lock:
metadata_sync_state["done"] += 1
if status == "error":
metadata_sync_state["errors"] += 1
metadata_sync_state["results"].append(
{"file": rel, "status": status, "message": msg}
)
with metadata_sync_lock:
metadata_sync_state["running"] = False
threading.Thread(target=run, args=(list(files),), daemon=True).start()
@app.route("/")
def index():
current_download_path = os.path.expanduser(os.getenv("DOWNLOAD_PATH", "~/Music"))
library_items = []
audio_files = []
if os.path.exists(current_download_path):
items = sorted(os.listdir(current_download_path))
for item in items:
path = os.path.join(current_download_path, item)
has_sync = os.path.isdir(path) and os.path.exists(
os.path.join(path, ".sync")
)
library_items.append({"name": item, "has_sync": has_sync})
for root, dirs, files in os.walk(current_download_path):
for file in files:
if file.lower().endswith(AUDIO_EXTS):
rel_path = os.path.relpath(
os.path.join(root, file), current_download_path
)
audio_files.append(rel_path)
audio_files.sort()
config = {
"DOWNLOAD_PATH": current_download_path,
"MAX_PARALLEL": os.getenv("MAX_PARALLEL", "1"),
"FILENAME_TEMPLATE": os.getenv("FILENAME_TEMPLATE", "$artist$ - $title$"),
"DIRECTORY_TEMPLATE": os.getenv("DIRECTORY_TEMPLATE", "$album$"),
"QUALITY": os.getenv("QUALITY", "MP3 128kbps"),
"SPOTIPY_CLIENT_ID": os.getenv("SPOTIPY_CLIENT_ID", ""),
"SPOTIPY_CLIENT_SECRET": os.getenv("SPOTIPY_CLIENT_SECRET", ""),
"PORT": os.getenv("PORT", "8080"),
}
library_albums = _build_library_albums(current_download_path)
library_tree = _build_library_tree(current_download_path)
return render_template(
"index.html",
library_items=library_items,
library_albums=library_albums,
library_tree=library_tree,
audio_files=audio_files,
queue=download_queue,
staging_queue=staging_queue,
config=config,
)
@app.get("/api/staging")
def api_get_staging():
return jsonify({"items": staging_queue})
@app.post("/api/staging/add")
def api_add_staging():
data = request.get_json(silent=True) or {}
link = (data.get("link") or "").strip()
if not link:
return jsonify({"error": "Missing link"}), 400
try:
item = None
if "spotify.com" in link:
item = spotify_get_initial(link)
elif "youtube.com" in link or "youtu.be" in link:
item = youtube_get_initial(link.split("&si=")[0])
else:
return (
jsonify(
{
"error": "Unsupported link! Only Spotify and YouTube are supported."
}
),
400,
)
if not item:
return jsonify({"error": "Failed to parse link"}), 400
if item.get("item-type") != "playlist":
return (
jsonify(
{
"error": "Unsupported link for staging view. Please add a Spotify album/playlist or a YouTube playlist."
}
),
400,
)
item["original_link"] = link
item["status"] = "staging"
staging_queue.append(item)
return jsonify({"item": item})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.get("/api/library")
def api_get_library():
base_path = os.path.expanduser(os.getenv("DOWNLOAD_PATH", "~/Music"))
return jsonify({"albums": _build_library_albums(base_path)})
@app.get("/api/library/tree")
def api_get_library_tree():
base_path = os.path.expanduser(os.getenv("DOWNLOAD_PATH", "~/Music"))
return jsonify({"tree": _build_library_tree(base_path)})
@app.route("/api/sync", methods=["POST"])
def api_sync_library():
base_path = os.path.expanduser(os.getenv("DOWNLOAD_PATH", "~/Music"))
tasks = _collect_sync_tasks(base_path)
_start_sync_thread(tasks)
return jsonify({"status": "started", "tasks": len(tasks)})
@app.get("/api/metadata/sync/status")
def api_metadata_sync_status():
with metadata_sync_lock:
return jsonify(metadata_sync_state)
@app.get("/api/database/update/status")
def api_database_update_status():
with database_update_lock:
return jsonify(database_update_state)
@app.post("/api/metadata/sync")
def api_metadata_sync():
data = request.get_json(silent=True) or {}
files = data.get("files") or []
if not isinstance(files, list):
return jsonify({"error": "Invalid payload"}), 400
files = [str(f) for f in files if str(f).strip()]
if not files:
return jsonify({"error": "No files selected"}), 400
with metadata_sync_lock:
if metadata_sync_state.get("running"):
return jsonify({"error": "Metadata sync already running"}), 409
_start_metadata_sync_thread(files)
return jsonify({"status": "started", "files": len(files)})
@app.route("/add", methods=["POST"])
def add_playlist():
link = request.form.get("playlist_link")
if not link:
flash("Please provide a link!", "error")
return redirect(url_for("index"))
try:
item = None
if "spotify.com" in link:
item = spotify_get_initial(link)
elif "youtube.com" in link or "youtu.be" in link:
item = youtube_get_initial(link.split("&si=")[0])
else:
flash("Unsupported link! Only Spotify and YouTube are supported.", "error")
return redirect(url_for("index"))
if item:
if item.get("item-type") != "playlist":
flash(
"Unsupported link for staging view. Please add a Spotify album/playlist or a YouTube playlist.",
"error",
)
return redirect(url_for("index"))
item["original_link"] = link
item["status"] = "staging"
staging_queue.append(item)
flash(f"Added '{item.get('title')}' to staging.", "success")
except Exception as e:
flash(f"An error occurred: {str(e)}", "error")
return redirect(url_for("index"))
@app.route("/sync", methods=["POST"])
def sync_library():
base_path = os.path.expanduser(os.getenv("DOWNLOAD_PATH", "~/Music"))
tasks = _collect_sync_tasks(base_path)
_start_sync_thread(tasks)
flash("Sync started!", "success")
return redirect(url_for("index"))
@app.route("/settings", methods=["POST"])
def update_settings():
env_file = os.path.join(os.path.dirname(__file__), ".env")
if not os.path.exists(env_file):
open(env_file, "a").close()
settings = {
"DOWNLOAD_PATH": request.form.get("DOWNLOAD_PATH"),
"MAX_PARALLEL": request.form.get("MAX_PARALLEL"),
"FILENAME_TEMPLATE": request.form.get("FILENAME_TEMPLATE"),
"DIRECTORY_TEMPLATE": request.form.get("DIRECTORY_TEMPLATE"),
"QUALITY": request.form.get("QUALITY"),
"SPOTIPY_CLIENT_ID": request.form.get("SPOTIPY_CLIENT_ID"),
"SPOTIPY_CLIENT_SECRET": request.form.get("SPOTIPY_CLIENT_SECRET"),
"PORT": request.form.get("PORT"),
}
restart_required = False
for key, value in settings.items():
if value is not None:
# Update .env file
set_key(env_file, key, value)
# Update current environment variables for immediate effect
os.environ[key] = value
# Note which settings require restart
if key in ["MAX_PARALLEL", "PORT"]:
restart_required = True
message = "Settings updated successfully!"
if restart_required:
message += " (Note: Restart required for MAX_PARALLEL and PORT to take effect)"
flash(message, "success")
return redirect(url_for("index"))
@app.route("/metadata", methods=["GET"])
def get_metadata():
filename = request.args.get("file")
if not filename:
return {"error": "No file specified"}, 400
try:
safe_path = _safe_join_downloads(filename)
except Exception:
return {"error": "Invalid file path"}, 403
data = read_metadata(safe_path)
return data
@app.route("/update_metadata", methods=["POST"])
def update_metadata():
data = request.json
filename = data.get("filename")
metadata = data.get("metadata")
if not filename:
return {"error": "No file specified"}, 400
try:
safe_path = _safe_join_downloads(filename)
except Exception:
return {"error": "Invalid file path"}, 403
# Map frontend keys to downloader keys if necessary, currently they match mostly
edit_audio_metadata(safe_path, metadata)
return {"status": "success"}
def start_download(item, force_collection_folder: bool = False, collection_folder_name: str | None = None):
def job_wrapper(track_data, folder_name=None):
def callback(state, type="status"):
if type == "status":
track_data["status"] = state
try:
track_data["status"] = "downloading"
download_single(track_data, folder_name, callback=callback)
track_data["status"] = "done"
except Exception as e:
track_data["status"] = "error"
print(f"Error downloading {track_data.get('title')}: {e}")
if item["item-type"] == "track":
queue_system.submit_jobs([lambda: job_wrapper(item)])
elif item["item-type"] == "playlist":
# Determine folder name
base_path = os.path.expanduser(os.getenv("DOWNLOAD_PATH", "~/Music"))
playlist_folder_name = sanitize(collection_folder_name or item["title"])
# Check if we are using a directory template that might scatter files
dir_template = _dir_template_value()
use_collection_folder = force_collection_folder or (dir_template is None)
jobs = []
track_filenames = []
# Check if this is an album or playlist
is_album = item.get("collection_type") == "album"
for track in item["tracks"]:
track["status"] = "waiting"
track["playlist_title"] = item["title"]
# Pre-calculate expected filename to check existence
templater_data = {
"title": track["title"],
"artist": ", ".join(track["artists"]),
"artists": track["artists"],
"album": track["album"],
"year": track["release"],
"length": track["duration_seconds"],
"platform": track["type"],
"track_number": int(track["track_number"]),
"playlist": item["title"],
}
# Logic to determine where the file WOULD go
if (not use_collection_folder) and dir_template:
sub_path = template_decoder(dir_template, data=templater_data)
target_folder = os.path.join(base_path, sub_path)
else:
target_folder = os.path.join(base_path, playlist_folder_name)
filename_template = os.getenv("FILENAME_TEMPLATE", "$artist$ - $title$")
final_filename = template_decoder(filename_template, data=templater_data)
quality = os.getenv("QUALITY", "MP3 128kbps")
# Simple extension guess based on quality (not perfect but good for check)
ext_map = {"MP3": "mp3", "OGG": "ogg", "M4A": "m4a", "FLAC": "flac"}
ext = "mp3"
for k, v in ext_map.items():
if k in quality:
ext = v
break
full_path = os.path.join(target_folder, f"{final_filename}.{ext}")
# Check database for existing song
artist_str = ", ".join(track["artists"])
existing_song = find_song(track["title"], artist_str, track.get("album"))
# Also check if file exists with any audio extension
existing_file_path = None
if os.path.exists(full_path):
existing_file_path = full_path
else:
# Check for file with different extension
base_name = os.path.join(target_folder, final_filename)
for audio_ext in AUDIO_EXTS:
test_path = f"{base_name}{audio_ext}"
if os.path.exists(test_path):
existing_file_path = test_path
break
if existing_song and os.path.exists(existing_song["path"]):
existing_path = existing_song["path"]
if is_album:
# For albums: move the file to the album folder
try:
os.makedirs(target_folder, exist_ok=True)
# Move file to new location
shutil.move(existing_path, full_path)
# Update database with new path
update_song_path(existing_path, full_path)
track["status"] = "moved"
print(f"Moved {track['title']} to album folder.")
except Exception as e:
print(f"Error moving {track['title']}: {e}")
track["status"] = "error"
# Use existing path if move failed
existing_path = existing_song["path"]
else:
# For playlists: use existing path, don't download again
track["status"] = "exists"
print(f"Skipping {track['title']}, already exists in database.")
full_path = existing_path
# Calculate relative path for m3u8 from existing file location
rel_path = os.path.relpath(
full_path,
(
os.path.join(base_path, playlist_folder_name)
if use_collection_folder
else base_path
),
)
track_filenames.append(rel_path)
elif existing_file_path:
# File exists at expected location but not in database
# Add it to database
try:
add_song(
title=track["title"],
artist=artist_str,
album=track.get("album", "Unknown Album"),
path=existing_file_path
)
except Exception as e:
print(f"Warning: Failed to add existing file to database: {e}")
if is_album:
# For albums: move the file to the expected location
try:
os.makedirs(target_folder, exist_ok=True)
shutil.move(existing_file_path, full_path)
update_song_path(existing_file_path, full_path)
track["status"] = "moved"
print(f"Moved {track['title']} to album folder.")
# full_path already points to the new location
except Exception as e:
print(f"Error moving {track['title']}: {e}")
track["status"] = "exists"
full_path = existing_file_path
else:
track["status"] = "exists"
print(f"Skipping {track['title']}, already exists.")
full_path = existing_file_path
rel_path = os.path.relpath(
full_path,
(
os.path.join(base_path, playlist_folder_name)
if use_collection_folder
else base_path
),
)
track_filenames.append(rel_path)
else:
# File doesn't exist, need to download
rel_path = os.path.relpath(
full_path,
(
os.path.join(base_path, playlist_folder_name)
if use_collection_folder
else base_path
),
)
track_filenames.append(rel_path)
jobs.append(
lambda t=track, f=(
playlist_folder_name if use_collection_folder else None
): job_wrapper(t, f)
)
queue_system.submit_jobs(jobs)
# Create M3U8
m3u8_folder = (
os.path.join(base_path, playlist_folder_name)
if use_collection_folder
else base_path
)
os.makedirs(m3u8_folder, exist_ok=True)
# Use the folder name for a stable playlist filename
create_m3u8(m3u8_folder, playlist_folder_name, track_filenames)
if __name__ == "__main__":
# Bind to all interfaces so it's reachable on the local network.
# Default port is 8080 (override with PORT env var).
port = int(os.getenv("PORT", "8080"))
app.run(host="0.0.0.0", port=port, debug=True)