-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.py
More file actions
74 lines (54 loc) · 2 KB
/
backend.py
File metadata and controls
74 lines (54 loc) · 2 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
import mimetypes
import os
import shutil
try:
import magic
except ImportError:
magic = None
mime = magic.Magic(mime=True) if magic is not None else None
CATEGORY_NAMES = {
"image": "images",
"video": "videos",
"audio": "audio",
"text": "documents",
"application": "documents",
}
def cleaner(path: str) -> None:
if not path or not os.path.isdir(path):
return
clean_up(path)
def _detect_file_type(file_path: str) -> str:
if mime is not None:
detected_type = mime.from_file(file_path)
if detected_type:
return detected_type
detected_type, _ = mimetypes.guess_type(file_path)
return detected_type or "unknown"
def _folder_names(file_path: str) -> tuple[str, str]:
detected_type = _detect_file_type(file_path).lower()
category, _, subtype = detected_type.partition("/")
main_folder = CATEGORY_NAMES.get(category, "others")
sub_folder = subtype or os.path.splitext(file_path)[1].lstrip(".").lower() or "unknown"
return main_folder, sub_folder
def _unique_destination(destination_dir: str, file_name: str) -> str:
candidate_path = os.path.join(destination_dir, file_name)
if not os.path.exists(candidate_path):
return candidate_path
name, extension = os.path.splitext(file_name)
counter = 1
while True:
candidate_name = f"{name}_{counter}{extension}"
candidate_path = os.path.join(destination_dir, candidate_name)
if not os.path.exists(candidate_path):
return candidate_path
counter += 1
def clean_up(path: str) -> None:
dir_list = (
file for file in os.listdir(path) if os.path.isfile(os.path.join(path, file))
)
for file in dir_list:
source_path = os.path.join(path, file)
main_folder, sub_folder = _folder_names(source_path)
destination_dir = os.path.join(path, main_folder, sub_folder)
os.makedirs(destination_dir, exist_ok=True)
shutil.move(source_path, _unique_destination(destination_dir, file))