Esempio n. 1
0
def main():
    if len(sys.argv) < 2:
        print_usage()
        sys.exit(1)

    releaseid = None
    embedcovers = True
    asin = None
    year = None
    noact = False
    totaldiscs = None

    for option in sys.argv[2:]:
        if option.startswith("--release-id="):
            releaseid = option.split("=")[1].strip()
        elif option.startswith("--no-embed-coverart"):
            embedcovers = False
        elif option.startswith("--release-asin="):
            asin = option.split("=", 1)[1].strip()
        elif option.startswith("--year="):
            year = option.split("=")[1].strip()
        elif option.startswith("-n"):
            noact = True
        elif option.startswith("--total-discs"):
            totaldiscs = option.split("=", 1)[1].strip()

    srcpath = os.path.abspath(sys.argv[1])

    if not os.path.exists(srcpath):
        print_usage()
        sys.exit(2)

    if noact:
        print "Performing dry-run"

    print "Source path: " + srcpath

    tocfilename = ""
    if os.path.exists(os.path.join(srcpath, "data.toc")):
        tocfilename = "data.toc"
    elif os.path.exists(os.path.join(srcpath, "TOC")):
        tocfilename = "TOC"
    else:
        print "No TOC in source path!"
        sys.exit(4)

    disc = toc.Disc(cdrdaotocfile=os.path.join(srcpath, tocfilename))

    disc.tocfilename = tocfilename
    disc.discid = discid.generate_musicbrainz_discid(
        disc.get_first_track_num(), disc.get_last_track_num(), disc.get_track_offsets()
    )

    for i in range(len(disc.tracks)):
        disc.tracks[i].filename = os.path.join(srcpath, "track" + str(i + 1).zfill(2) + ".flac")
        if not os.path.exists(disc.tracks[i].filename):
            disc.tracks[i].filename = os.path.join(srcpath, "track" + str(i + 1).zfill(2) + ".cdda.flac")

    print "discID: " + disc.discid

    if releaseid:
        disc.releaseid = releaseid

    release = get_musicbrainz_release(disc)

    if release is None:
        raise Exception("Couldn't find a matching release. Sorry, I tried.")

    print "release id: %s.html" % (release.id)

    disc.releasetypes = release.getTypes()

    disc.set_musicbrainz_tracks(release.getTracks())
    disc.releasedate = release.getEarliestReleaseDate()

    disc.artist = release.artist.name
    disc.album = release.title
    if year is not None:
        disc.year = year
        disc.releasedate = year
    elif disc.releasedate is not None:
        disc.year = disc.releasedate[0:4]
    else:
        raise Exception("Unknown year: %s %s " % (` disc.artist `, ` disc.album `))

    disc.compilation = 0
    disc.number = 0
    disc.totalnumber = 0
    if asin is not None:
        disc.asin = asin
    else:
        disc.asin = lookups.get_asin_from_release(release, prefer=".co.uk")

        # Set the compilation tag appropriately
    if musicbrainz2.model.Release.TYPE_COMPILATION in disc.releasetypes:
        disc.compilation = 1

        # Name the target folder differently for soundtracks
    if musicbrainz2.model.Release.TYPE_SOUNDTRACK in disc.releasetypes:
        newpath = "Soundtrack - %s - %s" % (disc.year, disc.album)
    else:
        newpath = "%s - %s - %s" % (mp3names.FixArtist(disc.artist), disc.year, disc.album)
    newpath = mp3names.FixFilename(newpath)
    newpath = os.path.join(srcpath, "../%s/" % newpath)
    newpath = os.path.normpath(newpath)

    print "Destination path: " + newpath

    if os.path.exists(newpath):
        print "Destination path already exists, skipping"
        sys.exit(3)

    if not noact:
        os.mkdir(newpath)

        # Get album art
    imageurl = lookups.get_album_art_url_for_asin(disc.asin)
    # Check for manual image
    if os.path.exists(os.path.join(srcpath, "folder.jpg")):
        print "Using existing image"
        if not noact:
            shutil.copyfile(os.path.join(srcpath, "folder.jpg"), os.path.join(newpath, "folder.jpg"))
    elif imageurl is not None:
        if not noact:
            try:
                (f, h) = urllib.urlretrieve(imageurl, os.path.join(newpath, "folder.jpg"))
                if h.getmaintype() != "image":
                    print "WARNING: Failed to retrieve coverart (%s)" % imageurl
                    embedcovers = False
            except:
                print "WARNING: Failed to retrieve coverart (%s)" % imageurl
                embedcovers = False
    else:
        embedcovers = False

        # Deal with disc x of y numbering
    (albumname, discnumber, disctitle) = lookups.parse_album_name(disc.album)
    if discnumber is None:
        disc.number = 1
        disc.totalnumber = 1
    elif totaldiscs is not None:
        disc.totalnumber = totaldiscs
        disc.number = int(discnumber)
    else:
        disc.number = int(discnumber)
        discs = lookups.get_all_releases_in_set(release.id)
        disc.totalnumber = len(discs)

    print "disc " + str(disc.number) + " of " + str(disc.totalnumber)
    flacname(disc, release, srcpath, newpath, embedcovers, noact)
Esempio n. 2
0
def find_albumart(srcpath, disc, options):
    imageurl = lookups.get_album_art_url_for_asin(disc.asin)
    images = []
    if imageurl is not None:
        print "Downloading album art from %s" % imageurl
        if not options.noact:
            try:
                (fd, tmpfile) = tempfile.mkstemp(suffix=".jpg")
                os.close(fd)
                (f, h) = urllib.urlretrieve(imageurl, tmpfile)
                if h.getmaintype() != "image":
                    print "WARNING: image url returned unexpected mimetype: %s" % h.gettype(
                    )
                    os.unlink(tmpfile)
                else:
                    imagemime = h.gettype()
                    imagepath = tmpfile
                    try:
                        import Image
                        i = Image.open(imagepath)
                        # Sometimes amazon will give us a 1x1 gif as an image.  Ignore.
                        if i.size[0] != 1:
                            images.append(
                                (imagepath, imagemime, True, "amazon"))
                    except ImportError, e:
                        # If the image library isn't there, check the filesize of the 1x1
                        if os.path.getsize(imagepath) != 807:
                            images.append(
                                (imagepath, imagemime, True, "amazon"))
            except:
                print "WARNING: Failed to retrieve coverart (%s)" % imageurl
    if os.path.exists(os.path.join(srcpath, "folder.jpg")):
        print "Found existing image file"
        imagemime = "image/jpeg"
        imagepath = os.path.join(srcpath, "folder.jpg")
        images.append((imagepath, imagemime, False, "local file"))

    dir = sort.sorted_dir(srcpath)
    filetags = tag.read_tags(dir[0])
    if tag.IMAGE in filetags:
        # Yuck
        tagdata = filetags[tag.IMAGE]
        if not isinstance(tagdata, list):
            tagdata = [tagdata]
        for image in tagdata:
            print "Found image embedded in file"
            if image['mime'] == "image/jpeg":
                suffix = ".jpg"
            elif image['mime'] == "image/png":
                suffix = ".png"
            else:
                print "Embeded Image is of unknown Mime Type"
                continue
            if image['pictype'] != 3:
                print "Embeded Image not coverart"
                continue
            (fd, tmpfile) = tempfile.mkstemp(suffix)
            os.write(fd, image['imagedata'])
            os.close(fd)
            images.append((tmpfile, image['mime'], True, "embedded tag"))

    best = find_best_image(images)[0]
    if best[0] is not None:
        util.report("Best cover image: %s (from %s)" % (best[0], best[3]))
    return best
Esempio n. 3
0
def find_albumart(srcpath,disc,options):
	imageurl = lookups.get_album_art_url_for_asin(disc.asin)
	images = []
	if imageurl is not None:
                print "Downloading album art from %s" % imageurl
		if not options.noact:
                        try:
                                (fd,tmpfile) = tempfile.mkstemp(suffix = ".jpg")
                                os.close(fd)
                                (f,h) = urllib.urlretrieve(imageurl, tmpfile)
                                if h.getmaintype() != "image":
                                        print "WARNING: image url returned unexpected mimetype: %s" % h.gettype()
                                        os.unlink(tmpfile)
                                else:
                                        imagemime = h.gettype()
                                        imagepath = tmpfile
					try:
						import Image
						i = Image.open(imagepath)
						# Sometimes amazon will give us a 1x1 gif as an image.  Ignore.
						if i.size[0] != 1:
							images.append((imagepath, imagemime, True, "amazon"))
					except ImportError, e:
						# If the image library isn't there, check the filesize of the 1x1
						if os.path.getsize(imagepath) != 807:
							images.append((imagepath, imagemime, True, "amazon"))
			except:
                                print "WARNING: Failed to retrieve coverart (%s)" % imageurl
	if os.path.exists(os.path.join(srcpath, "folder.jpg")):
		print "Found existing image file"
                imagemime="image/jpeg"
                imagepath = os.path.join(srcpath, "folder.jpg")
		images.append((imagepath, imagemime, False, "local file"))
	
	dir = sort.sorted_dir(srcpath)
	filetags = tag.read_tags(dir[0])
	if tag.IMAGE in filetags:
		# Yuck
		tagdata = filetags[tag.IMAGE]
		if not isinstance(tagdata, list):
			tagdata = [tagdata]
		for image in tagdata:
			print "Found image embedded in file"
			if image['mime'] == "image/jpeg":
				suffix = ".jpg"
			elif image['mime'] == "image/png":
				suffix = ".png"
			else:
				print "Embeded Image is of unknown Mime Type"
				continue
			if image['pictype'] != 3:
				print "Embeded Image not coverart"
				continue
			(fd,tmpfile) = tempfile.mkstemp(suffix)
			os.write(fd, image['imagedata'])
			os.close(fd)
			images.append((tmpfile, image['mime'], True, "embedded tag"))

	best = find_best_image(images)[0]
	if best[0] is not None:
		util.report("Best cover image: %s (from %s)" % (best[0], best[3]))
	return best