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.
@@ -0,0 +1,162 @@
1
+ """Shared helpers, enums and small value objects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass, field
7
+ from datetime import datetime, timezone
8
+ from enum import Enum
9
+ from typing import Any
10
+
11
+ __all__ = [
12
+ "Alliance",
13
+ "Realm",
14
+ "Region",
15
+ "RegionInfo",
16
+ "format_datetime",
17
+ "parse_datetime",
18
+ "region_value",
19
+ ]
20
+
21
+
22
+ def _fallback_member(cls: type[Enum], value: str) -> Any:
23
+ """Create a pseudo-member for values unknown to the enum (forward compatibility)."""
24
+
25
+ member = str.__new__(cls, value) # type: ignore[arg-type]
26
+ member._name_ = value # type: ignore[attr-defined]
27
+ member._value_ = value # type: ignore[attr-defined]
28
+ return member
29
+
30
+
31
+ class Region(str, Enum):
32
+ """Game region (server). Unknown regions are accepted as-is."""
33
+
34
+ RU = "RU"
35
+ EU = "EU"
36
+ NA = "NA"
37
+ SEA = "SEA"
38
+ NEA = "NEA"
39
+
40
+ def __str__(self) -> str:
41
+ return self.value
42
+
43
+ @classmethod
44
+ def _missing_(cls, value: object) -> "Region | None":
45
+ if isinstance(value, str) and value.strip():
46
+ normalized = value.strip().upper()
47
+ if normalized in cls.__members__:
48
+ return cls.__members__[normalized]
49
+ return _fallback_member(cls, normalized)
50
+ return None
51
+
52
+
53
+ class Realm(str, Enum):
54
+ """Game version the items database is tied to."""
55
+
56
+ RU = "ru"
57
+ GLOBAL = "global"
58
+
59
+ def __str__(self) -> str:
60
+ return self.value
61
+
62
+ @classmethod
63
+ def _missing_(cls, value: object) -> "Realm | None":
64
+ if isinstance(value, str):
65
+ normalized = value.strip().lower()
66
+ for member in cls:
67
+ if member.value == normalized:
68
+ return member
69
+ aliases = {"en": "global", "world": "global", "global": "global", "ru": "ru"}
70
+ alias = aliases.get(normalized)
71
+ if alias is not None:
72
+ return cls(alias)
73
+ return None
74
+
75
+
76
+ class Alliance(str, Enum):
77
+ """Known in-game alliances; unknown values are still accepted."""
78
+
79
+ DUTY = "duty"
80
+ COVENANT = "covenant"
81
+ MERCENARIES = "mercenaries"
82
+ UNKNOWN = "unknown"
83
+
84
+ def __str__(self) -> str:
85
+ return self.value
86
+
87
+ @classmethod
88
+ def _missing_(cls, value: object) -> "Alliance | None":
89
+ if isinstance(value, str) and value.strip():
90
+ normalized = value.strip().lower()
91
+ for member in cls:
92
+ if member.value == normalized:
93
+ return member
94
+ return _fallback_member(cls, normalized)
95
+ return None
96
+
97
+
98
+ def region_value(value: str | Region) -> str:
99
+ """Normalize a region argument to the uppercase string expected by the API."""
100
+
101
+ if isinstance(value, Enum):
102
+ value = value.value
103
+ normalized = str(value).strip().upper()
104
+ if not normalized:
105
+ raise ValueError("region must not be empty")
106
+ return normalized
107
+
108
+
109
+ def parse_datetime(value: Any) -> datetime | None:
110
+ """Parse an ISO-8601 timestamp returned by the API (``Z`` suffix and >6 digits supported)."""
111
+
112
+ if value is None or value == "":
113
+ return None
114
+ if isinstance(value, datetime):
115
+ return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
116
+ text = str(value).strip()
117
+ if not text:
118
+ return None
119
+ if text.endswith(("Z", "z")):
120
+ text = text[:-1] + "+00:00"
121
+ try:
122
+ parsed = datetime.fromisoformat(text)
123
+ except ValueError:
124
+ # Python < 3.11 rejects more than 6 fractional digits; trim them.
125
+ fixed = re.sub(r"(\.\d{6})\d+", r"\1", text)
126
+ if fixed == text:
127
+ return None
128
+ parsed = datetime.fromisoformat(fixed)
129
+ if parsed.tzinfo is None:
130
+ parsed = parsed.replace(tzinfo=timezone.utc)
131
+ return parsed
132
+
133
+
134
+ def format_datetime(value: datetime | str) -> str:
135
+ """Serialize a datetime the way the API expects (``2025-01-20T10:15:30Z``)."""
136
+
137
+ if isinstance(value, str):
138
+ return value
139
+ if value.tzinfo is None:
140
+ value = value.replace(tzinfo=timezone.utc)
141
+ return value.astimezone(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
142
+
143
+
144
+ @dataclass
145
+ class RegionInfo:
146
+ """One entry of ``GET /regions``."""
147
+
148
+ id: str
149
+ name: str
150
+ extra: dict[str, Any] = field(default_factory=dict, repr=False)
151
+
152
+ @classmethod
153
+ def from_dict(cls, data: dict[str, Any]) -> "RegionInfo":
154
+ known = {"id", "name"}
155
+ return cls(
156
+ id=str(data.get("id", "")),
157
+ name=str(data.get("name", "")),
158
+ extra={k: v for k, v in data.items() if k not in known},
159
+ )
160
+
161
+ def __str__(self) -> str:
162
+ return self.id
@@ -0,0 +1,44 @@
1
+ """Model for the emission endpoint."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime
7
+ from typing import Any
8
+
9
+ from .common import parse_datetime
10
+
11
+ __all__ = ["Emission"]
12
+
13
+
14
+ @dataclass
15
+ class Emission:
16
+ """Current and previous emission timestamps."""
17
+
18
+ current_start: datetime | None = None
19
+ previous_start: datetime | None = None
20
+ previous_end: datetime | None = None
21
+ extra: dict[str, Any] = field(default_factory=dict, repr=False)
22
+
23
+ @classmethod
24
+ def from_dict(cls, data: dict[str, Any]) -> "Emission":
25
+ known = {"currentStart", "previousStart", "previousEnd"}
26
+ return cls(
27
+ current_start=parse_datetime(data.get("currentStart")),
28
+ previous_start=parse_datetime(data.get("previousStart")),
29
+ previous_end=parse_datetime(data.get("previousEnd")),
30
+ extra={k: v for k, v in data.items() if k not in known},
31
+ )
32
+
33
+ @property
34
+ def active(self) -> bool:
35
+ """Whether an emission is running right now."""
36
+
37
+ return self.current_start is not None
38
+
39
+ def __str__(self) -> str:
40
+ if self.active and self.current_start is not None:
41
+ return f"Emission: active since {self.current_start:%Y-%m-%d %H:%M} UTC"
42
+ if self.previous_end is not None:
43
+ return f"Emission: inactive, last ended {self.previous_end:%Y-%m-%d %H:%M} UTC"
44
+ return "Emission: no data"
@@ -0,0 +1,149 @@
1
+ """Models for operation sessions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime
7
+ from typing import Any, Iterator
8
+
9
+ from .common import parse_datetime
10
+
11
+ __all__ = ["OperationSession", "SessionPage", "SessionParticipant"]
12
+
13
+
14
+ @dataclass
15
+ class SessionParticipant:
16
+ username: str
17
+ death: int = 0
18
+ mob_kills: int = 0
19
+ damage_received: float = 0.0
20
+ damage_dealt: float = 0.0
21
+ armor_class: str | None = None
22
+ armor_item_id: str | None = None
23
+ armor_level: int = 0
24
+ primary_weapon_item_id: str | None = None
25
+ primary_weapon_level: int = 0
26
+ secondary_weapon_item_id: str | None = None
27
+ secondary_weapon_level: int = 0
28
+ extra: dict[str, Any] = field(default_factory=dict, repr=False)
29
+
30
+ @classmethod
31
+ def from_dict(cls, data: dict[str, Any]) -> "SessionParticipant":
32
+ known = {
33
+ "username",
34
+ "death",
35
+ "mobKills",
36
+ "damageReceived",
37
+ "damageDealt",
38
+ "armorClass",
39
+ "armorItemId",
40
+ "armorLevel",
41
+ "primaryWeaponItemId",
42
+ "primaryWeaponLevel",
43
+ "secondaryWeaponItemId",
44
+ "secondaryWeaponLevel",
45
+ }
46
+ return cls(
47
+ username=str(data.get("username", "")),
48
+ death=int(data.get("death") or 0),
49
+ mob_kills=int(data.get("mobKills") or 0),
50
+ damage_received=float(data.get("damageReceived") or 0.0),
51
+ damage_dealt=float(data.get("damageDealt") or 0.0),
52
+ armor_class=data.get("armorClass"),
53
+ armor_item_id=data.get("armorItemId"),
54
+ armor_level=int(data.get("armorLevel") or 0),
55
+ primary_weapon_item_id=data.get("primaryWeaponItemId"),
56
+ primary_weapon_level=int(data.get("primaryWeaponLevel") or 0),
57
+ secondary_weapon_item_id=data.get("secondaryWeaponItemId"),
58
+ secondary_weapon_level=int(data.get("secondaryWeaponLevel") or 0),
59
+ extra={k: v for k, v in data.items() if k not in known},
60
+ )
61
+
62
+
63
+ @dataclass
64
+ class OperationSession:
65
+ id: int
66
+ map: str
67
+ start_time: datetime | None = None
68
+ end_time: datetime | None = None
69
+ difficulty: int = 0
70
+ session_duration_seconds: float = 0.0
71
+ difficulty_reward: int = 0
72
+ participants: list[SessionParticipant] = field(default_factory=list)
73
+ extra: dict[str, Any] = field(default_factory=dict, repr=False)
74
+
75
+ @classmethod
76
+ def from_dict(cls, data: dict[str, Any]) -> "OperationSession":
77
+ known = {
78
+ "id",
79
+ "map",
80
+ "startTime",
81
+ "endTime",
82
+ "difficulty",
83
+ "sessionDurationSeconds",
84
+ "difficultyReward",
85
+ "participants",
86
+ }
87
+ return cls(
88
+ id=int(data.get("id") or 0),
89
+ map=str(data.get("map", "")),
90
+ start_time=parse_datetime(data.get("startTime")),
91
+ end_time=parse_datetime(data.get("endTime")),
92
+ difficulty=int(data.get("difficulty") or 0),
93
+ session_duration_seconds=float(data.get("sessionDurationSeconds") or 0.0),
94
+ difficulty_reward=int(data.get("difficultyReward") or 0),
95
+ participants=[SessionParticipant.from_dict(entry) for entry in data.get("participants") or []],
96
+ extra={k: v for k, v in data.items() if k not in known},
97
+ )
98
+
99
+ def participant(self, username: str) -> SessionParticipant | None:
100
+ username = username.casefold()
101
+ for entry in self.participants:
102
+ if entry.username.casefold() == username:
103
+ return entry
104
+ return None
105
+
106
+ def __str__(self) -> str:
107
+ return f"{self.id} · {self.map} · {len(self.participants)} players"
108
+
109
+
110
+ @dataclass
111
+ class SessionPage:
112
+ """Response of ``GET /{region}/operations/sessions``."""
113
+
114
+ total: int
115
+ sessions: list[OperationSession] = field(default_factory=list)
116
+ offset: int = 0
117
+
118
+ @property
119
+ def items(self) -> list[OperationSession]:
120
+ return self.sessions
121
+
122
+ def __iter__(self) -> Iterator[OperationSession]:
123
+ return iter(self.sessions)
124
+
125
+ def __len__(self) -> int:
126
+ return len(self.sessions)
127
+
128
+ def __getitem__(self, index: int) -> OperationSession:
129
+ return self.sessions[index]
130
+
131
+ @property
132
+ def next_offset(self) -> int:
133
+ return self.offset + len(self.sessions)
134
+
135
+ @property
136
+ def is_last(self) -> bool:
137
+ return not self.sessions or self.next_offset >= self.total
138
+
139
+ @classmethod
140
+ def from_dict(cls, data: dict[str, Any], *, offset: int = 0) -> "SessionPage":
141
+ return cls(
142
+ total=int(data.get("total") or 0),
143
+ sessions=[OperationSession.from_dict(entry) for entry in data.get("sessions") or []],
144
+ offset=offset,
145
+ )
146
+
147
+ def __str__(self) -> str:
148
+ lines = [str(session) for session in self.sessions]
149
+ return f"{len(lines)} of {self.total}" + ("\n" + "\n".join(lines) if lines else "")
@@ -0,0 +1,50 @@
1
+ """Helpers for walking paginated endpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable, Iterator, Protocol, TypeVar
6
+
7
+ __all__ = ["Paginated", "paginate"]
8
+
9
+ T = TypeVar("T", covariant=True)
10
+
11
+
12
+ class Paginated(Protocol[T]):
13
+ """Minimal protocol implemented by all ``*Page`` models."""
14
+
15
+ total: int
16
+ offset: int
17
+
18
+ @property
19
+ def items(self) -> Any: ...
20
+
21
+
22
+ def paginate(
23
+ fetch: Callable[[int, int], Paginated],
24
+ *,
25
+ page_size: int = 200,
26
+ limit: int | None = None,
27
+ start: int = 0,
28
+ ) -> Iterator:
29
+ """Yield items page by page until the response is exhausted or ``limit`` is reached."""
30
+
31
+ if page_size <= 0:
32
+ raise ValueError("page_size must be positive")
33
+ if limit is not None and limit <= 0:
34
+ return
35
+
36
+ offset = start
37
+ produced = 0
38
+ while True:
39
+ page = fetch(offset, page_size)
40
+ items = list(page.items)
41
+ if not items:
42
+ return
43
+ for item in items:
44
+ yield item
45
+ produced += 1
46
+ if limit is not None and produced >= limit:
47
+ return
48
+ if page.total is not None and offset + len(items) >= page.total:
49
+ return
50
+ offset += len(items)
stalzone_api/py.typed ADDED
File without changes