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 save(self, parts_count=None, *args, **kwargs):
60 from catalogue.utils import ExistingFile, remove_zip
63 parts_count = 1 + BookMedia.objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
65 self.name = self.book.pretty_title()
67 no = ('%02d' if parts_count < 100 else '%03d') % self.index
68 self.name = '%s. %s' % (no, self.book.pretty_title())
70 self.name += ', ' + self.part_name
73 old = BookMedia.objects.get(pk=self.pk)
74 except BookMedia.DoesNotExist:
77 # if name changed, change the file name, too
78 if slugify(self.name) != slugify(old.name):
79 self.file.save(None, ExistingFile(self.file.path), save=False)
81 super(BookMedia, self).save(*args, **kwargs)
83 # remove the zip package for book with modified media
85 remove_zip("%s_%s" % (old.book.slug, old.type))
86 remove_zip("%s_%s" % (self.book.slug, self.type))
88 extra_info = self.get_extra_info_json()
89 extra_info.update(self.read_meta())
90 self.extra_info = json.dumps(extra_info)
91 self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
92 return super(BookMedia, self).save(*args, **kwargs)
96 Reads some metadata from the audiobook.
99 from mutagen import id3
101 artist_name = director_name = project = funded_by = license = ''
102 if self.type == 'mp3':
104 audio = id3.ID3(self.file.path)
105 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
106 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
107 license = ', '.join(tag.url for tag in audio.getall('WCOP'))
108 project = ", ".join([
109 t.data.decode('utf-8') for t in audio.getall('PRIV')
110 if t.owner == 'wolnelektury.pl?project'])
111 funded_by = ", ".join([
112 t.data.decode('utf-8') for t in audio.getall('PRIV')
113 if t.owner == 'wolnelektury.pl?funded_by'])
116 elif self.type == 'ogg':
118 audio = mutagen.File(self.file.path)
119 artist_name = ', '.join(audio.get('artist', []))
120 director_name = ', '.join(audio.get('conductor', []))
121 license = ', '.join(audio.get('license', []))
122 project = ", ".join(audio.get('project', []))
123 funded_by = ", ".join(audio.get('funded_by', []))
124 except (MutagenError, AttributeError):
128 return {'artist_name': artist_name, 'director_name': director_name,
129 'project': project, 'funded_by': funded_by, 'license': license}
132 return self.formats[self.type].ext
135 def read_source_sha1(filepath, filetype):
137 Reads source file SHA1 from audiobok metadata.
140 from mutagen import id3
142 if filetype == 'mp3':
144 audio = id3.ID3(filepath)
145 return [t.data.decode('utf-8') for t in audio.getall('PRIV')
146 if t.owner == 'wolnelektury.pl?flac_sha1'][0]
147 except (MutagenError, IndexError):
149 elif filetype == 'ogg':
151 audio = mutagen.File(filepath)
152 return audio.get('flac_sha1', [None])[0]
153 except (MutagenError, AttributeError, IndexError):
160 return self.get_extra_info_json().get('director_name', None)
164 return self.get_extra_info_json().get('artist_name', None)