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 | class ComicboxSources(ComicboxArchive):
"""Getting and storing source metadata."""
def _get_source_config_metadata(self) -> list[SourceData]:
source_data_list = []
general = self._config.general
if not general.metadata:
return source_data_list
fmt = general.metadata_format
try:
if isinstance(fmt, str):
fmt = MetadataFormats[fmt.upper()]
if not fmt or fmt in self._config.read.formats:
source_data_list = [SourceData(general.metadata, fmt=fmt)]
except Exception as exc:
logger.warning(f"Error reading metadata from config: {exc}")
return source_data_list
def _get_source_cli_metadata(self) -> list[SourceData]:
"""Get metadatas from cli."""
source_data_list = []
metadata_cli = self._config.general.metadata_cli
if not metadata_cli:
return source_data_list
for source_string in metadata_cli:
try:
sd = SourceData(source_string)
source_data_list.append(sd)
except Exception as exc:
logger.warning(
f"Error reading metadata from cli '{source_string}': {exc}"
)
return source_data_list
def _get_source_import_metadata(self) -> list[SourceData]:
"""Read multiple import paths into strings."""
source_data_list = []
paths = self._config.convert.import_paths
if not paths:
return source_data_list
for path_str in paths:
try:
path = Path(path_str)
with path.open("r") as f:
source_string = f.read()
fmt = FILENAME_FORMAT_MAP.get(path.name.lower())
if not fmt or fmt in self._config.read.formats:
sd = SourceData(source_string, path, fmt)
source_data_list.append(sd)
except Exception as exc:
logger.warning(
f"Error reading metadata from import path {path_str}: {exc}"
)
logger.exception("")
return source_data_list
def _get_source_filename_metadata(self) -> list[SourceData]:
source_data_list = []
if not self._path:
return source_data_list
try:
source_data_list.extend(
SourceData(self._path.name, fmt=fmt, from_archive=True)
for fmt in self._config.read_filename_formats
)
except Exception as exc:
logger.warning(
f"Error reading metadata from archive filename {self._path}: {exc}"
)
return source_data_list
def _get_source_comment_metadata(self) -> list[SourceData]:
source_data_list = []
if not self._path:
return source_data_list
try:
# Only one archive comment format exists, so assume it.
only_comment_format = MetadataSources.ARCHIVE_COMMENT.value.formats[0]
formats = only_comment_format in self._config.read.formats
if formats and (comment := self._get_comment()):
comment = comment.decode(errors="replace")
source_data_list = [
SourceData(comment, from_archive=True, fmt=only_comment_format)
]
except Exception as exc:
logger.warning(f"Error reading archive comment from {self._path}: {exc}")
return source_data_list
def _get_source_pdf_metadata(self) -> list[SourceData]:
"""If an archive is a pdf and we're configured to read pdf metadata, get the pdf metadata as source."""
source_data_list = []
if not self._path:
return source_data_list
pdf_fmts = (
frozenset(MetadataSources.ARCHIVE_PDF.value.formats)
& self._config.read.formats
)
if not pdf_fmts:
return source_data_list
try:
archive = self._get_archive()
if not archive or not self._archive_is_pdf:
return source_data_list
if md := cast("PDFFile", archive).get_metadata():
md = MappingProxyType({MuPDFSchema.ROOT_TAG: md})
source_data_list = [
SourceData(md, fmt=MetadataFormats.PDF, from_archive=True)
]
except Exception as exc:
logger.warning(f"Error reading from PDF header {self._path}: {exc}")
return source_data_list
def _store_top_source_archive_files(
self, fn: str, files_dict: dict[Any, Any]
) -> None:
path = Path(fn)
lower_name = path.name.lower()
if (
fmt := FILENAME_FORMAT_MAP.get(lower_name)
) and fmt in self._config.read.formats:
old_entry = files_dict.get(fmt)
path_level = len(path.parents)
if not old_entry or old_entry[1] > path_level:
files_dict[fmt] = (fn, path_level)
def _add_top_source_archive_file(
self,
fmt: MetadataFormats,
fn: str,
source_data_list: list[Any],
) -> None:
source_string = self._archive_readfile(fn)
sd = SourceData(source_string, Path(fn), fmt, from_archive=True)
source_data_list.append(sd)
def _get_source_archive_files_metadata(self) -> list[SourceData]:
"""Get source metadata from files in the archive."""
# search filenames for metadata files and read.
source_data_list = []
if not self._path or not self._config.read_file_formats:
return source_data_list
files_dict = {}
for fn in self.namelist():
try:
self._store_top_source_archive_files(fn, files_dict)
except Exception as exc:
logger.warning(f"Error reading {self._path}:{fn}: {exc}")
for fmt, value in files_dict.items():
fn = value[0]
try:
self._add_top_source_archive_file(fmt, fn, source_data_list)
except Exception as exc:
logger.warning(f"Error reading {self._path}:{fn}: {exc}")
return source_data_list
SOURCE_METHOD_MAP: MappingProxyType[
MetadataSources, Callable[["ComicboxSources"], list[SourceData]]
] = MappingProxyType(
{
MetadataSources.CONFIG: _get_source_config_metadata,
MetadataSources.CLI: _get_source_cli_metadata,
MetadataSources.IMPORT_FILE: _get_source_import_metadata,
MetadataSources.ARCHIVE_FILENAME: _get_source_filename_metadata,
MetadataSources.ARCHIVE_COMMENT: _get_source_comment_metadata,
MetadataSources.ARCHIVE_PDF: _get_source_pdf_metadata,
MetadataSources.ARCHIVE_FILE: _get_source_archive_files_metadata,
}
)
# API is set by the public Comicbox(...) constructor; online sources are
# set by the online-lookup pipeline. Either way, the standard
# SOURCE_METHOD_MAP dispatch does not apply.
SOURCES_SET_ELSEWHERE = frozenset(
{MetadataSources.API}
| {
MetadataSources[source_name]
for registration in FORMAT_REGISTRATIONS.values()
if registration.is_online
for source_name in registration.sources
}
)
def _set_source_metadata(
self, source: MetadataSources
) -> list[SourceData] | tuple[SourceData, ...] | None:
"""Set source metadata by source."""
if self._config.write.delete_all_tags:
return
if source in self.SOURCES_SET_ELSEWHERE:
# Set by init & add metadata below.
return
func = self.SOURCE_METHOD_MAP.get(source)
if func:
source_data_list = func(self)
else:
reason = f"{source} not a valid source metadata key."
raise MetadataError(reason)
if source_data_list:
source_data_list = tuple(source_data_list)
self._sources[source] = source_data_list
def get_source_metadata(
self, source: MetadataSources
) -> list[SourceData] | tuple[SourceData, ...] | None:
"""Get source metadata by key."""
try:
if source not in self._sources:
self._set_source_metadata(source)
return self._sources.get(source)
except Exception as exc:
logger.warning(
f"{self._path} reading source metadata from {source.value.label}: {exc}"
)
def add_source(
self,
source: MetadataSources,
metadata: str | bytes | Mapping,
fmt: MetadataFormats | None = None,
path: str | Path = "",
) -> None:
"""Add metadata directly to sources cache."""
source_data_list = self._sources.get(source)
if not isinstance(source_data_list, list):
source_data_list = list(source_data_list or ())
self._sources[source] = source_data_list
source_data_list.append(SourceData(metadata, Path(path), fmt))
self._invalidate_source(source)
def _invalidate_source(self, source: MetadataSources) -> None:
"""
Invalidate one source's parse caches and everything downstream.
The single chokepoint for mid-chain invalidation: per-source
_loaded AND _normalized entries (the normalize getter skips
re-normalization whenever its key exists, so a stale entry would
silently swallow newly added metadata), then the merged /
computed / final-metadata caches via the shared reset.
"""
self._loaded.pop(source, None)
self._failed_loads = {key for key in self._failed_loads if key[0] != source}
self._normalized.pop(source, None)
self._reset_loaded_forward_caches()
def add_metadata(
self,
metadata: str | bytes | Mapping,
fmt: MetadataFormats | None = None,
) -> None:
"""Add metadata directly to sources cache."""
self.add_source(MetadataSources.API, metadata, fmt)
def add_metadata_file(
self, path: Path | str, fmt: MetadataFormats | None = None
) -> None:
"""Add file contents to added sources."""
path = Path(path)
with path.open("r") as f:
string = f.read()
self.add_source(MetadataSources.IMPORT_FILE, string, fmt, path)
|