1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from collections import OrderedDict
6 from collections import namedtuple
7 from django.db import models
8 from slugify import slugify
10 from mutagen import id3
11 from fnpdjango.storage import BofhFileSystemStorage
14 def _file_upload_to(i, _n):
17 name += f'_{i.index:03d}'
19 name += f'_' + slugify(i.part_name)
21 return f'book/{ext}/{name}.{ext}'
24 class BookMedia(models.Model):
25 """Represents media attached to a book."""
26 FileFormat = namedtuple("FileFormat", "name ext")
27 formats = OrderedDict([
28 ('mp3', FileFormat(name='MP3', ext='mp3')),
29 ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
30 ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
31 ('audio.epub', FileFormat(name='EPUB+audio', ext='audio.epub')),
32 ('sync', FileFormat(name='sync', ext='sync.txt')),
34 format_choices = [(k, 'plik %s' % t.name) for k, t in formats.items()]
36 type = models.CharField('typ', db_index=True, choices=format_choices, max_length=20)
37 name = models.CharField('nazwa', max_length=512)
38 part_name = models.CharField('nazwa części', default='', blank=True, max_length=512)
39 index = models.IntegerField('indeks', default=0)
40 file = models.FileField('plik', max_length=600, upload_to=_file_upload_to, storage=BofhFileSystemStorage())
41 duration = models.FloatField(null=True, blank=True)
42 uploaded_at = models.DateTimeField('data utworzenia', auto_now_add=True, editable=False, db_index=True)
43 project_description = models.CharField(max_length=2048, blank=True)
44 project_icon = models.CharField(max_length=2048, blank=True)
45 extra_info = models.TextField('dodatkowe informacje', default='{}', editable=False)
46 book = models.ForeignKey('Book', models.CASCADE, related_name='media')
47 source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
50 return self.file.name.split("/")[-1]
53 ordering = ('type', 'index')
54 verbose_name = 'media książki'
55 verbose_name_plural = 'media książek'
56 app_label = 'catalogue'
58 def get_extra_info_json(self):
59 return json.loads(self.extra_info or '{}')
61 def get_nice_filename(self):
62 parts_count = 1 + type(self).objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
66 name += f'_{self.index:03d}'
68 name += f'_' + slugify(self.part_name)
70 return f'{name}.{ext}'
72 def save(self, parts_count=None, *args, **kwargs):
73 from catalogue.utils import ExistingFile, remove_zip
76 parts_count = 1 + BookMedia.objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
78 self.name = self.book.pretty_title()
80 no = ('%02d' if parts_count < 100 else '%03d') % self.index
81 self.name = '%s. %s' % (no, self.book.pretty_title())
83 self.name += ', ' + self.part_name
86 old = BookMedia.objects.get(pk=self.pk)
87 except BookMedia.DoesNotExist:
90 super(BookMedia, self).save(*args, **kwargs)
92 # remove the zip package for book with modified media
94 remove_zip("%s_%s" % (old.book.slug, old.type))
95 remove_zip("%s_%s" % (self.book.slug, self.type))
97 extra_info = self.get_extra_info_json()
98 extra_info.update(self.read_meta())
99 self.extra_info = json.dumps(extra_info)
100 self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
101 self.duration = self.read_duration()
102 return super(BookMedia, self).save(*args, **kwargs)
104 def read_duration(self):
106 return mutagen.File(self.file.path).info.length
112 Reads some metadata from the audiobook.
114 artist_name = director_name = project = funded_by = license = ''
115 if self.type == 'mp3':
117 audio = id3.ID3(self.file.path)
118 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
119 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
120 license = ', '.join(tag.url for tag in audio.getall('WCOP'))
121 project = ", ".join([
122 t.data.decode('utf-8') for t in audio.getall('PRIV')
123 if t.owner == 'wolnelektury.pl?project'])
124 funded_by = ", ".join([
125 t.data.decode('utf-8') for t in audio.getall('PRIV')
126 if t.owner == 'wolnelektury.pl?funded_by'])
127 except mutagen.MutagenError:
129 elif self.type == 'ogg':
131 audio = mutagen.File(self.file.path)
132 artist_name = ', '.join(audio.get('artist', []))
133 director_name = ', '.join(audio.get('conductor', []))
134 license = ', '.join(audio.get('license', []))
135 project = ", ".join(audio.get('project', []))
136 funded_by = ", ".join(audio.get('funded_by', []))
137 except (mutagen.MutagenError, AttributeError):
141 return {'artist_name': artist_name, 'director_name': director_name,
142 'project': project, 'funded_by': funded_by, 'license': license}
145 return self.formats[self.type].ext
148 def read_source_sha1(filepath, filetype):
150 Reads source file SHA1 from audiobok metadata.
152 if filetype == 'mp3':
154 audio = id3.ID3(filepath)
155 return [t.data.decode('utf-8') for t in audio.getall('PRIV')
156 if t.owner == 'wolnelektury.pl?flac_sha1'][0]
157 except (mutagen.MutagenError, IndexError):
159 elif filetype == 'ogg':
161 audio = mutagen.File(filepath)
162 return audio.get('flac_sha1', [None])[0]
163 except (mutagen.MutagenError, AttributeError, IndexError):
170 return self.get_extra_info_json().get('director_name', None)
174 return self.get_extra_info_json().get('artist_name', None)