fdc25cb5aa276369a393b54d2db7f47cd58d7401
[wolnelektury.git] / apps / catalogue / management / commands / savemedia.py
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.
4 #
5 import os.path
6
7 from django.core.management.base import BaseCommand
8 from django.core.files import File
9 from slughifi import slughifi
10
11 from catalogue.models import Book, BookMedia
12 from catalogue.utils import ExistingFile
13
14
15 class Command(BaseCommand):
16     help = "Saves uploaded media with a given book and a given name. If media has a source SHA1 info - matching media is replaced."
17     args = 'path slug name'
18
19     def handle(self, *args, **options):
20         from django.db import transaction
21
22         path, slug, name = args
23
24         # Start transaction management.
25         transaction.commit_unless_managed()
26         transaction.enter_transaction_management()
27         transaction.managed(True)
28
29         book = Book.objects.get(slug=slug)
30
31         root, ext = os.path.splitext(path)
32         ext = ext.lower()
33         if ext:
34             ext = ext[1:]
35             if ext == 'zip':
36                 ext = 'daisy'
37
38         source_sha1 = BookMedia.read_source_sha1(path, ext)
39         print "Source file SHA1:", source_sha1
40         try:
41             assert source_sha1
42             bm = book.media.get(type=ext, source_sha1=source_sha1)
43             print "Replacing media: %s (%s)" % (bm.name, ext)
44         except (AssertionError, BookMedia.DoesNotExist):
45             bm = BookMedia(book=book, type=ext, name=name)
46             print "Creating new media"
47         bm.file.save(slughifi(name), ExistingFile(path))
48         bm.save()
49         transaction.commit()
50         transaction.leave_transaction_management()