stalzone-api 0.1.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.
- stalzone_api/__init__.py +228 -0
- stalzone_api/_http.py +375 -0
- stalzone_api/_version.py +3 -0
- stalzone_api/auth.py +525 -0
- stalzone_api/client.py +1033 -0
- stalzone_api/constants.py +32 -0
- stalzone_api/database/__init__.py +165 -0
- stalzone_api/database/cache.py +146 -0
- stalzone_api/database/icons.py +90 -0
- stalzone_api/database/index.py +135 -0
- stalzone_api/database/items.py +692 -0
- stalzone_api/database/providers.py +393 -0
- stalzone_api/errors.py +138 -0
- stalzone_api/models/__init__.py +41 -0
- stalzone_api/models/auction.py +217 -0
- stalzone_api/models/character.py +188 -0
- stalzone_api/models/clan.py +146 -0
- stalzone_api/models/common.py +162 -0
- stalzone_api/models/emission.py +44 -0
- stalzone_api/models/operations.py +149 -0
- stalzone_api/pagination.py +50 -0
- stalzone_api/py.typed +0 -0
- stalzone_api/simple.py +403 -0
- stalzone_api-0.1.0.dist-info/METADATA +213 -0
- stalzone_api-0.1.0.dist-info/RECORD +27 -0
- stalzone_api-0.1.0.dist-info/WHEEL +4 -0
- stalzone_api-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,692 @@
|
|
|
1
|
+
"""Typed representation of the items database (JSON files from stalzone-database)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass, field
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Callable, Iterator
|
|
8
|
+
|
|
9
|
+
from ..errors import DatabaseError, DatabaseNotFound
|
|
10
|
+
from .index import ItemIndex, build_index
|
|
11
|
+
from .providers import Provider
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"Block",
|
|
15
|
+
"DamageBlock",
|
|
16
|
+
"Element",
|
|
17
|
+
"Formatted",
|
|
18
|
+
"GroupedBlock",
|
|
19
|
+
"Item",
|
|
20
|
+
"ItemElement",
|
|
21
|
+
"ItemStatus",
|
|
22
|
+
"ItemStore",
|
|
23
|
+
"KeyValueElement",
|
|
24
|
+
"ListBlock",
|
|
25
|
+
"NumericElement",
|
|
26
|
+
"PriceElement",
|
|
27
|
+
"RangeElement",
|
|
28
|
+
"RawBlock",
|
|
29
|
+
"RawElement",
|
|
30
|
+
"Text",
|
|
31
|
+
"TextBlock",
|
|
32
|
+
"TextElement",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
_LANG_FALLBACK = "en"
|
|
36
|
+
_WEIGHT_KEY = "core.tooltip.info.weight"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# ------------------------------------------------------------------------ texts
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class Text:
|
|
42
|
+
"""A localizable string from the item database."""
|
|
43
|
+
|
|
44
|
+
type: str = "text"
|
|
45
|
+
key: str | None = None
|
|
46
|
+
args: dict[str, str] = field(default_factory=dict)
|
|
47
|
+
lines: dict[str, str] = field(default_factory=dict)
|
|
48
|
+
text: str | None = None
|
|
49
|
+
|
|
50
|
+
@classmethod
|
|
51
|
+
def from_dict(cls, data: Any) -> "Text | None":
|
|
52
|
+
if data is None:
|
|
53
|
+
return None
|
|
54
|
+
if isinstance(data, str):
|
|
55
|
+
return cls(text=data)
|
|
56
|
+
if not isinstance(data, dict):
|
|
57
|
+
return cls(text=str(data))
|
|
58
|
+
lines = data.get("lines")
|
|
59
|
+
args = data.get("args")
|
|
60
|
+
return cls(
|
|
61
|
+
type=str(data.get("type") or ("translation" if lines else "text")),
|
|
62
|
+
key=data.get("key"),
|
|
63
|
+
args={str(k): str(v) for k, v in args.items()} if isinstance(args, dict) else {},
|
|
64
|
+
lines={str(k): str(v) for k, v in lines.items()} if isinstance(lines, dict) else {},
|
|
65
|
+
text=data.get("text"),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
def get(
|
|
69
|
+
self,
|
|
70
|
+
lang: str = _LANG_FALLBACK,
|
|
71
|
+
*,
|
|
72
|
+
default: str = _LANG_FALLBACK,
|
|
73
|
+
line_breaks: bool = True,
|
|
74
|
+
) -> str | None:
|
|
75
|
+
"""Return the translation for ``lang``, falling back to English/the first locale."""
|
|
76
|
+
|
|
77
|
+
value: str | None
|
|
78
|
+
if self.lines:
|
|
79
|
+
value = self.lines.get(lang) or self.lines.get(default)
|
|
80
|
+
if value is None and self.lines:
|
|
81
|
+
value = next(iter(self.lines.values()))
|
|
82
|
+
else:
|
|
83
|
+
value = self.text
|
|
84
|
+
if value is None:
|
|
85
|
+
return None
|
|
86
|
+
return value.replace("@", "\n") if line_breaks else value
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def ru(self) -> str | None:
|
|
90
|
+
return self.get("ru")
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def en(self) -> str | None:
|
|
94
|
+
return self.get("en")
|
|
95
|
+
|
|
96
|
+
def format(self, **kwargs: Any) -> str | None:
|
|
97
|
+
"""Substitute placeholders (if any) into the translated line."""
|
|
98
|
+
|
|
99
|
+
value = self.get()
|
|
100
|
+
if value is None or not kwargs:
|
|
101
|
+
return value
|
|
102
|
+
try:
|
|
103
|
+
return value.format(**kwargs)
|
|
104
|
+
except (KeyError, IndexError, ValueError):
|
|
105
|
+
return value
|
|
106
|
+
|
|
107
|
+
def __str__(self) -> str:
|
|
108
|
+
return self.get() or ""
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass(frozen=True)
|
|
112
|
+
class Formatted:
|
|
113
|
+
"""Pre-rendered value with colors, e.g. ``formatted.value.ru``."""
|
|
114
|
+
|
|
115
|
+
value: dict[str, str] = field(default_factory=dict)
|
|
116
|
+
name_color: str | None = None
|
|
117
|
+
value_color: str | None = None
|
|
118
|
+
|
|
119
|
+
@classmethod
|
|
120
|
+
def from_dict(cls, data: Any) -> "Formatted | None":
|
|
121
|
+
if not isinstance(data, dict):
|
|
122
|
+
return None
|
|
123
|
+
values = data.get("value")
|
|
124
|
+
return cls(
|
|
125
|
+
value={str(k): str(v) for k, v in values.items()} if isinstance(values, dict) else {},
|
|
126
|
+
name_color=data.get("nameColor"),
|
|
127
|
+
value_color=data.get("valueColor"),
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
def get(self, lang: str = _LANG_FALLBACK, *, default: str = _LANG_FALLBACK) -> str | None:
|
|
131
|
+
if not self.value:
|
|
132
|
+
return None
|
|
133
|
+
return self.value.get(lang) or self.value.get(default) or next(iter(self.value.values()))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# --------------------------------------------------------------------- elements
|
|
137
|
+
@dataclass
|
|
138
|
+
class Element:
|
|
139
|
+
type: str = ""
|
|
140
|
+
formatted: Formatted | None = None
|
|
141
|
+
extra: dict[str, Any] = field(default_factory=dict, repr=False)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@dataclass
|
|
145
|
+
class NumericElement(Element):
|
|
146
|
+
name: Text | None = None
|
|
147
|
+
value: float | None = None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@dataclass
|
|
151
|
+
class KeyValueElement(Element):
|
|
152
|
+
key: Text | None = None
|
|
153
|
+
value: Text | None = None
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@dataclass
|
|
157
|
+
class RangeElement(Element):
|
|
158
|
+
name: Text | None = None
|
|
159
|
+
min: float | None = None
|
|
160
|
+
max: float | None = None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@dataclass
|
|
164
|
+
class TextElement(Element):
|
|
165
|
+
text: Text | None = None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@dataclass
|
|
169
|
+
class PriceElement(Element):
|
|
170
|
+
currency: str | None = None
|
|
171
|
+
amount: float | None = None
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@dataclass
|
|
175
|
+
class ItemElement(Element):
|
|
176
|
+
name: Text | None = None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@dataclass
|
|
180
|
+
class RawElement(Element):
|
|
181
|
+
raw: dict[str, Any] = field(default_factory=dict, repr=False)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# ----------------------------------------------------------------------- blocks
|
|
185
|
+
@dataclass
|
|
186
|
+
class Block:
|
|
187
|
+
type: str = ""
|
|
188
|
+
title: Text | None = None
|
|
189
|
+
extra: dict[str, Any] = field(default_factory=dict, repr=False)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@dataclass
|
|
193
|
+
class TextBlock(Block):
|
|
194
|
+
text: Text | None = None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
@dataclass
|
|
198
|
+
class ListBlock(Block):
|
|
199
|
+
elements: list[Element] = field(default_factory=list)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@dataclass
|
|
203
|
+
class DamageBlock(Block):
|
|
204
|
+
start_damage: float | None = None
|
|
205
|
+
damage_decrease_start: float | None = None
|
|
206
|
+
end_damage: float | None = None
|
|
207
|
+
damage_decrease_end: float | None = None
|
|
208
|
+
max_distance: float | None = None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@dataclass
|
|
212
|
+
class GroupedBlock(Block):
|
|
213
|
+
compact: list[Block] = field(default_factory=list)
|
|
214
|
+
detailed: list[Block] = field(default_factory=list)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@dataclass
|
|
218
|
+
class RawBlock(Block):
|
|
219
|
+
raw: dict[str, Any] = field(default_factory=dict, repr=False)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
_BLOCK_KEYS = {"type", "title"}
|
|
223
|
+
_ELEMENT_KEYS = {"type", "formatted"}
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def parse_element(data: dict[str, Any]) -> Element:
|
|
227
|
+
kind = str(data.get("type") or "")
|
|
228
|
+
formatted = Formatted.from_dict(data.get("formatted"))
|
|
229
|
+
extra = {k: v for k, v in data.items() if k not in _ELEMENT_KEYS}
|
|
230
|
+
if kind == "numeric":
|
|
231
|
+
return NumericElement(
|
|
232
|
+
type=kind,
|
|
233
|
+
formatted=formatted,
|
|
234
|
+
extra=extra,
|
|
235
|
+
name=Text.from_dict(data.get("name")),
|
|
236
|
+
value=data.get("value"),
|
|
237
|
+
)
|
|
238
|
+
if kind == "key-value":
|
|
239
|
+
return KeyValueElement(
|
|
240
|
+
type=kind,
|
|
241
|
+
formatted=formatted,
|
|
242
|
+
extra=extra,
|
|
243
|
+
key=Text.from_dict(data.get("key")),
|
|
244
|
+
value=Text.from_dict(data.get("value")),
|
|
245
|
+
)
|
|
246
|
+
if kind == "range":
|
|
247
|
+
return RangeElement(
|
|
248
|
+
type=kind,
|
|
249
|
+
formatted=formatted,
|
|
250
|
+
extra=extra,
|
|
251
|
+
name=Text.from_dict(data.get("name")),
|
|
252
|
+
min=data.get("min"),
|
|
253
|
+
max=data.get("max"),
|
|
254
|
+
)
|
|
255
|
+
if kind == "text":
|
|
256
|
+
return TextElement(type=kind, formatted=formatted, extra=extra, text=Text.from_dict(data.get("text")))
|
|
257
|
+
if kind == "price":
|
|
258
|
+
return PriceElement(
|
|
259
|
+
type=kind,
|
|
260
|
+
formatted=formatted,
|
|
261
|
+
extra=extra,
|
|
262
|
+
currency=data.get("currency"),
|
|
263
|
+
amount=data.get("amount"),
|
|
264
|
+
)
|
|
265
|
+
if kind == "item":
|
|
266
|
+
return ItemElement(type=kind, formatted=formatted, extra=extra, name=Text.from_dict(data.get("name")))
|
|
267
|
+
return RawElement(type=kind, formatted=formatted, extra=extra, raw=dict(data))
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def parse_block(data: dict[str, Any]) -> Block:
|
|
271
|
+
kind = str(data.get("type") or "")
|
|
272
|
+
title = Text.from_dict(data.get("title"))
|
|
273
|
+
base_extra = {k: v for k, v in data.items() if k not in ("type", "title", "text", "elements")}
|
|
274
|
+
if kind == "text":
|
|
275
|
+
return TextBlock(type=kind, title=title, extra=base_extra, text=Text.from_dict(data.get("text")))
|
|
276
|
+
if kind == "list":
|
|
277
|
+
elements = [parse_element(entry) for entry in data.get("elements") or [] if isinstance(entry, dict)]
|
|
278
|
+
return ListBlock(type=kind, title=title, extra=base_extra, elements=elements)
|
|
279
|
+
if kind == "grouped":
|
|
280
|
+
return GroupedBlock(
|
|
281
|
+
type=kind,
|
|
282
|
+
title=title,
|
|
283
|
+
extra=base_extra,
|
|
284
|
+
compact=[
|
|
285
|
+
parse_block(entry)
|
|
286
|
+
for entry in data.get("compact") or []
|
|
287
|
+
if isinstance(entry, dict)
|
|
288
|
+
],
|
|
289
|
+
detailed=[
|
|
290
|
+
parse_block(entry)
|
|
291
|
+
for entry in data.get("detailed") or []
|
|
292
|
+
if isinstance(entry, dict)
|
|
293
|
+
],
|
|
294
|
+
)
|
|
295
|
+
if kind in ("damage", "damage_ramp"):
|
|
296
|
+
return DamageBlock(
|
|
297
|
+
type=kind,
|
|
298
|
+
title=title,
|
|
299
|
+
extra=base_extra,
|
|
300
|
+
start_damage=data.get("startDamage"),
|
|
301
|
+
damage_decrease_start=data.get("damageDecreaseStart"),
|
|
302
|
+
end_damage=data.get("endDamage"),
|
|
303
|
+
damage_decrease_end=data.get("damageDecreaseEnd"),
|
|
304
|
+
max_distance=data.get("maxDistance"),
|
|
305
|
+
)
|
|
306
|
+
return RawBlock(type=kind, title=title, extra=base_extra, raw=dict(data))
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
# ------------------------------------------------------------------------- item
|
|
310
|
+
@dataclass
|
|
311
|
+
class ItemStatus:
|
|
312
|
+
state: str | None = None
|
|
313
|
+
extra: dict[str, Any] = field(default_factory=dict, repr=False)
|
|
314
|
+
|
|
315
|
+
@classmethod
|
|
316
|
+
def from_dict(cls, data: Any) -> "ItemStatus | None":
|
|
317
|
+
if not isinstance(data, dict):
|
|
318
|
+
return None
|
|
319
|
+
return cls(state=data.get("state"), extra={k: v for k, v in data.items() if k != "state"})
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _text_key(text: Text | None) -> str | None:
|
|
323
|
+
if text is None:
|
|
324
|
+
return None
|
|
325
|
+
return text.key or text.get(line_breaks=False)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _iter_elements(blocks: list[Block]) -> Iterator[Element]:
|
|
329
|
+
for block in blocks:
|
|
330
|
+
if isinstance(block, ListBlock):
|
|
331
|
+
yield from block.elements
|
|
332
|
+
elif isinstance(block, GroupedBlock):
|
|
333
|
+
yield from _iter_elements(block.compact)
|
|
334
|
+
yield from _iter_elements(block.detailed)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _iter_blocks(blocks: list[Block]) -> Iterator[Block]:
|
|
338
|
+
for block in blocks:
|
|
339
|
+
yield block
|
|
340
|
+
if isinstance(block, GroupedBlock):
|
|
341
|
+
yield from _iter_blocks(block.compact)
|
|
342
|
+
yield from _iter_blocks(block.detailed)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
@dataclass
|
|
346
|
+
class Item:
|
|
347
|
+
"""An in-game item from the official database."""
|
|
348
|
+
|
|
349
|
+
id: str
|
|
350
|
+
category: str
|
|
351
|
+
name: Text = field(default_factory=Text)
|
|
352
|
+
color: str | None = None
|
|
353
|
+
status: ItemStatus | None = None
|
|
354
|
+
info_blocks: list[Block] = field(default_factory=list)
|
|
355
|
+
path: str | None = None
|
|
356
|
+
realm: str | None = None
|
|
357
|
+
extra: dict[str, Any] = field(default_factory=dict, repr=False)
|
|
358
|
+
|
|
359
|
+
@classmethod
|
|
360
|
+
def from_dict(
|
|
361
|
+
cls,
|
|
362
|
+
data: dict[str, Any],
|
|
363
|
+
*,
|
|
364
|
+
path: str | None = None,
|
|
365
|
+
realm: str | None = None,
|
|
366
|
+
) -> "Item":
|
|
367
|
+
known = {"id", "category", "name", "color", "status", "infoBlocks"}
|
|
368
|
+
return cls(
|
|
369
|
+
id=str(data.get("id", "")),
|
|
370
|
+
category=str(data.get("category", "")),
|
|
371
|
+
name=Text.from_dict(data.get("name")) or Text(),
|
|
372
|
+
color=data.get("color"),
|
|
373
|
+
status=ItemStatus.from_dict(data.get("status")),
|
|
374
|
+
info_blocks=[parse_block(entry) for entry in data.get("infoBlocks") or [] if isinstance(entry, dict)],
|
|
375
|
+
path=path,
|
|
376
|
+
realm=realm,
|
|
377
|
+
extra={k: v for k, v in data.items() if k not in known},
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
# ------------------------------------------------------------------ category
|
|
381
|
+
@property
|
|
382
|
+
def category_type(self) -> str:
|
|
383
|
+
return self.category.split("/", 1)[0]
|
|
384
|
+
|
|
385
|
+
@property
|
|
386
|
+
def category_subtype(self) -> str | None:
|
|
387
|
+
parts = self.category.split("/", 1)
|
|
388
|
+
return parts[1] if len(parts) > 1 else None
|
|
389
|
+
|
|
390
|
+
@property
|
|
391
|
+
def type(self) -> str:
|
|
392
|
+
return self.category_type
|
|
393
|
+
|
|
394
|
+
@property
|
|
395
|
+
def subtype(self) -> str | None:
|
|
396
|
+
return self.category_subtype
|
|
397
|
+
|
|
398
|
+
# -------------------------------------------------------------- convenience
|
|
399
|
+
@property
|
|
400
|
+
def blocks(self) -> list[Block]:
|
|
401
|
+
return self.info_blocks
|
|
402
|
+
|
|
403
|
+
def blocks_of(self, kind: str) -> list[Block]:
|
|
404
|
+
return [block for block in self.info_blocks if block.type == kind]
|
|
405
|
+
|
|
406
|
+
@property
|
|
407
|
+
def stats(self) -> dict[str, Any]:
|
|
408
|
+
"""Flatten every element of every list block into a ``key → value`` mapping."""
|
|
409
|
+
|
|
410
|
+
result: dict[str, Any] = {}
|
|
411
|
+
for element in _iter_elements(self.info_blocks):
|
|
412
|
+
if isinstance(element, NumericElement):
|
|
413
|
+
key = _text_key(element.name)
|
|
414
|
+
if key:
|
|
415
|
+
result[key] = element.value
|
|
416
|
+
elif isinstance(element, RangeElement):
|
|
417
|
+
key = _text_key(element.name)
|
|
418
|
+
if key:
|
|
419
|
+
result[key] = (element.min, element.max)
|
|
420
|
+
elif isinstance(element, KeyValueElement):
|
|
421
|
+
key = _text_key(element.key)
|
|
422
|
+
if key:
|
|
423
|
+
result[key] = element.value
|
|
424
|
+
elif isinstance(element, TextElement) and element.text is not None:
|
|
425
|
+
key = _text_key(element.text)
|
|
426
|
+
if key:
|
|
427
|
+
result[key] = element.text
|
|
428
|
+
elif isinstance(element, PriceElement):
|
|
429
|
+
result[f"price:{element.currency}"] = element.amount
|
|
430
|
+
return result
|
|
431
|
+
|
|
432
|
+
def stat(self, key: str, default: Any = None) -> Any:
|
|
433
|
+
return self.stats.get(key, default)
|
|
434
|
+
|
|
435
|
+
def find(self, key: str) -> Block | Element | None:
|
|
436
|
+
"""Find a block or element by its translation key (e.g. ``core.tooltip.info.weight``)."""
|
|
437
|
+
|
|
438
|
+
for block in _iter_blocks(self.info_blocks):
|
|
439
|
+
if _text_key(block.title) == key:
|
|
440
|
+
return block
|
|
441
|
+
if isinstance(block, TextBlock) and _text_key(block.text) == key:
|
|
442
|
+
return block
|
|
443
|
+
if isinstance(block, ListBlock):
|
|
444
|
+
for element in block.elements:
|
|
445
|
+
candidates = [
|
|
446
|
+
getattr(element, "name", None),
|
|
447
|
+
getattr(element, "key", None),
|
|
448
|
+
getattr(element, "text", None),
|
|
449
|
+
]
|
|
450
|
+
if isinstance(element, KeyValueElement):
|
|
451
|
+
candidates.append(element.value)
|
|
452
|
+
for candidate in candidates:
|
|
453
|
+
if isinstance(candidate, Text) and candidate.key == key:
|
|
454
|
+
return element
|
|
455
|
+
return None
|
|
456
|
+
|
|
457
|
+
@property
|
|
458
|
+
def weight(self) -> float | None:
|
|
459
|
+
"""Item weight in kilograms, if present."""
|
|
460
|
+
|
|
461
|
+
element = self.find(_WEIGHT_KEY)
|
|
462
|
+
if isinstance(element, NumericElement):
|
|
463
|
+
return element.value
|
|
464
|
+
for candidate in _iter_elements(self.info_blocks):
|
|
465
|
+
if isinstance(candidate, NumericElement) and candidate.name is not None:
|
|
466
|
+
if (candidate.name.en or "").strip().casefold() == "weight":
|
|
467
|
+
return candidate.value
|
|
468
|
+
return None
|
|
469
|
+
|
|
470
|
+
@property
|
|
471
|
+
def damage(self) -> DamageBlock | None:
|
|
472
|
+
"""Damage ramp of a weapon, if present."""
|
|
473
|
+
|
|
474
|
+
for block in self.info_blocks:
|
|
475
|
+
if isinstance(block, DamageBlock):
|
|
476
|
+
return block
|
|
477
|
+
return None
|
|
478
|
+
|
|
479
|
+
@property
|
|
480
|
+
def description(self) -> Text | None:
|
|
481
|
+
for block in self.info_blocks:
|
|
482
|
+
if isinstance(block, TextBlock) and block.text is not None:
|
|
483
|
+
if (block.text.key or "").endswith(".description"):
|
|
484
|
+
return block.text
|
|
485
|
+
for block in self.info_blocks:
|
|
486
|
+
if isinstance(block, TextBlock) and block.text is not None:
|
|
487
|
+
return block.text
|
|
488
|
+
return None
|
|
489
|
+
|
|
490
|
+
def to_dict(self) -> dict[str, Any]:
|
|
491
|
+
return asdict(self)
|
|
492
|
+
|
|
493
|
+
def __str__(self) -> str:
|
|
494
|
+
return self.name.get() or self.id
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
# ------------------------------------------------------------------------ store
|
|
498
|
+
ProgressCallback = Callable[[str, int, int], Any]
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
class ItemStore:
|
|
502
|
+
"""Access to items of one realm (``db.items``)."""
|
|
503
|
+
|
|
504
|
+
def __init__(self, provider: Provider) -> None:
|
|
505
|
+
self.provider = provider
|
|
506
|
+
self._index: ItemIndex | None = None
|
|
507
|
+
self._names: dict[str, dict[str, Any]] | None = None
|
|
508
|
+
self._names_variants: dict[str, dict[str, Any]] | None = None
|
|
509
|
+
|
|
510
|
+
# --------------------------------------------------------------------- index
|
|
511
|
+
@property
|
|
512
|
+
def index(self) -> ItemIndex:
|
|
513
|
+
if self._index is None:
|
|
514
|
+
self._index = build_index(self.provider)
|
|
515
|
+
return self._index
|
|
516
|
+
|
|
517
|
+
def ids(self) -> list[str]:
|
|
518
|
+
"""All item ids in the realm (sorted)."""
|
|
519
|
+
|
|
520
|
+
return sorted(self.index.by_id)
|
|
521
|
+
|
|
522
|
+
def categories(self) -> list[str]:
|
|
523
|
+
"""Top-level categories (``weapon``, ``armor``, ``artefact``, ...)."""
|
|
524
|
+
|
|
525
|
+
return list(self.index.categories)
|
|
526
|
+
|
|
527
|
+
def subcategories(self, category: str) -> list[str]:
|
|
528
|
+
return self.index.subcategories(category)
|
|
529
|
+
|
|
530
|
+
# ---------------------------------------------------------------------- read
|
|
531
|
+
def get(self, item_id: str) -> Item:
|
|
532
|
+
"""Load an item by id; raises :class:`DatabaseNotFound` when it is absent."""
|
|
533
|
+
|
|
534
|
+
paths = self.index.locate(item_id)
|
|
535
|
+
if not paths:
|
|
536
|
+
raise DatabaseNotFound(f"item {item_id!r} not found in realm {self.provider.realm!r}")
|
|
537
|
+
return self._load(paths[0])
|
|
538
|
+
|
|
539
|
+
def get_all(self, item_id: str) -> list[Item]:
|
|
540
|
+
"""Load every item sharing the same id (ids are not guaranteed to be unique)."""
|
|
541
|
+
|
|
542
|
+
return [self._load(path) for path in self.index.locate(item_id)]
|
|
543
|
+
|
|
544
|
+
def variants(self, item_id: str) -> list[Item]:
|
|
545
|
+
"""Load the ``_variants/<id>/*.json`` list of an item."""
|
|
546
|
+
|
|
547
|
+
entries = self.index.variants.get(item_id)
|
|
548
|
+
if not entries:
|
|
549
|
+
canonical = self.index.lower_ids.get(item_id.casefold())
|
|
550
|
+
entries = self.index.variants.get(canonical, []) if canonical else []
|
|
551
|
+
return [self._load(path) for _number, path in entries]
|
|
552
|
+
|
|
553
|
+
def all(self, category: str | None = None) -> Iterator[Item]:
|
|
554
|
+
"""Iterate over every item (optionally inside a category, e.g. ``"weapon/pistol"``)."""
|
|
555
|
+
|
|
556
|
+
for path in self.index.category_paths(category):
|
|
557
|
+
yield self._load(path)
|
|
558
|
+
|
|
559
|
+
def _load(self, path: str) -> Item:
|
|
560
|
+
data = self.provider.read_json(path)
|
|
561
|
+
return Item.from_dict(data, path=path, realm=self.provider.realm)
|
|
562
|
+
|
|
563
|
+
def __iter__(self) -> Iterator[Item]:
|
|
564
|
+
return self.all()
|
|
565
|
+
|
|
566
|
+
def __len__(self) -> int:
|
|
567
|
+
return len(self.index.by_id)
|
|
568
|
+
|
|
569
|
+
def __contains__(self, item_id: object) -> bool:
|
|
570
|
+
return isinstance(item_id, str) and bool(self.index.locate(item_id))
|
|
571
|
+
|
|
572
|
+
# -------------------------------------------------------------------- search
|
|
573
|
+
def _name_cache_key(self, include_variants: bool) -> str:
|
|
574
|
+
suffix = ":variants" if include_variants else ""
|
|
575
|
+
return f"name_index:{self.provider.namespace}{suffix}"
|
|
576
|
+
|
|
577
|
+
def _load_names(self, include_variants: bool = False) -> dict[str, dict[str, Any]] | None:
|
|
578
|
+
if self._names is not None and not include_variants:
|
|
579
|
+
return self._names
|
|
580
|
+
cached_names = self._names_variants
|
|
581
|
+
if include_variants and cached_names is not None:
|
|
582
|
+
return cached_names
|
|
583
|
+
cache = self.provider.cache
|
|
584
|
+
if cache is not None:
|
|
585
|
+
value, _etag, _fresh = cache.get_json(self._name_cache_key(include_variants), allow_stale=True)
|
|
586
|
+
if isinstance(value, dict) and isinstance(value.get("items"), dict):
|
|
587
|
+
if include_variants:
|
|
588
|
+
self._names_variants = value["items"]
|
|
589
|
+
else:
|
|
590
|
+
self._names = value["items"]
|
|
591
|
+
return value["items"]
|
|
592
|
+
return None
|
|
593
|
+
|
|
594
|
+
def build_name_index(
|
|
595
|
+
self,
|
|
596
|
+
*,
|
|
597
|
+
include_variants: bool = False,
|
|
598
|
+
progress: ProgressCallback | None = None,
|
|
599
|
+
force: bool = False,
|
|
600
|
+
) -> int:
|
|
601
|
+
"""Download every item name and cache it; required by :meth:`search`.
|
|
602
|
+
|
|
603
|
+
By default only regular items are indexed; pass ``include_variants=True``
|
|
604
|
+
to include ``_variants/*.json`` entries as well.
|
|
605
|
+
"""
|
|
606
|
+
|
|
607
|
+
if not force:
|
|
608
|
+
existing = self._load_names(include_variants)
|
|
609
|
+
if existing is not None:
|
|
610
|
+
return len(existing)
|
|
611
|
+
|
|
612
|
+
if include_variants:
|
|
613
|
+
paths = list(self.index.item_paths)
|
|
614
|
+
else:
|
|
615
|
+
paths = list(self.index.main_paths)
|
|
616
|
+
paths.sort()
|
|
617
|
+
total = len(paths)
|
|
618
|
+
entries: dict[str, dict[str, Any]] = {}
|
|
619
|
+
for done, path in enumerate(paths, start=1):
|
|
620
|
+
data = self.provider.read_json(path)
|
|
621
|
+
name = data.get("name")
|
|
622
|
+
names: dict[str, str] = {}
|
|
623
|
+
if isinstance(name, dict):
|
|
624
|
+
lines = name.get("lines")
|
|
625
|
+
if isinstance(lines, dict):
|
|
626
|
+
names = {str(lang): str(value) for lang, value in lines.items()}
|
|
627
|
+
elif name.get("text"):
|
|
628
|
+
names = {"en": str(name["text"])}
|
|
629
|
+
entries[path] = {"id": str(data.get("id") or Path(path).stem), "names": names}
|
|
630
|
+
if progress is not None:
|
|
631
|
+
progress(path, done, total)
|
|
632
|
+
|
|
633
|
+
if include_variants:
|
|
634
|
+
self._names_variants = entries
|
|
635
|
+
else:
|
|
636
|
+
self._names = entries
|
|
637
|
+
cache = self.provider.cache
|
|
638
|
+
if cache is not None:
|
|
639
|
+
cache.set_json(self._name_cache_key(include_variants), {"items": entries})
|
|
640
|
+
return len(entries)
|
|
641
|
+
|
|
642
|
+
def search(
|
|
643
|
+
self,
|
|
644
|
+
query: str,
|
|
645
|
+
*,
|
|
646
|
+
lang: str = "en",
|
|
647
|
+
limit: int | None = 50,
|
|
648
|
+
include_variants: bool = False,
|
|
649
|
+
) -> list[Item]:
|
|
650
|
+
"""Search items by (part of) their localized name.
|
|
651
|
+
|
|
652
|
+
Regular items are searched by default. For the GitHub provider the name index
|
|
653
|
+
must be built first (:meth:`build_name_index`); local checkouts build it
|
|
654
|
+
automatically.
|
|
655
|
+
"""
|
|
656
|
+
|
|
657
|
+
needle = query.strip().casefold()
|
|
658
|
+
if not needle:
|
|
659
|
+
return []
|
|
660
|
+
entries = self._load_names(include_variants)
|
|
661
|
+
if entries is None:
|
|
662
|
+
if not self.provider.is_bulk:
|
|
663
|
+
raise DatabaseError(
|
|
664
|
+
"the name index is not built yet; call build_name_index() once "
|
|
665
|
+
"(or use Database.local()/Database.sync() for offline search)"
|
|
666
|
+
)
|
|
667
|
+
self.build_name_index(include_variants=include_variants)
|
|
668
|
+
entries = self._load_names(include_variants) or {}
|
|
669
|
+
|
|
670
|
+
ranked: list[tuple[int, str, str]] = []
|
|
671
|
+
for path, info in entries.items():
|
|
672
|
+
names = info.get("names") or {}
|
|
673
|
+
value = names.get(lang) or names.get(_LANG_FALLBACK)
|
|
674
|
+
if value is None and names:
|
|
675
|
+
value = next(iter(names.values()))
|
|
676
|
+
if not value:
|
|
677
|
+
continue
|
|
678
|
+
folded = str(value).casefold()
|
|
679
|
+
if folded == needle:
|
|
680
|
+
score = 0
|
|
681
|
+
elif folded.startswith(needle):
|
|
682
|
+
score = 1
|
|
683
|
+
elif needle in folded:
|
|
684
|
+
score = 2
|
|
685
|
+
else:
|
|
686
|
+
continue
|
|
687
|
+
ranked.append((score, folded, path))
|
|
688
|
+
|
|
689
|
+
ranked.sort()
|
|
690
|
+
if limit is not None:
|
|
691
|
+
ranked = ranked[:limit]
|
|
692
|
+
return [self._load(path) for _score, _name, path in ranked]
|