diff --git a/delojza.py b/delojza.py index 9d94742..2e89082 100755 --- a/delojza.py +++ b/delojza.py @@ -26,6 +26,7 @@ import pytumblr import requests import telegram import youtube_dl +from mutagen.easyid3 import EasyID3 from telegram.ext import Updater, CommandHandler, MessageHandler from youtube_dl import DownloadError from youtube_dl.version import __version__ as YTDL_VERSION @@ -165,6 +166,14 @@ class DelojzaBot: filepath = unicodedata.normalize('NFKD', filepath).encode('ascii', 'ignore').decode('ascii') return re.sub(r'[^\w.()\[\]{}#-]', '_', filepath) + @staticmethod + def _get_tags(filepath): + try: + audio = EasyID3(filepath) + return audio["artist"][0] if audio["artist"] else None, audio["title"][0] if audio["title"] else None + except mutagen.id3.ID3NoHeaderError: + return None, None + @staticmethod def _tag_file(filepath, artist, title): try: @@ -599,19 +608,32 @@ class DelojzaBot: def tg_retag(self, _, update): self._log_msg(update) - if self.last_downloaded.get(update.message.chat.id) is not None and " - " in update.message.text: + if self.last_downloaded.get(update.message.chat.id) is not None: files, hashtags, tumblr_ids = self.last_downloaded[update.message.chat.id] mp3s = [filename for filename in files if filename.endswith("mp3")] if len(mp3s) > 0: - tagline = re.sub(r'^/[\w]+', '', update.message.text).split(" - ") - artist = tagline[0].strip() - title = tagline[1].strip() + arg_raw = re.sub(r'^/[\w]+ ', '', update.message.text).strip() + artist, title = None, None + + reverse = len(arg_raw) == 0 + if not reverse: + tagline = arg_raw.split(" - ") + if len(tagline) == 1: + title = tagline[0].strip() + else: + artist = tagline[0].strip() + title = tagline[1].strip() + for mp3 in mp3s: + if reverse: + orig_artist, orig_title = self._get_tags(mp3) + title, artist = orig_artist, orig_title + self._tag_file(mp3, artist, title) update.message.reply_text("Tagging \"{}\" as \"{}\" by \"{}\"!" .format(mp3[len(self.out_dir) + 1:], title, artist)) - return - update.message.reply_text((self.markov.make_sentence() if self.markov and random() > .7 else "") + "???") + else: + update.message.reply_text((self.markov.make_sentence() if self.markov and random() > .7 else "") + "???") def tg_delete(self, _, update): self._log_msg(update)