Tidying up all the covers craziness and storages.
[wolnelektury.git] / src / catalogue / models / bookmedia.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 from collections import OrderedDict
5 import json
6 from collections import namedtuple
7 from django.core.files.storage import storages
8 from django.db import models
9 from slugify import slugify
10 import mutagen
11 from mutagen import id3
12
13
14 def _file_upload_to(i, _n):
15     name = i.book.slug
16     if i.index:
17         name += f'_{i.index:03d}'
18     if i.part_name:
19         name += f'_' + slugify(i.part_name)
20     ext = i.ext()
21     return f'book/{ext}/{name}.{ext}'
22
23
24 def get_storage():
25     return storages['bookmedia']
26
27
28 class BookMedia(models.Model):
29     """Represents media attached to a book."""
30     FileFormat = namedtuple("FileFormat", "name ext")
31     formats = OrderedDict([
32         ('mp3', FileFormat(name='MP3', ext='mp3')),
33         ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
34         ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
35         ('audio.epub', FileFormat(name='EPUB+audio', ext='audio.epub')),
36         ('sync', FileFormat(name='sync', ext='sync.txt')),
37     ])
38     format_choices = [(k, 'plik %s' % t.name) for k, t in formats.items()]
39
40     type = models.CharField('typ', db_index=True, choices=format_choices, max_length=20)
41     name = models.CharField('nazwa', max_length=512)
42     part_name = models.CharField('nazwa części', default='', blank=True, max_length=512)
43     index = models.IntegerField('indeks', default=0)
44     file = models.FileField('plik', max_length=600, upload_to=_file_upload_to, storage=get_storage)
45     duration = models.FloatField(null=True, blank=True)
46     uploaded_at = models.DateTimeField('data utworzenia', auto_now_add=True, editable=False, db_index=True)
47     project_description = models.CharField(max_length=2048, blank=True)
48     project_icon = models.CharField(max_length=2048, blank=True)
49     extra_info = models.TextField('dodatkowe informacje', default='{}', editable=False)
50     book = models.ForeignKey('Book', models.CASCADE, related_name='media')
51     source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
52
53     def __str__(self):
54         return self.file.name.split("/")[-1]
55
56     class Meta:
57         ordering = ('type', 'index')
58         verbose_name = 'media książki'
59         verbose_name_plural = 'media książek'
60         app_label = 'catalogue'
61
62     def get_extra_info_json(self):
63         return json.loads(self.extra_info or '{}')
64
65     def get_nice_filename(self):
66         parts_count = 1 + type(self).objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
67
68         name = self.book.slug
69         if parts_count > 0:
70             name += f'_{self.index:03d}'
71         if self.part_name:
72             name += f'_' + slugify(self.part_name)
73         ext = self.ext()
74         return f'{name}.{ext}'
75
76     def save(self, parts_count=None, *args, **kwargs):
77         if self.type in ('daisy', 'audio.epub'):
78             return super().save(*args, **kwargs)
79         from catalogue.utils import ExistingFile, remove_zip
80
81         if not parts_count:
82             parts_count = 1 + BookMedia.objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
83         if parts_count == 1:
84             self.name = self.book.pretty_title()
85         else:
86             no = ('%02d' if parts_count < 100 else '%03d') % self.index
87             self.name = '%s. %s' % (no, self.book.pretty_title())
88             if self.part_name:
89                 self.name += ', ' + self.part_name
90
91         try:
92             old = BookMedia.objects.get(pk=self.pk)
93         except BookMedia.DoesNotExist:
94             old = None
95
96         #super(BookMedia, self).save(*args, **kwargs)
97         
98         # remove the zip package for book with modified media
99         if old:
100             remove_zip("%s_%s" % (old.book.slug, old.type))
101         remove_zip("%s_%s" % (self.book.slug, self.type))
102
103         extra_info = self.get_extra_info_json()
104         extra_info.update(self.read_meta())
105         self.extra_info = json.dumps(extra_info)
106         self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
107         self.duration = self.read_duration()
108         super(BookMedia, self).save(*args, **kwargs)
109         self.book.update_narrators()
110         self.book.update_has_audio()
111
112     def read_duration(self):
113         try:
114             return mutagen.File(self.file.path).info.length
115         except:
116             return None
117
118     def read_meta(self):
119         """
120             Reads some metadata from the audiobook.
121         """
122         artist_name = director_name = project = funded_by = license = ''
123         if self.type == 'mp3':
124             try:
125                 audio = id3.ID3(self.file.path)
126                 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
127                 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
128                 license = ', '.join(tag.url for tag in audio.getall('WCOP'))
129                 project = ", ".join([
130                     t.data.decode('utf-8') for t in audio.getall('PRIV')
131                     if t.owner == 'wolnelektury.pl?project'])
132                 funded_by = ", ".join([
133                     t.data.decode('utf-8') for t in audio.getall('PRIV')
134                     if t.owner == 'wolnelektury.pl?funded_by'])
135             except mutagen.MutagenError:
136                 pass
137         elif self.type == 'ogg':
138             try:
139                 audio = mutagen.File(self.file.path)
140                 artist_name = ', '.join(audio.get('artist', []))
141                 director_name = ', '.join(audio.get('conductor', []))
142                 license = ', '.join(audio.get('license', []))
143                 project = ", ".join(audio.get('project', []))
144                 funded_by = ", ".join(audio.get('funded_by', []))
145             except (mutagen.MutagenError, AttributeError):
146                 pass
147         else:
148             return {}
149         return {'artist_name': artist_name, 'director_name': director_name,
150                 'project': project, 'funded_by': funded_by, 'license': license}
151
152     def ext(self):
153         return self.formats[self.type].ext
154
155     @staticmethod
156     def read_source_sha1(filepath, filetype):
157         """
158             Reads source file SHA1 from audiobok metadata.
159         """
160         if filetype == 'mp3':
161             try:
162                 audio = id3.ID3(filepath)
163                 return [t.data.decode('utf-8') for t in audio.getall('PRIV')
164                         if t.owner == 'wolnelektury.pl?flac_sha1'][0]
165             except (mutagen.MutagenError, IndexError):
166                 return None
167         elif filetype == 'ogg':
168             try:
169                 audio = mutagen.File(filepath)
170                 return audio.get('flac_sha1', [None])[0]
171             except (mutagen.MutagenError, AttributeError, IndexError):
172                 return None
173         else:
174             return None
175
176     @property
177     def director(self):
178         return self.get_extra_info_json().get('director_name', None)
179
180     @property
181     def artist(self):
182         return self.get_extra_info_json().get('artist_name', None)
183
184     def file_url(self):
185         return self.file.url