Support password-protected MPD servers

This commit is contained in:
Midgard 2021-08-08 17:36:42 +02:00
parent f99830847d
commit a792299f04
Signed by: midgard
GPG key ID: 511C112F1331BBB4

32
mmmpd
View file

@ -2,6 +2,7 @@
import os
import sys
import re
import subprocess
import datetime
import time
@ -77,6 +78,30 @@ def formatted_status(mpd_client):
return (emoji, song_str, expire)
def host_and_pass_from_MPD_HOST(mpd_host_string):
"""
mpc accepts passwords by setting MPD_HOST to pass@host. For compatibility, we do the same.
"""
m = re.match(r"""
(?: # Optional password, followed by @, but cannot
(?P<pass> [^@]+?) @ # start with @ (that's for abstract sockets on Linux).
)? # If present, after the password there'll be an @.
(?P<host> .*)
""", mpd_host_string, re.VERBOSE)
if not m:
return None
return (m.group("host"), m.group("pass") or None)
def create_mpd_client(mpd_host, mpd_port, mpd_pass):
mpd_client = mpd.MPDClient()
mpd_client.connect(mpd_host, port=mpd_port)
if mpd_pass:
mpd_client.password(mpd_pass)
LOGGER.info("Connected")
return mpd_client
# Driving stuff {{{1
# -------------
@ -97,7 +122,7 @@ def loop(mpd_client, on_status_change):
time.sleep(1)
def main(mpd_host, mpd_port):
def main(mpd_host_string, mpd_port):
if "-v" in sys.argv[1:]:
logging.basicConfig(level=logging.INFO)
LOGGER.info("Log level INFO")
@ -105,9 +130,8 @@ def main(mpd_host, mpd_port):
logging.basicConfig(level=logging.DEBUG)
LOGGER.info("Log level DEBUG")
mpd_client = mpd.MPDClient()
mpd_client.connect(mpd_host, port=mpd_port)
LOGGER.info("Connected")
mpd_host, mpd_pass = host_and_pass_from_MPD_HOST(mpd_host_string)
mpd_client = create_mpd_client(mpd_host, mpd_port, mpd_pass)
set_status_from_mpd(mpd_client)
try: