diff --git a/.gitignore b/.gitignore index 610faed..00cb8b4 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ __pycache__/ *.swp *.swo config.py +*.m3u diff --git a/load_playlist.py b/load_playlist.py new file mode 100644 index 0000000..1d17b35 --- /dev/null +++ b/load_playlist.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +""" +Load a playlist into the database. +""" +import os +import asyncio + +import asyncpg + +import config + + +async def load_playlist(path): + """Load a playlist into the database.""" + print("Loading:", path) + with open(path, 'r') as file: + data = file.read().splitlines() + data = [line.replace('.flac', '.opus') for line in data] ## not generic ## + + pname = os.path.basename(path) + + db_pool = await asyncpg.create_pool(**config.db) + async with db_pool.acquire() as conn: + pid = await conn.fetchrow( + "SELECT id FROM playlist WHERE name = $1", pname) + + if not pid: + pid = await conn.fetchrow( + "INSERT INTO playlist (name) VALUES ($1) RETURNING id", pname) + pid = pid['id'] + + data = [(pid, line) for line in data] + stmt = await conn.prepare( + "INSERT INTO playlist_track (playlist_id, filepath) VALUES ($1, $2)") + await stmt.executemany(data) + print("Done. Loaded", len(data), "tracks") + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser( + description="Load a new playlist into the database.") + parser.add_argument( + "path", + help="The filepath of the .m3u file.") + args = parser.parse_args() + + asyncio.run(load_playlist(args.path)) diff --git a/pyrite.sql b/pyrite.sql index f4e7607..57ed529 100644 --- a/pyrite.sql +++ b/pyrite.sql @@ -10,4 +10,15 @@ CREATE TABLE IF NOT EXISTS track ( genre TEXT, duration FLOAT, last_modified FLOAT -) +); + +CREATE TABLE IF NOT EXISTS playlist ( + id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, + name TEXT UNIQUE +); + +CREATE TABLE IF NOT EXISTS playlist_track ( + playlist_id INT REFERENCES playlist (id) ON UPDATE CASCADE ON DELETE CASCADE, + filepath TEXT REFERENCES track (filepath) ON UPDATE CASCADE ON DELETE CASCADE, + CONSTRAINT playlist_track_pkey PRIMARY KEY (playlist_id, filepath) +);