add /retag command

This commit is contained in:
Tomáš Mládek 2019-05-29 10:25:34 +02:00
parent d6372671be
commit e291a41ea9

View file

@ -13,6 +13,7 @@ from configparser import ConfigParser
from datetime import datetime, timedelta from datetime import datetime, timedelta
from glob import glob from glob import glob
from operator import itemgetter from operator import itemgetter
from random import random
import acoustid import acoustid
import filetype import filetype
@ -60,6 +61,7 @@ class DelojzaBot:
dp.add_handler(CommandHandler("stats", self.tg_stats)) dp.add_handler(CommandHandler("stats", self.tg_stats))
dp.add_handler(CommandHandler("orphans", self.tg_orphan)) dp.add_handler(CommandHandler("orphans", self.tg_orphan))
dp.add_handler(CommandHandler("orphans_full", self.tg_orphan_full)) dp.add_handler(CommandHandler("orphans_full", self.tg_orphan_full))
dp.add_handler(CommandHandler("retag", self.tg_retag))
dp.add_handler(CommandHandler("delete", self.tg_delete)) dp.add_handler(CommandHandler("delete", self.tg_delete))
dp.add_handler(CommandHandler("version", self.tg_version)) dp.add_handler(CommandHandler("version", self.tg_version))
dp.add_handler(MessageHandler(None, self.tg_handle)) dp.add_handler(MessageHandler(None, self.tg_handle))
@ -94,7 +96,22 @@ class DelojzaBot:
filepath = unicodedata.normalize('NFKD', filepath).encode('ascii', 'ignore').decode('ascii') filepath = unicodedata.normalize('NFKD', filepath).encode('ascii', 'ignore').decode('ascii')
return re.sub(r'[^\w.()\[\]{}#-]', '_', filepath) return re.sub(r'[^\w.()\[\]{}#-]', '_', filepath)
def tag_file(self, filepath, message, info=None): @staticmethod
def _tag_file(filepath, artist, title):
try:
id3 = mutagen.id3.ID3(filepath)
except mutagen.id3.ID3NoHeaderError:
mutafile = mutagen.File(filepath)
mutafile.add_tags()
mutafile.save()
id3 = mutagen.id3.ID3(filepath)
id3.add(mutagen.id3.TIT2(encoding=3, text=title))
if artist:
id3.add(mutagen.id3.TOPE(encoding=3, text=artist))
id3.add(mutagen.id3.TPE1(encoding=3, text=artist))
id3.save()
def _autotag_file(self, filepath, message, info=None):
if info is None: if info is None:
info = {} info = {}
@ -154,18 +171,7 @@ class DelojzaBot:
message.reply_text("Tagging as \"{}\" by \"{}\"\nvia {}".format(title, artist, source)) message.reply_text("Tagging as \"{}\" by \"{}\"\nvia {}".format(title, artist, source))
self.logger.info("Tagging {} w/ {} - {} [{}]...".format(filepath, title, artist, source)) self.logger.info("Tagging {} w/ {} - {} [{}]...".format(filepath, title, artist, source))
try: self._tag_file(filepath, artist, title)
id3 = mutagen.id3.ID3(filepath)
except mutagen.id3.ID3NoHeaderError:
mutafile = mutagen.File(filepath)
mutafile.add_tags()
mutafile.save()
id3 = mutagen.id3.ID3(filepath)
id3.add(mutagen.id3.TIT2(encoding=3, text=title))
if artist:
id3.add(mutagen.id3.TOPE(encoding=3, text=artist))
id3.add(mutagen.id3.TPE1(encoding=3, text=artist))
id3.save()
# noinspection PyUnusedLocal # noinspection PyUnusedLocal
def download_ytdl(self, urls, out_path, date, message, audio=False, filetitle=None): def download_ytdl(self, urls, out_path, date, message, audio=False, filetitle=None):
@ -189,7 +195,7 @@ class DelojzaBot:
globbeds = glob(os.path.splitext(filename)[0] + '.*') globbeds = glob(os.path.splitext(filename)[0] + '.*')
for globbed in globbeds: for globbed in globbeds:
if globbed.endswith("mp3"): if globbed.endswith("mp3"):
self.tag_file(globbed, message, info=info) self._autotag_file(globbed, message, info=info)
self.logger.info("Moving %s to %s..." % (globbed, out_path)) self.logger.info("Moving %s to %s..." % (globbed, out_path))
dest = shutil.move(globbed, out_path) dest = shutil.move(globbed, out_path)
filenames.append(dest) filenames.append(dest)
@ -227,7 +233,7 @@ class DelojzaBot:
except mutagen.id3.ID3NoHeaderError: except mutagen.id3.ID3NoHeaderError:
untagged = True untagged = True
if untagged: if untagged:
self.tag_file(final_filename, message) self._autotag_file(final_filename, message)
return filenames return filenames
@ -442,6 +448,23 @@ class DelojzaBot:
if len(tmp_reply) > 0: if len(tmp_reply) > 0:
update.message.reply_text(tmp_reply) update.message.reply_text(tmp_reply)
def tg_retag(self, _, update):
message_is_sensible = update.message.text.count("-") == 1
if self.last_downloaded is not None and message_is_sensible:
chat, files, hashtags, tumblr_ids = self.last_downloaded
if chat == update.message.chat:
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()
for mp3 in mp3s:
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 "") + "???")
def tg_delete(self, _, update): def tg_delete(self, _, update):
if self.last_downloaded is not None: if self.last_downloaded is not None:
chat, files, hashtags, tumblr_ids = self.last_downloaded chat, files, hashtags, tumblr_ids = self.last_downloaded
@ -466,7 +489,6 @@ class DelojzaBot:
self.tumblr_client.delete_post(self.tumblr_name, tumblr_id) self.tumblr_client.delete_post(self.tumblr_name, tumblr_id)
self.last_downloaded = None self.last_downloaded = None
return return
update.message.reply_text("Nothing to remove!") update.message.reply_text("Nothing to remove!")
# noinspection PyMethodMayBeStatic # noinspection PyMethodMayBeStatic