+ @staticmethod
+ def tags_from_info(info):
+ from slughifi import slughifi
+ from sortify import sortify
+ meta_tags = []
+ categories = (('kinds', 'kind'), ('genres', 'genre'), ('authors', 'author'), ('epochs', 'epoch'))
+ for field_name, category in categories:
+ try:
+ tag_names = getattr(info, field_name)
+ except:
+ try:
+ tag_names = [getattr(info, category)]
+ except:
+ # For instance, Pictures do not have 'genre' field.
+ continue
+ for tag_name in tag_names:
+ tag_sort_key = tag_name
+ if category == 'author':
+ tag_sort_key = tag_name.last_name
+ tag_name = tag_name.readable()
+ tag, created = Tag.objects.get_or_create(slug=slughifi(tag_name), category=category)
+ if created:
+ tag.name = tag_name
+ tag.sort_key = sortify(tag_sort_key.lower())
+ tag.save()
+ meta_tags.append(tag)
+ return meta_tags
+
+
+
+def get_dynamic_path(media, filename, ext=None, maxlen=100):
+ from slughifi import slughifi
+
+ # how to put related book's slug here?
+ if not ext:
+ # BookMedia case
+ ext = media.formats[media.type].ext
+ if media is None or not media.name:
+ name = slughifi(filename.split(".")[0])
+ else:
+ name = slughifi(media.name)
+ return 'book/%s/%s.%s' % (ext, name[:maxlen-len('book/%s/.%s' % (ext, ext))-4], ext)
+
+
+# TODO: why is this hard-coded ?
+def book_upload_path(ext=None, maxlen=100):
+ return lambda *args: get_dynamic_path(*args, ext=ext, maxlen=maxlen)
+
+
+def get_customized_pdf_path(book, customizations):
+ """
+ Returns a MEDIA_ROOT relative path for a customized pdf. The name will contain a hash of customization options.
+ """
+ customizations.sort()
+ h = hash(tuple(customizations))
+
+ pdf_name = '%s-custom-%s' % (book.slug, h)
+ pdf_file = get_dynamic_path(None, pdf_name, ext='pdf')
+
+ return pdf_file
+
+
+def get_existing_customized_pdf(book):
+ """
+ Returns a list of paths to generated customized pdf of a book
+ """
+ pdf_glob = '%s-custom-' % (book.slug,)
+ pdf_glob = get_dynamic_path(None, pdf_glob, ext='pdf')
+ pdf_glob = re.sub(r"[.]([a-z0-9]+)$", "*.\\1", pdf_glob)
+ return glob(path.join(settings.MEDIA_ROOT, pdf_glob))
+
+
+class BookMedia(models.Model):
+ FileFormat = namedtuple("FileFormat", "name ext")
+ formats = SortedDict([
+ ('mp3', FileFormat(name='MP3', ext='mp3')),
+ ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
+ ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
+ ])
+ format_choices = [(k, _('%s file') % t.name)
+ for k, t in formats.items()]
+
+ type = models.CharField(_('type'), choices=format_choices, max_length="100")
+ name = models.CharField(_('name'), max_length="100")
+ file = OverwritingFileField(_('file'), upload_to=book_upload_path())
+ uploaded_at = models.DateTimeField(_('creation date'), auto_now_add=True, editable=False)
+ extra_info = JSONField(_('extra information'), default='{}', editable=False)
+ book = models.ForeignKey('Book', related_name='media')
+ source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)