1 from datetime import datetime
9 from tempfile import NamedTemporaryFile
10 from time import sleep
12 from celery.task import Task
13 from django.db.models import F
14 from django.contrib.auth.models import User
15 from mutagen import File
16 from mutagen import id3
18 from apiclient import api_call
19 from archive.constants import status
20 from archive.models import Audiobook
21 from archive.settings import BUILD_PATH, COVER_IMAGE, UPLOAD_URL
22 from archive.utils import ExistingFile
25 class AudioFormatTask(Task):
28 class RemoteOperationError(BaseException):
32 def set_status(cls, aid, status):
33 Audiobook.objects.filter(pk=aid).update(
34 **{'%s_status' % cls.ext: status})
37 def encode(in_path, out_path):
41 def set_tags(cls, audiobook, file_name):
42 tags = getattr(audiobook, "get_%s_tags" % cls.ext)()['tags']
43 if not tags.get('flac_sha1'):
44 tags['flac_sha1'] = audiobook.get_source_sha1()
45 audio = File(file_name)
46 for k, v in tags.items():
51 def save(cls, audiobook, file_name):
52 field = "%s_file" % cls.ext
53 getattr(audiobook, field).save(
54 "%d.%s" % (audiobook.pk, cls.ext),
55 ExistingFile(file_name),
58 os.chmod(getattr(audiobook, field).path, stat.S_IREAD|stat.S_IWRITE|stat.S_IRGRP|stat.S_IROTH)
59 Audiobook.objects.filter(pk=audiobook.pk).update(
60 **{field: getattr(audiobook, field)})
63 def published(cls, aid):
65 "%s_published_tags" % cls.ext: F("%s_tags" % cls.ext),
66 "%s_tags" % cls.ext: None,
67 "%s_published" % cls.ext: datetime.now(),
68 '%s_status' % cls.ext: None,
70 Audiobook.objects.filter(pk=aid).update(**kwargs)
73 def put(cls, user, audiobook, path):
74 tags = getattr(audiobook, "get_%s_tags" % cls.ext)()
79 'part_name': audiobook.part_name,
80 'part_index': audiobook.index,
81 'parts_count': audiobook.parts_count,
82 'source_sha1': audiobook.source_sha1,
84 api_call(user, UPLOAD_URL, data=data, files={
85 "file": open(path, 'rb'),
88 def run(self, uid, aid, publish=True):
90 audiobook = Audiobook.objects.get(id=aid)
91 self.set_status(aid, status.ENCODING)
93 user = User.objects.get(id=uid)
96 os.makedirs(BUILD_PATH)
98 if e.errno == errno.EEXIST:
103 out_file = NamedTemporaryFile(delete=False, prefix='%d-' % aid, suffix='.%s' % self.ext, dir=BUILD_PATH)
105 self.encode(audiobook.source_file.path, out_file.name)
106 self.set_status(aid, status.TAGGING)
107 self.set_tags(audiobook, out_file.name)
108 self.set_status(aid, status.SENDING)
111 self.put(user, audiobook, out_file.name)
114 self.set_status(aid, None)
116 self.save(audiobook, out_file.name)
118 def on_failure(self, exc, task_id, args, kwargs, einfo):
119 aid = (args[0], kwargs.get('aid'))[0]
120 self.set_status(aid, None)
123 class Mp3Task(AudioFormatTask):
126 # these shouldn't be staticmethods
127 def id3_text(tag, text):
128 return tag(encoding=1, text=text)
129 def id3_url(tag, text):
131 def id3_comment(tag, text, lang=u'pol'):
132 return tag(encoding=1, lang=lang, desc=u'', text=text)
133 def id3_priv(tag, text, what=u''):
134 return tag(owner='wolnelektury.pl?%s' % what, data=text.encode('utf-8'))
137 'album': (id3_text, id3.TALB),
138 'albumartist': (id3_text, id3.TPE2),
139 'artist': (id3_text, id3.TPE1),
140 'conductor': (id3_text, id3.TPE3),
141 'copyright': (id3_text, id3.TCOP),
142 'date': (id3_text, id3.TDRC),
143 'genre': (id3_text, id3.TCON),
144 'language': (id3_text, id3.TLAN),
145 'organization': (id3_text, id3.TPUB),
146 'title': (id3_text, id3.TIT2),
147 'comment': (id3_comment, id3.COMM, 'pol'),
148 'contact': (id3_url, id3.WOAF),
149 'license': (id3_url, id3.WCOP),
150 'flac_sha1': (id3_priv, id3.PRIV, 'flac_sha1'),
151 'project': (id3_priv, id3.PRIV, 'project'),
152 'funded_by': (id3_priv, id3.PRIV, 'funded_by'),
156 def encode(in_path, out_path):
157 # 44.1kHz 64kbps mono MP3
158 subprocess.check_call(['ffmpeg',
159 '-i', in_path.encode('utf-8'),
164 '-acodec', 'libmp3lame',
165 out_path.encode('utf-8')
169 def set_tags(cls, audiobook, file_name):
170 mp3_tags = audiobook.get_mp3_tags()['tags']
171 if not mp3_tags.get('flac_sha1'):
172 mp3_tags['flac_sha1'] = audiobook.get_source_sha1()
173 audio = id3.ID3(file_name)
174 for k, v in mp3_tags.items():
175 factory_tuple = cls.TAG_MAP[k]
176 factory, tagtype = factory_tuple[:2]
177 audio.add(factory(tagtype, v, *factory_tuple[2:]))
180 mime = mimetypes.guess_type(COVER_IMAGE)
181 f = open(COVER_IMAGE)
182 audio.add(id3.APIC(encoding=0, mime=mime, type=3, desc=u'', data=f.read()))
188 class OggTask(AudioFormatTask):
192 def encode(in_path, out_path):
193 # 44.1kHz 64kbps mono Ogg Vorbis
194 subprocess.check_call(['ffmpeg',
195 '-i', in_path.encode('utf-8'),
200 '-acodec', 'libvorbis',
201 out_path.encode('utf-8')