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