From: Frédéric Péters Date: Sun, 20 Feb 2022 14:05:40 +0000 (+0100) Subject: add import-tracks management command X-Git-Tag: v2022^0 X-Git-Url: https://git.0d.be/?p=django-panik-nonstop.git;a=commitdiff_plain;h=89bc776eb0943d93624461eefa78e8ebe8ee29b2 add import-tracks management command --- diff --git a/nonstop/management/commands/import-tracks.py b/nonstop/management/commands/import-tracks.py new file mode 100644 index 0000000..8742c80 --- /dev/null +++ b/nonstop/management/commands/import-tracks.py @@ -0,0 +1,83 @@ +import datetime +import os + +import mutagen +from django.core.files.storage import default_storage +from django.core.management.base import BaseCommand +from django.utils.timezone import now +from emissions.models import Nonstop + +from ...models import Artist, NonstopFile, Track + + +class Command(BaseCommand): + def add_arguments(self, parser): + parser.add_argument('--directory', metavar='DIRECTORY') + parser.add_argument('--zone', metavar='ZONE') + + def handle(self, verbosity, directory, zone=None, **kwargs): + monthdir = datetime.datetime.today().strftime('%Y-%m') + + nonstop_zone = Nonstop.objects.get(slug=zone) if zone else None + + filepaths = [] + for basedir, dirnames, filenames in os.walk(directory): + filepaths.extend( + [ + os.path.join(basedir, x) + for x in filenames + if os.path.splitext(x)[-1] in ('.mp3', '.ogg', '.flac', '.opus') + ] + ) + filepaths.sort() + + total = len(filepaths) + + for i, filepath in enumerate(filepaths): + try: + metadata = mutagen.File(filepath, easy=True) + except: + print('failed to get metadata', filepath) + continue + if not metadata or not metadata.get('artist') or not metadata.get('title'): + print('missing metadata', filepath) + continue + + artist_name = metadata.get('artist')[0] + track_title = metadata.get('title')[0] + + if verbosity: + print('[%s/%s] %s - %s' % (i, total, artist_name, track_title)) + + new_filepath = '%s/%s - %s - %s%s' % ( + monthdir, + datetime.datetime.today().strftime('%y%m%d'), + artist_name[:50].replace('/', ' ').strip(), + track_title[:80].replace('/', ' ').strip(), + os.path.splitext(filepath)[-1], + ) + + artist, created = Artist.objects.get_or_create(name=artist_name) + track, created = Track.objects.get_or_create( + title=track_title, + artist=artist, + ) + if created or not track.file_exists(): + with open(filepath, 'rb') as fd: + default_storage.save(os.path.join('nonstop', 'tracks', new_filepath), content=fd) + nonstop_file = NonstopFile() + nonstop_file.set_track_filepath(new_filepath) + nonstop_file.track = track + nonstop_file.save() + + if nonstop_zone: + track.nonstop_zones.add(nonstop_zone) + if not track.added_to_nonstop_timestamp: + track.added_to_nonstop_timestamp = now() + track.save() + else: + if nonstop_zone: + track.nonstop_zones.add(nonstop_zone) + if not track.added_to_nonstop_timestamp: + track.added_to_nonstop_timestamp = now() + track.save()