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 | class ComicboxArchiveRead(ComicboxArchiveInit):
"""Comic archive read methods."""
def _ensure_read_archive(self) -> None:
if not self._archive_cls or not self._path:
reason = "Cannot read archive without a path."
raise ArchiveError(reason)
def namelist(self) -> tuple[str, ...]:
"""Get list of files in the archive."""
self._ensure_read_archive()
if self._namelist is None:
if self._infolist:
# Derive from cached infolist - both are sorted by the same
# lowercased-filename key, so re-sort is unnecessary.
self._namelist: tuple[str, ...] | None = tuple(
self._get_info_fn(i) for i in self._infolist
)
else:
archive = self._get_archive()
namelist = Archive.namelist(archive)
# SORTED CASE INSENSITIVELY
self._namelist = tuple(sorted(namelist, key=lambda x: x.lower()))
return self._namelist
def _get_info_fn(self, info: InfoType) -> str:
return getattr(info, self._info_fn_attr)
def _get_info_size(self, info: InfoType) -> int | None:
return getattr(info, self._info_size_attr) if self._info_size_attr else None
def infolist(self) -> tuple[InfoType, ...]:
"""Get info list of members from the archive."""
self._ensure_read_archive()
if not self._infolist:
archive = self._get_archive()
infolist = Archive.infolist(archive)
# SORTED CASE INSENSITIVELY
infolist = tuple(
sorted(infolist, key=lambda i: self._get_info_fn(i).lower())
)
self._infolist = infolist
return self._infolist
def dirnames(self) -> frozenset[str]:
"""Get the names of the archive's directory entries."""
self._ensure_read_archive()
if self._dirnames is None:
self._dirnames: frozenset[str] | None = frozenset(
self._get_info_fn(info)
for info in self.infolist()
if ArchiveInfo.is_dir(info)
)
return self._dirnames
@classmethod
def check_unrar_executable(cls) -> bool:
"""Raise UnsupportedArchiveTypeError unless RAR members can be extracted."""
if reason := rar_unsupported_reason():
raise UnsupportedArchiveTypeError(reason)
return True
@classmethod
def is_unrar_supported(cls) -> bool:
"""Return if rar file contents can be read."""
try:
return cls.check_unrar_executable()
except UnsupportedArchiveTypeError:
return False
def _get_7zfactory(self) -> BytesIOFactory | None:
# Use the file-type enum rather than `self._archive_cls == SevenZipFile`
# so the py7zr import only fires when we actually have a CB7.
if not self._7zfactory and self._file_type == FileTypeEnum.CB7:
from py7zr.io import BytesIOFactory
self._7zfactory: BytesIOFactory | None = BytesIOFactory(maxsize)
return self._7zfactory
def _get_7z_sizes(self) -> Mapping[str, int]:
"""Map 7z member name to decompressed size, for batch budgeting."""
return {
info.filename: info.uncompressed
for info in cast("tuple[SevenZipInfo, ...]", self.infolist())
}
def _prefetch_7z(self, filenames: Sequence[str]) -> None:
"""Decompress a batch of 7z members into the shared factory."""
factory = self._get_7zfactory()
if not factory:
return
archive = cast("SevenZipFile", self._get_archive())
Archive.extract_7zipfile(archive, factory, filenames)
def _iter_prefetched(self, filenames: Sequence[str]) -> Iterator[str]:
"""
Yield filenames, decompressing them ahead in batches where it pays.
Only 7z benefits: every other archive type this reads can seek to
a member and decompress just that member, so they pass straight
through. Members already decompressed are still batched — the
reader pops each buffer as it consumes it, so a name can only be
resident once.
"""
if self._file_type != FileTypeEnum.CB7:
yield from filenames
return
sizes = self._get_7z_sizes()
batch: list[str] = []
batch_bytes = 0
for filename in filenames:
size = sizes.get(filename, 0)
# Never emit an empty batch: a single member over the cap is
# its own batch rather than an error.
if batch and batch_bytes + size > _7Z_BATCH_MAX_BYTES:
self._prefetch_7z(batch)
yield from batch
batch = []
batch_bytes = 0
batch.append(filename)
batch_bytes += size
if batch:
self._prefetch_7z(batch)
yield from batch
def _get_pdf_format(self, pdf_format: str = "", default: str = "") -> str:
return pdf_format or (self._config.convert.pdf_pages or default)
def _archive_read_pdf_range(
self, index_from: int, index_to: int, props: dict | None = None
) -> bytes:
"""Read a range of pdf pages to memory as a single pdf."""
self._ensure_read_archive()
archive = self._get_archive()
if not self._archive_is_pdf:
reason = f"Cannot read a pdf page range from {self._path}"
raise ArchiveError(reason)
data, ext = cast("PDFFile", archive).read_pdf(index_from, index_to)
if props is not None:
props["ext"] = ext
return data
def _archive_readfile(
self, filename: str, pdf_format: str = "", props: dict | None = None
) -> bytes:
"""Read an archive file to memory."""
# Consider chunking files by 4096 bytes and streaming them.
data = b""
self._ensure_read_archive()
# Ask the archive, not the filesystem. Path(filename).is_dir()
# resolved an archive-internal name against the process cwd, so a
# directory that happened to share a page's name made the read
# return b"" -- and a real directory entry was never caught at all.
if filename in self.dirnames():
return data
archive = self._get_archive()
factory = self._get_7zfactory()
pdf_format = self._get_pdf_format(pdf_format)
try:
data = Archive.read(
archive, filename, factory, pdf_format=pdf_format, props=props
)
except Exception as exc:
self._raise_if_rar_tool_failure(exc)
raise
return data
def _get_comment(self) -> bytes:
"""Get the comment from the archive."""
archive = self._get_archive()
comment = getattr(archive, "comment", b"")
if isinstance(comment, str):
comment = comment.encode(errors="replace")
return comment
|