080e70770500b1263f450ede15188fa23700f1f5
[redakcja.git] / apps / dvcs / storage.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of MIL/PEER, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from __future__ import unicode_literals
7
8 from django.core.files.base import ContentFile
9 from django.core.files.storage import FileSystemStorage
10
11 try:
12     from gzip import compress, decompress
13 except ImportError:
14     # Python < 3.2
15     from gzip import GzipFile
16     from StringIO import StringIO
17
18     def compress(data):
19         compressed = StringIO()
20         GzipFile(fileobj=compressed, mode="wb").write(data)
21         return compressed.getvalue()
22
23     def decompress(data):
24         return GzipFile(fileobj=StringIO(data)).read()
25
26
27 class GzipFileSystemStorage(FileSystemStorage):
28     def _open(self, name, mode='rb'):
29         """TODO: This is good for reading; what about writing?"""
30         f = open(self.path(name), 'rb')
31         text = f.read()
32         f.close()
33         return ContentFile(decompress(text))
34
35     def _save(self, name, content):
36         content = ContentFile(compress(content.read()))
37         return super(GzipFileSystemStorage, self)._save(name, content)
38
39     def get_available_name(self, name):
40         if self.exists(name):
41             self.delete(name)
42         return name