Completed
Pull Request — master (#5)
by
unknown
56s
created

FileService.get_file()   A

Complexity

Conditions 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
1
2
import errno, hashlib, os, tinydb
3
4
def mkdir_p(path):
5
    try:
6
        os.makedirs(path)
7
    except OSError as exc:
8
        if exc.errno == errno.EEXIST and os.path.isdir(path):
9
            pass
10
        else:
11
            raise
12
13
class FileService:
14
    db_dir = ".browsepy/share/"
15
    db_path = db_dir + "db.json"
16
    table_name = "share"
17
18
    mkdir_p(db_dir)
19
    db = tinydb.TinyDB(db_path)
20
    share_table = db.table(table_name)
21
22
    def clear(self):
23
        self.db.purge_table(self.table_name)
24
        self.share_table = self.db.table(self.table_name)
25
26
    def add_file(self, filepath):
27
        hash = hashlib.sha256(filepath).hexdigest()
28
        existing = self.get_file(hash)
29
30
        if existing:
31
            return existing["hash"]
32
33
        self.share_table.insert({
34
            "hash": hash,
35
            "path": filepath
36
        })
37
        return hash
38
39
    def get_file(self, hash):
40
        file = tinydb.Query()
41
        results = self.share_table.search(file.hash == hash)
42
        if not results:
43
            return None
44
        else:
45
            return results[0]
46
47
    def file_read_generator(self, file):
48
        file = open(file["path"])
49
        while True:
50
            data = file.read(1024)
51
            if not data:
52
                break
53
            yield data
54