Passed
Push — master ( 805c58...4a8ad5 )
by Nikita
10:14 queued 04:50
created

DedicatedServersController::certificatesZip()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 20
rs 9.7666
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Gameap\Http\Controllers\API;
4
5
use Gameap\Helpers\OsHelper;
6
use Gameap\Http\Controllers\AuthController;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Gameap\Http\Controllers\API\AuthController. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use Gameap\Http\Requests\API\Admin\StoreNodeRequest;
8
use Gameap\Http\Requests\API\Admin\UpdateNodeRequest;
9
use Gameap\Models\DedicatedServer;
10
use Gameap\Repositories\NodeRepository;
11
use Gameap\Services\Daemon\CertificateService;
12
use Gameap\Services\Daemon\DebugService;
13
use Illuminate\Support\Facades\Cache;
14
use Illuminate\Support\Facades\Storage;
15
use Illuminate\Support\Str;
16
use Knik\Gameap\GdaemonStatus;
17
use RuntimeException;
18
use ZipArchive;
19
20
class DedicatedServersController extends AuthController
21
{
22
    /**
23
     * The DedicatedServersRepository instance.
24
     *
25
     * @var \Gameap\Repositories\NodeRepository
26
     */
27
    public $repository;
28
29
    /** @var DebugService */
30
    protected $debugService;
31
32
    /** @var GdaemonStatus */
33
    private $gdaemonStatus;
34
35
    public function __construct(
36
        NodeRepository $repository,
37
        DebugService   $downloadDebugService,
38
        GdaemonStatus $gdaemonStatus
39
    ) {
40
        parent::__construct();
41
42
        $this->repository   = $repository;
43
        $this->debugService = $downloadDebugService;
44
        $this->gdaemonStatus = $gdaemonStatus;
45
    }
46
47
    public function list()
48
    {
49
        $collection = $this->repository->getAll();
50
51
        return $collection->map(function ($item) {
52
            return $item->only([
53
                'id',
54
                'enabled',
55
                'name',
56
                'os',
57
                'location',
58
                'provider',
59
                'ip',
60
            ]);
61
        });
62
    }
63
64
    public function summary()
65
    {
66
        $nodes = $this->repository->getAll();
67
68
        $online = 0;
69
        $offline = 0;
70
71
        foreach ($nodes as $node) {
72
            $this->gdaemonStatus->setConfig($node->gdaemonSettings());
73
74
            try {
75
                $this->gdaemonStatus->connect();
76
                $online++;
77
            } catch (\RuntimeException $exception) {
78
                $offline++;
79
            }
80
81
            $this->gdaemonStatus->disconnect();
82
        }
83
84
        return [
85
            'total' => $nodes->count(),
86
            'online' => $online,
87
            'offline' => $offline,
88
        ];
89
    }
90
91
    public function get(int $id)
92
    {
93
        return $this->repository->findById($id)->only(
94
            'id',
95
            'enabled',
96
            'name',
97
            'os',
98
            'location',
99
            'provider',
100
            'ip',
101
            'ram',
102
            'cpu',
103
            'work_path',
104
            'steamcmd_path',
105
            'gdaemon_host',
106
            'gdaemon_port',
107
            'gdaemon_api_key',
108
            'gdaemon_login',
109
            'gdaemon_password',
110
            'gdaemon_server_cert',
111
            'client_certificate_id',
112
            'prefer_install_method',
113
            'script_install',
114
            'script_reinstall',
115
            'script_update',
116
            'script_start',
117
            'script_pause',
118
            'script_unpause',
119
            'script_stop',
120
            'script_kill',
121
            'script_restart',
122
            'script_status',
123
            'script_stats',
124
            'script_get_console',
125
            'script_send_command',
126
            'script_delete',
127
            'created_at',
128
            'updated_at',
129
            'deleted_at',
130
        );
131
    }
132
133
    public function daemon(int $id, GdaemonStatus $gdaemonStatus)
134
    {
135
        $node = $this->repository->findById($id);
136
        $gdaemonStatus->setConfig($node->gdaemonSettings());
137
138
        try {
139
            $gdaemonVersion = $gdaemonStatus->version();
140
            $baseInfo       = $gdaemonStatus->infoBase();
141
        } catch (RuntimeException $e) {
142
            $gdaemonVersion = [];
143
            $baseInfo       = [];
144
        }
145
146
        return [
147
            'id'        => $node->id,
148
            'name'      => $node->name,
149
            'api_key'   => $node->gdaemon_api_key,
150
            'version'   => $gdaemonVersion,
151
            'base_info' => $baseInfo,
152
        ];
153
    }
154
155
    public function update($id, UpdateNodeRequest $request)
156
    {
157
        $attributes = $request->all();
158
159
        $node = $this->repository->findById($id);
160
161
        if (!empty($attributes['gdaemon_server_cert'])) {
162
            $cert = $attributes['gdaemon_server_cert'];
163
            if (!$cert) {
164
                return response()->json(['message' => 'Invalid certificate'], 400);
165
            }
166
167
            $path = 'certs/server/'.Str::Random(32).'.crt';
168
            Storage::disk('local')->put($path, $cert);
169
170
            $attributes['gdaemon_server_cert'] = $path;
171
        } else {
172
            $attributes['gdaemon_server_cert'] = $node->gdaemon_server_cert;
173
        }
174
175
        $this->repository->update($node, $attributes);
176
177
        return ['message' => 'success'];
178
    }
179
180
    public function setup()
181
    {
182
        // Add auto setup token
183
        $autoSetupToken = env('DAEMON_SETUP_TOKEN');
184
185
        if (empty($autoSetupToken)) {
186
            $autoSetupToken = Str::random(24);
187
            Cache::put('gdaemonAutoSetupToken', $autoSetupToken, 300);
188
        }
189
190
        return [
191
            'link' => route('gdaemon.setup', ['token' => $autoSetupToken]),
192
            'token' => $autoSetupToken,
193
            'host' => request()->getSchemeAndHttpHost(),
194
        ];
195
    }
196
197
    public function store(StoreNodeRequest $request)
198
    {
199
        $attributes = $request->all();
200
201
        $node = $this->repository->store($attributes);
202
203
        return ['message' => 'success', 'result' => $node->id];
204
    }
205
206
    public function destroy(int $id)
207
    {
208
        $node = $this->repository->findById($id);
209
        if (count($node->servers) > 0) {
210
            return ['message' => 'error', 'error' => __('dedicated_servers.delete_has_servers_error_msg')];
211
        }
212
213
        $this->repository->destroy($node);
214
215
        return ['message' => 'success'];
216
    }
217
218
    /**
219
     * @param int $id
220
     * @return array
221
     */
222
    public function getIpList(int $id)
223
    {
224
        return $this->repository->getIpList($id);
225
    }
226
227
    /**
228
     * @param int $id
229
     * @return array
230
     */
231
    public function getBusyPorts(int $id)
232
    {
233
        return $this->repository->getBusyPorts($id);
234
    }
235
236
    public function logsZip(int $id)
237
    {
238
        $node = $this->repository->findById($id);
239
240
        try {
241
            $zipPath = $this->debugService->downloadLogs($node);
242
        } catch (RuntimeException $exception) {
243
            return response()->json([
244
                'message' => $exception->getMessage()
245
            ], 500);
246
        }
247
248
        return response()->download($zipPath, "logs.zip");
249
    }
250
251
    public function certificatesZip()
252
    {
253
        $key                     = CertificateService::generateKey();
254
        $csr                     = CertificateService::generateCsr($key);
255
        $serverSignedCertificate = CertificateService::signCsr($csr);
256
257
        $zipFilePath = OsHelper::tempFile();
258
        $zip = new ZipArchive();
259
        $zip->open($zipFilePath, ZipArchive::CREATE);
260
        $zip->addFromString("server.key", $key);
261
        $zip->addFromString("server.crt", $serverSignedCertificate);
262
        $zip->addFromString("ca.crt", CertificateService::getRootCert());
263
        $zip->addFromString(
264
            "README.md",
265
            "* Move this files to certs directory (For linux: /etc/gameap-daemon/certs/)\n" .
266
            "* Edit gameap-daemon configuration, set `ca_certificate_file`, `certificate_chain_file` and `private_key_file`"
267
        );
268
        $zip->close();
269
270
        return response()->download($zipFilePath, "certificates.zip");
271
    }
272
}
273