more cleanup

This commit is contained in:
Connor Olding 2014-11-02 13:29:44 -08:00
parent 2bbe301cdc
commit 62f12d031a
2 changed files with 31 additions and 46 deletions

View file

@ -25,23 +25,23 @@ def rating2byte(r):
return 0 return 0
def rating_get(id3, key): def rating_get(id3, key):
try: if 'TXXX:RATING' in id3:
rating = id3['TXXX:RATING'] rating = id3['TXXX:RATING']
except KeyError: return list(rating.text)
else:
try: try:
_, popm = next(popms(id3)) _, popm = next(popms(id3))
except StopIteration: except StopIteration:
return [] return []
else: else:
return [str(byte2rating(popm.rating))] return [str(byte2rating(popm.rating))]
else:
return list(rating.text)
def _canconv(r): def _canconv(r):
try: try:
if int(r) != str(int(r)): ir = int(r)
if ir != str(ir):
return False return False
return int(r) >= 1 and int(r) <= 5 return ir >= 1 and ir <= 5
except (ValueError, TypeError): except (ValueError, TypeError):
return False return False
@ -77,9 +77,6 @@ EasyID3.RegisterTextKey('albumartist', 'TPE2')
EasyID3.RegisterKey('rating', rating_get, rating_set, rating_delete) EasyID3.RegisterKey('rating', rating_get, rating_set, rating_delete)
class SyncFile(MutableMapping): class SyncFile(MutableMapping):
"""Dumb OOP crap that just adds more code
and a sense of self-importance"""
def __init__(self, path): def __init__(self, path):
self.md = mutagenx.File(path, easy=True) self.md = mutagenx.File(path, easy=True)
self.path = path self.path = path
@ -113,3 +110,6 @@ class SyncFile(MutableMapping):
def __len__(self): def __len__(self):
return len([k for k in self.__iter__()]) return len([k for k in self.__iter__()])
def save(self):
return self.md.save()

View file

@ -1,25 +1,22 @@
#!/bin/python #!/bin/python
import os import os, os.path
import os.path
import sys import sys
import shutil from shutil import copy2
import tempfile from tempfile import mkstemp
from zlib import crc32 from zlib import crc32
import mutaext import mutaext
import convert import convert
from mutaext import SyncFile from mutaext import SyncFile
# BUG: doesn't work with my .m4a files?
#goodexts = ('.mp3', '.mp2', '.m4a', '.flac', '.ogg')
goodexts = ('.mp3', '.flac', '.ogg') goodexts = ('.mp3', '.flac', '.ogg')
matchtags = ['artist', 'album', 'title'] matchtags = ['artist', 'album', 'title']
alltags = [\ alltags = [
'albumartist', 'composer', 'comment' \ 'albumartist', 'composer', 'comment',
'tracknumber', 'discnumber', \ 'tracknumber', 'discnumber',
'genre', 'date', \ 'genre', 'date',
] ]
alltags.extend(mutaext.replaygain_tags) alltags.extend(mutaext.replaygain_tags)
alltags.extend(mutaext.extra_tags) alltags.extend(mutaext.extra_tags)
@ -29,15 +26,12 @@ lament = lambda *args, **kwargs: print(*args, file=sys.stderr, **kwargs)
walkfiles = lambda w: (os.path.join(r, f) for r, _, fs in w for f in fs) walkfiles = lambda w: (os.path.join(r, f) for r, _, fs in w for f in fs)
extof = lambda p: os.path.splitext(p)[1].lower() extof = lambda p: os.path.splitext(p)[1].lower()
filterext = lambda ps, es: (p for p in ps if extof(p) in es) filterext = lambda ps, es: (p for p in ps if extof(p) in es)
ansty = lambda u: str(u.decode('ascii', errors='replace').replace('\ufffd', '?'))
def shouldsync(md): def shouldsync(md):
rating = md.get('rating', '') rating = md.get('rating', '')
sync = md.get('sync', '') sync = md.get('sync', '')
try: if rating.isnumeric():
rating = int(rating) rating = int(rating)
except ValueError:
pass
if sync: if sync:
sync = sync.lower() sync = sync.lower()
@ -80,8 +74,8 @@ def makefilename(md):
album = md['album'] album = md['album']
fn = "%(artist)s - %(album)s - %(title)s" % locals() fn = "%(artist)s - %(album)s - %(title)s" % locals()
crc = crc32(fn.encode('utf-8')) & 0xFFFFFFFF
# FAT is a pain to deal with so just use nondescript filenames # FAT is a pain to deal with so just use nondescript filenames
crc = crc32(fn.encode('utf-8')) & 0xFFFFFFFF
fn = '{:08X}.ogg'.format(crc) fn = '{:08X}.ogg'.format(crc)
return fn return fn
@ -108,7 +102,7 @@ def run(args):
if inonly: if inonly:
return 0 return 0
lament("Matching...") lament("Matching tags...")
outdir = args[2] outdir = args[2]
for p in paths(outdir): for p in paths(outdir):
@ -119,42 +113,33 @@ def run(args):
os.remove(p) os.remove(p)
elif updatemetadata(md, match): elif updatemetadata(md, match):
print("UPD", p) print("UPD", p)
md.md.save() md.save()
lament("Syncing files...")
lament("[beginning tosync]")
for md in tosync: for md in tosync:
#print("SYN", md.path)
fn = makefilename(md) fn = makefilename(md)
fout = os.path.join(outdir, fn) fout = os.path.join(outdir, fn)
if md.seen: if md.seen:
try:
_from = md.seen _from = md.seen
_to = fout _to = fout
if type(_from) != type(_to):
raise TypeError
if _from != _to: if _from != _to:
print("MOV", _from) print("MOV", _from)
os.rename(_from, _to) os.rename(_from, _to)
continue continue
except:
lament(type(_from), type(_to))
lament("_from:", [_from])
lament("_to:", [_to])
raise
print("ADD", md.path) print("ADD", md.path)
_, ftemp = tempfile.mkstemp() _, ftemp = mkstemp()
try: try:
convert.ogg(md.path, ftemp) convert.ogg(md.path, ftemp)
mdnew = SyncFile(ftemp) mdnew = SyncFile(ftemp)
for tag in alltags: for tag in alltags:
if tag in md: if tag in md:
mdnew[tag] = md[tag] mdnew[tag] = md[tag]
mdnew.md.save() mdnew.save()
shutil.copy2(ftemp, fout) copy2(ftemp, fout)
finally: finally:
os.remove(ftemp) os.remove(ftemp)