Added the ability to create a new server

This commit is contained in:
Gregory Ballantine 2022-09-22 23:28:06 -04:00
parent 6af39995f7
commit 1fd7bb7a9a
2 changed files with 75 additions and 0 deletions

View File

@ -13,3 +13,38 @@ $app->get('/', function (Request $request, Response $response, $args) {
'server_dir' => $config->get('server_directory'),
]);
})->setName('index');
// create GET route - this page allows a user to create a new server instance
$app->get('/create', function (Request $request, Response $response, $args) {
$view = Twig::fromRequest($request);
return $view->render($response, 'create.twig');
})->setName('create');
// create POST route - processes the new server creation
$app->post('/create', function (Request $request, Response $response, $args) {
// set up the POST parameters and grab our config
$params = (array)$request->getParsedBody();
$config = $this->get('config');
// create our server directory
$serverDir = join('/', array($config->get('server_directory'), $params['serverName']));
mkdir($serverDir);
// grab the server JAR file
$serverJarUrl = "https://piston-data.mojang.com/v1/objects/f69c284232d7c7580bd89a5a4931c3581eae1378/server.jar";
$serverJarName = "server_" . $params['serverVersion'] . ".jar";
$serverJarPath = join('/', array($serverDir, $serverJarName));
file_put_contents($serverJarPath, file_get_contents($serverJarUrl));
// create the start.sh shell script
$scriptFilePath = join('/', array($serverDir, 'start.sh'));
$scriptFile = fopen($scriptFilePath, 'w');
$scriptContent = "#!/bin/sh\n\ncd " . $serverDir . "\njava -Xmx2048M -Xms2048M -jar server_1.19.2.jar nogui";
fwrite($scriptFile, $scriptContent);
fclose($scriptFile);
chmod($scriptFilePath, 0755);
return $response
->withHeader('Location', '/')
->withStatus(302);
});

40
views/create.twig Normal file
View File

@ -0,0 +1,40 @@
{% extends 'layout.twig' %}
{% block content %}
<!-- page header -->
<header class="row">
<div class="columns twelve">
<h1>Create new server</h1>
</div>
</header>
<!-- create server form -->
<section class="row">
<div class="columns twelve">
<form action="/create" method="POST">
<div class="row">
<div class="columns six">
<label for="serverName">Server name:</label>
<input id="serverName" name="serverName" class="u-full-width" type="text" placeholder="MyServer">
</div>
<div class="columns six">
<label for="serverVersion">Minecraft version:</label>
<input id="serverVersion" name="serverVersion" class="u-full-width" type="text" placeholder="1.19.2">
</div>
</div>
<input type="submit" value="Submit">
</form>
</div>
</section>
<!-- lower navigation -->
<div class="row">
<div class="columns twelve">
<p><a href="/">Back</a></p>
</div>
</div>
{% endblock %}