1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
4 from collections import OrderedDict
6 from collections import namedtuple
7 from django.core.files.storage import storages
8 from django.db import models
9 from slugify import slugify
13 def _file_upload_to(i, _n):
16 name += f'_{i.index:03d}'
18 name += f'_' + slugify(i.part_name)
20 return f'book/{ext}/{name}.{ext}'
24 return storages['bookmedia']
27 class BookMedia(models.Model):
28 """Represents media attached to a book."""
29 FileFormat = namedtuple("FileFormat", "name ext")
30 formats = OrderedDict([
31 ('mp3', FileFormat(name='MP3', ext='mp3')),
32 ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
33 ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
34 ('audio.epub', FileFormat(name='EPUB+audio', ext='audio.epub')),
35 ('sync', FileFormat(name='sync', ext='sync.txt')),
37 format_choices = [(k, 'plik %s' % t.name) for k, t in formats.items()]
39 type = models.CharField('typ', db_index=True, choices=format_choices, max_length=20)
40 name = models.CharField('nazwa', max_length=512)
41 part_name = models.CharField('nazwa części', default='', blank=True, max_length=512)
42 index = models.IntegerField('indeks', default=0)
43 file = models.FileField('plik', max_length=600, upload_to=_file_upload_to, storage=get_storage)
44 file_size = models.IntegerField(null=True, blank=True)
45 duration = models.FloatField(null=True, blank=True)
46 uploaded_at = models.DateTimeField('data utworzenia', auto_now_add=True, editable=False, db_index=True)
47 project_description = models.CharField(max_length=2048, blank=True)
48 project_icon = models.CharField(max_length=2048, blank=True)
49 extra_info = models.TextField('dodatkowe informacje', default='{}', editable=False)
50 book = models.ForeignKey('Book', models.CASCADE, related_name='media')
51 source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
54 return self.file.name.split("/")[-1]
57 ordering = ('type', 'index')
58 verbose_name = 'media książki'
59 verbose_name_plural = 'media książek'
60 app_label = 'catalogue'
62 def get_extra_info_json(self):
63 return json.loads(self.extra_info or '{}')
65 def get_nice_filename(self):
66 parts_count = 1 + type(self).objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
70 name += f'_{self.index:03d}'
72 name += f'_' + slugify(self.part_name)
74 return f'{name}.{ext}'
76 def set_file(self, content, parts_count=None):
78 parts_count = 1 + type(self).objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
80 self.name = self.book.pretty_title()
82 no = ('%02d' if parts_count < 100 else '%03d') % self.index
83 self.name = '%s. %s' % (no, self.book.pretty_title())
85 self.name += ', ' + self.part_name
87 if self.type in ('mp3', 'ogg'):
89 audio = mutagen.File(content)
90 self.duration = audio.info.length
91 except (mutagen.MutagenError, AttributeError):
92 self.extra_info = '{}'
94 self.source_sha1 = None
96 self.extra_info = json.dumps(
97 self.read_meta(audio, self.type))
98 self.source_sha1 = self.read_source_sha1(audio, self.type)
99 self.file_size = content.size
100 self.file.save(None, content)
101 self.book.update_narrators()
102 self.book.update_has_audio()
105 def read_meta(audio, file_type):
107 Reads some metadata from the audiobook.
112 artist_name = director_name = project = funded_by = license = ''
113 if file_type == 'mp3':
114 artist_name = ', '.join(', '.join(tag.text) for tag in tags.getall('TPE1'))
115 director_name = ', '.join(', '.join(tag.text) for tag in tags.getall('TPE3'))
116 license = ', '.join(tag.url for tag in tags.getall('WCOP'))
117 project = ", ".join([
118 t.data.decode('utf-8') for t in tags.getall('PRIV')
119 if t.owner == 'wolnelektury.pl?project'])
120 funded_by = ", ".join([
121 t.data.decode('utf-8') for t in tags.getall('PRIV')
122 if t.owner == 'wolnelektury.pl?funded_by'])
123 elif file_type == 'ogg':
124 artist_name = ', '.join(tags.get('artist', []))
125 director_name = ', '.join(tags.get('conductor', []))
126 license = ', '.join(tags.get('license', []))
127 project = ", ".join(tags.get('project', []))
128 funded_by = ", ".join(tags.get('funded_by', []))
131 return {'artist_name': artist_name, 'director_name': director_name,
132 'project': project, 'funded_by': funded_by, 'license': license}
135 return self.formats[self.type].ext
138 def read_source_sha1(audio, filetype):
140 Reads source file SHA1 from audiobok metadata.
144 if filetype == 'mp3':
146 return [t.data.decode('utf-8') for t in audio.tags.getall('PRIV')
147 if t.owner == 'wolnelektury.pl?flac_sha1'][0]
150 elif filetype == 'ogg':
152 return audio.tags.get('flac_sha1', [None])[0]
160 return self.get_extra_info_json().get('director_name', None)
164 return self.get_extra_info_json().get('artist_name', None)