]> git.draconx.ca Git - scripts.git/commitdiff
caa-fetcher: Allow pasting musicbrainz URIs for MBIDs
authorNick Bowler <nbowler@draconx.ca>
Thu, 16 May 2019 23:27:32 +0000 (19:27 -0400)
committerNick Bowler <nbowler@draconx.ca>
Thu, 16 May 2019 23:27:32 +0000 (19:27 -0400)
This alters the input parsing so you can simply paste any string
containing a substring that looks like an MBID.  The first such
substring will be used.  This makes it easier to browse to a release
on Musicbrainz and just copy+paste the URI into caa-fetcher.

And improve the error messages if you paste some other kind of MBID.

caa-fetcher.py

index 7f90f2c34b4fc61aa1935627c2057e7712152d58..de19aebf5b6394160964ce651f7e5bcc907f037c 100755 (executable)
@@ -12,8 +12,10 @@ from pathlib import Path
 import musicbrainzngs
 import argparse
 import tempfile
+import urllib
 import sys
 import os
+import re
 
 umask = os.umask(0)
 os.umask(umask)
@@ -26,6 +28,9 @@ parser = argparse.ArgumentParser(
     description='Download album artwork from the Cover Art Archive'
 )
 
+def errmsg(msg, prog=parser.prog):
+    print("%s: %s" % (prog, msg), file=sys.stderr)
+
 # NamedTemporaryFile workalike which allows control of the file mode...
 def open_tmp(prefix="tmp", suffix="", dir=".", mode=0o600):
     names = tempfile._get_candidate_names()
@@ -38,6 +43,14 @@ def open_tmp(prefix="tmp", suffix="", dir=".", mode=0o600):
         return tempfile._TemporaryFileWrapper(f, name)
     return None
 
+# Given an arbitrary string, return the first substring that looks like an
+# mbid, or None if no such substring is found.
+def extract_mbid(arg):
+    xdigit = r'[0-9abcdefABCDEF]'
+    m = re.search(r'{0}{{8}}(-{0}{{4}}){{3}}-{0}{{12}}'.format(xdigit), arg)
+    if m:
+        return m.group()
+
 class VersionAction(argparse.Action):
     def __init__(self, **kw):
         super().__init__(nargs=0, help="show a version message and exit", **kw)
@@ -56,10 +69,22 @@ parser.add_argument('-o', '--output-directory', metavar='DIR',
 parser.add_argument('-r', '--release-mbid', metavar='MBID', required=True)
 args = parser.parse_args()
 
+release_mbid = extract_mbid(args.release_mbid)
+if release_mbid is None:
+    parser.error("invalid release MBID: %s" % (args.release_mbid))
+
 # TODO: allow the naming scheme to be configured...
 name_format = "{num:02d}"
 
-covers = musicbrainzngs.get_image_list(args.release_mbid)
+try:
+    covers = musicbrainzngs.get_image_list(release_mbid)
+except musicbrainzngs.ResponseError as e:
+    errmsg("error: cannot retrieve image list for release")
+    errmsg(e)
+    if isinstance(e.cause, urllib.error.HTTPError) and e.cause.code == 404:
+        errmsg("is %s a release MBID?" % (release_mbid))
+    sys.exit(1)
+
 if len(covers["images"]) == 0:
     print("release has no cover art, nothing to do")
     sys.exit()