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 django.utils.translation import ugettext_lazy as _
9 from slugify import slugify
10 from mutagen import MutagenError
12 from catalogue.fields import OverwriteStorage
15 def _file_upload_to(i, _n):
18 name += f'_{i.index:03d}'
20 name += f'_' + slugify(i.part_name)
22 return f'book/{ext}/{name}.{ext}'
25 class BookMedia(models.Model):
26 """Represents media attached to a book."""
27 FileFormat = namedtuple("FileFormat", "name ext")
28 formats = OrderedDict([
29 ('mp3', FileFormat(name='MP3', ext='mp3')),
30 ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
31 ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
33 format_choices = [(k, _('%s file' % t.name)) for k, t in formats.items()]
35 type = models.CharField(_('type'), db_index=True, choices=format_choices, max_length=20)
36 name = models.CharField(_('name'), max_length=512)
37 part_name = models.CharField(_('part name'), default='', blank=True, max_length=512)
38 index = models.IntegerField(_('index'), default=0)
39 file = models.FileField(_('file'), max_length=600, upload_to=_file_upload_to, storage=OverwriteStorage())
40 uploaded_at = models.DateTimeField(_('creation date'), auto_now_add=True, editable=False, db_index=True)
41 project_description = models.CharField(max_length=2048, blank=True)
42 project_icon = models.CharField(max_length=2048, blank=True)
43 extra_info = models.TextField(_('extra information'), default='{}', editable=False)
44 book = models.ForeignKey('Book', models.CASCADE, related_name='media')
45 source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
48 return self.file.name.split("/")[-1]
51 ordering = ('type', 'index')
52 verbose_name = _('book media')
53 verbose_name_plural = _('book media')
54 app_label = 'catalogue'
56 def get_extra_info_json(self):
57 return json.loads(self.extra_info or '{}')
59 def get_nice_filename(self):
60 parts_count = 1 + type(self).objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
64 name += f'_{self.index:03d}'
66 name += f'_' + slugify(self.part_name)
68 return f'{name}.{ext}'
70 def save(self, parts_count=None, *args, **kwargs):
71 from catalogue.utils import ExistingFile, remove_zip
74 parts_count = 1 + BookMedia.objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
76 self.name = self.book.pretty_title()
78 no = ('%02d' if parts_count < 100 else '%03d') % self.index
79 self.name = '%s. %s' % (no, self.book.pretty_title())
81 self.name += ', ' + self.part_name
84 old = BookMedia.objects.get(pk=self.pk)
85 except BookMedia.DoesNotExist:
88 super(BookMedia, self).save(*args, **kwargs)
90 # remove the zip package for book with modified media
92 remove_zip("%s_%s" % (old.book.slug, old.type))
93 remove_zip("%s_%s" % (self.book.slug, self.type))
95 extra_info = self.get_extra_info_json()
96 extra_info.update(self.read_meta())
97 self.extra_info = json.dumps(extra_info)
98 self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
99 return super(BookMedia, self).save(*args, **kwargs)
103 Reads some metadata from the audiobook.
106 from mutagen import id3
108 artist_name = director_name = project = funded_by = license = ''
109 if self.type == 'mp3':
111 audio = id3.ID3(self.file.path)
112 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
113 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
114 license = ', '.join(tag.url for tag in audio.getall('WCOP'))
115 project = ", ".join([
116 t.data.decode('utf-8') for t in audio.getall('PRIV')
117 if t.owner == 'wolnelektury.pl?project'])
118 funded_by = ", ".join([
119 t.data.decode('utf-8') for t in audio.getall('PRIV')
120 if t.owner == 'wolnelektury.pl?funded_by'])
123 elif self.type == 'ogg':
125 audio = mutagen.File(self.file.path)
126 artist_name = ', '.join(audio.get('artist', []))
127 director_name = ', '.join(audio.get('conductor', []))
128 license = ', '.join(audio.get('license', []))
129 project = ", ".join(audio.get('project', []))
130 funded_by = ", ".join(audio.get('funded_by', []))
131 except (MutagenError, AttributeError):
135 return {'artist_name': artist_name, 'director_name': director_name,
136 'project': project, 'funded_by': funded_by, 'license': license}
139 return self.formats[self.type].ext
142 def read_source_sha1(filepath, filetype):
144 Reads source file SHA1 from audiobok metadata.
147 from mutagen import id3
149 if filetype == 'mp3':
151 audio = id3.ID3(filepath)
152 return [t.data.decode('utf-8') for t in audio.getall('PRIV')
153 if t.owner == 'wolnelektury.pl?flac_sha1'][0]
154 except (MutagenError, IndexError):
156 elif filetype == 'ogg':
158 audio = mutagen.File(filepath)
159 return audio.get('flac_sha1', [None])[0]
160 except (MutagenError, AttributeError, IndexError):
167 return self.get_extra_info_json().get('director_name', None)
171 return self.get_extra_info_json().get('artist_name', None)