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