Publish volumes of audiobooks on YT.
[audio.git] / src / archive / tasks.py
1 from datetime import datetime
2 import errno
3 import mimetypes
4 import os
5 import os.path
6 import pipes
7 import stat
8 import subprocess
9 from tempfile import NamedTemporaryFile
10 from time import sleep
11
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
17
18 from apiclient import api_call
19 from archive.constants import status
20 from archive.models import Audiobook
21 from archive.settings import COVER_IMAGE, UPLOAD_URL
22 from archive.utils import ExistingFile
23
24
25 class AudioFormatTask(Task):
26     abstract = True
27
28     class RemoteOperationError(BaseException):
29         pass
30
31     @classmethod
32     def set_status(cls, aid, status):
33         Audiobook.objects.filter(pk=aid).update(
34             **{'%s_status' % cls.prefix: status})
35
36     @staticmethod
37     def encode(in_path, out_path):
38         raise NotImplemented
39
40     @classmethod
41     def set_tags(cls, audiobook, file_name):
42         tags = getattr(audiobook, "get_%s_tags" % cls.prefix)()['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():
47             audio[k] = v
48         audio.save()
49
50     @classmethod
51     def save(cls, audiobook, file_name):
52         field = "%s_file" % cls.prefix
53         getattr(audiobook, field).save(
54             "%d.%s" % (audiobook.pk, cls.ext),
55             ExistingFile(file_name),
56             save=False
57             )
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)})
61
62     @classmethod
63     def published(cls, aid):
64         kwargs = {
65             "%s_published_tags" % cls.prefix: F("%s_tags" % cls.prefix),
66             "%s_tags" % cls.prefix: None,
67             "%s_published" % cls.prefix: datetime.now(),
68             '%s_status' % cls.prefix: None,
69         }
70         Audiobook.objects.filter(pk=aid).update(**kwargs)
71
72     @classmethod
73     def put(cls, user, audiobook, path):
74         tags = getattr(audiobook, "get_%s_tags" % cls.prefix)()
75         data = {
76             'book': tags['url'],
77             'type': cls.ext,
78             'name': tags['name'],
79             'part_name': audiobook.part_name,
80             'part_index': audiobook.index,
81             'parts_count': audiobook.parts_count,
82             'source_sha1': audiobook.source_sha1,
83         }
84         with open(path, 'rb') as f:
85             api_call(user, UPLOAD_URL, data=data, files={
86                 "file": f,
87             })
88
89     def run(self, uid, aid, publish=True):
90         aid = int(aid)
91         audiobook = Audiobook.objects.get(id=aid)
92         self.set_status(aid, status.ENCODING)
93
94         if uid:
95             user = User.objects.get(id=uid)
96         else:
97             user = None
98
99         out_file = NamedTemporaryFile(delete=False, prefix='%d-' % aid, suffix='.%s' % self.ext)
100         out_file.close()
101         self.encode(self.get_source_file_paths(audiobook), out_file.name)
102         self.set_status(aid, status.TAGGING)
103         self.set_tags(audiobook, out_file.name)
104         self.set_status(aid, status.SENDING)
105
106         if publish:
107             self.put(user, audiobook, out_file.name)
108             self.published(aid)
109         else:
110             self.set_status(aid, None)
111
112         self.save(audiobook, out_file.name)
113
114     def get_source_file_paths(self, audiobook):
115         return [audiobook.source_file.path]
116
117     def on_failure(self, exc, task_id, args, kwargs, einfo):
118         aid = (args[0], kwargs.get('aid'))[0]
119         self.set_status(aid, None)
120
121
122 class Mp3Task(AudioFormatTask):
123     prefix = ext = 'mp3'
124
125     # these shouldn't be staticmethods
126     def id3_text(tag, text):
127         return tag(encoding=3, text=text)
128     def id3_url(tag, text):
129         return tag(url=text)
130     def id3_comment(tag, text, lang='pol'):
131         return tag(encoding=3, lang=lang, desc='', text=text)
132     def id3_priv(tag, text, what=''):
133         return tag(owner='wolnelektury.pl?%s' % what, data=text.encode('utf-8'))
134
135     TAG_MAP = {
136         'album': (id3_text, id3.TALB),
137         'albumartist': (id3_text, id3.TPE2),
138         'artist': (id3_text, id3.TPE1),
139         'conductor': (id3_text, id3.TPE3),
140         'copyright': (id3_text, id3.TCOP),
141         'date': (id3_text, id3.TDRC),
142         'genre': (id3_text, id3.TCON),
143         'language': (id3_text, id3.TLAN),
144         'organization': (id3_text, id3.TPUB),
145         'title': (id3_text, id3.TIT2),
146         'comment': (id3_comment, id3.COMM, 'pol'),
147         'contact': (id3_url, id3.WOAF),
148         'license': (id3_url, id3.WCOP),
149         'flac_sha1': (id3_priv, id3.PRIV, 'flac_sha1'),
150         'project': (id3_priv, id3.PRIV, 'project'),
151         'funded_by': (id3_priv, id3.PRIV, 'funded_by'),
152     }
153
154     @staticmethod
155     def encode(in_paths, out_path):
156         assert len(in_paths) == 1
157         in_path = in_paths[0]
158         # 44.1kHz 64kbps mono MP3
159         subprocess.check_call(['ffmpeg', 
160             '-i', in_path.encode('utf-8'),
161             '-ar', '44100',
162             '-ab', '64k',
163             '-ac', '1',
164             '-y',
165             '-acodec', 'libmp3lame',
166             out_path.encode('utf-8')
167             ])
168
169     @classmethod
170     def set_tags(cls, audiobook, file_name):
171         mp3_tags = audiobook.get_mp3_tags()['tags']
172         if not mp3_tags.get('flac_sha1'):
173             mp3_tags['flac_sha1'] = audiobook.get_source_sha1()
174         audio = id3.ID3(file_name)
175         for k, v in mp3_tags.items():
176             factory_tuple = cls.TAG_MAP[k]
177             factory, tagtype = factory_tuple[:2]
178             audio.add(factory(tagtype, v, *factory_tuple[2:]))
179
180         if COVER_IMAGE:
181             mime = mimetypes.guess_type(COVER_IMAGE)
182             with open(COVER_IMAGE, 'rb') as f:
183                 audio.add(id3.APIC(encoding=0, mime=mime, type=3, desc='', data=f.read()))
184
185         audio.save()
186
187
188 class OggTask(AudioFormatTask):
189     prefix = ext = 'ogg'
190
191     @staticmethod
192     def encode(in_paths, out_path):
193         assert len(in_paths) == 1
194         in_path = in_paths[0]
195         # 44.1kHz 64kbps mono Ogg Vorbis
196         subprocess.check_call(['ffmpeg', 
197             '-i', in_path.encode('utf-8'),
198             '-ar', '44100',
199             '-ab', '64k',
200             '-ac', '1',
201             '-y',
202             '-acodec', 'libvorbis',
203             out_path.encode('utf-8')
204             ])