hungerbridge 1.0.dev4__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,47 @@
1
+ '''Python client for the HungerBridge Minecraft HTTP bridge.'''
2
+
3
+ from __future__ import annotations
4
+
5
+ from .auth import Credentials
6
+ from .client import BridgeClient, redeem_pickup
7
+ from .exceptions import (
8
+ HungerBridgeAuthError,
9
+ HungerBridgeConnectionError,
10
+ HungerBridgeError,
11
+ HungerBridgeForbidden,
12
+ HungerBridgeNotFound,
13
+ HungerBridgeRateLimit,
14
+ InvalidModeError,
15
+ )
16
+ from .protocol import PROTOCOL_VERSION
17
+ from .stream import Stream
18
+
19
+ try: # installed distribution
20
+ from importlib.metadata import PackageNotFoundError, version as _dist_version
21
+
22
+ try:
23
+ __version__ = _dist_version('hungerbridge')
24
+ except PackageNotFoundError:
25
+ __version__ = '0.0.0'
26
+ except ImportError: # pragma: no cover
27
+ __version__ = '0.0.0'
28
+
29
+ #: Alias kept for the name the original ``__init__`` tried to export.
30
+ HungerBridge = BridgeClient
31
+
32
+ __all__ = [
33
+ 'BridgeClient',
34
+ 'HungerBridge',
35
+ 'Stream',
36
+ 'Credentials',
37
+ 'redeem_pickup',
38
+ 'PROTOCOL_VERSION',
39
+ 'HungerBridgeError',
40
+ 'HungerBridgeRateLimit',
41
+ 'HungerBridgeAuthError',
42
+ 'HungerBridgeForbidden',
43
+ 'HungerBridgeNotFound',
44
+ 'HungerBridgeConnectionError',
45
+ 'InvalidModeError',
46
+ '__version__',
47
+ ]
hungerbridge/auth.py ADDED
@@ -0,0 +1,106 @@
1
+ '''HMAC-SHA256 request signing (HungerBridge protocol v1).
2
+
3
+ Signature input (``string_to_sign``)::
4
+
5
+ METHOD \\n normalized_path \\n timestamp \\n nonce \\n canonical_body
6
+
7
+ The key is the 32-byte per-token secret handed out once by the server's
8
+ ``/pickup/<id>?passkey=...`` endpoint, encoded as 64 hex characters.
9
+ '''
10
+
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import hmac
15
+ import time
16
+ import uuid
17
+ from dataclasses import dataclass, field
18
+ from typing import Any, Mapping
19
+
20
+ from .canonical import canonical_body, normalize_path
21
+
22
+ __all__ = [
23
+ 'HEADER_ID',
24
+ 'HEADER_TIMESTAMP',
25
+ 'HEADER_NONCE',
26
+ 'HEADER_SIGNATURE',
27
+ 'Credentials',
28
+ 'string_to_sign',
29
+ 'sign',
30
+ 'build_auth_headers',
31
+ ]
32
+
33
+ HEADER_ID = 'X-Auth-Id'
34
+ HEADER_TIMESTAMP = 'X-Auth-Timestamp'
35
+ HEADER_NONCE = 'X-Auth-Nonce'
36
+ HEADER_SIGNATURE = 'X-Auth-Signature'
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class Credentials:
41
+ '''A HungerBridge API token (id + hex secret).'''
42
+
43
+ token_id: str
44
+ secret: str = field(repr=False)
45
+
46
+ @classmethod
47
+ def parse(cls, token_id: str | None, token_secret: str | None = None) -> 'Credentials | None':
48
+ '''Build credentials from ``(id, secret)`` or a single ``'id:secret'`` string.
49
+
50
+ Returns ``None`` when no usable credentials were supplied (unauthenticated
51
+ client; every protected endpoint will answer 401).
52
+ '''
53
+ if token_id and not token_secret and ':' in token_id:
54
+ token_id, _, token_secret = token_id.rpartition(':')
55
+ if not token_id or not token_secret:
56
+ return None
57
+ return cls(token_id=token_id.strip(), secret=token_secret.strip())
58
+
59
+ @property
60
+ def key(self) -> bytes:
61
+ try:
62
+ return bytes.fromhex(self.secret)
63
+ except ValueError:
64
+ # Historical fallback: non-hex secrets are used as raw UTF-8 bytes.
65
+ return self.secret.encode('utf-8')
66
+
67
+
68
+ def string_to_sign(method: str, path: str, timestamp: str, nonce: str, body: str) -> str:
69
+ return f'{method.strip().upper()}\n{normalize_path(path)}\n{timestamp}\n{nonce}\n{body}'
70
+
71
+
72
+ def sign(key: bytes, message: str) -> str:
73
+ return hmac.new(key, message.encode('utf-8'), hashlib.sha256).hexdigest()
74
+
75
+
76
+ def build_auth_headers(
77
+ credentials: Credentials | None,
78
+ method: str,
79
+ path: str,
80
+ payload: Any = None,
81
+ *,
82
+ base_headers: Mapping[str, str] | None = None,
83
+ timestamp: int | str | None = None,
84
+ nonce: str | None = None,
85
+ ) -> dict:
86
+ '''Return request headers including a fresh signature.
87
+
88
+ A new nonce and timestamp are generated on every call; never reuse the
89
+ returned headers for another request (including retries) — the server
90
+ rejects replayed nonces.
91
+ '''
92
+ headers = dict(base_headers or {})
93
+ if credentials is None:
94
+ return headers
95
+ ts = str(int(time.time()) if timestamp is None else timestamp)
96
+ n = nonce or uuid.uuid4().hex
97
+ message = string_to_sign(method, path, ts, n, canonical_body(payload))
98
+ headers.update(
99
+ {
100
+ HEADER_ID: credentials.token_id,
101
+ HEADER_TIMESTAMP: ts,
102
+ HEADER_NONCE: n,
103
+ HEADER_SIGNATURE: sign(credentials.key, message),
104
+ }
105
+ )
106
+ return headers
hungerbridge/bridge.py ADDED
@@ -0,0 +1,30 @@
1
+ '''Backwards-compatibility module.
2
+
3
+ The client used to live entirely in this file. It has been split into:
4
+
5
+ * :mod:`hungerbridge.canonical` – canonical JSON / path normalization
6
+ * :mod:`hungerbridge.auth` – HMAC request signing
7
+ * :mod:`hungerbridge.transport` – HTTP, retries, timeouts, error mapping
8
+ * :mod:`hungerbridge.stream` – SSE log stream
9
+ * :mod:`hungerbridge.client` – ``BridgeClient`` endpoint wrappers
10
+ * :mod:`hungerbridge.exceptions`, :mod:`hungerbridge.units`
11
+
12
+ Existing imports such as ``from hungerbridge.bridge import BridgeClient``
13
+ keep working.
14
+ '''
15
+
16
+ from __future__ import annotations
17
+
18
+ from .canonical import canonical_body as _canonical_body
19
+ from .canonical import normalize_path as _normalize_path
20
+ from .client import BridgeClient
21
+ from .exceptions import HungerBridgeError, HungerBridgeRateLimit, InvalidModeError
22
+ from .stream import Stream
23
+ from .units import convert
24
+
25
+ __all__ = ['BridgeClient', 'Stream', 'HungerBridgeError', 'HungerBridgeRateLimit', 'InvalidModeError', 'convert']
26
+
27
+
28
+ def _canonicalize_json_body(value):
29
+ '''Deprecated private helper kept for compatibility (``None`` → ``''``).'''
30
+ return _canonical_body(value)
@@ -0,0 +1,123 @@
1
+ '''Canonical request encoding shared with the HungerBridge server.
2
+
3
+ Everything in this module is part of the wire protocol: the output must match
4
+ ``com.hungerbridge.common.security.TokenManager`` (``canonicalizeJson`` and
5
+ ``normalizePath``) byte for byte, otherwise HMAC signatures will not verify.
6
+
7
+ Rules (protocol v1):
8
+
9
+ * Objects: keys sorted by UTF-16 code unit order (Java ``TreeMap<String>``),
10
+ no whitespace, ``key:value`` pairs joined with ``,``.
11
+ * Strings: JSON escapes for ``'`` ``\\`` ``\\b`` ``\\f`` ``\\n`` ``\\r`` ``\\t``;
12
+ every other code unit below U+0020 or above U+007F is written as a
13
+ lower-case ``\\uXXXX`` escape. Characters outside the BMP are written as a
14
+ UTF-16 surrogate pair (two escapes), exactly like Java does.
15
+ * Numbers are emitted with :func:`json.dumps`; the body that is *sent* is the
16
+ canonical string itself, so the server canonicalizes the very same lexeme.
17
+ NaN and infinities are not valid JSON and are rejected.
18
+ * Paths: query string and fragment removed, leading ``/`` enforced, trailing
19
+ ``/`` removed (except for the root path).
20
+ '''
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import math
26
+ from typing import Any
27
+ from urllib.parse import urlparse
28
+
29
+ __all__ = ['canonical_json', 'canonical_body', 'normalize_path', 'quote_string']
30
+
31
+ _SIMPLE_ESCAPES = {
32
+ '"': '\\"',
33
+ "\\": "\\\\",
34
+ "\b": "\\b",
35
+ "\f": "\\f",
36
+ "\n": "\\n",
37
+ "\r": "\\r",
38
+ "\t": "\\t",
39
+ }
40
+
41
+
42
+ def quote_string(value: str | None) -> str:
43
+ '''Quote ``value`` as an ASCII-only JSON string literal (Java-compatible).'''
44
+ if value is None:
45
+ return '""'
46
+ out = ['"']
47
+ for ch in value:
48
+ simple = _SIMPLE_ESCAPES.get(ch)
49
+ if simple is not None:
50
+ out.append(simple)
51
+ continue
52
+ code = ord(ch)
53
+ if code > 0xFFFF:
54
+ # Java strings are UTF-16: emit the surrogate pair, not a 5+ digit escape.
55
+ code -= 0x10000
56
+ out.append('\\u%04x\\u%04x' % (0xD800 + (code >> 10), 0xDC00 + (code & 0x3FF)))
57
+ elif code < 0x20 or code > 0x7F:
58
+ out.append('\\u%04x' % code)
59
+ else:
60
+ out.append(ch)
61
+ out.append('"')
62
+ return ''.join(out)
63
+
64
+
65
+ def _utf16_sort_key(key: str) -> bytes:
66
+ # Java's TreeMap<String> orders by UTF-16 code units; Python orders by code
67
+ # points. They differ only when non-BMP characters are compared with
68
+ # characters in U+E000..U+FFFF. Encoding as UTF-16-BE gives Java's order.
69
+ return key.encode('utf-16-be', 'surrogatepass')
70
+
71
+
72
+ def canonical_json(value: Any) -> str:
73
+ '''Return the canonical JSON encoding of ``value``.
74
+
75
+ ``None`` encodes as ``null``. Unknown objects are encoded as their ``str()``
76
+ (quoted), matching the historical client behavior.
77
+ '''
78
+ if value is None:
79
+ return 'null'
80
+ if isinstance(value, bool):
81
+ return 'true' if value else 'false'
82
+ if isinstance(value, int):
83
+ return str(int(value))
84
+ if isinstance(value, float):
85
+ if not math.isfinite(value):
86
+ raise ValueError('NaN and infinite floats cannot be encoded as JSON')
87
+ return json.dumps(value)
88
+ if isinstance(value, str):
89
+ return quote_string(value)
90
+ if isinstance(value, (list, tuple)):
91
+ return '[' + ','.join(canonical_json(v) for v in value) + ']'
92
+ if isinstance(value, dict):
93
+ items = sorted(((str(k), v) for k, v in value.items()), key=lambda kv: _utf16_sort_key(kv[0]))
94
+ return '{' + ','.join(quote_string(k) + ':' + canonical_json(v) for k, v in items) + '}'
95
+ return quote_string(str(value))
96
+
97
+
98
+ def canonical_body(payload: Any) -> str:
99
+ '''Canonical request body: empty string when there is no payload.'''
100
+ if payload is None:
101
+ return ''
102
+ return canonical_json(payload)
103
+
104
+
105
+ def normalize_path(path: str | None) -> str:
106
+ '''Normalize a request path exactly like ``TokenManager.normalizePath``.'''
107
+ if not path:
108
+ return '/'
109
+ normalized = path.strip()
110
+ if not normalized:
111
+ return '/'
112
+ if '://' in normalized:
113
+ try:
114
+ normalized = urlparse(normalized).path or '/'
115
+ except ValueError:
116
+ normalized = normalized.split('://', 1)[1]
117
+ normalized = '/' + normalized.split('/', 1)[1] if '/' in normalized else '/'
118
+ normalized = normalized.split('?', 1)[0].split('#', 1)[0]
119
+ if not normalized.startswith('/'):
120
+ normalized = '/' + normalized
121
+ while len(normalized) > 1 and normalized.endswith('/'):
122
+ normalized = normalized[:-1]
123
+ return normalized or '/'
hungerbridge/client.py ADDED
@@ -0,0 +1,353 @@
1
+ '''High-level HungerBridge API client.'''
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import time
7
+ from typing import Any, Optional, Tuple
8
+ from urllib.parse import parse_qs, urlparse
9
+
10
+ import requests
11
+
12
+ from .auth import Credentials
13
+ from .exceptions import HungerBridgeError, InvalidModeError
14
+ from .stream import Stream
15
+ from .transport import DEFAULT_TIMEOUT, Timeout, Transport, _json_or_none
16
+ from .units import BYTE_UNITS, convert_bytes
17
+
18
+ __all__ = ['BridgeClient', 'redeem_pickup']
19
+
20
+
21
+ def _extract(response: Any, path: Optional[str]) -> Any:
22
+ '''Return ``response[a][b]...`` for a dotted ``path`` (``None`` if absent).'''
23
+ if response is None:
24
+ return None
25
+ if not path:
26
+ return response
27
+ cur = response
28
+ for part in path.split('.'):
29
+ if not isinstance(cur, dict):
30
+ return None
31
+ cur = cur.get(part)
32
+ return cur
33
+
34
+
35
+ def redeem_pickup(
36
+ url: str,
37
+ pickup_id: Optional[str] = None,
38
+ passkey: Optional[str] = None,
39
+ *,
40
+ timeout: Timeout = DEFAULT_TIMEOUT,
41
+ ) -> Tuple[str, str]:
42
+ '''Redeem a one-time token pickup and return ``(token_id, token_secret)``.
43
+
44
+ Accepts either the full URL printed by ``/hb token create``
45
+ (``http://host:1913/pickup/<id>?passkey=<hex>``) or a base URL plus
46
+ ``pickup_id`` and ``passkey``. Pickups are single-use.
47
+ '''
48
+ if pickup_id is None:
49
+ parsed = urlparse(url)
50
+ pickup_id = parsed.path.rstrip('/').rsplit('/', 1)[-1]
51
+ passkey = passkey or (parse_qs(parsed.query).get('passkey') or [None])[0]
52
+ url = f'{parsed.scheme}://{parsed.netloc}'
53
+ if not pickup_id or not passkey:
54
+ raise ValueError('pickup id and passkey are required')
55
+ response = requests.get(f'{url.rstrip("/")}/pickup/{pickup_id}', params={'passkey': passkey}, timeout=timeout)
56
+ if not response.ok:
57
+ raise Transport._error_for(response)
58
+ data = _json_or_none(response) or {}
59
+ token_id, secret = data.get('token_id'), data.get('token_secret')
60
+ if not token_id or not secret:
61
+ raise HungerBridgeError('Pickup response did not contain a token', status=response.status_code, body=data)
62
+ return token_id, secret
63
+
64
+
65
+ class BridgeClient:
66
+ '''Client for the HungerBridge HTTP API.
67
+
68
+ ``token_id``/``token_secret`` may also be given as a single ``'id:secret'``
69
+ string in ``token_id``. All getters return plain Python values/dicts.
70
+ '''
71
+
72
+ def __init__(
73
+ self,
74
+ url: str,
75
+ token_id: Optional[str] = None,
76
+ token_secret: Optional[str] = None,
77
+ history_handler=None,
78
+ new_log_handler=None,
79
+ max_retries: int = 0,
80
+ retry_backoff_sec: float = 1.0,
81
+ swallow_rate_limit: bool = False,
82
+ static_delay: float = 0.0,
83
+ *,
84
+ timeout: Timeout = DEFAULT_TIMEOUT,
85
+ session: Optional[requests.Session] = None,
86
+ ):
87
+ self.base = url.rstrip('/')
88
+ self.credentials = Credentials.parse(token_id, token_secret)
89
+ self.transport = Transport(
90
+ self.base,
91
+ self.credentials,
92
+ max_retries=max_retries,
93
+ retry_backoff_sec=retry_backoff_sec,
94
+ swallow_rate_limit=swallow_rate_limit,
95
+ static_delay=static_delay,
96
+ timeout=timeout,
97
+ session=session,
98
+ )
99
+ self.stream = Stream(
100
+ base_url=self.base,
101
+ headers_provider=lambda: self.transport.auth_headers('GET', '/server/stream'),
102
+ history_handler=history_handler,
103
+ new_log_handler=new_log_handler,
104
+ )
105
+
106
+ # -- backwards-compatible internals ---------------------------------------------
107
+
108
+ @property
109
+ def _token_id(self) -> Optional[str]:
110
+ return self.credentials.token_id if self.credentials else None
111
+
112
+ @property
113
+ def _token_secret(self) -> Optional[str]:
114
+ return self.credentials.secret if self.credentials else None
115
+
116
+ def _get(self, path: str) -> Any:
117
+ return self.transport.get(path)
118
+
119
+ def _post(self, path: str, payload: Any) -> Any:
120
+ return self.transport.post(path, payload)
121
+
122
+ def _build_auth_headers(self, method: str, path: str, body: Any) -> dict:
123
+ return self.transport.auth_headers(method, path, body)
124
+
125
+ def _extract(self, response: Any, path: Optional[str]) -> Any:
126
+ return _extract(response, path)
127
+
128
+ def _convert(self, value: Any, unit: Optional[str]) -> Any:
129
+ # Unknown units (and 'b') return the raw byte value, as before.
130
+ if value is None or not isinstance(unit, str) or unit.lower() not in BYTE_UNITS or unit.lower() == 'b':
131
+ return value
132
+ return convert_bytes(value, 'b', unit)
133
+
134
+ # -- connectivity ---------------------------------------------------------------
135
+
136
+ def isOk(self) -> bool:
137
+ return str(_extract(self._get('ping'), 'ok')).lower() == 'true'
138
+
139
+ def getServerTime(self):
140
+ '''Server wall-clock time in epoch milliseconds.'''
141
+ return _extract(self._get('ping'), 'server_time')
142
+
143
+ def getPing(self) -> int:
144
+ '''Round-trip time of an authenticated ``/ping`` in milliseconds.'''
145
+ start = time.perf_counter()
146
+ self._get('ping')
147
+ return int((time.perf_counter() - start) * 1000)
148
+
149
+ def getTokenInfo(self) -> dict:
150
+ resp = self._get('auth/check')
151
+ return {
152
+ 'token_id': _extract(resp, 'tokenId'),
153
+ 'policy_id': _extract(resp, 'policyId'),
154
+ 'permissions': _extract(resp, 'permissions'),
155
+ }
156
+
157
+ # -- server metadata ------------------------------------------------------------
158
+
159
+ def getServerMeta(self) -> dict:
160
+ resp = self._get('server/meta')
161
+ return {
162
+ 'platform': _extract(resp, 'platform'),
163
+ 'minecraft_version': _extract(resp, 'minecraft_version'),
164
+ 'bridge_version': _extract(resp, 'bridge_version'),
165
+ 'port': _extract(resp, 'port'),
166
+ 'protocol_version': _extract(resp, 'protocol_version'),
167
+ }
168
+
169
+ def getPlatform(self):
170
+ return self.getServerMeta()['platform']
171
+
172
+ def getMinecraftVersion(self):
173
+ return self.getServerMeta()['minecraft_version']
174
+
175
+ def getBridgeVersion(self):
176
+ return self.getServerMeta()['bridge_version']
177
+
178
+ def getBridgePort(self):
179
+ return self.getServerMeta()['port']
180
+
181
+ def getProtocolVersion(self) -> int:
182
+ '''Protocol version spoken by the server (1 for servers that predate versioning).'''
183
+ version = self.getServerMeta().get('protocol_version')
184
+ return int(version) if version is not None else 1
185
+
186
+ # -- players --------------------------------------------------------------------
187
+
188
+ def getPlayers(self, mode: str = 'count'):
189
+ resp = self._get('players/list')
190
+ if mode == 'count':
191
+ return _extract(resp, 'count')
192
+ if mode == 'list':
193
+ return _extract(resp, 'players')
194
+ raise InvalidModeError(f'Invalid mode: "{mode}"')
195
+
196
+ def getMaxPlayers(self) -> int:
197
+ max_players = _extract(self._get('players/list'), 'max')
198
+ try:
199
+ return int(max_players) if max_players is not None else 0
200
+ except (TypeError, ValueError):
201
+ return 0
202
+
203
+ # -- world ----------------------------------------------------------------------
204
+
205
+ _TPS_FIELDS = {'current': 'tps', '1m': 'tps_1m', '5m': 'tps_5m', '15m': 'tps_15m'}
206
+
207
+ def getTPS(self, mode: str = 'current'):
208
+ field = self._TPS_FIELDS.get(mode)
209
+ if field is None:
210
+ raise InvalidModeError(f'Invalid mode: "{mode}"')
211
+ return _extract(self._get('world/tps'), field)
212
+
213
+ def getMSPT(self):
214
+ return _extract(self._get('world/mspt'), 'mspt')
215
+
216
+ def getWorldTime(self):
217
+ '''Overworld time of day in ticks (0-23999); ``-1`` if unavailable.'''
218
+ return _extract(self._get('world/time'), 'time')
219
+
220
+ def getWorldTimeInfo(self) -> dict:
221
+ resp = self._get('world/time')
222
+ return {key: _extract(resp, key) for key in ('time', 'full_time', 'day', 'server_time')}
223
+
224
+ def getWorldWeather(self):
225
+ return _extract(self._get('world/weather'), 'weather')
226
+
227
+ def _world_counts(self, path: str) -> dict:
228
+ resp = self._get(path)
229
+ return {key: _extract(resp, key) for key in ('total', 'world', 'world_nether', 'world_the_end')}
230
+
231
+ def getLoadedChunks(self) -> dict:
232
+ return self._world_counts('world/chunks')
233
+
234
+ def getLoadedEntities(self) -> dict:
235
+ return self._world_counts('world/entities')
236
+
237
+ # -- system ---------------------------------------------------------------------
238
+
239
+ def getUptime(self):
240
+ return _extract(self._get('system/uptime'), 'uptime_ms')
241
+
242
+ def getCPUStats(self) -> dict:
243
+ resp = self._get('system/cpu')
244
+ return {'load': _extract(resp, 'cpu_load'), 'processors': _extract(resp, 'processors')}
245
+
246
+ _MEMORY_FIELDS = (
247
+ 'heap_used',
248
+ 'heap_committed',
249
+ 'heap_max',
250
+ 'nonheap_used',
251
+ 'nonheap_committed',
252
+ 'nonheap_max',
253
+ 'jvm_used',
254
+ 'jvm_committed',
255
+ 'jvm_max',
256
+ 'process_used',
257
+ 'process_virtual',
258
+ )
259
+
260
+ def getMemoryStats(self, unit: str = 'mib') -> dict:
261
+ resp = self._get('system/memory')
262
+ raw = {name: _extract(resp, name + '_bytes') for name in self._MEMORY_FIELDS}
263
+ out = {name: self._convert(value, unit) for name, value in raw.items()}
264
+ used, committed = raw['heap_used'], raw['heap_committed']
265
+ out.update(
266
+ {
267
+ 'used': self._convert(used, unit),
268
+ 'total': self._convert(committed, unit),
269
+ 'free': self._convert(max(0, committed - used) if committed is not None and used is not None else None, unit),
270
+ 'max': self._convert(raw['heap_max'], unit),
271
+ }
272
+ )
273
+ return out
274
+
275
+ def getProcessMemory(self, unit: str = 'mib') -> dict:
276
+ resp = self._get('system/memory')
277
+ return {
278
+ 'process_used': self._convert(_extract(resp, 'process_used_bytes'), unit),
279
+ 'process_virtual': self._convert(_extract(resp, 'process_virtual_bytes'), unit),
280
+ }
281
+
282
+ def getGCStats(self) -> dict:
283
+ resp = self._get('system/gc')
284
+ return {k: _extract(resp, k) for k in ('gc_type', 'gc_count', 'gc_time_ms', 'last_gc_pause_ms', 'avg_gc_pause_ms')}
285
+
286
+ def getThreadStats(self) -> dict:
287
+ resp = self._get('system/threads')
288
+ return {k: _extract(resp, k) for k in ('current', 'peak', 'daemon')}
289
+
290
+ def getNetworkStats(self) -> dict:
291
+ resp = self._get('system/network')
292
+ return {k: _extract(resp, k) for k in ('bytes_in_per_sec', 'bytes_out_per_sec', 'total_bytes_in', 'total_bytes_out')}
293
+
294
+ # -- actions --------------------------------------------------------------------
295
+
296
+ def log(self, message: str, level: Optional[str] = 'info', thread: Optional[str] = None):
297
+ '''``POST /server/log`` and return the server's response dict.
298
+
299
+ ``level`` accepts builtin or custom level names. ``level=None`` prefixes
300
+ the message with backspaces so consoles render it without a level tag.
301
+ ``thread`` sets the logger/thread label of the emitted event.
302
+ '''
303
+ if level is not None:
304
+ body = {'level': level, 'message': message}
305
+ else:
306
+ body = {'level': 'info', 'message': ('\b' * 50) + message}
307
+ if thread is not None:
308
+ body['thread'] = thread
309
+ return self._post('server/log', body)
310
+
311
+ def runCommand(self, command: str, showConsole: bool = False, silent: bool = False, normalize: bool = True):
312
+ '''``POST /server/run``.
313
+
314
+ With ``normalize=False`` the full response dict is returned; otherwise the
315
+ captured output lines joined with ``\\n`` (or ``None``).
316
+ '''
317
+ resp = self._post('server/run', {'command': command, 'silent': silent, 'show_console': showConsole})
318
+ if not normalize:
319
+ return resp
320
+ if isinstance(resp, dict):
321
+ out = resp.get('output')
322
+ if isinstance(out, list):
323
+ return '\n'.join(str(x) for x in out)
324
+ if isinstance(out, (str, bytes)):
325
+ return out
326
+ return None
327
+ if isinstance(resp, list):
328
+ return '\n'.join(str(x) for x in resp)
329
+ if isinstance(resp, (str, bytes)):
330
+ return resp
331
+ return None
332
+
333
+ def broadcast(self, msg: str, prefix: Optional[str] = None):
334
+ '''Broadcast ``msg`` (optionally prefixed) to all players via ``tellraw @a``.'''
335
+ component = json.dumps({'text': (prefix or '') + msg}, ensure_ascii=False)
336
+ return self.runCommand(f'tellraw @a {component}', showConsole=True, silent=False, normalize=True)
337
+
338
+ def stopServer(self):
339
+ '''``POST /server/stop`` — stops the Minecraft server; returns the response dict.'''
340
+ return self._post('server/stop', {})
341
+
342
+ # -- token pickup -----------------------------------------------------------------
343
+
344
+ @staticmethod
345
+ def redeemPickup(url: str, pickup_id: Optional[str] = None, passkey: Optional[str] = None) -> Tuple[str, str]:
346
+ return redeem_pickup(url, pickup_id, passkey)
347
+
348
+ @classmethod
349
+ def fromPickup(cls, pickup_url: str, **kwargs: Any) -> 'BridgeClient':
350
+ '''Redeem ``pickup_url`` and return a client authenticated with the new token.'''
351
+ token_id, secret = redeem_pickup(pickup_url)
352
+ parsed = urlparse(pickup_url)
353
+ return cls(f'{parsed.scheme}://{parsed.netloc}', token_id, secret, **kwargs)