1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
 
   2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 
   4 from collections import OrderedDict
 
   6 from collections import namedtuple
 
   7 from django.db import models
 
   8 from django.utils.translation import ugettext_lazy as _
 
   9 from slugify import slugify
 
  10 from mutagen import MutagenError
 
  12 from catalogue.fields import OverwriteStorage
 
  15 def _file_upload_to(i, _n):
 
  16     return 'book/%(ext)s/%(name)s.%(ext)s' % {'ext': i.ext(), 'name': slugify(i.name)}
 
  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')),
 
  27     format_choices = [(k, _('%s file' % t.name)) for k, t in formats.items()]
 
  29     type = models.CharField(_('type'), db_index=True, choices=format_choices, max_length=20)
 
  30     name = models.CharField(_('name'), max_length=512)
 
  31     part_name = models.CharField(_('part name'), default='', blank=True, max_length=512)
 
  32     index = models.IntegerField(_('index'), default=0)
 
  33     file = models.FileField(_('file'), max_length=600, upload_to=_file_upload_to, storage=OverwriteStorage())
 
  34     uploaded_at = models.DateTimeField(_('creation date'), auto_now_add=True, editable=False, db_index=True)
 
  35     extra_info = models.TextField(_('extra information'), default='{}', editable=False)
 
  36     book = models.ForeignKey('Book', models.CASCADE, related_name='media')
 
  37     source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
 
  40         return "%s (%s)" % (self.name, self.file.name.split("/")[-1])
 
  43         ordering = ('type', 'name')
 
  44         verbose_name = _('book media')
 
  45         verbose_name_plural = _('book media')
 
  46         app_label = 'catalogue'
 
  48     def get_extra_info_json(self):
 
  49         return json.loads(self.extra_info or '{}')
 
  51     def save(self, parts_count=None, *args, **kwargs):
 
  52         from catalogue.utils import ExistingFile, remove_zip
 
  55             parts_count = 1 + BookMedia.objects.filter(book=self.book, type=self.type).exclude(pk=self.pk).count()
 
  57             self.name = self.book.pretty_title()
 
  59             no = ('%02d' if parts_count < 100 else '%03d') % self.index
 
  60             self.name = '%s. %s' % (no, self.book.pretty_title())
 
  62                 self.name += ', ' + self.part_name
 
  65             old = BookMedia.objects.get(pk=self.pk)
 
  66         except BookMedia.DoesNotExist:
 
  69             # if name changed, change the file name, too
 
  70             if slugify(self.name) != slugify(old.name):
 
  71                 self.file.save(None, ExistingFile(self.file.path), save=False)
 
  73         super(BookMedia, self).save(*args, **kwargs)
 
  75         # remove the zip package for book with modified media
 
  77             remove_zip("%s_%s" % (old.book.slug, old.type))
 
  78         remove_zip("%s_%s" % (self.book.slug, self.type))
 
  80         extra_info = self.get_extra_info_json()
 
  81         extra_info.update(self.read_meta())
 
  82         self.extra_info = json.dumps(extra_info)
 
  83         self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
 
  84         return super(BookMedia, self).save(*args, **kwargs)
 
  88             Reads some metadata from the audiobook.
 
  91         from mutagen import id3
 
  93         artist_name = director_name = project = funded_by = license = ''
 
  94         if self.type == 'mp3':
 
  96                 audio = id3.ID3(self.file.path)
 
  97                 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
 
  98                 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
 
  99                 license = ', '.join(tag.url for tag in audio.getall('WCOP'))
 
 100                 project = ", ".join([
 
 101                     t.data.decode('utf-8') for t in audio.getall('PRIV')
 
 102                     if t.owner == 'wolnelektury.pl?project'])
 
 103                 funded_by = ", ".join([
 
 104                     t.data.decode('utf-8') for t in audio.getall('PRIV')
 
 105                     if t.owner == 'wolnelektury.pl?funded_by'])
 
 108         elif self.type == 'ogg':
 
 110                 audio = mutagen.File(self.file.path)
 
 111                 artist_name = ', '.join(audio.get('artist', []))
 
 112                 director_name = ', '.join(audio.get('conductor', []))
 
 113                 license = ', '.join(audio.get('license', []))
 
 114                 project = ", ".join(audio.get('project', []))
 
 115                 funded_by = ", ".join(audio.get('funded_by', []))
 
 116             except (MutagenError, AttributeError):
 
 120         return {'artist_name': artist_name, 'director_name': director_name,
 
 121                 'project': project, 'funded_by': funded_by, 'license': license}
 
 124         return self.formats[self.type].ext
 
 127     def read_source_sha1(filepath, filetype):
 
 129             Reads source file SHA1 from audiobok metadata.
 
 132         from mutagen import id3
 
 134         if filetype == 'mp3':
 
 136                 audio = id3.ID3(filepath)
 
 137                 return [t.data.decode('utf-8') for t in audio.getall('PRIV')
 
 138                         if t.owner == 'wolnelektury.pl?flac_sha1'][0]
 
 139             except (MutagenError, IndexError):
 
 141         elif filetype == 'ogg':
 
 143                 audio = mutagen.File(filepath)
 
 144                 return audio.get('flac_sha1', [None])[0]
 
 145             except (MutagenError, AttributeError, IndexError):
 
 152         return self.get_extra_info_json().get('director_name', None)
 
 156         return self.get_extra_info_json().get('artist_name', None)