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.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 if self.type in ('daisy', 'audio.epub'):
74 return super().save(*args, **kwargs)
75 from catalogue.utils import ExistingFile, remove_zip
78 parts_count = 1 + BookMedia.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
88 old = BookMedia.objects.get(pk=self.pk)
89 except BookMedia.DoesNotExist:
92 super(BookMedia, self).save(*args, **kwargs)
94 # remove the zip package for book with modified media
96 remove_zip("%s_%s" % (old.book.slug, old.type))
97 remove_zip("%s_%s" % (self.book.slug, self.type))
99 extra_info = self.get_extra_info_json()
100 extra_info.update(self.read_meta())
101 self.extra_info = json.dumps(extra_info)
102 self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
103 self.duration = self.read_duration()
104 return super(BookMedia, self).save(*args, **kwargs)
106 def read_duration(self):
108 return mutagen.File(self.file.path).info.length
114 Reads some metadata from the audiobook.
116 artist_name = director_name = project = funded_by = license = ''
117 if self.type == 'mp3':
119 audio = id3.ID3(self.file.path)
120 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
121 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
122 license = ', '.join(tag.url for tag in audio.getall('WCOP'))
123 project = ", ".join([
124 t.data.decode('utf-8') for t in audio.getall('PRIV')
125 if t.owner == 'wolnelektury.pl?project'])
126 funded_by = ", ".join([
127 t.data.decode('utf-8') for t in audio.getall('PRIV')
128 if t.owner == 'wolnelektury.pl?funded_by'])
129 except mutagen.MutagenError:
131 elif self.type == 'ogg':
133 audio = mutagen.File(self.file.path)
134 artist_name = ', '.join(audio.get('artist', []))
135 director_name = ', '.join(audio.get('conductor', []))
136 license = ', '.join(audio.get('license', []))
137 project = ", ".join(audio.get('project', []))
138 funded_by = ", ".join(audio.get('funded_by', []))
139 except (mutagen.MutagenError, AttributeError):
143 return {'artist_name': artist_name, 'director_name': director_name,
144 'project': project, 'funded_by': funded_by, 'license': license}
147 return self.formats[self.type].ext
150 def read_source_sha1(filepath, filetype):
152 Reads source file SHA1 from audiobok metadata.
154 if filetype == 'mp3':
156 audio = id3.ID3(filepath)
157 return [t.data.decode('utf-8') for t in audio.getall('PRIV')
158 if t.owner == 'wolnelektury.pl?flac_sha1'][0]
159 except (mutagen.MutagenError, IndexError):
161 elif filetype == 'ogg':
163 audio = mutagen.File(filepath)
164 return audio.get('flac_sha1', [None])[0]
165 except (mutagen.MutagenError, AttributeError, IndexError):
172 return self.get_extra_info_json().get('director_name', None)
176 return self.get_extra_info_json().get('artist_name', None)