Total Complexity | 9 |
Total Lines | 57 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 0 |
1 | #!/usr/bin/python |
||
2 | # -*- coding: utf-8 -*- |
||
3 | 1 | import html |
|
4 | 1 | import os |
|
5 | 1 | import re |
|
6 | 1 | from shutil import move |
|
7 | 1 | from typing import Generator |
|
8 | |||
9 | 1 | from saucenao.files.filter import Filter |
|
10 | |||
11 | |||
12 | 1 | class FileHandler: |
|
13 | 1 | @staticmethod |
|
14 | 1 | def get_files(directory, file_filter=None) -> Generator[str, None, None]: |
|
15 | """Get all files from given directory |
||
16 | |||
17 | :type directory: str |
||
18 | :type file_filter: Filter |
||
19 | :return: |
||
20 | """ |
||
21 | 1 | if file_filter: |
|
22 | 1 | for f in file_filter.apply(directory=directory): |
|
23 | 1 | yield f |
|
24 | else: |
||
25 | 1 | for f in os.listdir(directory): |
|
26 | 1 | if os.path.isfile(os.path.join(directory, f)): |
|
27 | 1 | yield f |
|
28 | |||
29 | 1 | @staticmethod |
|
30 | 1 | def unicode_translate(text, chars="", replacement="") -> str: |
|
31 | """Replacement for the string.maketrans function |
||
32 | |||
33 | :type text: str |
||
34 | :type chars: str |
||
35 | :type replacement: str |
||
36 | :return: |
||
37 | """ |
||
38 | 1 | for char in chars: |
|
39 | 1 | text = text.replace(char, replacement[chars.index(char)]) |
|
40 | 1 | return text |
|
41 | |||
42 | 1 | @staticmethod |
|
43 | 1 | def move_to_category(filename, category, base_directory=os.getcwd()): |
|
44 | """Move file to the sub_category folder |
||
45 | |||
46 | :type base_directory: str |
||
47 | :type filename: str |
||
48 | :type category: str |
||
49 | :return: |
||
50 | """ |
||
51 | 1 | folder = re.sub(r'["/?*:<>|]', r'', html.unescape(category)) |
|
52 | 1 | folder = os.path.join(base_directory, folder) |
|
53 | 1 | folder = os.path.abspath(FileHandler.unicode_translate(folder, "\n\t\r", " ")) |
|
54 | 1 | if not os.path.exists(folder): |
|
55 | 1 | os.makedirs(folder) |
|
56 | move(os.path.join(base_directory, filename), os.path.join(folder, filename)) |
||
57 |