Compare commits
14 Commits
0e74848d14
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 2982d40811 | |||
| d9194dcd76 | |||
| 6e9f348089 | |||
| c5fbad8ad6 | |||
| 196767001c | |||
| a04becb616 | |||
| a8d940b101 | |||
| 1dace0938a | |||
| f7f3a04168 | |||
| b99ccd6f98 | |||
| 42c1bf1053 | |||
| 3d81ef065b | |||
| 1e5add8710 | |||
| e6a3220d67 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -151,3 +151,4 @@ out.*
|
|||||||
*.txt
|
*.txt
|
||||||
*.json
|
*.json
|
||||||
.aider*
|
.aider*
|
||||||
|
settings.py
|
||||||
|
|||||||
22
README.md
Normal file
22
README.md
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
# Navidrome - Mopidy Playlist Sync
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
Make sure your user is added to the `docker` group and whatever group owns your Mopidy playlist directory:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ ls -la /var/lib/mopidy/m3u
|
||||||
|
|
||||||
|
total 24
|
||||||
|
drwxrwxr-x 2 mopidy audio 4096 Feb 4 18:22 .
|
||||||
|
drwxr-xr-x 8 mopidy audio 4096 Oct 1 18:42 ..
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
$ sudo usermod -aG docker tanner
|
||||||
|
$ sudo usermod -aG audio tanner
|
||||||
|
```
|
||||||
|
|
||||||
|
Configure `settings.py`.
|
||||||
|
|
||||||
|
You can either use your Navridrome password, or get the Subsonic salt and hash from the Web UI login request.
|
||||||
211
main.py
211
main.py
@@ -1,48 +1,120 @@
|
|||||||
import os, logging
|
import os, logging
|
||||||
import hashlib
|
|
||||||
import random
|
|
||||||
import string
|
|
||||||
import subprocess
|
|
||||||
import time
|
|
||||||
|
|
||||||
import requests
|
|
||||||
DEBUG = os.environ.get('DEBUG')
|
DEBUG = os.environ.get('DEBUG')
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
format='[%(asctime)s] %(levelname)s %(module)s/%(funcName)s - %(message)s',
|
format='[%(asctime)s] %(levelname)s %(module)s/%(funcName)s - %(message)s',
|
||||||
level=logging.DEBUG if DEBUG else logging.INFO)
|
level=logging.DEBUG if DEBUG else logging.INFO)
|
||||||
|
|
||||||
def run_pls_command(playlist_id, playlist_name):
|
import argparse
|
||||||
"""Runs the docker exec command for a given playlist."""
|
import hashlib
|
||||||
|
import random
|
||||||
|
import string
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
import urllib.parse
|
||||||
|
import requests
|
||||||
|
|
||||||
|
import settings
|
||||||
|
|
||||||
|
def transform_m3u_to_m3u8(m3u_content):
|
||||||
|
"""Transforms M3U content to M3U8 format."""
|
||||||
|
transformed_lines = []
|
||||||
|
for line in m3u_content.strip().splitlines():
|
||||||
|
if line.strip() and not line.startswith('#'):
|
||||||
|
if line.startswith('/music/'):
|
||||||
|
path = line[len('/music/'):]
|
||||||
|
encoded_path = urllib.parse.quote(path)
|
||||||
|
transformed_lines.append(f"local:track:{encoded_path}")
|
||||||
|
return '\n'.join(transformed_lines)
|
||||||
|
|
||||||
|
|
||||||
|
def run_pls_command(playlist_id):
|
||||||
|
"""Runs the docker exec command and returns combined stdout/stderr."""
|
||||||
cmd = ['docker', 'exec', 'navidrome-navidrome-1', '/app/navidrome', 'pls', '-l', 'error', '-np', playlist_id]
|
cmd = ['docker', 'exec', 'navidrome-navidrome-1', '/app/navidrome', 'pls', '-l', 'error', '-np', playlist_id]
|
||||||
try:
|
try:
|
||||||
result = subprocess.run(cmd, capture_output=True, text=True, check=False)
|
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False)
|
||||||
print(f"\n--- Output for playlist '{playlist_name}' ---")
|
return result.stdout
|
||||||
if result.stdout.strip():
|
|
||||||
print(result.stdout.strip())
|
|
||||||
if result.stderr.strip():
|
|
||||||
print("STDERR:")
|
|
||||||
print(result.stderr.strip())
|
|
||||||
print("--- End output ---\n")
|
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
logging.error("Command 'docker' not found. Please ensure it is installed and in your PATH.")
|
logging.error("Command 'docker' not found. Please ensure it is installed and in your PATH.")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def sanitize_for_filename(name):
|
||||||
|
"""Sanitizes a string to be safe as a filename component."""
|
||||||
|
return name.replace('/', '_').replace('\\', '_')
|
||||||
|
|
||||||
|
|
||||||
|
def save_playlist_file(playlist_dir, playlist_name, content):
|
||||||
|
"""Saves the transformed playlist content to a file."""
|
||||||
|
filename = f"{sanitize_for_filename(playlist_name)}.m3u8"
|
||||||
|
filepath = os.path.join(playlist_dir, filename)
|
||||||
|
try:
|
||||||
|
with open(filepath, 'w', encoding='utf-8') as f:
|
||||||
|
f.write(content)
|
||||||
|
logging.info(f"Saved playlist to {filepath}")
|
||||||
|
except IOError as e:
|
||||||
|
logging.error(f"Error writing to file {filepath}: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
def delete_playlist_file(playlist_dir, playlist_name):
|
||||||
|
"""Deletes a playlist file."""
|
||||||
|
filename = f"{sanitize_for_filename(playlist_name)}.m3u8"
|
||||||
|
filepath = os.path.join(playlist_dir, filename)
|
||||||
|
if os.path.exists(filepath):
|
||||||
|
try:
|
||||||
|
os.remove(filepath)
|
||||||
|
logging.info(f"Deleted playlist file {filepath}")
|
||||||
|
except OSError as e:
|
||||||
|
logging.error(f"Error deleting file {filepath}: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
def call_mopidy_rpc(method, params=None):
|
||||||
|
"""Calls a Mopidy RPC method."""
|
||||||
|
if not settings.MOPIDY_RPC_URL:
|
||||||
|
return
|
||||||
|
|
||||||
|
data = {
|
||||||
|
'jsonrpc': '2.0',
|
||||||
|
'id': 1,
|
||||||
|
'method': method,
|
||||||
|
}
|
||||||
|
if params:
|
||||||
|
data['params'] = params
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = requests.post(settings.MOPIDY_RPC_URL, json=data, timeout=5)
|
||||||
|
response.raise_for_status()
|
||||||
|
logging.info(f"Successfully called Mopidy RPC method: {method}")
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
logging.error(f"Error calling Mopidy RPC: {e}")
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
"""Get playlists from a Navidrome server using the Subsonic API."""
|
"""Get playlists from a Navidrome server using the Subsonic API."""
|
||||||
navidrome_url = os.environ.get('NAVIDROME_URL')
|
parser = argparse.ArgumentParser(description="Sync Navidrome playlists to Mopidy.")
|
||||||
username = os.environ.get('NAVIDROME_USER')
|
parser.add_argument('--force-sync', action='store_true', help='Perform a one-time sync of all playlists and exit.')
|
||||||
|
args = parser.parse_args()
|
||||||
if not all([navidrome_url, username]):
|
mopidy_playlist_dir = settings.MOPIDY_PLAYLIST_DIR
|
||||||
logging.error("NAVIDROME_URL and NAVIDROME_USER environment variables must be set.")
|
if not mopidy_playlist_dir:
|
||||||
|
logging.error("MOPIDY_PLAYLIST_DIR must be set in settings.py.")
|
||||||
|
return
|
||||||
|
if not os.path.isdir(mopidy_playlist_dir):
|
||||||
|
logging.error(f"Mopidy playlist directory not found: {mopidy_playlist_dir}")
|
||||||
return
|
return
|
||||||
|
|
||||||
salt = os.environ.get('SUBSONIC_SALT')
|
navidrome_url = settings.NAVIDROME_URL
|
||||||
token = os.environ.get('SUBSONIC_TOKEN')
|
username = settings.NAVIDROME_USER
|
||||||
|
|
||||||
|
if not all([navidrome_url, username]):
|
||||||
|
logging.error("NAVIDROME_URL and NAVIDROME_USER must be set in settings.py.")
|
||||||
|
return
|
||||||
|
|
||||||
|
salt = settings.SUBSONIC_SALT
|
||||||
|
token = settings.SUBSONIC_TOKEN
|
||||||
|
|
||||||
if not all([salt, token]):
|
if not all([salt, token]):
|
||||||
password = os.environ.get('NAVIDROME_PASSWORD')
|
password = settings.NAVIDROME_PASSWORD
|
||||||
if not password:
|
if not password:
|
||||||
logging.error("Either (SUBSONIC_SALT and SUBSONIC_TOKEN) or NAVIDROME_PASSWORD must be set.")
|
logging.error("Either (SUBSONIC_SALT and SUBSONIC_TOKEN) or NAVIDROME_PASSWORD must be set in settings.py.")
|
||||||
return
|
return
|
||||||
|
|
||||||
# Subsonic API requires a salt and a token (md5(password + salt))
|
# Subsonic API requires a salt and a token (md5(password + salt))
|
||||||
@@ -58,13 +130,55 @@ def main():
|
|||||||
'f': 'json'
|
'f': 'json'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if args.force_sync:
|
||||||
|
logging.info("Starting one-time force sync of all playlists...")
|
||||||
|
api_url = f"{navidrome_url.rstrip('/')}/rest/getPlaylists.view"
|
||||||
|
try:
|
||||||
|
response = requests.get(api_url, params=params, timeout=5)
|
||||||
|
response.raise_for_status()
|
||||||
|
except requests.exceptions.RequestException as e:
|
||||||
|
logging.error(f"Error connecting to Navidrome: {e}")
|
||||||
|
return
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
subsonic_response = data.get('subsonic-response')
|
||||||
|
if not subsonic_response or subsonic_response.get('status') == 'failed':
|
||||||
|
error = subsonic_response.get('error', {}) if subsonic_response else {}
|
||||||
|
logging.error(f"API Error during sync: {error.get('message')} (code: {error.get('code')})")
|
||||||
|
return
|
||||||
|
|
||||||
|
playlists = subsonic_response.get('playlists', {}).get('playlist', [])
|
||||||
|
if not playlists:
|
||||||
|
logging.info("No playlists found to sync.")
|
||||||
|
return
|
||||||
|
|
||||||
|
logging.info(f"Found {len(playlists)} playlists to sync.")
|
||||||
|
synced_a_playlist = False
|
||||||
|
for playlist in playlists:
|
||||||
|
playlist_id = playlist.get('id')
|
||||||
|
playlist_name = playlist.get('name')
|
||||||
|
logging.info(f"Syncing playlist: '{playlist_name}' ({playlist_id})")
|
||||||
|
raw_output = run_pls_command(playlist_id)
|
||||||
|
if raw_output:
|
||||||
|
transformed_output = transform_m3u_to_m3u8(raw_output)
|
||||||
|
if transformed_output:
|
||||||
|
save_playlist_file(mopidy_playlist_dir, playlist_name, transformed_output)
|
||||||
|
synced_a_playlist = True
|
||||||
|
|
||||||
|
if synced_a_playlist:
|
||||||
|
call_mopidy_rpc('core.playlists.refresh')
|
||||||
|
|
||||||
|
logging.info("Force sync complete.")
|
||||||
|
return
|
||||||
|
|
||||||
known_playlists = {}
|
known_playlists = {}
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
|
playlists_changed = False
|
||||||
api_url = f"{navidrome_url.rstrip('/')}/rest/getPlaylists.view"
|
api_url = f"{navidrome_url.rstrip('/')}/rest/getPlaylists.view"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = requests.get(api_url, params=params)
|
response = requests.get(api_url, params=params, timeout=5)
|
||||||
response.raise_for_status() # Raise an exception for bad status codes
|
response.raise_for_status() # Raise an exception for bad status codes
|
||||||
except requests.exceptions.RequestException as e:
|
except requests.exceptions.RequestException as e:
|
||||||
logging.error(f"Error connecting to Navidrome: {e}")
|
logging.error(f"Error connecting to Navidrome: {e}")
|
||||||
@@ -105,30 +219,57 @@ def main():
|
|||||||
for playlist_id in newly_added_ids:
|
for playlist_id in newly_added_ids:
|
||||||
playlist_data = current_playlists[playlist_id]
|
playlist_data = current_playlists[playlist_id]
|
||||||
playlist_name = playlist_data.get('name')
|
playlist_name = playlist_data.get('name')
|
||||||
logging.info(f"New playlist detected: '{playlist_name}' ({playlist_id}). Running command.")
|
logging.info(f"New playlist detected: '{playlist_name}' ({playlist_id}). Generating file.")
|
||||||
run_pls_command(playlist_id, playlist_name)
|
raw_output = run_pls_command(playlist_id)
|
||||||
|
if raw_output:
|
||||||
|
transformed_output = transform_m3u_to_m3u8(raw_output)
|
||||||
|
if transformed_output:
|
||||||
|
save_playlist_file(mopidy_playlist_dir, playlist_name, transformed_output)
|
||||||
|
|
||||||
# Deleted playlists
|
# Deleted playlists
|
||||||
deleted_ids = set(known_playlists.keys()) - set(current_playlists.keys())
|
deleted_ids = set(known_playlists.keys()) - set(current_playlists.keys())
|
||||||
for playlist_id in deleted_ids:
|
for playlist_id in deleted_ids:
|
||||||
playlist_data = known_playlists[playlist_id]
|
playlist_data = known_playlists[playlist_id]
|
||||||
logging.info(f"Playlist deleted: '{playlist_data.get('name')}' ({playlist_id}).")
|
playlist_name = playlist_data.get('name')
|
||||||
|
logging.info(f"Playlist deleted: '{playlist_name}' ({playlist_id}). Removing file.")
|
||||||
|
delete_playlist_file(mopidy_playlist_dir, playlist_name)
|
||||||
|
playlists_changed = True
|
||||||
|
|
||||||
# Check for song count changes in existing playlists
|
# Check for song count or name changes in existing playlists
|
||||||
for playlist_id, playlist_data in current_playlists.items():
|
for playlist_id, playlist_data in current_playlists.items():
|
||||||
if playlist_id in known_playlists:
|
if playlist_id in known_playlists:
|
||||||
previous_data = known_playlists[playlist_id]
|
previous_data = known_playlists[playlist_id]
|
||||||
current_song_count = playlist_data.get('songCount')
|
current_song_count = playlist_data.get('songCount')
|
||||||
previous_song_count = previous_data.get('songCount')
|
previous_song_count = previous_data.get('songCount')
|
||||||
|
current_name = playlist_data.get('name')
|
||||||
|
previous_name = previous_data.get('name')
|
||||||
|
|
||||||
if previous_song_count != current_song_count:
|
song_count_changed = previous_song_count != current_song_count
|
||||||
playlist_name = playlist_data.get('name')
|
name_changed = previous_name != current_name
|
||||||
logging.info(f"Song count changed for '{playlist_name}' ({playlist_id}): {previous_song_count} -> {current_song_count}. Running command.")
|
|
||||||
run_pls_command(playlist_id, playlist_name)
|
if song_count_changed or name_changed:
|
||||||
|
playlists_changed = True
|
||||||
|
log_msg = f"Playlist '{previous_name}' ({playlist_id}) changed."
|
||||||
|
if name_changed:
|
||||||
|
log_msg += f" Name: '{previous_name}' -> '{current_name}'."
|
||||||
|
delete_playlist_file(mopidy_playlist_dir, previous_name)
|
||||||
|
if song_count_changed:
|
||||||
|
log_msg += f" Song count: {previous_song_count} -> {current_song_count}."
|
||||||
|
|
||||||
|
logging.info(log_msg + " Regenerating file.")
|
||||||
|
|
||||||
|
raw_output = run_pls_command(playlist_id)
|
||||||
|
if raw_output:
|
||||||
|
transformed_output = transform_m3u_to_m3u8(raw_output)
|
||||||
|
if transformed_output:
|
||||||
|
save_playlist_file(mopidy_playlist_dir, current_name, transformed_output)
|
||||||
|
|
||||||
# Update the state for the next iteration.
|
# Update the state for the next iteration.
|
||||||
known_playlists = current_playlists
|
known_playlists = current_playlists
|
||||||
|
|
||||||
|
if playlists_changed:
|
||||||
|
call_mopidy_rpc('core.playlists.refresh')
|
||||||
|
|
||||||
time.sleep(5)
|
time.sleep(5)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
13
settings.py.example
Normal file
13
settings.py.example
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
MOPIDY_PLAYLIST_DIR = '/var/lib/mopidy/m3u'
|
||||||
|
|
||||||
|
MOPIDY_RPC_URL = 'http://127.0.0.1:6680/mopidy/rpc'
|
||||||
|
NAVIDROME_URL = 'https://navidrome.example.com'
|
||||||
|
|
||||||
|
NAVIDROME_USER = ''
|
||||||
|
|
||||||
|
# Set this one:
|
||||||
|
NAVIDROME_PASSWORD = ''
|
||||||
|
# or these two:
|
||||||
|
SUBSONIC_SALT = ''
|
||||||
|
SUBSONIC_TOKEN = ''
|
||||||
|
|
||||||
Reference in New Issue
Block a user