From 0ebbc205a14b08152a6ee8060984c09625126128 Mon Sep 17 00:00:00 2001 From: Leonardo Segala Date: Fri, 1 Aug 2025 23:23:00 +0200 Subject: [PATCH] Add add song api endpoint --- backend/src/app.py | 30 +++++++++++++++++++++++++++--- backend/src/song.py | 7 ++++--- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/backend/src/app.py b/backend/src/app.py index 304c603..75a8ca7 100644 --- a/backend/src/app.py +++ b/backend/src/app.py @@ -4,9 +4,8 @@ from flask_cors import CORS from flask_socketio import SocketIO, emit from .room import Room -from .song import Song, init_db - -# from .song_fetch import * +from .song import Song, init_db, get_song_by_title_artist, add_song_in_db +from .song_fetch import lastfm_query_search, download_song_mp3 dotenv.load_dotenv() @@ -120,6 +119,31 @@ def room(): ] +@app.post("/api/addsong") +def add_song(): + if (room_id := request.args.get("room")) is None: + return error("Missing room id") + + if (room := ROOMS.get(int(room_id))) is None: + return error("Invalid room") + + if (query := request.args.get("query")) is None: + return error("Missing query") + + info = lastfm_query_search(query) + + if (song := get_song_by_title_artist(info.title, info.artist)) is None: + res = download_song_mp3(info.title, info.artist) + if res is None: + ops + yt_id, _ = res + ## song not found, downolad from YT + ## add in DB + add_song_in_db(info.artist, info.title, info.tags, info.img_id, yt_id) + + return {"artist": info.artist, "title": info.title, "tags": info.tags, "image_id": info.img_id} + + init_db() if __name__ == "__main__": diff --git a/backend/src/song.py b/backend/src/song.py index 9b95add..1d82b93 100644 --- a/backend/src/song.py +++ b/backend/src/song.py @@ -1,4 +1,5 @@ from dataclasses import dataclass +import uuid from .connect import get_connection @@ -43,7 +44,7 @@ def get_song_by_mbid(mbid: str) -> Song | None: return song -def add_song(song: Song): +def add_song_in_db(title: str, artist: str, tags: list[str], image_id: str, yt_id: str) -> None: conn = get_connection() cursor = conn.cursor() @@ -51,8 +52,8 @@ def add_song(song: Song): """ INSERT OR REPLACE INTO songs (mbid, title, artist, tags, lastfm_image_id, youtube_id) VALUES (?, ?, ?, ?, ?, ?) - """, - (song.mbid, song.title, song.artist, ",".join(song.tags), song.image_id, song.youtube_id), + """, + (uuid.uuid4(), title, artist, ",".join(tags), image_id, yt_id), ) # Updates song info if it already exists conn.commit() conn.close()