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