-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprocess.py
More file actions
370 lines (326 loc) · 12.3 KB
/
process.py
File metadata and controls
370 lines (326 loc) · 12.3 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import logging
from datetime import date
from enum import Enum
from pathlib import Path
from platform import python_version
from typing import Annotated
from comicfn2dict import comicfn2dict
from typer import Argument, Option
from perdoo import __version__, get_cache_root, setup_logging
from perdoo.cli._typer import app
from perdoo.comic import Comic
from perdoo.comic.archives import ArchiveSession
from perdoo.comic.errors import ComicArchiveError, ComicMetadataError
from perdoo.comic.metadata import ComicInfo, MetronInfo
from perdoo.comic.metadata.metron_info import Id, InformationSource
from perdoo.console import CONSOLE
from perdoo.services import BaseService, Comicvine, Metron
from perdoo.settings import Naming, Output, Service, Services, Settings
from perdoo.utils import (
IssueSearch,
Search,
SeriesSearch,
delete_empty_folders,
list_files,
recursive_delete,
)
LOGGER = logging.getLogger(__name__)
class SyncOption(str, Enum):
FORCE = "Force"
OUTDATED = "Outdated"
SKIP = "Skip"
def get_services(settings: Services) -> dict[Service, BaseService]:
output = {}
if settings.comicvine.api_key:
output[Service.COMICVINE] = Comicvine(api_key=settings.comicvine.api_key)
if settings.metron.username and settings.metron.password:
output[Service.METRON] = Metron(
username=settings.metron.username, password=settings.metron.password
)
return output
def setup_environment(
clean_cache: bool, sync: SyncOption, settings: Settings, debug: bool = False
) -> tuple[dict[Service, BaseService], SyncOption]:
setup_logging(debug=debug)
LOGGER.info("Python v%s", python_version())
LOGGER.info("Perdoo v%s", __version__)
if clean_cache:
LOGGER.info("Cleaning Cache")
recursive_delete(path=get_cache_root())
services = get_services(settings=settings.services)
if not services and sync is not SyncOption.SKIP:
LOGGER.warning("No external services configured")
sync = SyncOption.SKIP
return services, sync
def load_comics(target: Path) -> list[Comic]:
comics = []
files = list_files(target) if target.is_dir() else [target]
for file in files:
try:
comics.append(Comic(filepath=file))
except (ComicArchiveError, ComicMetadataError) as err: # noqa: PERF203
LOGGER.error("Failed to load '%s' as a Comic: %s", file, err)
return comics
def prepare_comic(entry: Comic, settings: Settings, skip_convert: bool) -> bool:
if not skip_convert:
entry.convert_to(settings.output.format)
if not entry.archive.IS_WRITEABLE:
LOGGER.warning("Archive format %s is not writeable", entry.archive.EXTENSION)
return False
return True
def should_sync_metadata(sync: SyncOption, metron_info: MetronInfo | None) -> bool:
if sync is SyncOption.SKIP:
return False
if sync is SyncOption.FORCE:
return True
if metron_info and metron_info.last_modified:
age = (date.today() - metron_info.last_modified.date()).days
return age >= 28
return True
def get_id(ids: list[Id], source: InformationSource) -> str | None:
return next((x.value for x in ids if x.source is source), None)
def search_from_metron_info(metron_info: MetronInfo, filename: str) -> Search:
series_id = metron_info.series.id
comicvine_id = get_id(metron_info.ids, InformationSource.COMIC_VINE)
metron_id = get_id(metron_info.ids, InformationSource.METRON)
source = next((x.source for x in metron_info.ids if x.primary), None)
return Search(
series=SeriesSearch(
name=metron_info.series.name,
volume=metron_info.series.volume,
year=metron_info.series.start_year,
comicvine=int(series_id)
if series_id and source == InformationSource.COMIC_VINE
else None,
metron=int(series_id) if series_id and source == InformationSource.METRON else None,
),
issue=IssueSearch(
number=metron_info.number,
comicvine=int(comicvine_id) if comicvine_id else None,
metron=int(metron_id) if metron_id else None,
),
filename=filename,
)
def search_from_comic_info(comic_info: ComicInfo, filename: str) -> Search:
volume = comic_info.volume
year = volume if volume and volume > 1900 else None
volume = volume if volume and volume < 1900 else None
return Search(
series=SeriesSearch(name=comic_info.series or filename, volume=volume, year=year),
issue=IssueSearch(number=comic_info.number),
filename=filename,
)
def search_from_filename(filename: str) -> Search:
series_name = comicfn2dict(filename).get("series", filename)
series_name = str(series_name).replace("-", " ")
return Search(series=SeriesSearch(name=series_name), issue=IssueSearch(), filename=filename)
def build_search(
metron_info: MetronInfo | None, comic_info: ComicInfo | None, filename: str
) -> Search:
if metron_info and metron_info.series and metron_info.series.name:
return search_from_metron_info(metron_info=metron_info, filename=filename)
if comic_info and comic_info.series:
return search_from_comic_info(comic_info=comic_info, filename=filename)
return search_from_filename(filename=filename)
def sync_metadata(
search: Search, services: dict[Service, BaseService], service_order: tuple[Service, ...]
) -> tuple[MetronInfo | None, ComicInfo | None]:
for service_name in service_order:
if service := services.get(service_name):
metron_info, comic_info = service.fetch(search=search)
if metron_info or comic_info:
return metron_info, comic_info
return None, None
def resolve_metadata(
entry: Comic,
session: ArchiveSession,
services: dict[Service, BaseService],
settings: Services,
sync: SyncOption,
) -> tuple[MetronInfo | None, ComicInfo | None]:
metron_info, comic_info = entry.read_metadata(session=session)
if not should_sync_metadata(sync=sync, metron_info=metron_info):
return metron_info, comic_info
search = build_search(
metron_info=metron_info, comic_info=comic_info, filename=entry.filepath.stem
)
return sync_metadata(search=search, services=services, service_order=settings.order)
def generate_naming(
settings: Naming, metron_info: MetronInfo | None, comic_info: ComicInfo | None
) -> str | None:
filepath = None
if metron_info:
filepath = metron_info.get_filename(settings=settings)
if not filepath and comic_info:
filepath = comic_info.get_filename(settings=settings)
return filepath.lstrip("/") if filepath else None
def apply_changes(
entry: Comic,
session: ArchiveSession,
metron_info: MetronInfo | None,
comic_info: ComicInfo | None,
skip_clean: bool,
skip_rename: bool,
settings: Output,
) -> str | None:
local_metron_info, local_comic_info = entry.read_metadata(session=session)
if local_metron_info != metron_info:
if metron_info:
session.write(filename=MetronInfo.FILENAME, data=metron_info.to_bytes())
else:
session.delete(filename=MetronInfo.FILENAME)
if local_comic_info != comic_info:
if comic_info:
session.write(filename=ComicInfo.FILENAME, data=comic_info.to_bytes())
else:
session.delete(filename=ComicInfo.FILENAME)
if not skip_clean:
for extra in entry.list_extras():
session.delete(filename=extra.name)
naming = None
if not skip_rename and (
naming := generate_naming(
settings=settings.naming, metron_info=metron_info, comic_info=comic_info
)
):
images = entry.list_images()
stem = Path(naming).stem
pad = len(str(len(images)))
for idx, img in enumerate(images):
new_name = f"{stem}_{str(idx).zfill(pad)}{img.suffix}"
if img.name != new_name:
session.rename(filename=img.name, new_name=new_name)
return naming
@app.command(help="Process comics by converting, syncing metadata, and organizing them.")
def process(
target: Annotated[
Path,
Argument(
exists=True, help="Process comics from the specified file/folder.", show_default=False
),
],
skip_convert: Annotated[
bool, Option("--skip-convert", help="Skip converting comics to the configured format.")
] = False,
sync: Annotated[
SyncOption,
Option(
"--sync",
"-s",
case_sensitive=False,
help="Sync ComicInfo/MetronInfo with online services.",
),
] = SyncOption.OUTDATED,
skip_clean: Annotated[
bool, Option("--skip-clean", help="Skip removing any non-image/MetronInfo/ComicInfo files.")
] = False,
skip_rename: Annotated[
bool,
Option(
"--skip-rename",
help="Skip organizing and renaming comics based on their MetronInfo/ComicInfo.",
),
] = False,
clean_cache: Annotated[
bool, Option("--clean", "-c", show_default=False, help="Remove all cached files.")
] = False,
debug: Annotated[
bool, Option("--debug", help="Enable debug mode to show extra information.")
] = False,
) -> None:
settings = Settings.load()
settings.save()
services, sync = setup_environment(
clean_cache=clean_cache, sync=sync, settings=settings, debug=debug
)
comics = load_comics(target=target)
total = len(comics)
for index, entry in enumerate(comics, start=1):
CONSOLE.rule(
f"[{index}/{total}] Importing {entry.filepath.name}", align="left", style="subtitle"
)
if not prepare_comic(entry=entry, settings=settings, skip_convert=skip_convert):
continue
with entry.open_session() as session:
metron_info, comic_info = resolve_metadata(
entry=entry,
session=session,
services=services,
settings=settings.services,
sync=sync,
)
naming = apply_changes(
entry=entry,
session=session,
metron_info=metron_info,
comic_info=comic_info,
skip_clean=skip_clean,
skip_rename=skip_rename,
settings=settings.output,
)
if naming:
entry.move_to(naming=naming, output_folder=settings.output.folder)
with CONSOLE.status("Cleaning up empty folders"):
delete_empty_folders(folder=target)
@app.command(
name="import",
deprecated=True,
help="Use `perdoo process` instead.\nImport comics into your collection using Perdoo.",
)
def run(
target: Annotated[
Path,
Argument(
exists=True, help="Import comics from the specified file/folder.", show_default=False
),
],
skip_convert: Annotated[
bool, Option("--skip-convert", help="Skip converting comics to the configured format.")
] = False,
sync: Annotated[
SyncOption,
Option(
"--sync",
"-s",
case_sensitive=False,
help="Sync ComicInfo/MetronInfo with online services.",
),
] = SyncOption.OUTDATED,
skip_clean: Annotated[
bool,
Option(
"--skip-clean",
help="Skip removing any files not listed in the 'image_extensions' setting.",
),
] = False,
skip_rename: Annotated[
bool,
Option(
"--skip-rename",
help="Skip organizing and renaming comics based on their MetronInfo/ComicInfo.",
),
] = False,
clean_cache: Annotated[
bool,
Option(
"--clean",
"-c",
show_default=False,
help="Clean the cache before starting the synchronization process. "
"Removes all cached files.",
),
] = False,
debug: Annotated[
bool, Option("--debug", help="Enable debug mode to show extra information.")
] = False,
) -> None:
LOGGER.warning("`perdoo import` is deprecated; use `perdoo process` instead.")
return process(
target=target,
skip_convert=skip_convert,
sync=sync,
skip_clean=skip_clean,
skip_rename=skip_rename,
clean_cache=clean_cache,
debug=debug,
)