From 254978f8bd61fb560f0ae9d50ae7af45d8cd709a Mon Sep 17 00:00:00 2001
From: sqozz <sqozz@geekify.de>
Date: Wed, 29 Sep 2021 23:55:23 +0200
Subject: [PATCH] Add first PoC

---
 config.ini |  9 +++++++++
 sync.py    | 32 ++++++++++++++++++++++++++++++++
 2 files changed, 41 insertions(+)
 create mode 100644 config.ini
 create mode 100644 sync.py

diff --git a/config.ini b/config.ini
new file mode 100644
index 0000000..d2f4c84
--- /dev/null
+++ b/config.ini
@@ -0,0 +1,9 @@
+[general]
+mixes_dir=/mnt/RAID/public/music/mixes
+
+[youtube-dl]
+options=--download-archive downloaded.txt --no-post-overwrites -ciwx --audio-format best -o "%(title)s.%(ext)s"
+
+[mpd]
+mpd_root=/mnt/RAID/public/music/
+update=True
diff --git a/sync.py b/sync.py
new file mode 100644
index 0000000..2d8b88a
--- /dev/null
+++ b/sync.py
@@ -0,0 +1,32 @@
+from urllib.parse import urlparse, quote
+from pathlib import Path
+import configparser
+import subprocess
+import pdb
+
+def read_config():
+    config = configparser.RawConfigParser()
+    config.read("config.ini")
+    return config
+
+def get_mixes(mixes_dir):
+    mixes = []
+    for path in Path(mixes_dir).rglob('url.txt'):
+        with open(path, "r") as fd:
+            first_line = fd.readline()
+            first_line = first_line.strip()
+            url = quote(urlparse(first_line).geturl(), safe=":/") # do a sanity url parse and quote
+        mixes.append((path.parent, url))
+    return mixes
+
+def download_channel(target_directory, channel_url, options="", update_mpd=False, mpd_root=""):
+    mpd_update_options = []
+    if update_mpd:
+        mpd_update_options = ["--exec", "mpc update \"{}\"".format(str(target_directory).replace(mpd_root, "", 1).lstrip("/"))]
+    p = subprocess.Popen(["youtube-dl", *options.split(" "), *mpd_update_options, channel_url], cwd=target_directory)
+    p.wait()
+
+config = read_config()
+mixes = get_mixes(config["general"]["mixes_dir"])
+for folder,url in mixes:
+    download_channel(folder, url, config["youtube-dl"]["options"], update_mpd=config["mpd"]["update"], mpd_root=config["mpd"]["mpd_root"])