summaryrefslogtreecommitdiff
path: root/fbin/file_storage/filesystem.py
blob: 1259002145dfb74a172dd4e708665d19354bd602 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import contextlib
import os
import tempfile

from .base import BaseStorage

class Storage(BaseStorage):
    def __init__(self, app):
        super().__init__(app)
        os.makedirs(self.app.config['FILE_DIRECTORY'], exist_ok=True)
        os.makedirs(self.app.config['THUMB_DIRECTORY'], exist_ok=True)

    def store_file(self, uploaded_file, file_hash, user, ip):
        size = uploaded_file.content_length
        if hasattr(uploaded_file.stream, 'file'):
            temp = None
            temp_path = uploaded_file.stream.name
        else:
            temp = tempfile.NamedTemporaryFile(prefix='upload_', dir=self.app.config['FILE_DIRECTORY'], delete=False)
            uploaded_file.save(temp.file)
            temp_path = temp.name
            size = os.path.getsize(temp_path)
        try:
            new_file = self.add_file(file_hash, uploaded_file.filename, size, user, ip)
            os.rename(temp_path, new_file.get_path())
            return new_file
        except:
            os.unlink(temp.name)
            raise
        finally:
            if self.app.config.get('DESTINATION_MODE'):
                os.chmod(new_file.get_path(), self.app.config.get('DESTINATION_MODE'))

    def get_file(self, f):
        path = f.get_path()
        if not os.path.exists(path):
            return
        return path

    def delete_file(self, f):
        path = f.get_path()
        if os.path.exists(path):
            os.unlink(path)

    @contextlib.contextmanager
    def temp_file(self, f):
        with open(f.get_path(), 'rb') as f:
            yield f

    def get_thumbnail(self, f):
        path = f.get_thumb_path()
        if not os.path.exists(path):
            return
        return path

    def store_thumbnail(self, f, stream):
        path = f.get_thumb_path()
        with open(path, 'wb') as f:
            buf = stream.read(1024*10)
            while buf:
                f.write(buf)
                buf = stream.read(1024*10)