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 | class ComicboxInit:
"""Initialization mixin."""
def _validate_path(self, path: Path | str | None) -> Path | None:
path = Path(path) if path else None
if not path:
return path
if not path.exists():
reason = f"{path} does not exist."
raise ComicNotFoundError(reason)
if path.is_dir():
reason = f"{path} is a directory."
raise IsADirectoryError(reason)
return path
def __init__(
self,
path: Path | str | None = None,
config: ComicboxSettings | Namespace | Mapping | None = None,
metadata: Mapping | str | bytes | None = None,
fmt: MetadataFormats | None = None,
) -> None:
"""
Initialize the archive with a path to the archive.
path: the path to the comic archive
config: a ComicboxSettings dataclass. If None, Comicbox generates its own from the
environment.
metadata: a comicbox-schema-shaped dict (the root-wrapped form, e.g.
``{"comicbox": {...}}``) to layer onto the metadata gathered from
the path. A raw string/bytes blob in any supported format is
also accepted (pass ``fmt`` to skip detection).
fmt: the MetadataFormats member describing the format of ``metadata``;
None means the comicbox format.
Logging is never (re)configured here: comicbox is a library, and its
modules log through whatever loguru sinks the host application
configured. The comicbox CLI and worker entry points call
``comicbox.logger.init_logging`` themselves.
"""
self._path = self._validate_path(path)
# Lazy import: comicbox.config imports comicbox.formats which
# transitively imports this module β keep the top-level import
# graph acyclic.
from comicbox.config import get_config
# An already-built ComicboxSettings goes through get_config too.
# Its fast path skips the confuse rebuild but still applies
# post_process_set_for_path, which turns off file-requiring
# options when there's no path. Short-circuiting around it here
# was what made that guard dead for every CLI run: Runner builds
# a ComicboxSettings once and hands it to each Comicbox.
self._config: ComicboxSettings = get_config(config, path=self._path, box=True)
self._reset_archive(fmt, metadata)
def _reset_loaded_forward_caches(self) -> None:
self._merged_metadata: MappingProxyType = MappingProxyType({}) # pyright: ignore[reportUninitializedInstanceVariable]
# The _dict_formats context each cache below was computed under.
# None is a wildcard: set_internal_metadata pins metadata for every
# context. See get_internal_metadata / get_computed_metadata.
self._computed_dict_formats: frozenset | None = frozenset() # pyright: ignore[reportUninitializedInstanceVariable]
self._metadata_dict_formats: frozenset | None = frozenset() # pyright: ignore[reportUninitializedInstanceVariable]
self._computed: tuple = () # pyright: ignore[reportUninitializedInstanceVariable]
self._extra_delete_keys: set = set() # pyright: ignore[reportUninitializedInstanceVariable]
self._computed_merged_metadata: MappingProxyType = MappingProxyType({}) # pyright: ignore[reportUninitializedInstanceVariable]
self._metadata: MappingProxyType = MappingProxyType({}) # pyright: ignore[reportUninitializedInstanceVariable]
def _reset_archive(
self,
fmt: MetadataFormats | None,
metadata: Mapping | str | bytes | None,
keep_sources: Mapping[
MetadataSources, list[SourceData] | tuple[SourceData, ...]
]
| None = None,
) -> None:
self._archive_cls: Callable | None = None
self._file_type: FileTypeEnum | None = None
self._set_archive_cls()
self._archive: ArchiveType | None = None
self._namelist: tuple[str, ...] | None = None
self._infolist: tuple[InfoType, ...] | None = None
self._dirnames: frozenset[str] | None = None
self._7zfactory: BytesIOFactory | None = None
self._transform_cache: dict = {}
self._page_filenames: tuple[str, ...] | None = None
self._cover_paths: tuple[str, ...] | None = None
self._page_count: int | None = None
from comicbox.formats.sources import MetadataSources
# keep_sources carries the sources a reset can't rebuild β see
# ComicboxDump._reset_caches_after_write.
self._sources: dict[
MetadataSources, list[SourceData] | tuple[SourceData, ...]
] = dict(keep_sources) if keep_sources else {}
if metadata:
self._sources[MetadataSources.API] = [SourceData(metadata, fmt=fmt)]
self._loaded: dict[MetadataSources, tuple[LoadedMetadata, ...]] = {}
# (source, path) of each source whose parser failed.
self._failed_loads: set[tuple[MetadataSources, str]] = set()
self._normalized: dict[MetadataSources, tuple[LoadedMetadata, ...]] = {}
self._path_mtime_dttm: datetime | None = None
self._dict_formats: frozenset[MetadataFormats] = frozenset()
self._reset_loaded_forward_caches()
@staticmethod
def is_pdf_supported() -> bool:
"""Are PDFs supported."""
# Not `"pdffile" in sys.modules`: that is also true when pdffile
# imported but comicbox's guard rejected it (an old pdffile without
# PageFormat), or when the embedding app imported pdffile itself.
return PDF_ENABLED
def _set_archive_cls_pdf(self) -> bool:
"""PDFFile is only optionally installed."""
if not PDF_ENABLED:
return self._archive_is_pdf
with suppress(OSError):
if PDFFile.is_pdffile(str(self._path)):
# Both attributes get unconditional defaults at the top of
# _set_archive_cls; the suppressions cover the documented
# init-in-reset-method pattern, not a real lifecycle gap.
self._archive_is_pdf = True # pyright: ignore[reportUninitializedInstanceVariable]
self._archive_cls = PDFFile
self._pdf_suffix = PDFFile.SUFFIX # pyright: ignore[reportUninitializedInstanceVariable]
return self._archive_is_pdf
def _try_detect_pdf(self, _path: Path) -> bool:
if self._set_archive_cls_pdf():
self._file_type = FileTypeEnum.PDF
return True
return False
def _try_detect_7z(self, path: Path) -> bool:
# py7zr is imported lazily β CB7 is rare and the package is heavy.
from py7zr import SevenZipFile, is_7zfile
if is_7zfile(path):
self._archive_cls = SevenZipFile
self._file_type = FileTypeEnum.CB7
return True
return False
# Every zip record signature starts with these two bytes.
_ZIP_LEADING_MAGIC = b"PK"
def _detect_zip(self, path: Path, *, strict: bool) -> bool:
# is_zipfile only scans the tail for an end-of-central-directory
# record, so a pdf or 7z with zip data appended matches it too.
# The strict pass also requires zip leading magic, making every
# detector lead-magic based so none can shadow another. The loose
# terminal pass still accepts zips the format allows to start with
# other data (self-extractors, prepended junk).
if strict:
# Swallow OSError like is_zipfile does, so an unreadable path
# falls through detection instead of raising here.
leading = b""
with suppress(OSError), path.open("rb") as archive_file:
leading = archive_file.read(2)
if leading != self._ZIP_LEADING_MAGIC:
return False
if is_zipfile(path):
self._archive_cls = ZipFile
self._file_type = FileTypeEnum.CBZ
return True
return False
def _try_detect_zip(self, path: Path) -> bool:
return self._detect_zip(path, strict=True)
def _try_detect_zip_loose(self, path: Path) -> bool:
return self._detect_zip(path, strict=False)
def _try_detect_rar(self, path: Path) -> bool:
# rarfile is imported lazily β defers the heavy package init for
# workers that only see CBZs (the common case at bulk-read scale).
# import_rarfile also applies comicbox's sub-second timestamp patch.
# Every RarFile is constructed from the class bound here, so patching
# at detection time covers them all.
from comicbox._rar import import_rarfile
rarfile = import_rarfile()
if rarfile.is_rarfile(path):
self._archive_cls = rarfile.RarFile
self._file_type = FileTypeEnum.CBR
return True
return False
def _try_detect_tar(self, path: Path) -> bool:
if is_tarfile(path):
self._archive_cls = tarfile_open
self._file_type = FileTypeEnum.CBT
return True
return False
# Full detection order (default when no extension hint), by observed
# archive frequency: cbz dominates, then cbr, then pdf; cb7 is very rare
# and cbt rarer still. Common types first also rules out most files
# before the heavy py7zr import, and leaves tar β the weakest magic,
# "ustar" at offset 257 β near last. Frequency ordering is safe because
# every detector here requires leading magic; the loose tail-scan zip
# detector runs terminally so it can never shadow another format.
_FULL_DETECT_ORDER: tuple[str, ...] = (
"zip",
"rar",
"pdf",
"7z",
"tar",
"zip_loose",
)
# Extension β which types to try first (saves disk reads)
_EXTENSION_HINT: ClassVar[dict[str, tuple[str, ...]]] = {
".cbz": ("zip",),
".cbr": ("rar",),
".cb7": ("7z",),
".cbt": ("tar",),
".pdf": ("pdf",),
}
def _try_detect(self, key: str, path: Path) -> bool:
"""Try a single archive type detection."""
detectors = {
"pdf": self._try_detect_pdf,
"7z": self._try_detect_7z,
"zip": self._try_detect_zip,
"rar": self._try_detect_rar,
"tar": self._try_detect_tar,
"zip_loose": self._try_detect_zip_loose,
}
return detectors[key](path)
def _detect_archive_cls(self, path: Path) -> None:
"""Try each detector in hint-first priority order; raise if none match."""
suffix = path.suffix.lower()
hinted = self._EXTENSION_HINT.get(suffix, ())
remaining = tuple(k for k in self._FULL_DETECT_ORDER if k not in hinted)
for key in hinted + remaining:
if self._try_detect(key, path):
return
reason = f"Unsupported archive type: {path}"
raise UnsupportedArchiveTypeError(reason)
def _set_archive_cls(self) -> None:
"""Set the path and determine the archive type."""
# Every attribute is assigned unconditionally before the early
# return so a pathless box has a complete, safe attribute set.
# The suppressions cover the documented init-in-reset-method
# pattern (__init__ β _reset_archive β here), not a lifecycle gap.
self._archive_is_pdf: bool = False
self._pdf_suffix: str = ""
self._info_size_attr: str = "file_size" # pyright: ignore[reportUninitializedInstanceVariable]
self._info_fn_attr: str = "filename" # pyright: ignore[reportUninitializedInstanceVariable]
if not self._path:
return
path = self._path
self._detect_archive_cls(path)
if self._archive_cls == tarfile_open:
# Tarfile info objects use different attribute names.
self._info_size_attr = "size"
self._info_fn_attr = "name"
def get_path(self) -> Path | None:
"""Get the path for the archive."""
return self._path
def get_file_type(self) -> str:
"""Return archive type string."""
return self._file_type.value if self._file_type else ""
|