calagoapi-minecraft 1.0.dev2__tar.gz

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.
Files changed (24) hide show
  1. calagoapi_minecraft-1.0.dev2/PKG-INFO +204 -0
  2. calagoapi_minecraft-1.0.dev2/README.md +180 -0
  3. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft/__init__.py +52 -0
  4. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft/aio.py +64 -0
  5. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft/bridge.py +86 -0
  6. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft/config.py +79 -0
  7. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft/exceptions.py +23 -0
  8. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft/extension.py +52 -0
  9. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft/manager.py +56 -0
  10. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft/properties.py +43 -0
  11. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft/server.py +631 -0
  12. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft/versions.py +232 -0
  13. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft.egg-info/PKG-INFO +204 -0
  14. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft.egg-info/SOURCES.txt +22 -0
  15. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft.egg-info/dependency_links.txt +1 -0
  16. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft.egg-info/entry_points.txt +2 -0
  17. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft.egg-info/requires.txt +3 -0
  18. calagoapi_minecraft-1.0.dev2/calagoapi_minecraft.egg-info/top_level.txt +1 -0
  19. calagoapi_minecraft-1.0.dev2/pyproject.toml +56 -0
  20. calagoapi_minecraft-1.0.dev2/setup.cfg +4 -0
  21. calagoapi_minecraft-1.0.dev2/tests/test_minecraft_examples.py +75 -0
  22. calagoapi_minecraft-1.0.dev2/tests/test_minecraft_extension.py +187 -0
  23. calagoapi_minecraft-1.0.dev2/tests/test_minecraft_server.py +241 -0
  24. calagoapi_minecraft-1.0.dev2/tests/test_minecraft_versions.py +111 -0
@@ -0,0 +1,204 @@
1
+ Metadata-Version: 2.4
2
+ Name: calagoapi-minecraft
3
+ Version: 1.0.dev2
4
+ Summary: Minecraft servers for CalagoAPI: commands with output, console streaming, players and metrics through HungerBridge, the Version Changer, server.properties.
5
+ Author: iFamished
6
+ License: GPL-3.0
7
+ Project-URL: Homepage, https://github.com/HungerNet/CalagoAPI
8
+ Project-URL: Documentation, https://github.com/HungerNet/CalagoAPI/tree/main/docs/tutorials/minecraft
9
+ Project-URL: Source, https://github.com/HungerNet/CalagoAPI/tree/main/src/extensions/calagoapi-minecraft
10
+ Project-URL: HungerBridge, https://github.com/HungerNet/HungerBridge
11
+ Project-URL: HungerBridgePy, https://github.com/HungerNet/HungerBridgePy
12
+ Keywords: calagopus,calagoapi,minecraft,hungerbridge,paper,fabric,extension
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Development Status :: 4 - Beta
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Topic :: Games/Entertainment
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+ Requires-Dist: calagoapi>=2.0.dev1
22
+ Requires-Dist: hungerbridge>=1.0.dev2
23
+ Requires-Dist: requests
24
+
25
+ # calagoapi-minecraft
26
+
27
+ Minecraft servers for [CalagoAPI](https://github.com/HungerNet/CalagoAPI), the Calagopus
28
+ panel SDK. `MinecraftServer` is a `calagoapi.Server` with Minecraft features:
29
+
30
+ - **commands with output** and **live console streaming** through
31
+ [HungerBridge](https://github.com/HungerNet/HungerBridge), the plugin/mod inside the
32
+ game, using [HungerBridgePy](https://github.com/HungerNet/HungerBridgePy);
33
+ - players, TPS/MSPT, world data and JVM information;
34
+ - the Calagopus **Minecraft Version Changer** (`server.versions`);
35
+ - `server.properties`, EULA, chat and moderation helpers;
36
+ - installing HungerBridge and creating its tokens through the panel.
37
+
38
+ ```bash
39
+ pip install calagoapi calagoapi-minecraft # also installs hungerbridge (HungerBridgePy)
40
+ ```
41
+
42
+ ```python
43
+ from calagoapi import Panel
44
+ from calagoapi.extensions import enable
45
+
46
+ enable('minecraft', config={'bridge_token': 'calagoapi:9f2c...'})
47
+
48
+ with Panel(url='https://panel.example.com', api_key='c7sp_...') as panel:
49
+ server = panel.minecraft.getServer('abc123', bridge_url='http://10.0.0.5:1913')
50
+
51
+ print(server.sendCommand('list')) # the command's output
52
+ for line in server.streamConsole(history=10, timeout=30):
53
+ print(line)
54
+ print(f'{server.getPlayerCount()} online, TPS {server.getTPS("1m")}')
55
+ print(f'container {server.getRAM()} MiB, heap {server.getMemoryInfo()["used"]:.0f} MiB')
56
+ ```
57
+
58
+ Learn it step by step in the [Minecraft tutorials](../../../docs/tutorials/README.md#track-3-minecraft);
59
+ runnable code is in [examples/minecraft/](../../../examples/minecraft/README.md).
60
+
61
+ ## Two channels
62
+
63
+ | Channel | Used by |
64
+ | --- | --- |
65
+ | **Panel / daemon** (CalagoAPI) | everything inherited from `Server`: `start()`, `stop()`, `restart()`, `getRAM()`, `getCPU()`, `getStatus()`, files, backups, ...; plus `server.properties`, EULA, `server.versions`, `sendPanelCommand()`, `installBridge()`, `createBridgeToken()`, `server.console` |
66
+ | **HungerBridge** (HungerBridgePy, `server.bridge`) | `sendCommand()`, `streamConsole()`, `onConsoleLine()`, chat helpers, players, TPS/MSPT, world, JVM info, `writeLog()` |
67
+
68
+ Nothing falls back silently. Bridge methods without a token raise
69
+ `BridgeNotConfiguredError`; HungerBridge errors are raised as HungerBridgePy's
70
+ `hungerbridge.HungerBridgeError` subclasses (`HungerBridgeAuthError` with `.reason`,
71
+ `HungerBridgeForbidden`, `HungerBridgeNotFound`, `HungerBridgeRateLimit`,
72
+ `HungerBridgeConnectionError`).
73
+
74
+ ## Getting a server
75
+
76
+ ```python
77
+ server = panel.minecraft.getServer('abc123') # after enable('minecraft')
78
+ server = panel.minecraft.getServer('abc123', address='play.example.com', bridge_url=..., bridge_token=...)
79
+ server = panel.minecraft.fromServer(panel.servers.getServerByName('Survival'))
80
+ servers = panel.minecraft.getServers() # every visible server, as MinecraftServer
81
+
82
+ from calagoapi_minecraft import MinecraftServer # works without enable() too
83
+ server = MinecraftServer(panel, 'abc123', bridge_token='calagoapi:9f2c...')
84
+ ```
85
+
86
+ ## Connecting HungerBridge
87
+
88
+ | Method | Description |
89
+ | --- | --- |
90
+ | `installBridge(minecraft_version=None, loader=None, release=None, replace=True)` | download the right jar into `/plugins` or `/mods` (detects loader and version); returns a `hungerbridge.ReleaseAsset` |
91
+ | `findBridgeRelease(minecraft_version, loader, release=None)` | the jar without installing it |
92
+ | `createBridgeToken(token_id='calagoapi', policy='admin', expiry=None, timeout=30, url=None)` | run `hb token create` on the console, redeem the pickup, connect; returns `'id:secret'` |
93
+ | `redeemBridgePickup(pickup_url)` | redeem a pickup URL (or its `/pickup/...` part) and connect |
94
+ | `connectBridge(url=None, token=None, **options)` | set URL/token (and `BridgeClient` options such as `timeout`) for this server |
95
+ | `setBridge(client)`, `closeBridge()` | use your own `BridgeClient`; close connections |
96
+ | `bridge` | the `hungerbridge.BridgeClient` (the full HungerBridgePy API) |
97
+ | `getBridgeUrl()`, `hasBridge()`, `isBridgeReachable()`, `waitForBridge(timeout=120)` | |
98
+ | `getBridgeInfo()`, `getBridgeTokenInfo()`, `getPlatform()`, `getMinecraftVersion()` | `/server/meta`, `/auth/check` |
99
+
100
+ The bridge URL is `bridge_url`, else the `bridge_url` config, else the server's address
101
+ with `bridge_port` (1913). HungerBridge binds `127.0.0.1` by default. Set its
102
+ `bind-address` and `security.yaml` `ips` so your code can reach it.
103
+
104
+ ## Commands and console
105
+
106
+ | Method | Description |
107
+ | --- | --- |
108
+ | `sendCommand(command, *, silent=False, showConsole=False)` | HungerBridgePy `runCommand()`: returns the output text, `None` when silent |
109
+ | `sendCommands(commands, *, silent=False, showConsole=False)` | list of outputs |
110
+ | `sendPanelCommand(command)` | through the panel (`Server.sendCommand`), no output |
111
+ | `streamConsole(history=0, timeout=None, *, reconnect=None, sanitize=True)` | HungerBridgePy `streamLogs()`: yields `[HH:mm:ss LEVEL]: message` lines; `history` ≤ 200 (`True` = 200) |
112
+ | `onConsoleLine(callback, history=0, *, reconnect=None, sanitize=True)` | background callbacks; returns the `hungerbridge.Stream` (`.disconnect()`) |
113
+ | `writeLog(message, level='info', thread=None)` | write a line to the server log |
114
+ | `say`, `broadcast(message, prefix=None)`, `tellraw`, `kick`, `ban`, `pardon`, `op`, `deop`, `whitelistAdd`, `whitelistRemove`, `saveAll` | chat and moderation (return the command output) |
115
+
116
+ ## Game and JVM information
117
+
118
+ These are **additional** to the panel's `getRAM()`, `getCPU()`, `getUptime()`, which stay
119
+ unchanged (the container as the panel sees it).
120
+
121
+ | Method | Returns |
122
+ | --- | --- |
123
+ | `getPlayers()`, `getPlayerCount()`, `getMaxPlayers()` | names, online count, slots |
124
+ | `getTPS(mode='current')` | `'current'`, `'1m'`, `'5m'`, `'15m'`; `-1` if unavailable |
125
+ | `getMSPT()` | milliseconds per tick |
126
+ | `getPerformance()` | `{'tps': {...}, 'mspt', 'players', 'max_players'}` |
127
+ | `getWorldTime()`, `getWorldTimeInfo()`, `getWeather()` | tick of day, time info, `clear`/`rain`/`thunder` |
128
+ | `getLoadedChunks()`, `getLoadedEntities()` | per dimension and total |
129
+ | `getMemoryInfo(unit='mib')` | heap, non-heap, JVM, process + `used`, `total`, `free`, `max` |
130
+ | `getProcessInfo(unit='mib')` | `process_used`, `process_virtual`, `uptime_ms` |
131
+ | `getProcessorInfo()` | `load` (JVM process, 0–1), `processors` |
132
+ | `getThreadInfo()` | `current`, `peak`, `daemon` |
133
+ | `getGarbageCollectorInfo()` | `gc_type`, `gc_count`, `gc_time_ms`, `last_gc_pause_ms`, `avg_gc_pause_ms` |
134
+ | `getNetworkInfo()` | `bytes_in_per_sec`, `bytes_out_per_sec`, `total_bytes_in`, `total_bytes_out` |
135
+ | `getJVMUptime(formatted=False)` | ms, or `'3h 12m'` |
136
+
137
+ ## Version Changer
138
+
139
+ Needs the Calagopus Minecraft Version Changer panel extension.
140
+
141
+ | `server.versions.` | |
142
+ | --- | --- |
143
+ | `isAvailable()` | is the panel extension installed? |
144
+ | `getInstalled()`, `getInstalledBuild()`, `isUpToDate()` | the installed build and the newest build of its version |
145
+ | `getTypes()`, `getVersions(type, ...)`, `getBuilds(type, version, ...)`, `getLatestBuild(type, version)` | |
146
+ | `install(build, truncate_directory=False, accept_eula=True, backup=None)` | `backup=None` uses `auto_backup`; a failed backup installs nothing |
147
+ | `update(truncate_directory=False, backup=None)` | newest build of the installed version; `False` if up to date |
148
+
149
+ Admin (`panel.minecraft.versionChanger.`): `getSettings()`, `updateSettings(**values)`,
150
+ `getStatistics()`, `getDefaultOrder()`.
151
+
152
+ ## server.properties and EULA
153
+
154
+ `getProperties()`, `getProperty(key, default=None)`, `setProperty(key, value)`,
155
+ `setProperties(values)` (comments and order are kept; booleans become `true`/`false`),
156
+ `getMOTD()`, `setMOTD(motd)`, `acceptEula()`, `isEulaAccepted()`.
157
+
158
+ ## Configuration
159
+
160
+ `enable('minecraft', config={...})`, all optional:
161
+
162
+ | Key | Default | Meaning |
163
+ | --- | --- | --- |
164
+ | `bridge_url` | `None` | HungerBridge URL for every server; `None` uses the server's address + `bridge_port` |
165
+ | `bridge_port` | `1913` | |
166
+ | `bridge_token` | `None` | `'tokenId:secret'` (secret: masked in diagnostics) |
167
+ | `bridge_timeout` | `None` | seconds or `(connect, read)`; `None` = HungerBridgePy's `(5, 30)` |
168
+ | `bridge_max_retries` | `2` | retries after HTTP 429 |
169
+ | `stream_reconnect` | `True` | default `reconnect` of `streamConsole()` / `onConsoleLine()` |
170
+ | `auto_backup` | `False` | back up before `server.versions.install()` |
171
+ | `backup_name`, `backup_timeout` | `'Before version change'`, `3600` | |
172
+ | `release` | `'latest'` | HungerBridge release for `installBridge()` |
173
+ | `repository`, `github_api` | `'HungerNet/HungerBridge'`, `'https://api.github.com'` | where releases are published |
174
+
175
+ Without `enable()`, `MinecraftServer` uses these defaults (`calagoapi_minecraft.settings()`).
176
+
177
+ ## Async
178
+
179
+ ```python
180
+ async with AsyncPanel(url=..., api_key=...) as panel:
181
+ server = await panel.minecraft.getServer('abc123')
182
+ print(await server.sendCommand('list'))
183
+ async for line in server.streamConsole(history=10):
184
+ print(line)
185
+ ```
186
+
187
+ `AsyncMinecraftServer` runs HungerBridgePy in worker threads (one per open stream);
188
+ `onConsoleLine()` accepts coroutine callbacks.
189
+
190
+ ## Package layout
191
+
192
+ | Module | Responsibility |
193
+ | --- | --- |
194
+ | `server.py` | `MinecraftServer` |
195
+ | `bridge.py` | client creation, pickup parsing, loader/version detection |
196
+ | `versions.py` | `VersionManager`, `VersionChangerAdmin`, `VersionChangerAPI` |
197
+ | `properties.py` | `server.properties` text handling |
198
+ | `manager.py` | `MinecraftManager` (`panel.minecraft`) |
199
+ | `extension.py`, `config.py` | `MinecraftExtension`, defaults, validation, `settings()` |
200
+ | `aio.py` | `AsyncMinecraftServer`, async type registrations |
201
+ | `exceptions.py` | `MinecraftError`, `BridgeNotConfiguredError` |
202
+
203
+ Replaces the CalagoAPI 1.x packages `calagoapi-hungerbridge` and `calagoapi-version-changer`;
204
+ see [Migrating to 2.0](../../../docs/migrating-to-2.0.md).
@@ -0,0 +1,180 @@
1
+ # calagoapi-minecraft
2
+
3
+ Minecraft servers for [CalagoAPI](https://github.com/HungerNet/CalagoAPI), the Calagopus
4
+ panel SDK. `MinecraftServer` is a `calagoapi.Server` with Minecraft features:
5
+
6
+ - **commands with output** and **live console streaming** through
7
+ [HungerBridge](https://github.com/HungerNet/HungerBridge), the plugin/mod inside the
8
+ game, using [HungerBridgePy](https://github.com/HungerNet/HungerBridgePy);
9
+ - players, TPS/MSPT, world data and JVM information;
10
+ - the Calagopus **Minecraft Version Changer** (`server.versions`);
11
+ - `server.properties`, EULA, chat and moderation helpers;
12
+ - installing HungerBridge and creating its tokens through the panel.
13
+
14
+ ```bash
15
+ pip install calagoapi calagoapi-minecraft # also installs hungerbridge (HungerBridgePy)
16
+ ```
17
+
18
+ ```python
19
+ from calagoapi import Panel
20
+ from calagoapi.extensions import enable
21
+
22
+ enable('minecraft', config={'bridge_token': 'calagoapi:9f2c...'})
23
+
24
+ with Panel(url='https://panel.example.com', api_key='c7sp_...') as panel:
25
+ server = panel.minecraft.getServer('abc123', bridge_url='http://10.0.0.5:1913')
26
+
27
+ print(server.sendCommand('list')) # the command's output
28
+ for line in server.streamConsole(history=10, timeout=30):
29
+ print(line)
30
+ print(f'{server.getPlayerCount()} online, TPS {server.getTPS("1m")}')
31
+ print(f'container {server.getRAM()} MiB, heap {server.getMemoryInfo()["used"]:.0f} MiB')
32
+ ```
33
+
34
+ Learn it step by step in the [Minecraft tutorials](../../../docs/tutorials/README.md#track-3-minecraft);
35
+ runnable code is in [examples/minecraft/](../../../examples/minecraft/README.md).
36
+
37
+ ## Two channels
38
+
39
+ | Channel | Used by |
40
+ | --- | --- |
41
+ | **Panel / daemon** (CalagoAPI) | everything inherited from `Server`: `start()`, `stop()`, `restart()`, `getRAM()`, `getCPU()`, `getStatus()`, files, backups, ...; plus `server.properties`, EULA, `server.versions`, `sendPanelCommand()`, `installBridge()`, `createBridgeToken()`, `server.console` |
42
+ | **HungerBridge** (HungerBridgePy, `server.bridge`) | `sendCommand()`, `streamConsole()`, `onConsoleLine()`, chat helpers, players, TPS/MSPT, world, JVM info, `writeLog()` |
43
+
44
+ Nothing falls back silently. Bridge methods without a token raise
45
+ `BridgeNotConfiguredError`; HungerBridge errors are raised as HungerBridgePy's
46
+ `hungerbridge.HungerBridgeError` subclasses (`HungerBridgeAuthError` with `.reason`,
47
+ `HungerBridgeForbidden`, `HungerBridgeNotFound`, `HungerBridgeRateLimit`,
48
+ `HungerBridgeConnectionError`).
49
+
50
+ ## Getting a server
51
+
52
+ ```python
53
+ server = panel.minecraft.getServer('abc123') # after enable('minecraft')
54
+ server = panel.minecraft.getServer('abc123', address='play.example.com', bridge_url=..., bridge_token=...)
55
+ server = panel.minecraft.fromServer(panel.servers.getServerByName('Survival'))
56
+ servers = panel.minecraft.getServers() # every visible server, as MinecraftServer
57
+
58
+ from calagoapi_minecraft import MinecraftServer # works without enable() too
59
+ server = MinecraftServer(panel, 'abc123', bridge_token='calagoapi:9f2c...')
60
+ ```
61
+
62
+ ## Connecting HungerBridge
63
+
64
+ | Method | Description |
65
+ | --- | --- |
66
+ | `installBridge(minecraft_version=None, loader=None, release=None, replace=True)` | download the right jar into `/plugins` or `/mods` (detects loader and version); returns a `hungerbridge.ReleaseAsset` |
67
+ | `findBridgeRelease(minecraft_version, loader, release=None)` | the jar without installing it |
68
+ | `createBridgeToken(token_id='calagoapi', policy='admin', expiry=None, timeout=30, url=None)` | run `hb token create` on the console, redeem the pickup, connect; returns `'id:secret'` |
69
+ | `redeemBridgePickup(pickup_url)` | redeem a pickup URL (or its `/pickup/...` part) and connect |
70
+ | `connectBridge(url=None, token=None, **options)` | set URL/token (and `BridgeClient` options such as `timeout`) for this server |
71
+ | `setBridge(client)`, `closeBridge()` | use your own `BridgeClient`; close connections |
72
+ | `bridge` | the `hungerbridge.BridgeClient` (the full HungerBridgePy API) |
73
+ | `getBridgeUrl()`, `hasBridge()`, `isBridgeReachable()`, `waitForBridge(timeout=120)` | |
74
+ | `getBridgeInfo()`, `getBridgeTokenInfo()`, `getPlatform()`, `getMinecraftVersion()` | `/server/meta`, `/auth/check` |
75
+
76
+ The bridge URL is `bridge_url`, else the `bridge_url` config, else the server's address
77
+ with `bridge_port` (1913). HungerBridge binds `127.0.0.1` by default. Set its
78
+ `bind-address` and `security.yaml` `ips` so your code can reach it.
79
+
80
+ ## Commands and console
81
+
82
+ | Method | Description |
83
+ | --- | --- |
84
+ | `sendCommand(command, *, silent=False, showConsole=False)` | HungerBridgePy `runCommand()`: returns the output text, `None` when silent |
85
+ | `sendCommands(commands, *, silent=False, showConsole=False)` | list of outputs |
86
+ | `sendPanelCommand(command)` | through the panel (`Server.sendCommand`), no output |
87
+ | `streamConsole(history=0, timeout=None, *, reconnect=None, sanitize=True)` | HungerBridgePy `streamLogs()`: yields `[HH:mm:ss LEVEL]: message` lines; `history` ≤ 200 (`True` = 200) |
88
+ | `onConsoleLine(callback, history=0, *, reconnect=None, sanitize=True)` | background callbacks; returns the `hungerbridge.Stream` (`.disconnect()`) |
89
+ | `writeLog(message, level='info', thread=None)` | write a line to the server log |
90
+ | `say`, `broadcast(message, prefix=None)`, `tellraw`, `kick`, `ban`, `pardon`, `op`, `deop`, `whitelistAdd`, `whitelistRemove`, `saveAll` | chat and moderation (return the command output) |
91
+
92
+ ## Game and JVM information
93
+
94
+ These are **additional** to the panel's `getRAM()`, `getCPU()`, `getUptime()`, which stay
95
+ unchanged (the container as the panel sees it).
96
+
97
+ | Method | Returns |
98
+ | --- | --- |
99
+ | `getPlayers()`, `getPlayerCount()`, `getMaxPlayers()` | names, online count, slots |
100
+ | `getTPS(mode='current')` | `'current'`, `'1m'`, `'5m'`, `'15m'`; `-1` if unavailable |
101
+ | `getMSPT()` | milliseconds per tick |
102
+ | `getPerformance()` | `{'tps': {...}, 'mspt', 'players', 'max_players'}` |
103
+ | `getWorldTime()`, `getWorldTimeInfo()`, `getWeather()` | tick of day, time info, `clear`/`rain`/`thunder` |
104
+ | `getLoadedChunks()`, `getLoadedEntities()` | per dimension and total |
105
+ | `getMemoryInfo(unit='mib')` | heap, non-heap, JVM, process + `used`, `total`, `free`, `max` |
106
+ | `getProcessInfo(unit='mib')` | `process_used`, `process_virtual`, `uptime_ms` |
107
+ | `getProcessorInfo()` | `load` (JVM process, 0–1), `processors` |
108
+ | `getThreadInfo()` | `current`, `peak`, `daemon` |
109
+ | `getGarbageCollectorInfo()` | `gc_type`, `gc_count`, `gc_time_ms`, `last_gc_pause_ms`, `avg_gc_pause_ms` |
110
+ | `getNetworkInfo()` | `bytes_in_per_sec`, `bytes_out_per_sec`, `total_bytes_in`, `total_bytes_out` |
111
+ | `getJVMUptime(formatted=False)` | ms, or `'3h 12m'` |
112
+
113
+ ## Version Changer
114
+
115
+ Needs the Calagopus Minecraft Version Changer panel extension.
116
+
117
+ | `server.versions.` | |
118
+ | --- | --- |
119
+ | `isAvailable()` | is the panel extension installed? |
120
+ | `getInstalled()`, `getInstalledBuild()`, `isUpToDate()` | the installed build and the newest build of its version |
121
+ | `getTypes()`, `getVersions(type, ...)`, `getBuilds(type, version, ...)`, `getLatestBuild(type, version)` | |
122
+ | `install(build, truncate_directory=False, accept_eula=True, backup=None)` | `backup=None` uses `auto_backup`; a failed backup installs nothing |
123
+ | `update(truncate_directory=False, backup=None)` | newest build of the installed version; `False` if up to date |
124
+
125
+ Admin (`panel.minecraft.versionChanger.`): `getSettings()`, `updateSettings(**values)`,
126
+ `getStatistics()`, `getDefaultOrder()`.
127
+
128
+ ## server.properties and EULA
129
+
130
+ `getProperties()`, `getProperty(key, default=None)`, `setProperty(key, value)`,
131
+ `setProperties(values)` (comments and order are kept; booleans become `true`/`false`),
132
+ `getMOTD()`, `setMOTD(motd)`, `acceptEula()`, `isEulaAccepted()`.
133
+
134
+ ## Configuration
135
+
136
+ `enable('minecraft', config={...})`, all optional:
137
+
138
+ | Key | Default | Meaning |
139
+ | --- | --- | --- |
140
+ | `bridge_url` | `None` | HungerBridge URL for every server; `None` uses the server's address + `bridge_port` |
141
+ | `bridge_port` | `1913` | |
142
+ | `bridge_token` | `None` | `'tokenId:secret'` (secret: masked in diagnostics) |
143
+ | `bridge_timeout` | `None` | seconds or `(connect, read)`; `None` = HungerBridgePy's `(5, 30)` |
144
+ | `bridge_max_retries` | `2` | retries after HTTP 429 |
145
+ | `stream_reconnect` | `True` | default `reconnect` of `streamConsole()` / `onConsoleLine()` |
146
+ | `auto_backup` | `False` | back up before `server.versions.install()` |
147
+ | `backup_name`, `backup_timeout` | `'Before version change'`, `3600` | |
148
+ | `release` | `'latest'` | HungerBridge release for `installBridge()` |
149
+ | `repository`, `github_api` | `'HungerNet/HungerBridge'`, `'https://api.github.com'` | where releases are published |
150
+
151
+ Without `enable()`, `MinecraftServer` uses these defaults (`calagoapi_minecraft.settings()`).
152
+
153
+ ## Async
154
+
155
+ ```python
156
+ async with AsyncPanel(url=..., api_key=...) as panel:
157
+ server = await panel.minecraft.getServer('abc123')
158
+ print(await server.sendCommand('list'))
159
+ async for line in server.streamConsole(history=10):
160
+ print(line)
161
+ ```
162
+
163
+ `AsyncMinecraftServer` runs HungerBridgePy in worker threads (one per open stream);
164
+ `onConsoleLine()` accepts coroutine callbacks.
165
+
166
+ ## Package layout
167
+
168
+ | Module | Responsibility |
169
+ | --- | --- |
170
+ | `server.py` | `MinecraftServer` |
171
+ | `bridge.py` | client creation, pickup parsing, loader/version detection |
172
+ | `versions.py` | `VersionManager`, `VersionChangerAdmin`, `VersionChangerAPI` |
173
+ | `properties.py` | `server.properties` text handling |
174
+ | `manager.py` | `MinecraftManager` (`panel.minecraft`) |
175
+ | `extension.py`, `config.py` | `MinecraftExtension`, defaults, validation, `settings()` |
176
+ | `aio.py` | `AsyncMinecraftServer`, async type registrations |
177
+ | `exceptions.py` | `MinecraftError`, `BridgeNotConfiguredError` |
178
+
179
+ Replaces the CalagoAPI 1.x packages `calagoapi-hungerbridge` and `calagoapi-version-changer`;
180
+ see [Migrating to 2.0](../../../docs/migrating-to-2.0.md).
@@ -0,0 +1,52 @@
1
+ '''
2
+ calagoapi-minecraft: Minecraft servers for CalagoAPI.
3
+
4
+ `MinecraftServer` is a `calagoapi.Server` with Minecraft features. Commands with
5
+ output, console streaming, players and game/JVM metrics go through HungerBridge (the
6
+ plugin/mod inside the game) using HungerBridgePy; power, resources and files stay on
7
+ the panel.
8
+
9
+ from calagoapi import Panel
10
+ from calagoapi.extensions import enable
11
+
12
+ enable('minecraft', config={'bridge_token': 'bot:9f2c...'})
13
+ panel = Panel(url='https://panel.example.com', api_key='...')
14
+
15
+ server = panel.minecraft.getServer('abc123', bridge_url='http://10.0.0.5:1913')
16
+ print(server.sendCommand('list'))
17
+ for line in server.streamConsole(history=10, timeout=30):
18
+ print(line)
19
+
20
+ MinecraftServer also works without enable(): MinecraftServer(panel, 'abc123', bridge_token=...).
21
+ '''
22
+ from importlib.metadata import version as _pkg_version, PackageNotFoundError
23
+
24
+ try:
25
+ __version__ = _pkg_version('calagoapi-minecraft')
26
+ except PackageNotFoundError:
27
+ __version__ = '0.0.0'
28
+
29
+ from .exceptions import BridgeNotConfiguredError, MinecraftError # noqa: E402
30
+ from .config import DEFAULT_CONFIG, settings # noqa: E402
31
+ from .versions import PANEL_EXTENSION, VersionChangerAdmin, VersionChangerAPI, VersionManager # noqa: E402
32
+ from .server import DEFAULT_PORT, MinecraftServer # noqa: E402
33
+ from .manager import MinecraftManager # noqa: E402
34
+ from .extension import MinecraftExtension # noqa: E402
35
+ from .aio import AsyncMinecraftServer # noqa: E402 (also registers the async wrappers)
36
+
37
+ __all__ = [
38
+ '__version__',
39
+ 'MinecraftServer',
40
+ 'MinecraftManager',
41
+ 'MinecraftExtension',
42
+ 'AsyncMinecraftServer',
43
+ 'VersionManager',
44
+ 'VersionChangerAdmin',
45
+ 'VersionChangerAPI',
46
+ 'MinecraftError',
47
+ 'BridgeNotConfiguredError',
48
+ 'DEFAULT_CONFIG',
49
+ 'DEFAULT_PORT',
50
+ 'PANEL_EXTENSION',
51
+ 'settings',
52
+ ]
@@ -0,0 +1,64 @@
1
+ '''
2
+ AsyncPanel support: registers how calagoapi-minecraft objects are wrapped.
3
+
4
+ async with AsyncPanel(url=..., api_key=...) as panel:
5
+ server = await panel.minecraft.getServer('abc123')
6
+ print(await server.getTPS())
7
+ async for line in server.streamConsole(history=10):
8
+ print(line)
9
+
10
+ HungerBridgePy is a blocking client, so bridge calls and streams run in worker
11
+ threads (one per active stream), like every other AsyncPanel call.
12
+ '''
13
+ import asyncio
14
+ import inspect
15
+
16
+ from hungerbridge import BridgeClient, Stream
17
+
18
+ from calagoapi.aio import AsyncServer, AsyncWrapper, iterateInThread, registerAsyncType, wrap
19
+
20
+ from calagoapi_minecraft.server import MinecraftServer
21
+ from calagoapi_minecraft.versions import VersionChangerAdmin, VersionManager
22
+
23
+
24
+ class AsyncMinecraftServer(AsyncServer):
25
+ '''
26
+ The async version of MinecraftServer. Every method is awaitable;
27
+ streamConsole() is an async generator over HungerBridge's log stream.
28
+ '''
29
+ async def streamConsole(self, history: int = 0, timeout: float = None, *, reconnect: bool = None,
30
+ sanitize: bool = True):
31
+ '''
32
+ Yields HungerBridge console lines (see MinecraftServer.streamConsole()).
33
+
34
+ Example:
35
+ async for line in server.streamConsole(history=20):
36
+ print(line)
37
+ '''
38
+ lines = await asyncio.to_thread(self.target.streamConsole, history, timeout, reconnect=reconnect,
39
+ sanitize=sanitize)
40
+ async for line in iterateInThread(lines):
41
+ yield line
42
+
43
+ async def onConsoleLine(self, callback, history: int = 0, *, reconnect: bool = None, sanitize: bool = True):
44
+ '''
45
+ Calls `callback(line)` for every console line; the callback may be a coroutine
46
+ function, it then runs on this event loop. Returns the stream (`await stream.disconnect()`).
47
+ '''
48
+ loop = asyncio.get_running_loop()
49
+
50
+ def deliver(line):
51
+ result = callback(line)
52
+ if inspect.isawaitable(result):
53
+ asyncio.run_coroutine_threadsafe(result, loop)
54
+
55
+ stream = await asyncio.to_thread(self.target.onConsoleLine, deliver, history, reconnect=reconnect,
56
+ sanitize=sanitize)
57
+ return wrap(stream)
58
+
59
+
60
+ registerAsyncType(MinecraftServer, AsyncMinecraftServer)
61
+ registerAsyncType(VersionManager, AsyncWrapper)
62
+ registerAsyncType(VersionChangerAdmin, AsyncWrapper)
63
+ registerAsyncType(BridgeClient, AsyncWrapper)
64
+ registerAsyncType(Stream, AsyncWrapper)
@@ -0,0 +1,86 @@
1
+ '''
2
+ Helpers that connect a MinecraftServer to its HungerBridge: client creation, console
3
+ pickup parsing and loader/version detection for installBridge().
4
+
5
+ The HungerBridge protocol itself (signing, endpoints, streaming, release names) lives
6
+ in HungerBridgePy (`hungerbridge`); nothing here talks HTTP to the bridge directly.
7
+ '''
8
+ import re
9
+
10
+ from hungerbridge import BridgeClient
11
+ from hungerbridge.releases import loader_for
12
+
13
+ from calagoapi.utils.exceptions import CalagoAPIError
14
+
15
+ from calagoapi_minecraft.config import settings
16
+
17
+
18
+ # "Token created. Retrieve it at: /pickup/<uuid>?passkey=<hex>" (also printed by "hb token rotate")
19
+ PICKUP_PATTERN = re.compile(r'(/pickup/[0-9A-Za-z-]+\?passkey=[0-9a-fA-F]+)')
20
+ ANSI_PATTERN = re.compile(r'\x1b\[[0-9;]*[A-Za-z]')
21
+
22
+ # startup variables eggs commonly use for the Minecraft version
23
+ VERSION_VARIABLES = ('MINECRAFT_VERSION', 'MC_VERSION', 'VERSION')
24
+
25
+
26
+ def newClient(url: str, token: str, **options) -> BridgeClient:
27
+ '''Creates a HungerBridgePy client with the configured timeout and retries; options win.'''
28
+ config = settings()
29
+ kwargs = {'max_retries': config['bridge_max_retries']}
30
+ if config['bridge_timeout'] is not None:
31
+ kwargs['timeout'] = config['bridge_timeout']
32
+ kwargs.update(options)
33
+ return BridgeClient(url, token, **kwargs)
34
+
35
+
36
+ def closeClient(client) -> None:
37
+ session = getattr(getattr(client, 'transport', None), 'session', None)
38
+ if session is not None:
39
+ session.close()
40
+
41
+
42
+ def findPickup(line: str):
43
+ '''Returns "/pickup/<id>?passkey=<hex>" from a console line, or None.'''
44
+ match = PICKUP_PATTERN.search(ANSI_PATTERN.sub('', line or ''))
45
+ return match.group(1) if match else None
46
+
47
+
48
+ def detectPlatform(server, loader=None, minecraft_version=None):
49
+ '''
50
+ Returns (loader, minecraft_version) for installBridge(). Unknown values stay None.
51
+
52
+ Sources, first match wins: the arguments, the Version Changer's installed build, a
53
+ reachable bridge (/server/meta), then the egg name and startup variables.
54
+ '''
55
+ def fill(found_loader, found_version):
56
+ nonlocal loader, minecraft_version
57
+ loader = loader or loader_for(found_loader)
58
+ minecraft_version = minecraft_version or found_version
59
+
60
+ if loader is not None:
61
+ # server types such as 'PAPER' or 'PURPUR' -> 'paper'; unknown values are left for
62
+ # find_release() to reject with a clear message
63
+ loader = loader_for(loader) or loader
64
+
65
+ if loader is None or minecraft_version is None:
66
+ try:
67
+ build = server.versions.getInstalledBuild() or {}
68
+ fill(build.get('type'), build.get('version_id'))
69
+ except CalagoAPIError:
70
+ pass # Version Changer not installed on the panel
71
+ if (loader is None or minecraft_version is None) and server.hasBridge():
72
+ try:
73
+ meta = server.bridge.getServerMeta()
74
+ fill(meta.get('platform'), meta.get('minecraft_version'))
75
+ except Exception:
76
+ pass # bridge not running (yet)
77
+ if loader is None or minecraft_version is None:
78
+ egg = (server.getEggName() or '').lower()
79
+ fill(next((word for word in re.split(r'[^a-z]+', egg) if loader_for(word)), None), None)
80
+ if minecraft_version is None:
81
+ for variable in server.getStartupVariables():
82
+ value = str(variable.get('value') or '')
83
+ if variable.get('env_variable') in VERSION_VARIABLES and re.fullmatch(r'\d+\.\d+(\.\d+)?', value):
84
+ minecraft_version = value
85
+ break
86
+ return loader, minecraft_version
@@ -0,0 +1,79 @@
1
+ '''
2
+ Configuration of calagoapi-minecraft.
3
+
4
+ `enable('minecraft', config={...})` sets process-wide defaults. Without enable(),
5
+ MinecraftServer uses DEFAULT_CONFIG. Per-server values (constructor arguments,
6
+ connectBridge()) always win.
7
+ '''
8
+ from types import MappingProxyType
9
+
10
+ from calagoapi.extensions import ConfigurationError, ExtensionNotEnabledError
11
+ from hungerbridge.auth import Credentials
12
+
13
+
14
+ DEFAULT_CONFIG = {
15
+ # HungerBridge connection
16
+ 'bridge_url': None, # None: the server's address with bridge_port
17
+ 'bridge_port': 1913,
18
+ 'bridge_token': None, # 'tokenId:secret'
19
+ 'bridge_timeout': None, # seconds or (connect, read); None: HungerBridgePy's default (5, 30)
20
+ 'bridge_max_retries': 2, # retries after HTTP 429, inside HungerBridgePy
21
+ 'stream_reconnect': True, # default for streamConsole() and onConsoleLine()
22
+ # Version Changer
23
+ 'auto_backup': False, # back up before server.versions.install()
24
+ 'backup_name': 'Before version change',
25
+ 'backup_timeout': 3600,
26
+ # installBridge()
27
+ 'release': 'latest',
28
+ 'repository': 'HungerNet/HungerBridge',
29
+ 'github_api': 'https://api.github.com',
30
+ }
31
+
32
+
33
+ def settings():
34
+ '''
35
+ Returns the effective configuration (read-only): the enabled extension's config,
36
+ or DEFAULT_CONFIG when enable('minecraft') was not called.
37
+
38
+ Example:
39
+ from calagoapi_minecraft import settings
40
+ print(settings()['bridge_port'])
41
+ '''
42
+ from calagoapi_minecraft.extension import MinecraftExtension
43
+
44
+ try:
45
+ return MinecraftExtension.get().config
46
+ except ExtensionNotEnabledError:
47
+ return MappingProxyType(dict(DEFAULT_CONFIG))
48
+
49
+
50
+ def checkToken(token, where: str = 'bridge_token'):
51
+ '''Raises ConfigurationError unless token is None or "tokenId:secret" with a hex secret.'''
52
+ if token is None:
53
+ return
54
+ credentials = Credentials.parse(token) if isinstance(token, str) else None
55
+ if credentials is None:
56
+ raise ConfigurationError(f'minecraft: {where} must look like "tokenId:secret", got a {type(token).__name__}')
57
+ try:
58
+ bytes.fromhex(credentials.secret)
59
+ except ValueError:
60
+ raise ConfigurationError(f'minecraft: the secret in {where} must be the 64 hex characters from the pickup') from None
61
+
62
+
63
+ def validate(config: dict) -> dict:
64
+ checkToken(config['bridge_token'])
65
+ port = config['bridge_port']
66
+ if isinstance(port, bool) or not isinstance(port, int) or not 0 < port < 65536:
67
+ raise ConfigurationError(f'minecraft: bridge_port must be 1-65535, got {port!r}')
68
+ if config['bridge_url'] is not None and not str(config['bridge_url']).startswith(('http://', 'https://')):
69
+ raise ConfigurationError(f'minecraft: bridge_url must start with http:// or https://, got {config["bridge_url"]!r}')
70
+ for key in ('auto_backup', 'stream_reconnect'):
71
+ if not isinstance(config[key], bool):
72
+ raise ConfigurationError(f'minecraft: {key} must be True or False')
73
+ timeout = config['backup_timeout']
74
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or timeout <= 0:
75
+ raise ConfigurationError('minecraft: backup_timeout must be a positive number of seconds')
76
+ retries = config['bridge_max_retries']
77
+ if isinstance(retries, bool) or not isinstance(retries, int) or retries < 0:
78
+ raise ConfigurationError('minecraft: bridge_max_retries must be 0 or more')
79
+ return config