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 fnpdjango.utils.text.slughifi import slughifi
12 from catalogue.fields import OverwritingFileField
15 def _file_upload_to(i, _n):
16 return 'book/%(ext)s/%(name)s.%(ext)s' % {
17 'ext': i.ext(), 'name': slughifi(i.name)}
19 class BookMedia(models.Model):
20 """Represents media attached to a book."""
21 FileFormat = namedtuple("FileFormat", "name ext")
22 formats = OrderedDict([
23 ('mp3', FileFormat(name='MP3', ext='mp3')),
24 ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
25 ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
27 format_choices = [(k, _('%s file' % t.name))
28 for k, t in formats.items()]
30 type = models.CharField(_('type'), db_index=True, choices=format_choices, max_length=20)
31 name = models.CharField(_('name'), max_length=512)
32 file = OverwritingFileField(_('file'), max_length=600,
33 upload_to=_file_upload_to)
34 uploaded_at = models.DateTimeField(_('creation date'), auto_now_add=True, editable=False, db_index=True)
35 extra_info = jsonfield.JSONField(_('extra information'), default={}, editable=False)
36 book = models.ForeignKey('Book', related_name='media')
37 source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
39 def __unicode__(self):
40 return "%s (%s)" % (self.name, self.file.name.split("/")[-1])
43 ordering = ('type', 'name')
44 verbose_name = _('book media')
45 verbose_name_plural = _('book media')
46 app_label = 'catalogue'
48 def save(self, *args, **kwargs):
49 from catalogue.utils import ExistingFile, remove_zip
52 old = BookMedia.objects.get(pk=self.pk)
53 except BookMedia.DoesNotExist:
56 # if name changed, change the file name, too
57 if slughifi(self.name) != slughifi(old.name):
58 self.file.save(None, ExistingFile(self.file.path), save=False, leave=True)
60 super(BookMedia, self).save(*args, **kwargs)
62 # remove the zip package for book with modified media
64 remove_zip("%s_%s" % (old.book.slug, old.type))
65 remove_zip("%s_%s" % (self.book.slug, self.type))
67 extra_info = self.extra_info
68 if isinstance(extra_info, basestring):
69 # Walkaround for weird jsonfield 'no-decode' optimization.
70 extra_info = json.loads(extra_info)
71 extra_info.update(self.read_meta())
72 self.extra_info = extra_info
73 self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
74 return super(BookMedia, self).save(*args, **kwargs)
78 Reads some metadata from the audiobook.
81 from mutagen import id3
83 artist_name = director_name = project = funded_by = ''
84 if self.type == 'mp3':
86 audio = id3.ID3(self.file.path)
87 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
88 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
89 project = ", ".join([t.data for t in audio.getall('PRIV')
90 if t.owner == 'wolnelektury.pl?project'])
91 funded_by = ", ".join([t.data for t in audio.getall('PRIV')
92 if t.owner == 'wolnelektury.pl?funded_by'])
95 elif self.type == 'ogg':
97 audio = mutagen.File(self.file.path)
98 artist_name = ', '.join(audio.get('artist', []))
99 director_name = ', '.join(audio.get('conductor', []))
100 project = ", ".join(audio.get('project', []))
101 funded_by = ", ".join(audio.get('funded_by', []))
106 return {'artist_name': artist_name, 'director_name': director_name,
107 'project': project, 'funded_by': funded_by}
110 return self.formats[self.type].ext
113 def read_source_sha1(filepath, filetype):
115 Reads source file SHA1 from audiobok metadata.
118 from mutagen import id3
120 if filetype == 'mp3':
122 audio = id3.ID3(filepath)
123 return [t.data for t in audio.getall('PRIV')
124 if t.owner == 'wolnelektury.pl?flac_sha1'][0]
127 elif filetype == 'ogg':
129 audio = mutagen.File(filepath)
130 return audio.get('flac_sha1', [None])[0]