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
8 from apiclient import youtube_call
20 from .thumbnail import create_thumbnail
23 YOUTUBE_TITLE_LIMIT = 100
26 class YouTube(models.Model):
27 title_template = models.CharField(max_length=1024, blank=True)
28 description_template = models.TextField(blank=True)
29 category = models.IntegerField(null=True, blank=True, choices=[
32 intro_flac = models.FileField(upload_to='youtube/intro_flac', blank=True)
33 outro_flac = models.FileField(upload_to='youtube/outro_flac', blank=True)
34 loop_card = models.FileField(upload_to='youtube/card', blank=True)
35 loop_video = models.FileField(upload_to='youtube/loop_video', blank=True)
36 privacy_status = models.CharField(max_length=16, choices=[
37 ('public', _('public')),
38 ('unlisted', _('unlisted')),
39 ('private', _('private')),
41 genres = models.CharField(max_length=2048, blank=True)
44 verbose_name = _("YouTube configuration")
45 verbose_name_plural = _("YouTube configurations")
47 def get_context(self, audiobook):
52 def get_description(self, audiobook):
53 return Template(self.description_template).render(self.get_context(audiobook))
55 def get_title(self, audiobook):
56 return Template(self.title_template).render(self.get_context(audiobook))[:YOUTUBE_TITLE_LIMIT]
58 def get_data(self, audiobook):
61 title=self.get_title(audiobook),
62 description=self.get_description(audiobook),
63 categoryId=self.category,
65 defaultAudioLanguage='pl',
68 privacyStatus=self.privacy_status,
72 def publish(self, audiobook, path):
73 data = self.get_data(audiobook)
74 part = ",".join(data.keys())
76 response = youtube_call(
78 "https://www.googleapis.com/upload/youtube/v3/videos",
79 params={'part': part},
81 resumable_file_path=path,
83 data = response.json()
84 audiobook.youtube_id = data['id']
85 audiobook.save(update_fields=['youtube_id'])
87 self.update_thumbnail(audiobook)
90 def update_data(self, audiobook):
91 data = self.get_data(audiobook)
92 data['id'] = audiobook.youtube_id
93 part = ",".join(data.keys())
96 "https://www.googleapis.com/youtube/v3/videos",
97 params={"part": part},
101 def prepare_file(self, input_paths, output_path=None):
102 audio = self.prepare_audio(input_paths)
103 duration = self.get_duration(input_paths)
104 video = self.prepare_video(duration)
105 output = mux([video, audio], output_path=output_path)
110 def get_duration(self, input_paths):
112 for input_path in input_paths:
113 d += get_duration(input_path)
115 d += get_duration(self.intro_flac.path)
117 d += get_duration(self.outro_flac.path)
120 def prepare_audio(self, input_paths):
123 files.append(standardize_audio(self.intro_flac.path))
124 for input_path in input_paths:
125 files.append(standardize_audio(input_path, cache=False))
127 files.append(standardize_audio(self.outro_flac.path))
128 output = concat_audio(files)
133 def prepare_video(self, duration):
139 fps = get_framerate(self.loop_video.path)
140 loop_video = standardize_video(self.loop_video.path)
144 loop_duration = duration
145 for card in self.card_set.filter(duration__gt=0):
146 loop_duration -= card.duration
147 card_video = video_from_image(
148 card.image.path, card.duration, fps=fps
150 (concat if card.order < 0 else outro).append(card_video)
151 delete.append(card_video)
154 loop_video_duration = get_duration(loop_video)
155 times_loop = int(loop_duration // loop_video_duration)
157 leftover_duration = loop_duration % loop_video_duration
158 leftover = cut_video(loop_video, leftover_duration)
159 concat.extend([loop_video] * times_loop + [leftover])
160 delete.append(leftover)
162 leftover = video_from_image(self.loop_card.path, loop_duration)
163 concat.append(video_from_image(self.loop_card.path, loop_duration, fps=fps))
164 delete.append(leftover)
167 output = concat_videos(concat)
175 # selfDeclaredMadeForKids
177 def update_thumbnail(self, audiobook):
178 thumbnail = self.prepare_thumbnail(audiobook)
179 if thumbnail is not None:
180 response = youtube_call(
182 "https://www.googleapis.com/upload/youtube/v3/thumbnails/set",
183 params={'videoId': audiobook.youtube_id},
184 data=thumbnail.getvalue(),
187 def prepare_thumbnail(self, audiobook):
188 for thumbnail_template in ThumbnailTemplate.objects.filter(is_active=True).order_by('order'):
189 if not thumbnail_template.is_for_audiobook(audiobook):
191 thumbnail = thumbnail_template.generate(audiobook)
192 if thumbnail is not None:
196 class Card(models.Model):
197 youtube = models.ForeignKey(YouTube, models.CASCADE)
198 order = models.SmallIntegerField()
199 image = models.FileField(upload_to='youtube/card')
200 duration = models.FloatField()
203 ordering = ('order', )
206 class Font(models.Model):
207 name = models.CharField(max_length=255, unique=True)
208 truetype = models.FileField(upload_to='youtube/font')
214 class ThumbnailTemplate(models.Model):
215 order = models.SmallIntegerField()
216 is_active = models.BooleanField()
217 background = models.FileField(upload_to='youtube/thumbnail')
218 definition = models.TextField()
219 authors = models.CharField(max_length=255, blank=True)
220 epochs = models.CharField(max_length=255, blank=True)
221 kinds = models.CharField(max_length=255, blank=True)
222 genres = models.CharField(max_length=255, blank=True)
223 collections = models.CharField(max_length=255, blank=True)
226 ordering = ('order', )
228 def generate(self, audiobook):
230 img = create_thumbnail(
231 self.background.path,
234 "author": ', '.join((a['name'] for a in audiobook.book['authors'])),
235 "title": audiobook.book['title'],
236 "part": (audiobook.youtube_volume or audiobook.part_name).strip(),
238 lambda name: Font.objects.get(name=name).truetype.path
240 except Exception as e:
245 img.save(buf, format='PNG')
248 def is_for_audiobook(self, audiobook):
249 for category in 'authors', 'epochs', 'kinds', 'genres':
250 if getattr(self, category):
251 book_slugs = set([g['slug'] for g in audiobook.book[category]])
252 template_slugs = set([g.strip() for g in getattr(self, category).split(',')])
253 if not book_slugs.intersection(template_slugs):
257 template_collections = set([g.strip() for g in self.collections.split(',')])
259 for collection in template_collections:
260 apidata = requests.get(
261 f'https://wolnelektury.pl/api/collections/{collection}/'
263 for book in apidata['books']:
264 if book['slug'] == audiobook.slug: