5 from django.core.files.storage import default_storage
6 from django.core.management.base import BaseCommand
7 from django.utils.timezone import now
8 from emissions.models import Nonstop
10 from ...models import Artist, NonstopFile, Track
13 class Command(BaseCommand):
14 def add_arguments(self, parser):
15 parser.add_argument('--directory', metavar='DIRECTORY')
16 parser.add_argument('--zone', metavar='ZONE')
18 def handle(self, verbosity, directory, zone=None, **kwargs):
19 monthdir = datetime.datetime.today().strftime('%Y-%m')
21 nonstop_zone = Nonstop.objects.get(slug=zone) if zone else None
24 for basedir, dirnames, filenames in os.walk(directory):
27 os.path.join(basedir, x)
29 if os.path.splitext(x)[-1] in ('.mp3', '.ogg', '.flac', '.opus')
34 total = len(filepaths)
36 for i, filepath in enumerate(filepaths):
38 metadata = mutagen.File(filepath, easy=True)
40 print('failed to get metadata', filepath)
42 if not metadata or not metadata.get('artist') or not metadata.get('title'):
43 print('missing metadata', filepath)
46 artist_name = metadata.get('artist')[0]
47 track_title = metadata.get('title')[0]
50 print('[%s/%s] %s - %s' % (i, total, artist_name, track_title))
52 new_filepath = '%s/%s - %s - %s%s' % (
54 datetime.datetime.today().strftime('%y%m%d'),
55 artist_name[:50].replace('/', ' ').strip(),
56 track_title[:80].replace('/', ' ').strip(),
57 os.path.splitext(filepath)[-1],
60 artist, created = Artist.objects.get_or_create(name=artist_name)
61 track, created = Track.objects.get_or_create(
65 if created or not track.file_exists():
66 with open(filepath, 'rb') as fd:
67 default_storage.save(os.path.join('nonstop', 'tracks', new_filepath), content=fd)
68 nonstop_file = NonstopFile()
69 nonstop_file.set_track_filepath(new_filepath)
70 nonstop_file.track = track
74 track.nonstop_zones.add(nonstop_zone)
75 if not track.added_to_nonstop_timestamp:
76 track.added_to_nonstop_timestamp = now()
80 track.nonstop_zones.add(nonstop_zone)
81 if not track.added_to_nonstop_timestamp:
82 track.added_to_nonstop_timestamp = now()