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 namedtuple
6 from django.db import models
7 from django.utils.translation import ugettext_lazy as _
8 from django.utils.datastructures import SortedDict
10 from catalogue.fields import OverwritingFileField
11 from catalogue.utils import book_upload_path
14 class BookMedia(models.Model):
15 """Represents media attached to a book."""
16 FileFormat = namedtuple("FileFormat", "name ext")
17 formats = SortedDict([
18 ('mp3', FileFormat(name='MP3', ext='mp3')),
19 ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
20 ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
22 format_choices = [(k, _('%s file') % t.name)
23 for k, t in formats.items()]
25 type = models.CharField(_('type'), choices=format_choices, max_length="100")
26 name = models.CharField(_('name'), max_length="100")
27 file = OverwritingFileField(_('file'), upload_to=book_upload_path())
28 uploaded_at = models.DateTimeField(_('creation date'), auto_now_add=True, editable=False)
29 extra_info = jsonfield.JSONField(_('extra information'), default='{}', editable=False)
30 book = models.ForeignKey('Book', related_name='media')
31 source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
33 def __unicode__(self):
34 return "%s (%s)" % (self.name, self.file.name.split("/")[-1])
37 ordering = ('type', 'name')
38 verbose_name = _('book media')
39 verbose_name_plural = _('book media')
40 app_label = 'catalogue'
42 def save(self, *args, **kwargs):
43 from slughifi import slughifi
44 from catalogue.utils import ExistingFile, remove_zip
47 old = BookMedia.objects.get(pk=self.pk)
48 except BookMedia.DoesNotExist:
51 # if name changed, change the file name, too
52 if slughifi(self.name) != slughifi(old.name):
53 self.file.save(None, ExistingFile(self.file.path), save=False, leave=True)
55 super(BookMedia, self).save(*args, **kwargs)
57 # remove the zip package for book with modified media
59 remove_zip("%s_%s" % (old.book.slug, old.type))
60 remove_zip("%s_%s" % (self.book.slug, self.type))
62 extra_info = self.extra_info
63 extra_info.update(self.read_meta())
64 self.extra_info = extra_info
65 self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
66 return super(BookMedia, self).save(*args, **kwargs)
70 Reads some metadata from the audiobook.
73 from mutagen import id3
75 artist_name = director_name = project = funded_by = ''
76 if self.type == 'mp3':
78 audio = id3.ID3(self.file.path)
79 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
80 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
81 project = ", ".join([t.data for t in audio.getall('PRIV')
82 if t.owner=='wolnelektury.pl?project'])
83 funded_by = ", ".join([t.data for t in audio.getall('PRIV')
84 if t.owner=='wolnelektury.pl?funded_by'])
87 elif self.type == 'ogg':
89 audio = mutagen.File(self.file.path)
90 artist_name = ', '.join(audio.get('artist', []))
91 director_name = ', '.join(audio.get('conductor', []))
92 project = ", ".join(audio.get('project', []))
93 funded_by = ", ".join(audio.get('funded_by', []))
98 return {'artist_name': artist_name, 'director_name': director_name,
99 'project': project, 'funded_by': funded_by}
102 def read_source_sha1(filepath, filetype):
104 Reads source file SHA1 from audiobok metadata.
107 from mutagen import id3
109 if filetype == 'mp3':
111 audio = id3.ID3(filepath)
112 return [t.data for t in audio.getall('PRIV')
113 if t.owner=='wolnelektury.pl?flac_sha1'][0]
116 elif filetype == 'ogg':
118 audio = mutagen.File(filepath)
119 return audio.get('flac_sha1', [None])[0]