Cache media file size. Reorganize uploading. Remove some unused code.
[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
12
13 def _file_upload_to(i, _n):
14     name = i.book.slug
15     if i.index:
16         name += f'_{i.index:03d}'
17     if i.part_name:
18         name += f'_' + slugify(i.part_name)
19     ext = i.ext()
20     return f'book/{ext}/{name}.{ext}'
21
22
23 def get_storage():
24     return storages['bookmedia']
25
26
27 class BookMedia(models.Model):
28     """Represents media attached to a book."""
29     FileFormat = namedtuple("FileFormat", "name ext")
30     formats = OrderedDict([
31         ('mp3', FileFormat(name='MP3', ext='mp3')),
32         ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
33         ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
34         ('audio.epub', FileFormat(name='EPUB+audio', ext='audio.epub')),
35         ('sync', FileFormat(name='sync', ext='sync.txt')),
36     ])
37     format_choices = [(k, 'plik %s' % t.name) for k, t in formats.items()]
38
39     type = models.CharField('typ', db_index=True, choices=format_choices, max_length=20)
40     name = models.CharField('nazwa', max_length=512)
41     part_name = models.CharField('nazwa części', default='', blank=True, max_length=512)
42     index = models.IntegerField('indeks', default=0)
43     file = models.FileField('plik', max_length=600, upload_to=_file_upload_to, storage=get_storage)
44     file_size = models.IntegerField(null=True, blank=True)
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 set_file(self, content, parts_count=None):
77         if not parts_count:
78             parts_count = 1 + type(self).objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
79         if parts_count == 1:
80             self.name = self.book.pretty_title()
81         else:
82             no = ('%02d' if parts_count < 100 else '%03d') % self.index
83             self.name = '%s. %s' % (no, self.book.pretty_title())
84             if self.part_name:
85                 self.name += ', ' + self.part_name
86
87         if self.type in ('mp3', 'ogg'):
88             try:
89                 audio = mutagen.File(content)
90                 self.duration = audio.info.length
91             except (mutagen.MutagenError, AttributeError):
92                 self.extra_info = '{}'
93                 self.duration = None
94                 self.source_sha1 = None
95             else:
96                 self.extra_info = json.dumps(
97                     self.read_meta(audio, self.type))
98                 self.source_sha1 = self.read_source_sha1(audio, self.type)
99         self.file_size = content.size
100         self.file.save(None, content)
101         self.book.update_narrators()
102         self.book.update_has_audio()
103
104     @staticmethod
105     def read_meta(audio, file_type):
106         """
107             Reads some metadata from the audiobook.
108         """
109         tags = audio.tags
110         if not tags:
111             return {}
112         artist_name = director_name = project = funded_by = license = ''
113         if file_type == 'mp3':
114             artist_name = ', '.join(', '.join(tag.text) for tag in tags.getall('TPE1'))
115             director_name = ', '.join(', '.join(tag.text) for tag in tags.getall('TPE3'))
116             license = ', '.join(tag.url for tag in tags.getall('WCOP'))
117             project = ", ".join([
118                 t.data.decode('utf-8') for t in tags.getall('PRIV')
119                 if t.owner == 'wolnelektury.pl?project'])
120             funded_by = ", ".join([
121                 t.data.decode('utf-8') for t in tags.getall('PRIV')
122                 if t.owner == 'wolnelektury.pl?funded_by'])
123         elif file_type == 'ogg':
124             artist_name = ', '.join(tags.get('artist', []))
125             director_name = ', '.join(tags.get('conductor', []))
126             license = ', '.join(tags.get('license', []))
127             project = ", ".join(tags.get('project', []))
128             funded_by = ", ".join(tags.get('funded_by', []))
129         else:
130             return {}
131         return {'artist_name': artist_name, 'director_name': director_name,
132                 'project': project, 'funded_by': funded_by, 'license': license}
133
134     def ext(self):
135         return self.formats[self.type].ext
136
137     @staticmethod
138     def read_source_sha1(audio, filetype):
139         """
140             Reads source file SHA1 from audiobok metadata.
141         """
142         if not audio.tags:
143             return None
144         if filetype == 'mp3':
145             try:
146                 return [t.data.decode('utf-8') for t in audio.tags.getall('PRIV')
147                         if t.owner == 'wolnelektury.pl?flac_sha1'][0]
148             except IndexError:
149                 return None
150         elif filetype == 'ogg':
151             try:
152                 return audio.tags.get('flac_sha1', [None])[0]
153             except IndexError:
154                 return None
155         else:
156             return None
157
158     @property
159     def director(self):
160         return self.get_extra_info_json().get('director_name', None)
161
162     @property
163     def artist(self):
164         return self.get_extra_info_json().get('artist_name', None)
165
166     def file_url(self):
167         return self.file.url