Code layout change.
[wolnelektury.git] / src / catalogue / models / bookmedia.py
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.
4 #
5 from collections import OrderedDict
6 import json
7 from collections import namedtuple
8 from django.db import models
9 from django.utils.translation import ugettext_lazy as _
10 import jsonfield
11 from fnpdjango.utils.text.slughifi import slughifi
12 from catalogue.fields import OverwritingFileField
13
14
15 def _file_upload_to(i, _n):
16     return 'book/%(ext)s/%(name)s.%(ext)s' % {
17             'ext': i.ext(), 'name': slughifi(i.name)}
18
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')),
26     ])
27     format_choices = [(k, _('%s file' % t.name))
28             for k, t in formats.items()]
29
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)
38
39     def __unicode__(self):
40         return "%s (%s)" % (self.name, self.file.name.split("/")[-1])
41
42     class Meta:
43         ordering            = ('type', 'name')
44         verbose_name        = _('book media')
45         verbose_name_plural = _('book media')
46         app_label = 'catalogue'
47
48     def save(self, *args, **kwargs):
49         from catalogue.utils import ExistingFile, remove_zip
50
51         try:
52             old = BookMedia.objects.get(pk=self.pk)
53         except BookMedia.DoesNotExist:
54             old = None
55         else:
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)
59
60         super(BookMedia, self).save(*args, **kwargs)
61
62         # remove the zip package for book with modified media
63         if old:
64             remove_zip("%s_%s" % (old.book.slug, old.type))
65         remove_zip("%s_%s" % (self.book.slug, self.type))
66
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)
75
76     def read_meta(self):
77         """
78             Reads some metadata from the audiobook.
79         """
80         import mutagen
81         from mutagen import id3
82
83         artist_name = director_name = project = funded_by = ''
84         if self.type == 'mp3':
85             try:
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'])
93             except:
94                 pass
95         elif self.type == 'ogg':
96             try:
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', []))
102             except:
103                 pass
104         else:
105             return {}
106         return {'artist_name': artist_name, 'director_name': director_name,
107                 'project': project, 'funded_by': funded_by}
108
109     def ext(self):
110         return self.formats[self.type].ext
111
112     @staticmethod
113     def read_source_sha1(filepath, filetype):
114         """
115             Reads source file SHA1 from audiobok metadata.
116         """
117         import mutagen
118         from mutagen import id3
119
120         if filetype == 'mp3':
121             try:
122                 audio = id3.ID3(filepath)
123                 return [t.data for t in audio.getall('PRIV')
124                         if t.owner == 'wolnelektury.pl?flac_sha1'][0]
125             except:
126                 return None
127         elif filetype == 'ogg':
128             try:
129                 audio = mutagen.File(filepath)
130                 return audio.get('flac_sha1', [None])[0]
131             except:
132                 return None
133         else:
134             return None