minecraft-server-creator 2.0.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.
mcsc/modules/pages.py ADDED
@@ -0,0 +1,379 @@
1
+ """
2
+ Pages
3
+ """
4
+
5
+ import asyncio
6
+ from nicegui import ui, html
7
+
8
+ from mcsc.config import settings as mcssettings
9
+
10
+ from mcsc.modules.utils import (
11
+ popup_create_server,
12
+ popup_edit_server,
13
+ write_to_console_and_clean,
14
+ popup_delete_server,
15
+ shutdown,
16
+ popup_update_app,
17
+ popup_app_settings,
18
+ open_file_explorer,
19
+ minimize_window,
20
+ )
21
+ from mcsc.modules.servers.models import MinecraftServer, get_server_list
22
+ from mcsc.modules.servers.paper import PaperServer
23
+ from mcsc.modules.servers.utils import get_server_by_uuid, FILE_TO_ATTR
24
+ from mcsc.modules.translations import translate as _
25
+ from mcsc.modules.logger import RotatingLogger
26
+ from mcsc.update import check_for_updates
27
+
28
+ # Why is this used here? Because we check for updates while initializing mcsc
29
+ # so as soon as the user loads the page it sees the update notification.
30
+ # Without this we would have to check every time the user loads the page.
31
+ update_available = check_for_updates()
32
+ logger = RotatingLogger()
33
+
34
+
35
+ def load_head():
36
+ """Loads page head"""
37
+ # add here other css files.
38
+ ui.add_head_html("<link rel='stylesheet' href='/static/style.css'>")
39
+ ui.colors(primary="#13c187")
40
+
41
+
42
+ def build_base_window(header: ui.header):
43
+ """Builds base window for app"""
44
+ load_head()
45
+ with header:
46
+ ui.button("", on_click=minimize_window, icon="remove").classes("minimize-button")
47
+ ui.button("", on_click=shutdown, icon="close").classes("close-button")
48
+
49
+
50
+ def build_drawer():
51
+ """Builds left drawer"""
52
+ # Setup
53
+ update_popup = popup_update_app()
54
+
55
+ async def _check_updates(update_btn: ui.button):
56
+ update_btn.disable()
57
+ global update_available # pylint: disable=global-statement
58
+
59
+ if not update_available:
60
+ notification = ui.notification(
61
+ message=_("Checking for updates..."),
62
+ timeout=3,
63
+ spinner=True,
64
+ type="info",
65
+ )
66
+ await asyncio.sleep(1)
67
+
68
+ if check_for_updates():
69
+ update_available = True
70
+ update_btn.style("background-color: rgb(255, 152, 0) !important")
71
+ notification.message = _("Update available")
72
+ notification.spinner = False
73
+ update_btn.set_text(_("Update available"))
74
+ update_popup.open()
75
+ else:
76
+ update_available = False
77
+ notification.message = _("No updates available")
78
+ notification.spinner = False
79
+
80
+ else:
81
+ update_popup.open()
82
+
83
+ update_btn.enable()
84
+
85
+ # Build drawer
86
+ with ui.left_drawer(top_corner=True, fixed=True).classes("left-drawer"):
87
+ # Logo
88
+ ui.image("/static/logo.png")
89
+
90
+ # App Buttons
91
+ ui.button(
92
+ _("Create Server"),
93
+ on_click=popup_create_server().open,
94
+ icon="add_circle",
95
+ ).classes("drawer-button drawer-button-primary")
96
+ ui.button(
97
+ _("Dashboard"),
98
+ on_click=home.refresh,
99
+ icon="space_dashboard",
100
+ ).classes("drawer-button")
101
+
102
+ # Split the buttons
103
+ ui.space()
104
+
105
+ # with ui.expansion(_("Settings"), icon="settings").style(
106
+ # "width: 100%; border-radius: 10px;"
107
+ # ):
108
+ # Update
109
+ update_button = ui.button(
110
+ _("Check for updates"),
111
+ on_click=lambda x: _check_updates(x.sender),
112
+ icon="download",
113
+ ).classes("drawer-button")
114
+
115
+ # Automatically check for updates (this could be a user setting)
116
+ if update_available:
117
+ update_button.style("background-color: rgb(255, 152, 0) !important")
118
+ update_button.set_text(_("Update available"))
119
+ update_popup.open()
120
+ ui.notification(
121
+ message=_("Update available"),
122
+ timeout=30,
123
+ spinner=False,
124
+ type="info",
125
+ )
126
+
127
+ # Settings
128
+ ui.button(
129
+ _("App Settings"),
130
+ on_click=popup_app_settings().open,
131
+ icon="tune",
132
+ ).classes("drawer-button")
133
+
134
+
135
+ @ui.page("/server_detail/{uuid}")
136
+ def server_detail(uuid: str):
137
+ """Page that displays the server details"""
138
+ logger.info(f"GET /server_detail/{uuid}")
139
+ # setup content
140
+ load_head()
141
+ header = ui.header().classes("content-header")
142
+ container = html.section().classes("content")
143
+
144
+ server = get_server_by_uuid(uuid=uuid)
145
+
146
+ build_base_window(header=header)
147
+
148
+ with header:
149
+ with ui.button(
150
+ "", on_click=ui.navigate.back, icon="arrow_back_ios_new"
151
+ ).classes("back-button"):
152
+ ui.tooltip(_("Back")).style("font-size: 15px;").props("delay=1500")
153
+ with ui.label(server.name).style("font-size: 40px;"):
154
+ ui.tooltip(server.uuid).style("font-size: 15px;")
155
+ with ui.button("", icon="folder").style("margin-left: 10px;").on_click(
156
+ lambda x: open_file_explorer(server.server_path)
157
+ ).classes("circular-button"):
158
+ ui.tooltip(_("Open server folder")).style("font-size: 15px;")
159
+ with ui.button_group().style("margin-top: 15px"):
160
+ ui.button(_("Start"), icon="play_arrow").on_click(server.start).classes(
161
+ "start-button"
162
+ ).bind_enabled_from(server, "running", lambda s: not s)
163
+
164
+ ui.button(icon="stop").on_click(server.stop).classes(
165
+ "stop-button"
166
+ ).bind_enabled_from(server, "running")
167
+
168
+ with ui.left_drawer(top_corner=True, fixed=True).classes("left-drawer"):
169
+ ui.label(_("Settings")).style("font-size: 35px")
170
+ ui.button(
171
+ _("Console"),
172
+ on_click=None,
173
+ icon="terminal",
174
+ ).classes("drawer-button")
175
+ ui.button(
176
+ _("Edit server settings"),
177
+ on_click=popup_edit_server(server=server).open,
178
+ icon="tune",
179
+ ).classes("drawer-button")
180
+ ui.button(
181
+ _("Edit server properties"),
182
+ on_click=lambda x: ui.navigate.to(f"/edit/{server.uuid}/server.properties"),
183
+ icon="edit_note",
184
+ ).classes("drawer-button").bind_enabled_from(
185
+ server,
186
+ "has_server_properties",
187
+ )
188
+ if isinstance(server, PaperServer):
189
+ ui.button(
190
+ _("Edit spigot properties"),
191
+ on_click=lambda x: ui.navigate.to(f"/edit/{server.uuid}/spigot.yml"),
192
+ icon="edit_note",
193
+ ).classes("drawer-button").bind_enabled_from(
194
+ server,
195
+ "has_spigot_yml",
196
+ )
197
+ ui.button(
198
+ _("Edit paper properties"),
199
+ on_click=lambda x: ui.navigate.to(f"/edit/{server.uuid}/paper.yml"),
200
+ icon="edit_note",
201
+ ).classes("drawer-button").bind_enabled_from(
202
+ server,
203
+ "has_paper_yml",
204
+ )
205
+ ui.button(
206
+ _("Delete server"),
207
+ on_click=lambda x: popup_delete_server(server=server),
208
+ icon="delete",
209
+ ).classes("drawer-button").style(
210
+ "background-color: rgb(216, 68, 68) !important"
211
+ )
212
+
213
+ # Stats section
214
+ ui.space()
215
+ # ui.label(_("System Usage")).style("font-size: 25px opacity: 0.6;")
216
+ ui.separator()
217
+ with ui.grid(rows=2, columns=2).classes("stat-grid"):
218
+ # RAM usage
219
+ with ui.chip("", icon="donut_large").bind_text_from(
220
+ server.monitor, "ram_usage", lambda x: f"{x} MB"
221
+ ).classes("stat-chip"):
222
+ ui.tooltip(_("RAM usage")).style("font-size: 15px;")
223
+ # CPU usage
224
+ with ui.chip("", icon="memory").bind_text_from(
225
+ server.monitor, "cpu_usage", lambda x: f"{x} %"
226
+ ).classes("stat-chip"):
227
+ ui.tooltip(_("CPU usage")).style("font-size: 15px;")
228
+ # Disk read
229
+ with ui.chip("", icon="swap_vert").bind_text_from(
230
+ server.monitor,
231
+ "disk_read",
232
+ lambda x: f"{x} MB/s",
233
+ ).classes("stat-chip"):
234
+ ui.tooltip(_("Disk read")).style("font-size: 15px;")
235
+ # Disk write
236
+ with ui.chip("", icon="swap_vert").bind_text_from(
237
+ server.monitor,
238
+ "disk_write",
239
+ lambda x: f"{x} MB/s",
240
+ ).classes("stat-chip"):
241
+ ui.tooltip(_("Disk write")).style("font-size: 15px;")
242
+
243
+ with container:
244
+ log = ui.log(mcssettings.MAX_LOG_LINES).classes("log-window")
245
+ server.log = log
246
+
247
+ with ui.row().style("width: 100%;"):
248
+ console_input = (
249
+ ui.input(_("Write command"))
250
+ .on(
251
+ "keydown.enter",
252
+ handler=lambda x: write_to_console_and_clean(
253
+ caller=console_input, server=server
254
+ ),
255
+ )
256
+ .classes("console-input")
257
+ )
258
+
259
+
260
+ def create_server_card(server: MinecraftServer):
261
+ """Create a server card for server"""
262
+ with ui.card().classes("server-card"):
263
+ with ui.row():
264
+ ui.link(server.name, f"/server_detail/{server.uuid}").classes(
265
+ "server-card-link"
266
+ )
267
+
268
+ with ui.row():
269
+ with ui.button_group():
270
+ ui.button(icon="play_arrow").on_click(server.start).classes(
271
+ "start-button"
272
+ ).bind_enabled_from(server, "running", lambda s: not s)
273
+
274
+ ui.button(icon="stop").on_click(server.stop).classes(
275
+ "stop-button"
276
+ ).bind_enabled_from(server, "running")
277
+
278
+ ui.label("").style(
279
+ "opacity: 0.6; margin-left: 200px; margin-top: 10px;"
280
+ ).bind_text_from(
281
+ server,
282
+ "status",
283
+ backward=lambda value: _("Status: {value}", value=value),
284
+ )
285
+
286
+
287
+ @ui.refreshable
288
+ def home(header: ui.header, container):
289
+ """Home page"""
290
+ logger.info("GET /home")
291
+ # clear content before
292
+ container.clear()
293
+ header.clear()
294
+ build_base_window(header=header)
295
+ server_list = get_server_list()
296
+
297
+ with header:
298
+ ui.label(_("Your servers")).style("font-size: 40px;")
299
+ ui.button("", icon="refresh", on_click=home.refresh).classes("refresh-button")
300
+
301
+ with container.classes("content"):
302
+ with ui.row(align_items="center").style("width: 100%"):
303
+ if server_list:
304
+ if "content-empty-state" in container.classes:
305
+ container.classes.remove("content-empty-state")
306
+ container.classes("content")
307
+ for server in server_list:
308
+ create_server_card(server=server)
309
+ else:
310
+ container.classes("content content-empty-state")
311
+ with ui.row().classes("center-text-horizontal").style(
312
+ "margin-left: 47% !important;"
313
+ ):
314
+ ui.icon("splitscreen").style("font-size: 80px;")
315
+ with ui.row().classes("center-text-horizontal"):
316
+ ui.label(_("Seems like you don't have any. Let's create one!"))
317
+
318
+
319
+ @ui.page("/edit/{uuid}/{what}")
320
+ def edit_server_properties(uuid: str, what: str = "server.properties"):
321
+ """
322
+ A page that displays to the user a text editor to edit
323
+ the a file.
324
+ This can be server.properties or spigot.yml
325
+ """
326
+ logger.info(f"GET /edit/{uuid}")
327
+ # setup content
328
+ load_head()
329
+ header = ui.header().classes("content-header")
330
+ container = html.section().classes("content")
331
+
332
+ server = get_server_by_uuid(uuid=uuid)
333
+
334
+ if what == "server.properties":
335
+ server.load_server_properties()
336
+ elif what in ("spigot.yml", "paper.yml") and isinstance(server, PaperServer):
337
+ if what == "spigot.yml":
338
+ server.load_spigot_yml()
339
+ elif what == "paper.yml":
340
+ server.load_paper_yml()
341
+ else:
342
+ logger.error(f"Unknown file {what} for server {server.uuid}")
343
+ raise ValueError(f"Unknown file {what} for server {server.uuid}")
344
+
345
+ data = getattr(server, FILE_TO_ATTR[what])
346
+
347
+ async def _saving(server: MinecraftServer, editor: ui.editor):
348
+ await asyncio.sleep(0.5)
349
+ try:
350
+ if what in ("spigot.yml", "paper.yml"):
351
+ saved = server.save_yml(filename=what, editor=editor)
352
+ else:
353
+ saved = server.save_server_properties(editor=editor)
354
+
355
+ if saved:
356
+ n = ui.notification(message="Saved", spinner=False, type="positive")
357
+ await asyncio.sleep(3)
358
+ n.dismiss()
359
+
360
+ except Exception as e:
361
+ n = ui.notification(
362
+ message=str(e),
363
+ type="negative",
364
+ spinner=False,
365
+ )
366
+ await asyncio.sleep(3)
367
+ n.dismiss()
368
+
369
+ with header.style("background-color: rgba(18, 18, 18, 0.75)"):
370
+ ui.button("", on_click=shutdown, icon="close").classes("close-button")
371
+ ui.button("", on_click=ui.navigate.back, icon="arrow_back_ios_new").classes(
372
+ "back-button"
373
+ )
374
+ ui.label(server.name).style("font-size: 40px;")
375
+
376
+ with container:
377
+ ui.json_editor({"content": {"json": data}}).classes(
378
+ "properties-editor"
379
+ ).on_change(lambda editor: _saving(server=server, editor=editor))
@@ -0,0 +1,175 @@
1
+ """
2
+ Forge server module
3
+ """
4
+
5
+ import asyncio
6
+ import subprocess
7
+ import os
8
+
9
+ from mcsc.modules.translations import translate as _
10
+
11
+ from mcsc.modules.servers.models import MinecraftServer
12
+ from mcsc.modules.logger import RotatingLogger
13
+ from mcsc.telemetry import TelemetryClient
14
+
15
+ telemetry_client = TelemetryClient()
16
+ logger = RotatingLogger()
17
+
18
+
19
+ class ForgeServer(MinecraftServer):
20
+ """
21
+ Forge server class
22
+ """
23
+ @property
24
+ def jar_path(self) -> str:
25
+ """server's jar path"""
26
+ return os.path.join(
27
+ self.server_path,
28
+ f"minecraft_server.{self.version.split('-')[0]}.jar",
29
+ )
30
+
31
+ @property
32
+ def server_path(self) -> str:
33
+ """server's jar path"""
34
+ return os.path.join(self.settings["folder_path"], "server")
35
+
36
+ def _init_forge_server(self):
37
+ """Initializes forge server"""
38
+ # install server
39
+ logger.info(f"Initializing forge server {self.uuid}")
40
+ assert self.jar_type == 2
41
+ try:
42
+ cmd = [
43
+ "java",
44
+ "-jar",
45
+ "server.jar",
46
+ "--installServer",
47
+ "server",
48
+ ]
49
+
50
+ # Start the subprocess
51
+ subprocess.run(
52
+ cmd,
53
+ cwd=self.settings["folder_path"],
54
+ check=False,
55
+ )
56
+
57
+ except Exception as e:
58
+ logger.error(f"Error while initializing forge server {self.uuid}: {e}")
59
+
60
+ def _set_user_jvm_args(self):
61
+ """Sets set_user_jvm_args for FORGE server. ONLY FORGE SERVERS"""
62
+ if self.jar_type == 2:
63
+ logger.info(f"Setting user jvm args for {self.uuid}")
64
+ user_jvm_args_path = os.path.join(self.server_path, "user_jvm_args.txt")
65
+ args = f"-Xmx{self.settings['dedicated_ram']}G -Xms{self.settings['dedicated_ram']}G"
66
+
67
+ # Wait for server folder to be created
68
+ exists = bool(os.path.exists(self.server_path))
69
+ while not exists:
70
+ exists = bool(os.path.exists(self.server_path))
71
+
72
+ if os.path.exists(user_jvm_args_path):
73
+ with open(user_jvm_args_path, "w", encoding="utf-8") as file:
74
+ file.write(args)
75
+ file.flush()
76
+
77
+ else:
78
+ raise ValueError(_("Unsupported Forge Version. THIS IS NOT A BUG!"))
79
+
80
+ else:
81
+ raise ValueError("This is not a Forge server")
82
+
83
+ async def start(self):
84
+ """Starts the forge server"""
85
+ self.starting = True
86
+ logger.info(f"Starting server {self.uuid}")
87
+ try:
88
+ if not os.path.exists(os.path.join(self.server_path, "run.bat")):
89
+ raise ValueError(_("Unsupported Forge Version. THIS IS NOT A BUG!"))
90
+
91
+ cmd = ["cmd.exe", "/c", "run.bat"]
92
+
93
+ # Start the subprocess
94
+ self.process = await asyncio.create_subprocess_exec(
95
+ *cmd,
96
+ cwd=self.server_path,
97
+ stdin=asyncio.subprocess.PIPE,
98
+ stdout=asyncio.subprocess.PIPE,
99
+ stderr=asyncio.subprocess.STDOUT,
100
+ )
101
+
102
+ # Start monitoring the process
103
+ self.monitor.process = self.process
104
+ monitor_task = asyncio.create_task(self.monitor.run())
105
+
106
+ # Start tasks for reading output and taking input
107
+ output_task = asyncio.create_task(self._console_reader())
108
+ # input_task = asyncio.create_task(self.console_writer())
109
+
110
+ telemetry_client.send_event("server_start", details=self.settings)
111
+ # Wait for the server process to finish
112
+ await self.process.wait()
113
+
114
+ self.running = False
115
+
116
+ # Cancel input and output tasks once the server stops
117
+ await asyncio.gather(output_task, return_exceptions=True)
118
+ await asyncio.gather(monitor_task, return_exceptions=True)
119
+
120
+ except FileNotFoundError as e:
121
+ logger.error(f"Error: {e}")
122
+
123
+ except Exception as e:
124
+ logger.error(f"An error occurred: {e}")
125
+
126
+ finally:
127
+ self.starting = False
128
+ self.running = False
129
+
130
+ async def stop(self):
131
+ """
132
+ Stops the server. Same as regular stop but
133
+ without waiting for the process to finish.
134
+ """
135
+ if self.process and self.running:
136
+ logger.info(f"Stopping server {self.uuid}...")
137
+ self.running = False
138
+ self.stopping = True
139
+ try:
140
+ # Send the 'stop' command to the server
141
+ if self.process.stdin:
142
+ self.process.stdin.write(b"stop\n")
143
+ telemetry_client.send_event("server_stop", details=self.settings)
144
+ await asyncio.sleep(2)
145
+ self.process.stdin.write(b"\n")
146
+ await self.process.stdin.drain()
147
+
148
+ logger.info(f"Server {self.uuid} stopped.")
149
+ except Exception as e:
150
+ logger.error(f"Error while stopping the server: {e}")
151
+ finally:
152
+ # Ensure process cleanup
153
+ self.process = None
154
+ self.running = False
155
+ self.stopping = False
156
+ self.monitor.stop()
157
+ else:
158
+ logger.error("Server is not running.")
159
+
160
+ def _create_server(self):
161
+ """
162
+ Creates the server
163
+ """
164
+ logger.info("Initializing server creation...")
165
+ # Create folder and download jar
166
+ self._create_server_folder()
167
+ self._download_jar()
168
+
169
+ # Additional setup for Forge servers
170
+ self._init_forge_server()
171
+ self._set_user_jvm_args()
172
+
173
+ # Complete by accepting EULA and saving
174
+ self.accept_eula()
175
+ self.save()
@@ -0,0 +1,13 @@
1
+ """
2
+ Java server module
3
+ """
4
+
5
+ from mcsc.modules.servers.models import MinecraftServer
6
+
7
+
8
+ class JavaServer(MinecraftServer):
9
+ """
10
+ Class for Java servers
11
+ """
12
+ # Java server do not differ from
13
+ # the base server model