8 from django.core.management.base import BaseCommand, CommandError
10 from ...models import SoundFile
13 class Command(BaseCommand):
15 def add_arguments(self, parser):
21 help='Create files even if they exist')
22 parser.add_argument('--reset-metadata',
24 dest='reset_metadata',
26 help='Reset metadata on all files')
27 parser.add_argument('--emission',
31 help='Process files belonging to emission only')
32 parser.add_argument('--episode',
36 help='Process files belonging to episode only')
37 parser.add_argument('--copy',
41 help='Copy initial file (ogg only)')
43 def handle(self, force, reset_metadata, copy, emission, episode, verbosity, **kwargs):
44 self.verbose = (verbosity > 1)
47 for soundfile in SoundFile.objects.select_related().exclude(podcastable=False):
48 if emission and soundfile.episode.emission.slug != emission:
50 if episode and soundfile.episode.slug != episode:
53 if soundfile.file is None or not os.path.exists(soundfile.file.path):
55 except ValueError: # no file associated with it
57 for format in ('ogg', 'mp3'):
58 file_path = soundfile.get_format_path(format)
60 if not os.path.exists(file_path) or force:
61 self.create(soundfile, format)
63 if created or reset_metadata:
64 self.set_metadata(soundfile, format)
65 if not soundfile.duration:
66 cmd = ['soxi', '-D', soundfile.get_format_path('ogg')]
67 soundfile.duration = int(float(subprocess.check_output(cmd)))
71 def create(self, soundfile, format):
72 file_path = soundfile.get_format_path(format)
73 if not os.path.exists(os.path.dirname(file_path)):
74 os.mkdir(os.path.dirname(file_path))
76 cmd = ['ffmpeg', '-y', '-i', soundfile.file.path]
80 shutil.copy(soundfile.file.path, file_path)
82 cmd.extend(['-q:a', '5'])
84 cmd.extend(['-q:a', '4'])
89 print 'creating', file_path
90 print ' ', ' '.join(cmd)
92 cmd[1:1] = ['-loglevel', 'quiet']
96 def set_metadata(self, soundfile, format):
97 file_path = soundfile.get_format_path(format)
99 audio = mutagen.File(file_path, easy=True)
101 if 'comment' in audio:
103 if soundfile.fragment is True and soundfile.title:
104 audio['title'] = '%s - %s' % (
105 soundfile.episode.title,
108 audio['title'] = soundfile.episode.title
109 audio['album'] = soundfile.episode.emission.title
110 audio['artist'] = 'Radio Panik'
112 if soundfile.episode.image or soundfile.episode.emission.image:
113 image = (soundfile.episode.image or soundfile.episode.emission.image)
115 if os.path.splitext(image.path)[1].lower() in ('.jpeg', '.jpg'):
116 mimetype = 'image/jpeg'
117 elif os.path.splitext(image.path)[1].lower() == '.png':
118 mimetype = 'image/png'
123 audio['coverartmime'] = mimetype
124 audio['coverartdescription'] = 'image'
125 audio['coverart'] = base64.encodestring(image.read()).replace('\n', '')
126 elif format == 'mp3':
128 audio = mutagen.mp3.MP3(file_path)
129 audio.tags.add(mutagen.id3.APIC(
130 encoding=3, description='image',
131 type=3, mime=mimetype, data=image.read()))