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.
 
   5 from collections import OrderedDict
 
   7 from collections import namedtuple
 
   8 from django.db import models
 
   9 from django.utils.translation import ugettext_lazy as _
 
  11 from fnpdjango.utils.text.slughifi import slughifi
 
  12 from mutagen import MutagenError
 
  14 from catalogue.fields import OverwritingFileField
 
  17 def _file_upload_to(i, _n):
 
  18     return 'book/%(ext)s/%(name)s.%(ext)s' % {'ext': i.ext(), 'name': slughifi(i.name)}
 
  21 class BookMedia(models.Model):
 
  22     """Represents media attached to a book."""
 
  23     FileFormat = namedtuple("FileFormat", "name ext")
 
  24     formats = OrderedDict([
 
  25         ('mp3', FileFormat(name='MP3', ext='mp3')),
 
  26         ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
 
  27         ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
 
  29     format_choices = [(k, _('%s file' % t.name)) for k, t in formats.items()]
 
  31     type = models.CharField(_('type'), db_index=True, choices=format_choices, max_length=20)
 
  32     name = models.CharField(_('name'), max_length=512)
 
  33     file = OverwritingFileField(_('file'), max_length=600, 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)
 
  39     def __unicode__(self):
 
  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 save(self, *args, **kwargs):
 
  49         from catalogue.utils import ExistingFile, remove_zip
 
  52             old = BookMedia.objects.get(pk=self.pk)
 
  53         except BookMedia.DoesNotExist:
 
  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)
 
  60         super(BookMedia, self).save(*args, **kwargs)
 
  62         # remove the zip package for book with modified media
 
  64             remove_zip("%s_%s" % (old.book.slug, old.type))
 
  65         remove_zip("%s_%s" % (self.book.slug, self.type))
 
  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)
 
  78             Reads some metadata from the audiobook.
 
  81         from mutagen import id3
 
  83         artist_name = director_name = project = funded_by = ''
 
  84         if self.type == 'mp3':
 
  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'))
 
  90                     t.data for t in audio.getall('PRIV')
 
  91                     if t.owner == 'wolnelektury.pl?project'])
 
  92                 funded_by = ", ".join([
 
  93                     t.data for t in audio.getall('PRIV')
 
  94                     if t.owner == 'wolnelektury.pl?funded_by'])
 
  97         elif self.type == 'ogg':
 
  99                 audio = mutagen.File(self.file.path)
 
 100                 artist_name = ', '.join(audio.get('artist', []))
 
 101                 director_name = ', '.join(audio.get('conductor', []))
 
 102                 project = ", ".join(audio.get('project', []))
 
 103                 funded_by = ", ".join(audio.get('funded_by', []))
 
 104             except (MutagenError, AttributeError):
 
 108         return {'artist_name': artist_name, 'director_name': director_name,
 
 109                 'project': project, 'funded_by': funded_by}
 
 112         return self.formats[self.type].ext
 
 115     def read_source_sha1(filepath, filetype):
 
 117             Reads source file SHA1 from audiobok metadata.
 
 120         from mutagen import id3
 
 122         if filetype == 'mp3':
 
 124                 audio = id3.ID3(filepath)
 
 125                 return [t.data for t in audio.getall('PRIV')
 
 126                         if t.owner == 'wolnelektury.pl?flac_sha1'][0]
 
 129         elif filetype == 'ogg':
 
 131                 audio = mutagen.File(filepath)
 
 132                 return audio.get('flac_sha1', [None])[0]
 
 133             except (MutagenError, AttributeError):