dr.botzo/scripts/mpd-notifications/mpd-notifications.py

82 lines
2.3 KiB
Python

"""Use dr.botzo's Dispatch to send mpd notifications."""
import argparse
import getpass
import logging
from select import select
import sys
import mpd
import requests
from requests.auth import HTTPBasicAuth
# set up some basic logging
logger = logging.getLogger()
handler = logging.StreamHandler(sys.stdout)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
# set up config flags
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--location')
parser.add_argument('-u', '--user')
parser.add_argument('-m', '--mpd-host', default='localhost')
parser.add_argument('-p', '--mpd-port', default=6600)
parser.add_argument('-a', '--mpd-password', action='store_true')
args = parser.parse_args()
if args.user is None or args.location is None:
print("script needs "
"-l/--location (url to connect to) -u/--user (user to authenticate to XML-RPC as)")
sys.exit(2)
password = getpass.getpass("password for {0:s}: ".format(args.user))
auth = HTTPBasicAuth(args.user, password)
client = mpd.MPDClient(use_unicode=True)
client.connect(args.mpd_host, args.mpd_port)
if args.mpd_password:
mpd_password = getpass.getpass("password for mpd: ")
client.password(mpd_password)
last_np = ''
def notify_song():
"""React to mpd event, send a now playing dispatch message if relevant."""
global last_np
status = client.status()
logger.debug(status)
state = status.get('state', None)
if state == 'play':
current = client.currentsong()
logger.debug(current)
filename = current.get('file', None)
if filename:
artist = current.get('artist', "Unknown")
title = current.get('title', "Unknown")
album = current.get('album', "Unknown")
np = "{0:s} - {1:s} [{2:s}]".format(artist, title, album)
if np != last_np:
last_np = np
logger.debug("notifying: {0:s}".format(np))
payload = {'message': np}
r = requests.post(args.location, auth=auth, data=payload)
print(r.json())
notify_song()
# loop forever on mpd events
while True:
client.send_idle()
select([client], [], [])
changed = client.fetch_idle()
for change in changed:
if change == 'player':
notify_song()