1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from collections import OrderedDict
7 from collections import namedtuple
8 from django.db import models
9 from django.utils.translation import ugettext_lazy as _
11 from slugify import slugify
12 from mutagen import MutagenError
14 from catalogue.fields import OverwriteStorage
17 def _file_upload_to(i, _n):
18 return 'book/%(ext)s/%(name)s.%(ext)s' % {'ext': i.ext(), 'name': slugify(i.name)}
21 class BookMedia(models.Model):
22 """Represents media attached to a book."""
23 FileFormat = namedtuple("FileFormat", "name ext")
24 formats = OrderedDict([
25 ('mp3', FileFormat(name='MP3', ext='mp3')),
26 ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
27 ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
29 format_choices = [(k, _('%s file' % t.name)) for k, t in formats.items()]
31 type = models.CharField(_('type'), db_index=True, choices=format_choices, max_length=20)
32 name = models.CharField(_('name'), max_length=512)
33 part_name = models.CharField(_('part name'), default='', blank=True, max_length=512)
34 index = models.IntegerField(_('index'), default=0)
35 file = models.FileField(_('file'), max_length=600, upload_to=_file_upload_to, storage=OverwriteStorage())
36 uploaded_at = models.DateTimeField(_('creation date'), auto_now_add=True, editable=False, db_index=True)
37 extra_info = jsonfield.JSONField(_('extra information'), default={}, editable=False)
38 book = models.ForeignKey('Book', related_name='media')
39 source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
42 return "%s (%s)" % (self.name, self.file.name.split("/")[-1])
45 ordering = ('type', 'name')
46 verbose_name = _('book media')
47 verbose_name_plural = _('book media')
48 app_label = 'catalogue'
50 def save(self, parts_count=None, *args, **kwargs):
51 from catalogue.utils import ExistingFile, remove_zip
54 parts_count = 1 + BookMedia.objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
56 self.name = self.book.pretty_title()
58 no = ('%02d' if parts_count < 100 else '%03d') % self.index
59 self.name = '%s. %s' % (no, self.book.pretty_title())
61 self.name += ', ' + self.part_name
64 old = BookMedia.objects.get(pk=self.pk)
65 except BookMedia.DoesNotExist:
68 # if name changed, change the file name, too
69 if slugify(self.name) != slugify(old.name):
70 self.file.save(None, ExistingFile(self.file.path), save=False)
72 super(BookMedia, self).save(*args, **kwargs)
74 # remove the zip package for book with modified media
76 remove_zip("%s_%s" % (old.book.slug, old.type))
77 remove_zip("%s_%s" % (self.book.slug, self.type))
79 extra_info = self.extra_info
80 if isinstance(extra_info, str):
81 # Walkaround for weird jsonfield 'no-decode' optimization.
82 extra_info = json.loads(extra_info)
83 extra_info.update(self.read_meta())
84 self.extra_info = extra_info
85 self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
86 return super(BookMedia, self).save(*args, **kwargs)
90 Reads some metadata from the audiobook.
93 from mutagen import id3
95 artist_name = director_name = project = funded_by = ''
96 if self.type == 'mp3':
98 audio = id3.ID3(self.file.path)
99 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
100 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
101 project = ", ".join([
102 t.data for t in audio.getall('PRIV')
103 if t.owner == 'wolnelektury.pl?project'])
104 funded_by = ", ".join([
105 t.data for t in audio.getall('PRIV')
106 if t.owner == 'wolnelektury.pl?funded_by'])
109 elif self.type == 'ogg':
111 audio = mutagen.File(self.file.path)
112 artist_name = ', '.join(audio.get('artist', []))
113 director_name = ', '.join(audio.get('conductor', []))
114 project = ", ".join(audio.get('project', []))
115 funded_by = ", ".join(audio.get('funded_by', []))
116 except (MutagenError, AttributeError):
120 return {'artist_name': artist_name, 'director_name': director_name,
121 'project': project, 'funded_by': funded_by}
124 return self.formats[self.type].ext
127 def read_source_sha1(filepath, filetype):
129 Reads source file SHA1 from audiobok metadata.
132 from mutagen import id3
134 if filetype == 'mp3':
136 audio = id3.ID3(filepath)
137 return [t.data for t in audio.getall('PRIV')
138 if t.owner == 'wolnelektury.pl?flac_sha1'][0]
139 except (MutagenError, IndexError):
141 elif filetype == 'ogg':
143 audio = mutagen.File(filepath)
144 return audio.get('flac_sha1', [None])[0]
145 except (MutagenError, AttributeError, IndexError):
152 return self.extra_info.get('director_name', None)
156 return self.extra_info.get('artist_name', None)