perdoo 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- perdoo/__init__.py +72 -0
- perdoo/__main__.py +256 -0
- perdoo/archives/__init__.py +49 -0
- perdoo/archives/_base.py +58 -0
- perdoo/archives/cb7.py +85 -0
- perdoo/archives/cbr.py +52 -0
- perdoo/archives/cbt.py +80 -0
- perdoo/archives/cbz.py +91 -0
- perdoo/archives/zipfile_remove.py +91 -0
- perdoo/cli/__init__.py +4 -0
- perdoo/cli/archive.py +34 -0
- perdoo/cli/settings.py +56 -0
- perdoo/console.py +67 -0
- perdoo/main.py +182 -0
- perdoo/metadata/__init__.py +50 -0
- perdoo/metadata/_base.py +48 -0
- perdoo/metadata/comic_info.py +314 -0
- perdoo/metadata/metron_info.py +389 -0
- perdoo/services/__init__.py +7 -0
- perdoo/services/_base.py +35 -0
- perdoo/services/comicvine.py +227 -0
- perdoo/services/league.py +51 -0
- perdoo/services/marvel.py +233 -0
- perdoo/services/metron.py +283 -0
- perdoo/settings.py +185 -0
- perdoo/utils.py +90 -0
- perdoo-0.4.0.dist-info/METADATA +183 -0
- perdoo-0.4.0.dist-info/RECORD +31 -0
- perdoo-0.4.0.dist-info/WHEEL +4 -0
- perdoo-0.4.0.dist-info/entry_points.txt +2 -0
- perdoo-0.4.0.dist-info/licenses/LICENSE +21 -0
perdoo/__init__.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
__all__ = [
|
|
2
|
+
"__version__",
|
|
3
|
+
"get_cache_root",
|
|
4
|
+
"get_config_root",
|
|
5
|
+
"get_data_root",
|
|
6
|
+
"get_state_root",
|
|
7
|
+
"setup_logging",
|
|
8
|
+
]
|
|
9
|
+
__version__ = "0.4.0"
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from rich.logging import RichHandler
|
|
16
|
+
from rich.traceback import install
|
|
17
|
+
|
|
18
|
+
from perdoo.console import CONSOLE
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_cache_root() -> Path:
|
|
22
|
+
cache_home = os.getenv("XDG_CACHE_HOME", default=str(Path.home() / ".cache"))
|
|
23
|
+
folder = Path(cache_home).resolve() / "perdoo"
|
|
24
|
+
folder.mkdir(exist_ok=True, parents=True)
|
|
25
|
+
return folder
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def get_config_root() -> Path:
|
|
29
|
+
config_home = os.getenv("XDG_CONFIG_HOME", default=str(Path.home() / ".config"))
|
|
30
|
+
folder = Path(config_home).resolve() / "perdoo"
|
|
31
|
+
folder.mkdir(exist_ok=True, parents=True)
|
|
32
|
+
return folder
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_data_root() -> Path:
|
|
36
|
+
data_home = os.getenv("XDG_DATA_HOME", default=str(Path.home() / ".local" / "share"))
|
|
37
|
+
folder = Path(data_home).resolve() / "perdoo"
|
|
38
|
+
folder.mkdir(exist_ok=True, parents=True)
|
|
39
|
+
return folder
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def get_state_root() -> Path:
|
|
43
|
+
data_home = os.getenv("XDG_STATE_HOME", default=str(Path.home() / ".local" / "state"))
|
|
44
|
+
folder = Path(data_home).resolve() / "perdoo"
|
|
45
|
+
folder.mkdir(exist_ok=True, parents=True)
|
|
46
|
+
return folder
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def setup_logging(debug: bool = False) -> None:
|
|
50
|
+
install(show_locals=True, max_frames=6, console=CONSOLE)
|
|
51
|
+
|
|
52
|
+
console_handler = RichHandler(
|
|
53
|
+
rich_tracebacks=True,
|
|
54
|
+
tracebacks_show_locals=True,
|
|
55
|
+
omit_repeated_times=False,
|
|
56
|
+
show_level=True,
|
|
57
|
+
show_time=False,
|
|
58
|
+
show_path=False,
|
|
59
|
+
console=CONSOLE,
|
|
60
|
+
)
|
|
61
|
+
console_handler.setLevel(logging.DEBUG if debug else logging.INFO)
|
|
62
|
+
console_handler.setFormatter(logging.Formatter("%(message)s"))
|
|
63
|
+
file_handler = logging.FileHandler(filename=get_state_root() / "perdoo.log")
|
|
64
|
+
file_handler.setLevel(logging.DEBUG)
|
|
65
|
+
logging.basicConfig(
|
|
66
|
+
format="[%(asctime)s] [%(levelname)-8s] {%(name)s} | %(message)s",
|
|
67
|
+
datefmt="%Y-%m-%d %H:%M:%S",
|
|
68
|
+
level=logging.DEBUG,
|
|
69
|
+
handlers=[console_handler, file_handler],
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
logging.getLogger("PIL").setLevel(logging.WARNING)
|
perdoo/__main__.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from datetime import date
|
|
3
|
+
from enum import Enum
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from platform import python_version
|
|
6
|
+
from typing import Annotated
|
|
7
|
+
|
|
8
|
+
from comicfn2dict import comicfn2dict
|
|
9
|
+
from typer import Argument, Context, Exit, Option, Typer
|
|
10
|
+
|
|
11
|
+
from perdoo import __version__, setup_logging
|
|
12
|
+
from perdoo.archives import CBRArchive, get_archive
|
|
13
|
+
from perdoo.cli import archive_app, settings_app
|
|
14
|
+
from perdoo.console import CONSOLE
|
|
15
|
+
from perdoo.main import (
|
|
16
|
+
clean_archive,
|
|
17
|
+
convert_file,
|
|
18
|
+
organize_file,
|
|
19
|
+
rename_file,
|
|
20
|
+
save_metadata,
|
|
21
|
+
sync_metadata,
|
|
22
|
+
)
|
|
23
|
+
from perdoo.metadata import ComicInfo, MetronInfo, get_metadata
|
|
24
|
+
from perdoo.metadata.metron_info import InformationSource
|
|
25
|
+
from perdoo.services import BaseService, Comicvine, League, Marvel, Metron
|
|
26
|
+
from perdoo.settings import Service, Services, Settings
|
|
27
|
+
from perdoo.utils import IssueSearch, Search, SeriesSearch, delete_empty_folders, list_files
|
|
28
|
+
|
|
29
|
+
app = Typer(help="CLI tool for managing comic collections and settings.")
|
|
30
|
+
app.add_typer(archive_app, name="archive")
|
|
31
|
+
app.add_typer(settings_app, name="settings")
|
|
32
|
+
LOGGER = logging.getLogger("perdoo")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class SyncOption(Enum):
|
|
36
|
+
FORCE = "Force"
|
|
37
|
+
OUTDATED = "Outdated"
|
|
38
|
+
SKIP = "Skip"
|
|
39
|
+
|
|
40
|
+
@staticmethod
|
|
41
|
+
def load(value: str) -> "SyncOption":
|
|
42
|
+
for entry in SyncOption:
|
|
43
|
+
if entry.value.replace(" ", "").casefold() == value.replace(" ", "").casefold():
|
|
44
|
+
return entry
|
|
45
|
+
raise ValueError(f"'{value}' isn't a valid SyncOption")
|
|
46
|
+
|
|
47
|
+
def __str__(self) -> str:
|
|
48
|
+
return self.value
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@app.callback(invoke_without_command=True)
|
|
52
|
+
def common(
|
|
53
|
+
ctx: Context,
|
|
54
|
+
version: Annotated[
|
|
55
|
+
bool | None, Option("--version", is_eager=True, help="Show the version and exit.")
|
|
56
|
+
] = None,
|
|
57
|
+
) -> None:
|
|
58
|
+
if ctx.invoked_subcommand:
|
|
59
|
+
return
|
|
60
|
+
if version:
|
|
61
|
+
CONSOLE.print(f"Perdoo v{__version__}")
|
|
62
|
+
raise Exit
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def get_services(settings: Services) -> dict[Service, BaseService]:
|
|
66
|
+
output = {}
|
|
67
|
+
if settings.comicvine.api_key:
|
|
68
|
+
output[Service.COMICVINE] = Comicvine(settings.comicvine)
|
|
69
|
+
if settings.league_of_comic_geeks.client_id and settings.league_of_comic_geeks.client_secret:
|
|
70
|
+
output[Service.LEAGUE_OF_COMIC_GEEKS] = League(settings.league_of_comic_geeks)
|
|
71
|
+
if settings.marvel.public_key and settings.marvel.private_key:
|
|
72
|
+
output[Service.MARVEL] = Marvel(settings.marvel)
|
|
73
|
+
if settings.metron.username and settings.metron.password:
|
|
74
|
+
output[Service.METRON] = Metron(settings.metron)
|
|
75
|
+
return output
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def get_search_details(
|
|
79
|
+
metadata: tuple[MetronInfo | None, ComicInfo | None], fallback_title: str
|
|
80
|
+
) -> Search:
|
|
81
|
+
metron_info, comic_info = metadata
|
|
82
|
+
|
|
83
|
+
if metron_info and metron_info.series and metron_info.series.name:
|
|
84
|
+
series_id = metron_info.series.id
|
|
85
|
+
source = next(iter(x.source for x in metron_info.ids if x.primary), None)
|
|
86
|
+
return Search(
|
|
87
|
+
series=SeriesSearch(
|
|
88
|
+
name=metron_info.series.name,
|
|
89
|
+
volume=metron_info.series.volume,
|
|
90
|
+
year=metron_info.series.start_year,
|
|
91
|
+
comicvine=series_id if source == InformationSource.COMIC_VINE else None,
|
|
92
|
+
league=series_id if source == InformationSource.LEAGUE_OF_COMIC_GEEKS else None,
|
|
93
|
+
marvel=series_id if source == InformationSource.MARVEL else None,
|
|
94
|
+
metron=series_id if source == InformationSource.METRON else None,
|
|
95
|
+
),
|
|
96
|
+
issue=IssueSearch(
|
|
97
|
+
number=metron_info.number,
|
|
98
|
+
comicvine=next(
|
|
99
|
+
iter(
|
|
100
|
+
x.value for x in metron_info.ids if x.source == InformationSource.COMIC_VINE
|
|
101
|
+
),
|
|
102
|
+
None,
|
|
103
|
+
),
|
|
104
|
+
league=next(
|
|
105
|
+
iter(
|
|
106
|
+
x.value
|
|
107
|
+
for x in metron_info.ids
|
|
108
|
+
if x.source == InformationSource.LEAGUE_OF_COMIC_GEEKS
|
|
109
|
+
),
|
|
110
|
+
None,
|
|
111
|
+
),
|
|
112
|
+
marvel=next(
|
|
113
|
+
iter(x.value for x in metron_info.ids if x.source == InformationSource.MARVEL),
|
|
114
|
+
None,
|
|
115
|
+
),
|
|
116
|
+
metron=next(
|
|
117
|
+
iter(x.value for x in metron_info.ids if x.source == InformationSource.METRON),
|
|
118
|
+
None,
|
|
119
|
+
),
|
|
120
|
+
),
|
|
121
|
+
)
|
|
122
|
+
if comic_info and comic_info.series:
|
|
123
|
+
return Search(
|
|
124
|
+
series=SeriesSearch(
|
|
125
|
+
name=comic_info.series,
|
|
126
|
+
volume=comic_info.volume
|
|
127
|
+
if comic_info.volume and comic_info.volume < 1900
|
|
128
|
+
else None,
|
|
129
|
+
year=comic_info.volume if comic_info.volume and comic_info.volume > 1900 else None,
|
|
130
|
+
),
|
|
131
|
+
issue=IssueSearch(number=comic_info.number),
|
|
132
|
+
)
|
|
133
|
+
series_name = comicfn2dict(fallback_title).get("series", fallback_title).replace("-", " ")
|
|
134
|
+
return Search(series=SeriesSearch(name=series_name), issue=IssueSearch())
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@app.command(name="import", help="Import comics into your collection using Perdoo.")
|
|
138
|
+
def run(
|
|
139
|
+
target: Annotated[
|
|
140
|
+
Path,
|
|
141
|
+
Argument(
|
|
142
|
+
exists=True, help="Import comics from the specified file/folder.", show_default=False
|
|
143
|
+
),
|
|
144
|
+
],
|
|
145
|
+
skip_convert: Annotated[
|
|
146
|
+
bool, Option("--skip-convert", help="Skip converting comics to the configured format.")
|
|
147
|
+
] = False,
|
|
148
|
+
sync: Annotated[
|
|
149
|
+
SyncOption,
|
|
150
|
+
Option(
|
|
151
|
+
"--sync",
|
|
152
|
+
"-s",
|
|
153
|
+
case_sensitive=False,
|
|
154
|
+
help="Sync ComicInfo/MetronInfo with online services.",
|
|
155
|
+
),
|
|
156
|
+
] = SyncOption.OUTDATED.value,
|
|
157
|
+
skip_clean: Annotated[
|
|
158
|
+
bool,
|
|
159
|
+
Option(
|
|
160
|
+
"--skip-clean",
|
|
161
|
+
help="Skip removing any files not listed in the 'image_extensions' setting.",
|
|
162
|
+
),
|
|
163
|
+
] = False,
|
|
164
|
+
skip_rename: Annotated[
|
|
165
|
+
bool,
|
|
166
|
+
Option("--skip-rename", help="Skip renaming comics based on their ComicInfo/MetronInfo."),
|
|
167
|
+
] = False,
|
|
168
|
+
skip_organize: Annotated[
|
|
169
|
+
bool,
|
|
170
|
+
Option("--skip-organize", help="Skip organize/moving comics to appropriate directories."),
|
|
171
|
+
] = False,
|
|
172
|
+
debug: Annotated[
|
|
173
|
+
bool, Option("--debug", help="Enable debug mode to show extra information.")
|
|
174
|
+
] = False,
|
|
175
|
+
) -> None:
|
|
176
|
+
setup_logging(debug=debug)
|
|
177
|
+
LOGGER.info("Python v%s", python_version())
|
|
178
|
+
LOGGER.info("Perdoo v%s", __version__)
|
|
179
|
+
|
|
180
|
+
settings = Settings.load()
|
|
181
|
+
settings.save()
|
|
182
|
+
if debug:
|
|
183
|
+
Settings.display(
|
|
184
|
+
extras={
|
|
185
|
+
"target": target,
|
|
186
|
+
"flags.skip-convert": skip_convert,
|
|
187
|
+
"flags.sync": sync,
|
|
188
|
+
"flags.skip-clean": skip_clean,
|
|
189
|
+
"flags.skip-rename": skip_rename,
|
|
190
|
+
"flags.skip-organize": skip_organize,
|
|
191
|
+
}
|
|
192
|
+
)
|
|
193
|
+
services = get_services(settings=settings.services)
|
|
194
|
+
if not services and sync != SyncOption.SKIP:
|
|
195
|
+
LOGGER.warning("No external services configured")
|
|
196
|
+
sync = SyncOption.SKIP
|
|
197
|
+
|
|
198
|
+
entries = []
|
|
199
|
+
for file in list_files(target) if target.is_dir() else [target]:
|
|
200
|
+
try:
|
|
201
|
+
entries.append(get_archive(file))
|
|
202
|
+
except NotImplementedError as nie: # noqa: PERF203
|
|
203
|
+
LOGGER.error("%s, Skipping", nie) # noqa: TRY400
|
|
204
|
+
|
|
205
|
+
for index, entry in enumerate(entries):
|
|
206
|
+
CONSOLE.rule(
|
|
207
|
+
f"[{index + 1}/{len(entries)}] Importing {entry.path.name}",
|
|
208
|
+
align="left",
|
|
209
|
+
style="subtitle",
|
|
210
|
+
)
|
|
211
|
+
if not skip_convert:
|
|
212
|
+
with CONSOLE.status(
|
|
213
|
+
f"Converting to '{settings.output.format}'", spinner="simpleDotsScrolling"
|
|
214
|
+
):
|
|
215
|
+
entry = convert_file(entry, output_format=settings.output.format)
|
|
216
|
+
if entry is None or isinstance(entry, CBRArchive):
|
|
217
|
+
continue
|
|
218
|
+
|
|
219
|
+
metadata = get_metadata(archive=entry, debug=debug)
|
|
220
|
+
|
|
221
|
+
if sync != SyncOption.SKIP:
|
|
222
|
+
search = get_search_details(metadata=metadata, fallback_title=entry.path.stem)
|
|
223
|
+
last_modified = date(1900, 1, 1)
|
|
224
|
+
if sync == SyncOption.OUTDATED:
|
|
225
|
+
metron_info, _ = metadata
|
|
226
|
+
if metron_info and metron_info.last_modified:
|
|
227
|
+
last_modified = metron_info.last_modified.date()
|
|
228
|
+
if (date.today() - last_modified).days >= 28:
|
|
229
|
+
metadata = sync_metadata(search=search, services=services, settings=settings)
|
|
230
|
+
else:
|
|
231
|
+
LOGGER.info("Metadata up-to-date")
|
|
232
|
+
|
|
233
|
+
if not skip_clean:
|
|
234
|
+
with CONSOLE.status("Cleaning Archive", spinner="simpleDotsScrolling"):
|
|
235
|
+
clean_archive(entry=entry, settings=settings)
|
|
236
|
+
save_metadata(entry=entry, metadata=metadata, settings=settings)
|
|
237
|
+
|
|
238
|
+
if not skip_rename:
|
|
239
|
+
with CONSOLE.status("Renaming to match metadata", spinner="simpleDotsScrolling"):
|
|
240
|
+
rename_file(entry=entry, metadata=metadata, settings=settings)
|
|
241
|
+
|
|
242
|
+
if not skip_organize:
|
|
243
|
+
with CONSOLE.status("Organizing based on metadata", spinner="simpleDotsScrolling"):
|
|
244
|
+
organize_file(
|
|
245
|
+
entry=entry,
|
|
246
|
+
metadata=metadata,
|
|
247
|
+
root=settings.output.folder,
|
|
248
|
+
target=target.parent,
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
with CONSOLE.status("Cleaning up empty folders"):
|
|
252
|
+
delete_empty_folders(folder=target)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
if __name__ == "__main__":
|
|
256
|
+
app(prog_name="Perdoo")
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
__all__ = [
|
|
2
|
+
"BaseArchive",
|
|
3
|
+
"CB7Archive",
|
|
4
|
+
"CBRArchive",
|
|
5
|
+
"CBTArchive",
|
|
6
|
+
"CBZArchive",
|
|
7
|
+
"get_archive",
|
|
8
|
+
"get_archive_class",
|
|
9
|
+
]
|
|
10
|
+
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from tarfile import is_tarfile
|
|
13
|
+
from zipfile import is_zipfile
|
|
14
|
+
|
|
15
|
+
from rarfile import is_rarfile
|
|
16
|
+
|
|
17
|
+
from perdoo.archives._base import BaseArchive
|
|
18
|
+
from perdoo.archives.cb7 import CB7Archive
|
|
19
|
+
from perdoo.archives.cbr import CBRArchive
|
|
20
|
+
from perdoo.archives.cbt import CBTArchive
|
|
21
|
+
from perdoo.archives.cbz import CBZArchive
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
from py7zr import is_7zfile
|
|
25
|
+
|
|
26
|
+
py7zr_loaded = True
|
|
27
|
+
except ImportError:
|
|
28
|
+
py7zr_loaded = False
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def get_archive(path: Path) -> BaseArchive:
|
|
32
|
+
if is_zipfile(path):
|
|
33
|
+
return CBZArchive(path=path)
|
|
34
|
+
if is_rarfile(path):
|
|
35
|
+
return CBRArchive(path=path)
|
|
36
|
+
if is_tarfile(path):
|
|
37
|
+
return CBTArchive(path=path)
|
|
38
|
+
if py7zr_loaded and is_7zfile:
|
|
39
|
+
return CB7Archive(path=path)
|
|
40
|
+
raise NotImplementedError(f"{path.name} is an unsupported archive")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def get_archive_class(extension: str) -> type[BaseArchive]:
|
|
44
|
+
archive_types = {"cbz": CBZArchive, "cbr": CBRArchive, "cbt": CBTArchive}
|
|
45
|
+
if extension == "cb7" and py7zr_loaded:
|
|
46
|
+
return CB7Archive
|
|
47
|
+
if extension in archive_types:
|
|
48
|
+
return archive_types[extension]
|
|
49
|
+
raise NotImplementedError(f"{extension} is an unsupported archive")
|
perdoo/archives/_base.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
__all__ = ["BaseArchive"]
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from tempfile import TemporaryDirectory
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
from perdoo.utils import list_files
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class BaseArchive(ABC):
|
|
12
|
+
def __init__(self, path: Path):
|
|
13
|
+
self.path = path
|
|
14
|
+
|
|
15
|
+
@abstractmethod
|
|
16
|
+
def list_filenames(self) -> list[str]: ...
|
|
17
|
+
|
|
18
|
+
@abstractmethod
|
|
19
|
+
def read_file(self, filename: str) -> bytes: ...
|
|
20
|
+
|
|
21
|
+
def remove_file(self, filename: str) -> bool:
|
|
22
|
+
if filename not in self.list_filenames():
|
|
23
|
+
return True
|
|
24
|
+
with TemporaryDirectory() as temp_str:
|
|
25
|
+
temp_folder = Path(temp_str)
|
|
26
|
+
if not self.extract_files(destination=temp_folder):
|
|
27
|
+
return False
|
|
28
|
+
(temp_folder / filename).unlink(missing_ok=True)
|
|
29
|
+
return (
|
|
30
|
+
self.archive_files(
|
|
31
|
+
src=temp_folder, output_name=self.path.stem, files=list_files(temp_folder)
|
|
32
|
+
)
|
|
33
|
+
is not None
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def write_file(self, filename: str, data: str) -> bool:
|
|
37
|
+
with TemporaryDirectory() as temp_str:
|
|
38
|
+
temp_folder = Path(temp_str)
|
|
39
|
+
if not self.extract_files(destination=temp_folder):
|
|
40
|
+
return False
|
|
41
|
+
(temp_folder / filename).write_text(data)
|
|
42
|
+
return (
|
|
43
|
+
self.archive_files(
|
|
44
|
+
src=temp_folder, output_name=self.path.stem, files=list_files(temp_folder)
|
|
45
|
+
)
|
|
46
|
+
is not None
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
@abstractmethod
|
|
50
|
+
def extract_files(self, destination: Path) -> bool: ...
|
|
51
|
+
|
|
52
|
+
@classmethod
|
|
53
|
+
@abstractmethod
|
|
54
|
+
def archive_files(cls, src: Path, output_name: str, files: list[Path]) -> Path | None: ...
|
|
55
|
+
|
|
56
|
+
@staticmethod
|
|
57
|
+
@abstractmethod
|
|
58
|
+
def convert(old_archive: "BaseArchive") -> Optional["BaseArchive"]: ...
|
perdoo/archives/cb7.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
__all__ = ["CB7Archive"]
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import shutil
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from tempfile import TemporaryDirectory
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
from perdoo.archives._base import BaseArchive
|
|
10
|
+
from perdoo.utils import list_files
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
import py7zr
|
|
14
|
+
|
|
15
|
+
py7zr_loaded = True
|
|
16
|
+
except ImportError:
|
|
17
|
+
py7zr_loaded = False
|
|
18
|
+
|
|
19
|
+
LOGGER = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CB7Archive(BaseArchive):
|
|
23
|
+
def __init__(self, path: Path):
|
|
24
|
+
if not py7zr_loaded:
|
|
25
|
+
raise ImportError("Install Perdoo with the cb7 dependency group to use CB7 files.")
|
|
26
|
+
super().__init__(path=path)
|
|
27
|
+
|
|
28
|
+
def list_filenames(self) -> list[str]:
|
|
29
|
+
try:
|
|
30
|
+
with py7zr.SevenZipFile(self.path, "r") as archive:
|
|
31
|
+
return archive.getnames()
|
|
32
|
+
except py7zr.Bad7zFile:
|
|
33
|
+
LOGGER.exception("Unable to read %s", self.path.name)
|
|
34
|
+
return []
|
|
35
|
+
|
|
36
|
+
def read_file(self, filename: str) -> bytes:
|
|
37
|
+
try:
|
|
38
|
+
with py7zr.SevenZipFile(self.path, "r") as archive, archive.open(filename) as file:
|
|
39
|
+
return file.read()
|
|
40
|
+
except (py7zr.Bad7zFile, KeyError):
|
|
41
|
+
LOGGER.exception("Unable to read %s", self.path.name)
|
|
42
|
+
return b""
|
|
43
|
+
|
|
44
|
+
def extract_files(self, destination: Path) -> bool:
|
|
45
|
+
try:
|
|
46
|
+
with py7zr.SevenZipFile(self.path, "r") as archive:
|
|
47
|
+
archive.extractall(path=destination)
|
|
48
|
+
return True
|
|
49
|
+
except py7zr.Bad7zFile:
|
|
50
|
+
LOGGER.exception("")
|
|
51
|
+
return False
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def archive_files(cls, src: Path, output_name: str, files: list[Path]) -> Path | None:
|
|
55
|
+
if not py7zr_loaded:
|
|
56
|
+
raise ImportError("Install Perdoo with the cb7 dependency group to use CB7 files.")
|
|
57
|
+
|
|
58
|
+
output_file = src.parent / f"{output_name}.cb7"
|
|
59
|
+
try:
|
|
60
|
+
with py7zr.SevenZipFile(output_file, "w") as archive:
|
|
61
|
+
for file in files:
|
|
62
|
+
archive.write(file, arcname=file.name)
|
|
63
|
+
return output_file
|
|
64
|
+
except py7zr.Bad7zFile:
|
|
65
|
+
LOGGER.exception("")
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
@staticmethod
|
|
69
|
+
def convert(old_archive: BaseArchive) -> Optional["CB7Archive"]:
|
|
70
|
+
if not py7zr_loaded:
|
|
71
|
+
raise ImportError("Install Perdoo with the cb7 dependency group to use CB7 files.")
|
|
72
|
+
|
|
73
|
+
with TemporaryDirectory(prefix=f"{old_archive.path.stem}_") as temp_str:
|
|
74
|
+
temp_folder = Path(temp_str)
|
|
75
|
+
if not old_archive.extract_files(destination=temp_folder):
|
|
76
|
+
return None
|
|
77
|
+
archive_file = CB7Archive.archive_files(
|
|
78
|
+
src=temp_folder, output_name=old_archive.path.stem, files=list_files(temp_folder)
|
|
79
|
+
)
|
|
80
|
+
if not archive_file:
|
|
81
|
+
return None
|
|
82
|
+
new_file = old_archive.path.with_suffix(".cb7")
|
|
83
|
+
old_archive.path.unlink(missing_ok=True)
|
|
84
|
+
shutil.move(archive_file, new_file)
|
|
85
|
+
return CB7Archive(path=new_file)
|
perdoo/archives/cbr.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
__all__ = ["CBRArchive"]
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
from rarfile import RarExecError, RarFile
|
|
8
|
+
|
|
9
|
+
from perdoo.archives._base import BaseArchive
|
|
10
|
+
|
|
11
|
+
LOGGER = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class CBRArchive(BaseArchive):
|
|
15
|
+
def list_filenames(self) -> list[str]:
|
|
16
|
+
try:
|
|
17
|
+
with RarFile(self.path) as stream:
|
|
18
|
+
return stream.namelist()
|
|
19
|
+
except RarExecError:
|
|
20
|
+
LOGGER.exception("Unable to read %s", self.path.name)
|
|
21
|
+
return []
|
|
22
|
+
|
|
23
|
+
def read_file(self, filename: str) -> bytes:
|
|
24
|
+
try:
|
|
25
|
+
with RarFile(self.path) as stream:
|
|
26
|
+
return stream.read(filename)
|
|
27
|
+
except RarExecError:
|
|
28
|
+
LOGGER.exception("Unable to read %s", self.path.name)
|
|
29
|
+
return b""
|
|
30
|
+
|
|
31
|
+
def remove_file(self, filename: str) -> bool:
|
|
32
|
+
raise NotImplementedError("Unable to remove a file from a CBR archive.")
|
|
33
|
+
|
|
34
|
+
def write_file(self, filename: str, data: str) -> bool:
|
|
35
|
+
raise NotImplementedError("Unable to write a file to a CBR archive.")
|
|
36
|
+
|
|
37
|
+
def extract_files(self, destination: Path) -> bool:
|
|
38
|
+
try:
|
|
39
|
+
with RarFile(self.path, "r") as stream:
|
|
40
|
+
stream.extractall(path=destination)
|
|
41
|
+
return True
|
|
42
|
+
except RarExecError:
|
|
43
|
+
LOGGER.exception("")
|
|
44
|
+
return False
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def archive_files(cls, src: Path, output_name: str, files: list[Path]) -> Path | None:
|
|
48
|
+
raise NotImplementedError("Unable to create a CBR archive.")
|
|
49
|
+
|
|
50
|
+
@staticmethod
|
|
51
|
+
def convert(old_archive: BaseArchive) -> Optional["CBRArchive"]:
|
|
52
|
+
raise NotImplementedError("Unable to convert an archive to CBR.")
|
perdoo/archives/cbt.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
__all__ = ["CBTArchive"]
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import shutil
|
|
5
|
+
import tarfile
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from tempfile import TemporaryDirectory
|
|
8
|
+
from typing import Optional
|
|
9
|
+
|
|
10
|
+
from perdoo.archives._base import BaseArchive
|
|
11
|
+
from perdoo.utils import list_files
|
|
12
|
+
|
|
13
|
+
LOGGER = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class CBTArchive(BaseArchive):
|
|
17
|
+
def list_filenames(self) -> list[str]:
|
|
18
|
+
try:
|
|
19
|
+
with tarfile.open(self.path, "r") as tar:
|
|
20
|
+
return tar.getnames()
|
|
21
|
+
except tarfile.ReadError:
|
|
22
|
+
LOGGER.exception("Unable to read %s", self.path.name)
|
|
23
|
+
return []
|
|
24
|
+
|
|
25
|
+
def read_file(self, filename: str) -> bytes:
|
|
26
|
+
try:
|
|
27
|
+
with tarfile.open(self.path, "r") as tar:
|
|
28
|
+
return tar.extractfile(filename).read()
|
|
29
|
+
except (tarfile.ReadError, KeyError):
|
|
30
|
+
LOGGER.exception("Unable to read %s", self.path.name)
|
|
31
|
+
return b""
|
|
32
|
+
|
|
33
|
+
def extract_files(self, destination: Path) -> bool:
|
|
34
|
+
try:
|
|
35
|
+
with tarfile.open(self.path, "r") as tar:
|
|
36
|
+
for member in tar.getmembers():
|
|
37
|
+
# Check for path traversal attack
|
|
38
|
+
if (
|
|
39
|
+
member.islnk()
|
|
40
|
+
or member.issym()
|
|
41
|
+
or ".." in member.name
|
|
42
|
+
or member.name.startswith("/")
|
|
43
|
+
):
|
|
44
|
+
LOGGER.warning(
|
|
45
|
+
"Potential path traversal attack detected in %s", self.path.name
|
|
46
|
+
)
|
|
47
|
+
return False
|
|
48
|
+
tar.extract(member, path=destination)
|
|
49
|
+
return True
|
|
50
|
+
except tarfile.ReadError:
|
|
51
|
+
LOGGER.exception("")
|
|
52
|
+
return False
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def archive_files(cls, src: Path, output_name: str, files: list[Path]) -> Path | None:
|
|
56
|
+
output_file = src.parent / f"{output_name}.cbt"
|
|
57
|
+
try:
|
|
58
|
+
with tarfile.open(output_file, "w:gz") as tar:
|
|
59
|
+
for file in files:
|
|
60
|
+
tar.add(file, arcname=file.name)
|
|
61
|
+
return output_file
|
|
62
|
+
except tarfile.CompressionError:
|
|
63
|
+
LOGGER.exception("")
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
@staticmethod
|
|
67
|
+
def convert(old_archive: BaseArchive) -> Optional["CBTArchive"]:
|
|
68
|
+
with TemporaryDirectory(prefix=f"{old_archive.path.stem}_") as temp_str:
|
|
69
|
+
temp_folder = Path(temp_str)
|
|
70
|
+
if not old_archive.extract_files(destination=temp_folder):
|
|
71
|
+
return None
|
|
72
|
+
archive_file = CBTArchive.archive_files(
|
|
73
|
+
src=temp_folder, output_name=old_archive.path.stem, files=list_files(temp_folder)
|
|
74
|
+
)
|
|
75
|
+
if not archive_file:
|
|
76
|
+
return None
|
|
77
|
+
new_file = old_archive.path.with_suffix(".cbt")
|
|
78
|
+
old_archive.path.unlink(missing_ok=True)
|
|
79
|
+
shutil.move(archive_file, new_file)
|
|
80
|
+
return CBTArchive(path=new_file)
|