]> git.draconx.ca Git - scripts.git/blob - caa-fetcher.py
Add tool to fetch album art from the Cover Art Archive
[scripts.git] / caa-fetcher.py
1 #!/usr/bin/env python
2 #
3 # Copyright © 2018 Nick Bowler
4 #
5 # Tool to fetch album art for a release from the Cover Art Archive.
6 #
7 # License WTFPL2: Do What The Fuck You Want To Public License, version 2.
8 # This is free software: you are free to do what the fuck you want to.
9 # There is NO WARRANTY, to the extent permitted by law.
10
11 from pathlib import Path
12 import musicbrainzngs
13 import argparse
14 import tempfile
15 import sys
16 import os
17
18 progname = "caa-fetcher"
19 version = "0"
20 musicbrainzngs.set_useragent(progname, version)
21
22 parser = argparse.ArgumentParser(
23     description='Download album artwork from the Cover Art Archive'
24 )
25
26 class VersionAction(argparse.Action):
27     def __init__(self, **kw):
28         super().__init__(nargs=0, help="show a version message and exit", **kw)
29     def __call__(self, parser, namespace, values, option_string=None):
30         print("%s %s" % (progname, version))
31         print('''Copyright © 2018 Nick Bowler
32 License WTFPL2: Do What The Fuck You Want To Public License, version 2.
33 This is free software: you are free to do what the fuck you want to.
34 There is NO WARRANTY, to the extent permitted by law.''')
35         sys.exit(0)
36 parser.add_argument('--version', action=VersionAction)
37
38 parser.add_argument('-o', '--output-directory', metavar='DIR',
39                     help='''downloaded files are written to DIR, which is
40                             created if it does not exists.  Default: .''')
41 parser.add_argument('-r', '--release-mbid', metavar='MBID', required=True)
42 args = parser.parse_args()
43
44 # TODO: allow the naming scheme to be configured...
45 name_format = "{num:02d}"
46
47 covers = musicbrainzngs.get_image_list(args.release_mbid)
48 if len(covers["images"]) == 0:
49     print("release has no cover art, nothing to do")
50     sys.exit()
51
52 if args.output_directory:
53     Path(args.output_directory).mkdir(parents=True, exist_ok=True)
54     os.chdir(args.output_directory)
55
56 failed = False
57 for c in covers["images"]:
58     (_,ext) = os.path.splitext(c["image"])
59     outname = (name_format + "{0}").format(ext,
60         num = (covers["images"].index(c) + 1)
61     )
62
63     if Path(outname).exists():
64         print("%s already exists, skipping..." % outname)
65         continue
66
67     outfile = tempfile.NamedTemporaryFile(suffix=ext, dir=".")
68     rc = os.spawnlp(os.P_WAIT, 'wget', 'wget', '-O', outfile.name, c["image"])
69     if rc:
70         failed = True
71     os.link(outfile.name, outname)
72     outfile.close()
73
74 if failed:
75     sys.exit(1)