def syncImage(img, current, session): """Add or updated the Image.""" def _img_str(i): return "%s - %s" % (i.type, i.description) for db_img in current.images: img_info = (img.type, img.md5, img.size) db_img_info = (db_img.type, db_img.md5, db_img.size) if db_img_info == img_info: img = None break elif (db_img.type == img.type and db_img.description == img.description): if img.md5 != db_img.md5: # Update image current.images.remove(db_img) current.images.append(img) session.add(current) pout(Fg.green("Updating image") + ": " + _img_str(img)) img = None break if img: # Add image current.images.append(img) session.add(current) pout(Fg.green("Adding image") + ": " + _img_str(img))
def _run(self): logo = figlet_format("``MishMash``", font="graffiti") print(Fg.green(logo, Style.BRIGHT)) self._displayMetaInfo() all_libs = { l.name: l for l in self.db_session.query(Library).filter( Library.id > NULL_LIB_ID).all() } lib_args = set(self.args.libs or all_libs.keys()) for lib in lib_args: if lib not in all_libs.keys(): print(Fg.red(f"Unknown library: {lib}")) continue lib = all_libs[lib] if self.args.show_artists: print(Fg.green(f"\n=== {lib.name} library artists ===")) self._displayArtists(lib) else: print(Fg.green(f"\n=== {lib.name} library ===")) self._displayLibraryInfo(lib)
def promptArtist(text, name=None, default_name=None, default_city=None, default_state=None, default_country=None, artist=None): if text: print(text) if name is None: name = prompt(Fg.green("Artist name"), default=default_name) origin = {} for o in ("city", "state", "country"): origin["origin_%s" % o] = prompt(" %s" % Fg.green(o.title()), default=locals()["default_%s" % o], required=False) if not artist: artist = Artist(name=name, **origin) else: artist.name = name for o in origin: setattr(artist, o, origin[o]) return artist
def _run(self): logo = figlet_format("``MishMash``", font="graffiti") print(Fg.green(logo, Style.BRIGHT)) self._displayMetaInfo() for lib in Library.iterall(self.db_session, names=self.args.libs): if self.args.show_artists: print(Fg.green(f"\n=== {lib.name} library artists ===")) self._displayArtists(lib) else: print(Fg.green(f"\n=== {lib.name} library ===")) self._displayLibraryInfo(lib)
def _run(self): session = self.db_session _output = [] def _addOutput(k, v): _output.append(tuple((k, v))) def _printOutput(_format, _olist): k_width = max([len(k) for k, v in _olist if k]) for k, v in _olist: if k: print((_format.format(k=k.ljust(k_width), v=v))) _olist.clear() logo = figlet_format("``MishMash``", font="graffiti") print((Fg.green(logo, Style.BRIGHT))) def mkkey(k): return Style.bright(Fg.blue(str(k))) def mkval(v): return Style.bright(Fg.blue(str(v))) _addOutput(mkkey("Version"), mkval(version)) _addOutput(mkkey("Database URL"), mkval(self.config.db_url)) try: meta = session.query(Meta).one() except (ProgrammingError, OperationalError) as ex: printError("\nError querying metadata. Database may not be " "initialized: %s" % str(ex)) return 1 _addOutput(mkkey("Database version"), mkval(meta.version)) _addOutput(mkkey("Last sync"), mkval(meta.last_sync or "Never")) _addOutput(mkkey("Configuration file "), mkval(self.args.config.filename or "None")) _printOutput("{k} : {v}", _output) def mkkey(k): return Style.bright(str(k)) print("") for lib in session.query(Library)\ .filter(Library.id > NULL_LIB_ID).all(): print((Fg.yellow("\n=== {} library ===").format(lib.name))) _addOutput(None, None) for name, orm_type in [ ("tracks", Track), ("artists", Artist), ("albums", Album), ("tags", Tag), ]: count = session.query(orm_type).filter_by(lib_id=lib.id)\ .count() _addOutput(mkkey(count), name) _printOutput("{k} music {v}", _output)
def test_ansi_formats(): ansi_init(True) s = "Heavy Cream - Run Free" assert Fg.green(s, Style.BRIGHT, Style.UNDERLINE, Style.ITALICS) == \ Style.BRIGHT + Style.UNDERLINE + Style.ITALICS + Fg.GREEN + s + \ Fg.RESET + Style.RESET_ALL print("%(BLUE)sNice%(RESET)s" % Fg)
def _write_log(self, environ, method, req_uri, start, status, bytes): if bytes is None: bytes = '-' if time.daylight: offset = time.altzone / 60 / 60 * -100 else: offset = time.timezone / 60 / 60 * -100 if offset >= 0: offset = "+%0.4d" % (offset) elif offset < 0: offset = "%0.4d" % (offset) remote_addr = '-' if environ.get('HTTP_X_FORWARDED_FOR'): remote_addr = environ['HTTP_X_FORWARDED_FOR'] elif environ.get('REMOTE_ADDR'): remote_addr = environ['REMOTE_ADDR'] stat = status.split(None, 1)[0] if (environ.get("webob._parsed_query_vars") and environ.get("webob._parsed_query_vars")[0].get("u")): user = environ.get("webob._parsed_query_vars")[0].get("u") user = environ.get('REMOTE_USER') or user or None else: user = None if user: remote_addr = "%s@%s" % (user, remote_addr) d = { 'REMOTE_ADDR': remote_addr, 'REQUEST_METHOD': method, 'REQUEST_URI': req_uri, 'HTTP_VERSION': environ.get('SERVER_PROTOCOL'), 'time': time.strftime('%d/%b/%Y:%H:%M:%S ', start) + offset, 'status': stat, 'bytes': bytes, 'HTTP_REFERER': environ.get('HTTP_REFERER', '-'), 'HTTP_USER_AGENT': environ.get('HTTP_USER_AGENT', '-'), } message = self.format % d stat = int(stat) if stat >= 200 and stat < 300: message = Fg.green(message) if stat >= 400 and stat < 500: message = Fg.yellow(message) if stat >= 500: message = Fg.red(message) self.logger.log(self.logging_level, message)
def _getArtist(self, session, name, resolved_artist): artist_rows = session.query(Artist).filter_by( name=name, lib_id=self._lib.id).all() if artist_rows: if len(artist_rows) > 1 and resolved_artist: # Use previously resolved artist for this directory. artist = resolved_artist elif len(artist_rows) > 1: # Resolve artist try: heading = "Multiple artists names '%s'" % \ artist_rows[0].name artist = console.selectArtist(Fg.blue(heading), choices=artist_rows, allow_create=True) except PromptExit: log.warn("Duplicate artist requires user " "intervention to resolve.") artist = None else: if artist not in artist_rows: session.add(artist) session.flush() pout(Fg.blue("Updating artist") + ": " + name) resolved_artist = artist else: # Artist match artist = artist_rows[0] else: # New artist artist = Artist(name=name, lib_id=self._lib.id) session.add(artist) session.flush() pout(Fg.green("Adding artist") + ": " + name) return artist, resolved_artist
def _syncAudioFile(self, audio_file, album_type, d_datetime, session): path = audio_file.path info = audio_file.info tag = audio_file.tag album = None is_various = (album_type == VARIOUS_TYPE) if not info or not tag: log.warn("File missing %s, skipping: %s" % ("audio" if not info else "tag/metadata", path)) return elif None in (tag.title, tag.artist): log.warn("File missing required artist and/or title " "metadata, skipping: %s" % path) return # Used when a duplicate artist is resolved for the entire directory. resolved_artist = None resolved_album_artist = None try: track = session.query(Track)\ .filter_by(path=path, lib_id=self._lib.id).one() except NoResultFound: track = None else: if datetime.fromtimestamp(getctime(path)) == track.ctime: # Track is in DB and the file is not modified. # stash the album though, we'll look for artwork # updates later album = track.album return # Either adding the track (track == None) # or modifying (track != None) artist, resolved_artist = self._getArtist(session, tag.artist, resolved_artist) if tag.album_type != SINGLE_TYPE: if tag.album_artist and tag.artist != tag.album_artist: album_artist, resolved_album_artist = \ self._getArtist(session, tag.album_artist, resolved_album_artist) else: album_artist = artist if artist is None: # see PromptExit return album_artist_id = album_artist.id if not is_various \ else VARIOUS_ARTISTS_ID album_rows = session.query(Album)\ .filter_by(title=tag.album, lib_id=self._lib.id, artist_id=album_artist_id).all() rel_date = tag.release_date rec_date = tag.recording_date or_date = tag.original_release_date if album_rows: if len(album_rows) > 1: # This artist has more than one album with the same # title. raise NotImplementedError("FIXME") album = album_rows[0] album.type = album_type album.release_date = rel_date album.original_release_date = or_date album.recording_date = rec_date pout(Fg.yellow("Updating album") + ": " + album.title) elif tag.album: album = Album(title=tag.album, lib_id=self._lib.id, artist_id=album_artist_id, type=album_type, release_date=rel_date, original_release_date=or_date, recording_date=rec_date, date_added=d_datetime) session.add(album) pout(Fg.green("Adding album") + ": " + album.title) session.flush() if not track: track = Track(audio_file=audio_file, lib_id=self._lib.id) self._num_added += 1 pout(Fg.green("Adding track") + ": " + path) else: track.update(audio_file) self._num_modified += 1 pout(Fg.yellow("Updating track") + ": " + path) genre = tag.genre genre_tag = None if genre: try: genre_tag = session.query(Tag)\ .filter_by(name=genre.name, lib_id=self._lib.id).one() except NoResultFound: genre_tag = Tag(name=genre.name, lib_id=self._lib.id) session.add(genre_tag) session.flush() track.artist_id = artist.id track.album_id = album.id if album else None if genre_tag: track.tags.append(genre_tag) session.add(track) if album: # Tag images for img in tag.images: for img_type in art.TO_ID3_ART_TYPES: if img.picture_type in \ art.TO_ID3_ART_TYPES[img_type]: break img_type = None if img_type is None: log.warn("Skipping unsupported image type: %s" % img.picture_type) continue new_img = Image.fromTagFrame(img, img_type) if new_img: syncImage( new_img, album if img_type in IMAGE_TYPES["album"] else album.artist, session) else: log.warn("Invalid image in tag") return album