-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocal_storage_service.py
55 lines (47 loc) · 1.87 KB
/
local_storage_service.py
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
import os
import re
class LocalStorageService:
def __init__(self, root_dir):
self.root_dir = root_dir
def list_folders(self):
return [
{"id": f, "name": f}
for f in os.listdir(self.root_dir)
if os.path.isdir(os.path.join(self.root_dir, f))
]
def list_files(self, folder_id=None):
directory = os.path.join(self.root_dir, folder_id if folder_id else "")
files = []
for root, _, filenames in os.walk(directory):
for filename in filenames:
relative_path = os.path.relpath(
os.path.join(root, filename), self.root_dir
)
files.append({"id": relative_path, "name": filename})
return files
def search(self, query):
pattern = re.compile(query, re.IGNORECASE)
matches = []
for root, dirs, files in os.walk(self.root_dir):
for file in files:
file_path = os.path.join(root, file)
with open(file_path, "r", errors="ignore") as f:
for line_num, line in enumerate(f, 1):
if pattern.search(line):
matches.append(file)
return matches
def get_file(self, file_id):
full_path = os.path.join(self.root_dir, file_id)
with open(full_path, "rb") as f:
return f.read()
def download_media(self, file_id, buffer):
full_path = os.path.join(self.root_dir, file_id)
with open(full_path, "rb") as f:
buffer.write(f.read())
async def media_stream(self, file_id):
full_path = os.path.join(self.root_dir, file_id)
if not os.path.exists(full_path):
raise FileNotFoundError(f"File {file_id} not found")
with open(full_path, "rb") as f:
while chunk := f.read(8192):
yield chunk