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.
6 from collections import namedtuple
7 from django.db import models
8 from django.utils.translation import ugettext_lazy as _
9 from django.utils.datastructures import SortedDict
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 = SortedDict([
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 fnpdjango.utils.text.slughifi import slughifi
50 from catalogue.utils import ExistingFile, remove_zip
53 old = BookMedia.objects.get(pk=self.pk)
54 except BookMedia.DoesNotExist:
57 # if name changed, change the file name, too
58 if slughifi(self.name) != slughifi(old.name):
59 self.file.save(None, ExistingFile(self.file.path), save=False, leave=True)
61 super(BookMedia, self).save(*args, **kwargs)
63 # remove the zip package for book with modified media
65 remove_zip("%s_%s" % (old.book.slug, old.type))
66 remove_zip("%s_%s" % (self.book.slug, self.type))
68 extra_info = self.extra_info
69 if isinstance(extra_info, basestring):
70 # Walkaround for weird jsonfield 'no-decode' optimization.
71 extra_info = json.loads(extra_info)
72 extra_info.update(self.read_meta())
73 self.extra_info = extra_info
74 self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
75 return super(BookMedia, self).save(*args, **kwargs)
79 Reads some metadata from the audiobook.
82 from mutagen import id3
84 artist_name = director_name = project = funded_by = ''
85 if self.type == 'mp3':
87 audio = id3.ID3(self.file.path)
88 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
89 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
90 project = ", ".join([t.data for t in audio.getall('PRIV')
91 if t.owner == 'wolnelektury.pl?project'])
92 funded_by = ", ".join([t.data for t in audio.getall('PRIV')
93 if t.owner == 'wolnelektury.pl?funded_by'])
96 elif self.type == 'ogg':
98 audio = mutagen.File(self.file.path)
99 artist_name = ', '.join(audio.get('artist', []))
100 director_name = ', '.join(audio.get('conductor', []))
101 project = ", ".join(audio.get('project', []))
102 funded_by = ", ".join(audio.get('funded_by', []))
107 return {'artist_name': artist_name, 'director_name': director_name,
108 'project': project, 'funded_by': funded_by}
111 return self.formats[self.type].ext
114 def read_source_sha1(filepath, filetype):
116 Reads source file SHA1 from audiobok metadata.
119 from mutagen import id3
121 if filetype == 'mp3':
123 audio = id3.ID3(filepath)
124 return [t.data for t in audio.getall('PRIV')
125 if t.owner == 'wolnelektury.pl?flac_sha1'][0]
128 elif filetype == 'ogg':
130 audio = mutagen.File(filepath)
131 return audio.get('flac_sha1', [None])[0]