| Total Complexity | 8 |
| Total Lines | 41 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | |||
| 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 |