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 extra_info = models.TextField(_('extra information'), default='{}', editable=False)
42 book = models.ForeignKey('Book', models.CASCADE, related_name='media')
43 source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
46 return self.file.name.split("/")[-1]
49 ordering = ('type', 'index')
50 verbose_name = _('book media')
51 verbose_name_plural = _('book media')
52 app_label = 'catalogue'
54 def get_extra_info_json(self):
55 return json.loads(self.extra_info or '{}')
57 def save(self, parts_count=None, *args, **kwargs):
58 from catalogue.utils import ExistingFile, remove_zip
61 parts_count = 1 + BookMedia.objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
63 self.name = self.book.pretty_title()
65 no = ('%02d' if parts_count < 100 else '%03d') % self.index
66 self.name = '%s. %s' % (no, self.book.pretty_title())
68 self.name += ', ' + self.part_name
71 old = BookMedia.objects.get(pk=self.pk)
72 except BookMedia.DoesNotExist:
75 # if name changed, change the file name, too
76 if slugify(self.name) != slugify(old.name):
77 self.file.save(None, ExistingFile(self.file.path), save=False)
79 super(BookMedia, self).save(*args, **kwargs)
81 # remove the zip package for book with modified media
83 remove_zip("%s_%s" % (old.book.slug, old.type))
84 remove_zip("%s_%s" % (self.book.slug, self.type))
86 extra_info = self.get_extra_info_json()
87 extra_info.update(self.read_meta())
88 self.extra_info = json.dumps(extra_info)
89 self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
90 return super(BookMedia, self).save(*args, **kwargs)
94 Reads some metadata from the audiobook.
97 from mutagen import id3
99 artist_name = director_name = project = funded_by = license = ''
100 if self.type == 'mp3':
102 audio = id3.ID3(self.file.path)
103 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
104 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
105 license = ', '.join(tag.url for tag in audio.getall('WCOP'))
106 project = ", ".join([
107 t.data.decode('utf-8') for t in audio.getall('PRIV')
108 if t.owner == 'wolnelektury.pl?project'])
109 funded_by = ", ".join([
110 t.data.decode('utf-8') for t in audio.getall('PRIV')
111 if t.owner == 'wolnelektury.pl?funded_by'])
114 elif self.type == 'ogg':
116 audio = mutagen.File(self.file.path)
117 artist_name = ', '.join(audio.get('artist', []))
118 director_name = ', '.join(audio.get('conductor', []))
119 license = ', '.join(audio.get('license', []))
120 project = ", ".join(audio.get('project', []))
121 funded_by = ", ".join(audio.get('funded_by', []))
122 except (MutagenError, AttributeError):
126 return {'artist_name': artist_name, 'director_name': director_name,
127 'project': project, 'funded_by': funded_by, 'license': license}
130 return self.formats[self.type].ext
133 def read_source_sha1(filepath, filetype):
135 Reads source file SHA1 from audiobok metadata.
138 from mutagen import id3
140 if filetype == 'mp3':
142 audio = id3.ID3(filepath)
143 return [t.data.decode('utf-8') for t in audio.getall('PRIV')
144 if t.owner == 'wolnelektury.pl?flac_sha1'][0]
145 except (MutagenError, IndexError):
147 elif filetype == 'ogg':
149 audio = mutagen.File(filepath)
150 return audio.get('flac_sha1', [None])[0]
151 except (MutagenError, AttributeError, IndexError):
158 return self.get_extra_info_json().get('director_name', None)
162 return self.get_extra_info_json().get('artist_name', None)