5 from urllib.parse import urljoin
7 from django.db import models
9 from django.contrib.sites.models import Site
10 from django.utils.functional import cached_property
11 from django.utils.timezone import now
12 from django.utils.translation import gettext_lazy as _
13 from django_pglocks import advisory_lock
15 from archive.constants import status
16 from archive.settings import FILES_SAVE_PATH, ADVERT, ORGANIZATION, PROJECT
17 from archive.utils import OverwriteStorage, sha1_file
18 from youtube.utils import concat_audio, standardize_audio
21 class License(models.Model):
22 uri = models.CharField(max_length=255, unique=True)
23 name = models.CharField(max_length=255)
29 class Project(models.Model):
30 """ an audiobook project, needed for specyfing sponsors """
32 name = models.CharField(max_length=128, unique=True, db_index=True, verbose_name="Nazwa")
33 sponsors = models.TextField(blank=True, null=True, verbose_name="Sponsorzy")
34 description = models.TextField(blank=True, verbose_name="Opis")
35 private_notes = models.TextField(blank=True, verbose_name="Prywatne notatki")
36 config = models.ForeignKey('Config', models.PROTECT)
37 can_sell = models.BooleanField(default=True, verbose_name="Do sprzedaży")
38 required_license = models.ForeignKey('License', models.PROTECT, blank=True, null=True, verbose_name='Wymagana licencja')
39 youtube = models.ForeignKey('youtube.YouTube', models.PROTECT)
40 icon = models.FileField(upload_to='archive/project', blank=True, null=True)
41 info_flac = models.FileField(upload_to='archive/info_flac', blank=True)
44 verbose_name = _("project")
45 verbose_name_plural = _("projects")
51 def get_description(self):
53 return self.description
54 return "Audiobook nagrany w ramach projektu %s%s." % (
56 " finansowanego przez %s" % self.sponsors if self.sponsors else "",
59 def get_icon_url(self):
63 'https://' + Site.objects.get_current().domain,
68 class Config(models.Model):
69 name = models.CharField(max_length=255)
70 intro_flac = models.FileField(upload_to='config/intro_flac', blank=True)
71 intro_min_seconds = models.IntegerField()
72 outro_flac = models.FileField(upload_to='config/outro_flac', blank=True)
73 outro_min_seconds = models.IntegerField()
76 verbose_name = _("Configuration")
77 verbose_name_plural = _("Configurations")
82 def prepare_audio(self, audiobook):
83 total_duration = audiobook.total_duration
85 if self.intro_flac and total_duration > self.intro_min_seconds and audiobook.is_first:
86 files.append(standardize_audio(self.intro_flac.path))
87 files.append(standardize_audio(audiobook.source_file.path))
88 if self.outro_flac and total_duration > self.outro_min_seconds and audiobook.is_last:
89 files.append(standardize_audio(self.outro_flac.path))
90 output = concat_audio(files)
96 def source_upload_to(intance, filename):
97 return os.path.join(FILES_SAVE_PATH, filename) # FIXME: what about really long file names?
100 class Audiobook(models.Model):
101 source_file = models.FileField(upload_to=source_upload_to, max_length=255,
102 verbose_name=_('source file'), editable=False)
103 source_sha1 = models.CharField(max_length=40, editable=False)
104 duration = models.FloatField(null=True, editable=False)
106 title = models.CharField(max_length=255, verbose_name=_('title'))
107 part_name = models.CharField(max_length=255, verbose_name=_('part name'), help_text=_('eg. chapter in a novel'),
108 default='', blank=True)
109 index = models.IntegerField(verbose_name=_('index'), default=0, help_text=_('Ordering of parts of a book.'))
110 youtube_volume = models.CharField(
111 _("Volume name for YouTube"),
115 "If set, audiobooks with the save value will be published as single YouTube video."
118 artist = models.CharField(max_length=255, verbose_name=_('artist'))
119 conductor = models.CharField(max_length=255, verbose_name=_('conductor'))
120 encoded_by = models.CharField(max_length=255, verbose_name=_('encoded by'))
121 date = models.CharField(max_length=255, verbose_name=_('date'))
122 project = models.ForeignKey(Project, models.PROTECT, verbose_name=_('project'))
123 slug = models.SlugField(max_length=120, blank=True, help_text=_('WL catalogue slug of the book.'))
124 translator = models.CharField(max_length=255, null=True, blank=True, verbose_name=_('translator'))
125 modified = models.DateTimeField(null=True, editable=False)
126 license = models.ForeignKey(License, models.PROTECT, null=True, blank=True, verbose_name=_('license'))
127 license_secondary = models.ForeignKey(License, models.PROTECT, null=True, blank=True, verbose_name=_('license'), related_name='secondary')
130 mp3_status = models.SmallIntegerField(null=True, editable=False, choices=status.choices)
131 mp3_file = models.FileField(null=True, upload_to='archive/final', storage=OverwriteStorage(), editable=False)
132 mp3_published = models.DateTimeField(null=True, editable=False)
134 ogg_status = models.SmallIntegerField(null=True, editable=False, choices=status.choices)
135 ogg_file = models.FileField(null=True, upload_to='archive/final', storage=OverwriteStorage(), editable=False)
136 ogg_published = models.DateTimeField(null=True, editable=False)
138 youtube_status = models.SmallIntegerField(null=True, editable=False, choices=status.choices)
139 youtube_published = models.DateTimeField(null=True, editable=False)
140 youtube_id = models.CharField(max_length=255, blank=True, default='')
141 youtube_queued = models.DateTimeField(null=True, blank=True)
144 verbose_name = _("audiobook")
145 verbose_name_plural = _("audiobooks")
146 ordering = ("title",)
153 return f'https://wolnelektury.pl/katalog/lektura/{self.slug}/'
156 def parts_count(self):
157 return type(self).objects.filter(slug=self.slug).count()
160 def total_duration(self):
161 return type(self).objects.filter(slug=self.slug).aggregate(s=models.Sum('duration'))['s']
165 return not type(self).objects.filter(slug=self.slug, index__lte=self.index).exclude(pk=self.pk).exists()
169 return not type(self).objects.filter(slug=self.slug, index__gte=self.index).exclude(pk=self.pk).exists()
172 def youtube_volume_count(self):
175 for a in type(self).objects.filter(slug=self.slug).order_by("index"):
176 if not a.youtube_volume or a.youtube_volume != prev_volume:
178 prev_volume = a.youtube_volume
182 def youtube_volume_index(self):
185 for a in type(self).objects.filter(slug=self.slug, index__lte=self.index).order_by("index"):
186 if not a.youtube_volume or a.youtube_volume != prev_volume:
188 prev_volume = a.youtube_volume
192 def is_youtube_publishable(self):
194 not self.youtube_volume
196 .objects.filter(slug=self.slug, youtube_volume=self.youtube_volume, index__lt=self.index)
200 def youtube_publish(self):
201 if not self.is_youtube_publishable:
203 self.youtube_status = status.QUEUED
204 self.youtube_queued = now()
205 self.save(update_fields=['youtube_status', 'youtube_queued'])
208 return self.mp3_published and self.ogg_published
210 def publish(self, user, publish=True):
212 self.mp3_status = self.ogg_status = status.WAITING
213 self.save(update_fields=['mp3_status', 'ogg_status'])
214 tasks.Mp3Task.delay(user.id, self.pk, publish=publish).task_id
215 tasks.OggTask.delay(user.id, self.pk, publish=publish).task_id
217 def get_source_sha1(self):
218 assert self.pk or self.source_sha1
219 if not self.source_sha1:
220 with advisory_lock(f'get_source_sha1_{self.pk}'):
221 with open(self.source_file.path, 'rb') as f:
222 self.source_sha1 = sha1_file(f)
223 self.save(update_fields=['source_sha1'])
224 return self.source_sha1
226 def new_publish_tags(self):
229 title += ' (tłum. %s)' % self.translator
231 copyright = "%s %s." % (
232 self.date, ORGANIZATION)
234 copyright += " Licensed to the public under %s verify at %s" % (
235 self.license.uri, self.url)
237 comment = "\n".join((
238 self.project.get_description(),
244 'albumartist': ORGANIZATION,
245 'artist': self.artist,
247 'conductor': self.conductor,
249 'copyright': copyright,
253 'organization': ORGANIZATION,
255 'project': self.project.name,
258 tags['license'] = self.license.uri
259 if self.project.sponsors:
260 tags['funded_by'] = self.project.sponsors
262 tags['flac_sha1'] = self.get_source_sha1()
266 def prepare_audio(self):
267 return self.project.config.prepare_audio(self)
272 apidata = requests.get(f'https://wolnelektury.pl/api/books/{self.slug}/').json()
279 from librarian.document import WLDocument, parser
280 from lxml import etree
282 xml_url = self.book.get('xml', None)
286 return WLDocument(url=xml_url)
290 from librarian.cover import LogoWLCover
291 return LogoWLCover(self.document.meta).output_file.get_bytes()