Skip to content

Instantly share code, notes, and snippets.

@pblocz
Last active March 6, 2017 03:03
Show Gist options
  • Save pblocz/f17fea7f57d6809b1dff280f1346baf0 to your computer and use it in GitHub Desktop.
Save pblocz/f17fea7f57d6809b1dff280f1346baf0 to your computer and use it in GitHub Desktop.
Script that syncs a playlist (m3u) with current audacious playlist.
#! /usr/bin/env python
'''
Script that syncs a playlist (m3u) with current audacious playlist.
'''
import click
import os
import shlex
import subprocess as sp
from pathlib import Path
import shutil, textwrap
TOOL = "audtool"
LENGTH = "--playlist-length"
ADD = "--playlist-addurl"
NAME = "--playlist-song-filename"
PLAYLISTS = "--number-of-playlists"
GET_PLAYLIST = "--current-playlist"
SET_PLAYLIST = "--set-current-playlist"
CURRENT_PLAYLIST_NAME = "--current-playlist-name"
COLUMNS, LINES = shutil.get_terminal_size(fallback=(75, 22))
def wrap(text, item_prefix="", indent=0, width=COLUMNS, *args, **kwargs):
prefix = "{}{}".format(" " * indent, item_prefix)
wrapper = textwrap.TextWrapper(
initial_indent=prefix,
subsequent_indent=" " * len(prefix),
width=width)
click.echo(wrapper.fill(text), *args, **kwargs)
def get_current_playlist():
total = sp.check_output([TOOL, PLAYLISTS])
current = sp.check_output([TOOL, GET_PLAYLIST])
name = sp.check_output([TOOL, CURRENT_PLAYLIST_NAME], encoding='utf-8')
return (int(current), name.strip(), int(total))
def get_audacious_playlist_files():
length = sp.check_output([TOOL, LENGTH])
length = int(length)
return [sp.check_output([TOOL, NAME, str(i)], encoding='utf-8').strip()
for i
in range(1, length + 1)]
def add_audacious_songs(songs):
click.echo("Adding %d new songs:" % len(songs))
for song in songs:
wrap("adding %s" % song, indent=2, item_prefix="- ")
sp.check_call([TOOL, ADD, song])
@click.command()
@click.argument('playlist')
@click.option('--yes', '-y', is_flag=True,
help="Don't confirm playlist to use")
@click.pass_context
def main(ctx, playlist, yes):
"Syncs a playlist with audacious using audtool"
try:
curr, name, total = get_current_playlist()
if not yes:
click.confirm(
"Use playlist %s?" % click.style(name, fg="blue"),
abort=True)
new_paths = []
playlist_dir = Path(playlist).parent
for line in open(playlist):
line = line.strip()
if line.startswith('#'):
continue
np = Path(line).expanduser()
if not np.is_absolute(): np = playlist_dir / np
new_paths.append(str(np.resolve()))
aud_paths = get_audacious_playlist_files()
diff = set(new_paths) - set(aud_paths)
if diff:
add_audacious_songs(diff)
except sp.CalledProcessError as e:
message = ""
message += "Exit status {} while using audtool command: {}\n".format(
click.style(str(e.returncode), bold=True),
click.style(
" ".join(shlex.quote(s) for s in e.cmd),
bold=True))
message += "Make sure audacious is running."
click.echo(message, err=True)
ctx.abort()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment