43db3b09b058e3576a3ab2452d53a0e882e680f6
[audio.git] / src / youtube / models.py
1 import io
2 from os import unlink
3 from tempfile import NamedTemporaryFile
4 from django.db import models
5 from django.utils.translation import gettext_lazy as _
6 from django.template import Template, Context
7 from apiclient import youtube_call
8 from .utils import (
9     concat_audio,
10     concat_videos,
11     cut_video,
12     get_duration,
13     get_framerate,
14     mux,
15     standardize_audio,
16     standardize_video,
17     video_from_image,
18 )
19 from .thumbnail import create_thumbnail
20
21
22 YOUTUBE_TITLE_LIMIT = 100
23
24
25 class YouTube(models.Model):
26     title_template = models.CharField(max_length=1024, blank=True)
27     description_template = models.TextField(blank=True)
28     category = models.IntegerField(null=True, blank=True, choices=[
29         (27, 'Edukacja'),
30     ])
31     intro_flac = models.FileField(upload_to='youtube/intro_flac', blank=True)
32     outro_flac = models.FileField(upload_to='youtube/outro_flac', blank=True)
33     loop_card = models.FileField(upload_to='youtube/card', blank=True)
34     loop_video = models.FileField(upload_to='youtube/loop_video', blank=True)
35     thumbnail_template = models.FileField(upload_to='youtube/thumbnail', blank=True)
36     thumbnail_definition = models.TextField(blank=True)
37     privacy_status = models.CharField(max_length=16, choices=[
38         ('public', _('public')),
39         ('unlisted', _('unlisted')),
40         ('private', _('private')),
41     ])
42     genres = models.CharField(max_length=2048, blank=True)
43
44     class Meta:
45         verbose_name = _("YouTube configuration")
46         verbose_name_plural = _("YouTube configurations")
47
48     def get_context(self, audiobook):
49         return Context(dict(
50             audiobook=audiobook,
51         ))
52
53     def get_description(self, audiobook):
54         return Template(self.description_template).render(self.get_context(audiobook))
55
56     def get_title(self, audiobook):
57         return Template(self.title_template).render(self.get_context(audiobook))[:YOUTUBE_TITLE_LIMIT]
58
59     def get_data(self, audiobook):
60         return dict(
61             snippet=dict(
62                 title=self.get_title(audiobook),
63                 description=self.get_description(audiobook),
64                 categoryId=self.category,
65                 defaultLanguage='pl',
66                 defaultAudioLanguage='pl',
67             ),
68             status=dict(
69                 privacyStatus=self.privacy_status,
70             ),
71         )
72
73     def publish(self, audiobook, path):
74         data = self.get_data(audiobook)
75         part = ",".join(data.keys())
76
77         response = youtube_call(
78             "POST",
79             "https://www.googleapis.com/upload/youtube/v3/videos",
80             params={'part': part},
81             json=data,
82             resumable_file_path=path,
83         )
84         data = response.json()
85         audiobook.youtube_id = data['id']
86         audiobook.save(update_fields=['youtube_id'])
87
88         self.update_thumbnail(audiobook)
89         return response
90
91     def update_data(self, audiobook):
92         data = self.get_data(audiobook)
93         data['id'] = audiobook.youtube_id
94         part = ",".join(data.keys())
95         youtube_call(
96             "PUT",
97             "https://www.googleapis.com/youtube/v3/videos",
98             params={"part": part},
99             json=data
100         )       
101
102     def prepare_file(self, input_path, output_path=None):
103         audio = self.prepare_audio(input_path)
104         duration = self.get_duration(input_path)
105         video = self.prepare_video(duration)
106         output = mux([video, audio], output_path=output_path)
107         unlink(audio)
108         unlink(video)
109         return output
110
111     def get_duration(self, input_path):
112         d = get_duration(input_path)
113         if self.intro_flac:
114             d += get_duration(self.intro_flac.path)
115         if self.outro_flac:
116             d += get_duration(self.outro_flac.path)
117         return d
118     
119     def prepare_audio(self, input_path):
120         files = []
121         if self.intro_flac:
122             files.append(standardize_audio(self.intro_flac.path))
123         files.append(standardize_audio(input_path, cache=False))
124         if self.outro_flac:
125             files.append(standardize_audio(self.outro_flac.path))
126         output = concat_audio(files)
127         for d in files:
128             unlink(d)
129         return output
130
131     
132     def prepare_video(self, duration):
133         concat = []
134         outro = []
135         delete = []
136
137         if self.loop_video:
138             fps = get_framerate(self.loop_video.path)
139             loop_video = standardize_video(self.loop_video.path)
140         else:
141             fps = 25
142
143         loop_duration = duration
144         for card in self.card_set.filter(duration__gt=0):
145             loop_duration -= card.duration
146             card_video = video_from_image(
147                 card.image.path, card.duration, fps=fps
148             )
149             (concat if card.order < 0 else outro).append(card_video)
150             delete.append(card_video)
151
152         if self.loop_video:
153             loop_video_duration = get_duration(loop_video)
154             times_loop = int(loop_duration // loop_video_duration)
155
156             leftover_duration = loop_duration % loop_video_duration
157             leftover = cut_video(loop_video, leftover_duration)
158             concat.extend([loop_video] * times_loop + [leftover])
159             delete.append(leftover)
160         else:
161             leftover = video_from_image(self.loop_card.path, loop_duration)
162             concat.append(video_from_image(self.loop_card.path, loop_duration, fps=fps))
163             delete.append(leftover)
164         concat.extend(outro)
165
166         output = concat_videos(concat)
167         for p in delete:
168             unlink(p)
169         unlink(loop_video)
170         return output
171
172     # tags
173     # license
174     # selfDeclaredMadeForKids
175
176     def update_thumbnail(self, audiobook):
177         thumbnail = self.prepare_thumbnail(audiobook)
178         response = youtube_call(
179             "POST",
180             "https://www.googleapis.com/upload/youtube/v3/thumbnails/set",
181             params={'videoId': audiobook.youtube_id},
182             data=thumbnail.getvalue(),
183         )
184
185     def prepare_thumbnail(self, audiobook):
186         img = create_thumbnail(
187             self.thumbnail_template.path,
188             self.thumbnail_definition,
189             {
190                 "author": ', '.join((a['name'] for a in audiobook.book['authors'])),
191                 "title": audiobook.book['title'],
192                 "part": audiobook.part_name,
193             },
194             lambda name: Font.objects.get(name=name).truetype.path
195         )
196         buf = io.BytesIO()
197         img.save(buf, format='PNG')
198         return buf
199         
200
201 class Card(models.Model):
202     youtube = models.ForeignKey(YouTube, models.CASCADE)
203     order = models.SmallIntegerField()
204     image = models.FileField(upload_to='youtube/card')
205     duration = models.FloatField()
206
207     class Meta:
208         ordering = ('order', )
209
210
211 class Font(models.Model):
212     name = models.CharField(max_length=255, unique=True)
213     truetype = models.FileField(upload_to='youtube/font')
214
215     def __str__(self):
216         return self.name