Passed
Push — master ( 5cca9a...5e004b )
by Nikita
10:18 queued 03:43
created

ServersController::store()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 11
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Gameap\Http\Controllers\API;
4
5
use Exception;
6
use Gameap\Exceptions\Repositories\GdaemonTaskRepository\EmptyServerStartCommandException;
7
use Gameap\Exceptions\Repositories\GdaemonTaskRepository\GdaemonTaskRepositoryException;
8
use Gameap\Exceptions\Repositories\RecordExistExceptions;
9
use Gameap\Helpers\PermissionHelper;
10
use Gameap\Helpers\ServerPermissionHelper;
11
use Gameap\Http\Controllers\AuthController;
12
use Gameap\Http\Requests\Admin\ServerDestroyRequest;
13
use Gameap\Http\Requests\API\SaveServerRequest;
14
use Gameap\Http\Requests\API\ServerConsoleCommandRequest;
15
use Gameap\Models\GdaemonTask;
16
use Gameap\Models\Server;
17
use Gameap\Models\User;
18
use Gameap\Repositories\GdaemonTaskRepository;
19
use Gameap\Repositories\ServerRepository;
20
use Gameap\Services\ServerControlService;
21
use Gameap\Services\ServerService;
22
use Gameap\UseCases\Commands\CreateGameServerCommand;
23
use Gameap\UseCases\Commands\EditGameServerCommand;
24
use Gameap\UseCases\CreateGameServer;
25
use Gameap\UseCases\EditGameServer;
26
use Illuminate\Contracts\Auth\Factory as AuthFactory;
27
use Illuminate\Http\Request;
28
use Illuminate\Http\Response;
29
use Illuminate\Support\Facades\Auth;
30
use Symfony\Component\Serializer\SerializerInterface;
31
32
class ServersController extends AuthController
33
{
34
    /**
35
     * The ServerRepository instance.
36
     *
37
     * @var \Gameap\Repositories\ServerRepository
38
     */
39
    public $repository;
40
41
    /**
42
     * The GdaemonTaskRepository instance.
43
     *
44
     * @var GdaemonTaskRepository
45
     */
46
    public $gdaemonTaskRepository;
47
48
    /** @var \Gameap\Services\ServerService  */
49
    public $serverService;
50
51
    /** @var \Gameap\Services\ServerControlService */
52
    public $serverControlService;
53
54
    /** @var SerializerInterface */
55
    protected $serializer;
56
57
    /** @var AuthFactory */
58
    protected $authFactory;
59
60
    /**
61
     * ServersController constructor.
62
     * @param ServerRepository $repository
63
     */
64
    public function __construct(
65
        ServerRepository $repository,
66
        GdaemonTaskRepository $gdaemonTaskRepository,
67
        ServerService $serverService,
68
        ServerControlService $serverControlService,
69
        SerializerInterface $serializer,
70
        AuthFactory $authFactory
71
    ) {
72
        parent::__construct();
73
74
        $this->repository            = $repository;
75
        $this->gdaemonTaskRepository = $gdaemonTaskRepository;
76
        $this->serverService         = $serverService;
77
        $this->serverControlService  = $serverControlService;
78
        $this->serializer            = $serializer;
79
        $this->authFactory           = $authFactory;
80
    }
81
82
    /**
83
     * @param Server $server
84
     *
85
     * @return array|\Illuminate\Http\JsonResponse
86
     *
87
     * @throws \Illuminate\Auth\Access\AuthorizationException
88
     */
89
    public function start(Server $server)
90
    {
91
        $this->authorize(ServerPermissionHelper::CONTROL_ABILITY, $server);
92
        $this->authorize(ServerPermissionHelper::START_ABILITY, $server);
93
94
        try {
95
            $gdaemonTaskId = $this->serverControlService->start($server);
96
        } catch (GdaemonTaskRepositoryException $exception) {
97
            return $this->handleException($exception);
98
        } catch (RecordExistExceptions $exception) {
99
            $gdaemonTaskId = $this->gdaemonTaskRepository->getOneWorkingTaskId(
100
                $server->id,
101
                GdaemonTask::TASK_SERVER_START
102
            );
103
104
            if (!$gdaemonTaskId) {
105
                return $this->makeErrorResponse($exception->getMessage());
106
            }
107
        }
108
109
        return [
110
            'gdaemonTaskId' => $gdaemonTaskId,
111
        ];
112
    }
113
114
    /**
115
     * @param Server $server
116
     *
117
     * @return array|\Illuminate\Http\JsonResponse
118
     *
119
     * @throws \Illuminate\Auth\Access\AuthorizationException
120
     */
121
    public function stop(Server $server)
122
    {
123
        $this->authorize(ServerPermissionHelper::CONTROL_ABILITY, $server);
124
        $this->authorize(ServerPermissionHelper::STOP_ABILITY, $server);
125
126
        try {
127
            $gdaemonTaskId = $this->serverControlService->stop($server);
128
        } catch (RecordExistExceptions $exception) {
129
            $gdaemonTaskId = $this->gdaemonTaskRepository->getOneWorkingTaskId(
130
                $server->id,
131
                GdaemonTask::TASK_SERVER_STOP
132
            );
133
134
            if (!$gdaemonTaskId) {
135
                return $this->makeErrorResponse($exception->getMessage());
136
            }
137
        }
138
139
        return [
140
            'gdaemonTaskId' => $gdaemonTaskId,
141
        ];
142
    }
143
144
    /**
145
     * @param Server $server
146
     * @return array|\Illuminate\Http\JsonResponse
147
     *
148
     * @throws \Gameap\Exceptions\Repositories\RecordExistExceptions
149
     * @throws \Illuminate\Auth\Access\AuthorizationException
150
     */
151
    public function restart(Server $server)
152
    {
153
        $this->authorize(ServerPermissionHelper::CONTROL_ABILITY, $server);
154
        $this->authorize(ServerPermissionHelper::RESTART_ABILITY, $server);
155
156
        try {
157
            $gdaemonTaskId = $this->serverControlService->restart($server);
158
        } catch (GdaemonTaskRepositoryException $exception) {
159
            return $this->handleException($exception);
160
        } catch (RecordExistExceptions $exception) {
161
            $gdaemonTaskId = $this->gdaemonTaskRepository->getOneWorkingTaskId(
162
                $server->id,
163
                GdaemonTask::TASK_SERVER_RESTART
164
            );
165
166
            if (!$gdaemonTaskId) {
167
                return $this->makeErrorResponse($exception->getMessage());
168
            }
169
        }
170
171
        return [
172
            'gdaemonTaskId' => $gdaemonTaskId,
173
        ];
174
    }
175
176
    /**
177
     * @param Server $server
178
     * @return array|\Illuminate\Http\JsonResponse
179
     *
180
     * @throws \Illuminate\Auth\Access\AuthorizationException
181
     */
182
    public function update(Server $server)
183
    {
184
        $this->authorize(ServerPermissionHelper::CONTROL_ABILITY, $server);
185
        $this->authorize(ServerPermissionHelper::UPDATE_ABILITY, $server);
186
187
        try {
188
            $gdaemonTaskId = $this->serverControlService->update($server);
189
        } catch (RecordExistExceptions $exception) {
190
            $gdaemonTaskId = $this->gdaemonTaskRepository->getOneWorkingTaskId(
191
                $server->id,
192
                GdaemonTask::TASK_SERVER_UPDATE
193
            );
194
195
            if (!$gdaemonTaskId) {
196
                return $this->makeErrorResponse($exception->getMessage());
197
            }
198
        }
199
200
        return [
201
            'gdaemonTaskId' => $gdaemonTaskId,
202
        ];
203
    }
204
205
    /**
206
     * @param Server $server
207
     * @return array|\Illuminate\Http\JsonResponse
208
     *
209
     * @throws \Illuminate\Auth\Access\AuthorizationException
210
     */
211
    public function install(Server $server)
212
    {
213
        $this->authorize(ServerPermissionHelper::CONTROL_ABILITY, $server);
214
        $this->authorize(ServerPermissionHelper::UPDATE_ABILITY, $server);
215
216
        try {
217
            $gdaemonTaskId = $this->serverControlService->install($server);
218
        } catch (RecordExistExceptions $exception) {
219
            $gdaemonTaskId = $this->gdaemonTaskRepository->getOneWorkingTaskId(
220
                $server->id,
221
                GdaemonTask::TASK_SERVER_INSTALL
222
            );
223
224
            if (!$gdaemonTaskId) {
225
                return $this->makeErrorResponse($exception->getMessage());
226
            }
227
        }
228
229
        return [
230
            'gdaemonTaskId' => $gdaemonTaskId,
231
        ];
232
    }
233
234
    /**
235
     * @param Server $server
236
     * @return array|\Illuminate\Http\JsonResponse
237
     *
238
     * @throws \Gameap\Exceptions\Repositories\RecordExistExceptions
239
     * @throws \Illuminate\Auth\Access\AuthorizationException
240
     */
241
    public function reinstall(Server $server)
242
    {
243
        $this->authorize(ServerPermissionHelper::CONTROL_ABILITY, $server);
244
        $this->authorize(ServerPermissionHelper::UPDATE_ABILITY, $server);
245
246
        try {
247
            $deleteTaskId  = $this->gdaemonTaskRepository->addServerDelete($server);
248
            $gdaemonTaskId = $this->gdaemonTaskRepository->addServerInstall($server, $deleteTaskId);
249
        } catch (RecordExistExceptions $exception) {
250
            return $this->makeErrorResponse($exception->getMessage());
251
        }
252
253
        return [
254
            'gdaemonTaskId' => $gdaemonTaskId,
255
        ];
256
    }
257
258
    /**
259
     * Get server status
260
     * @param Server $server
261
     * @return array
262
     *
263
     * @throws \Illuminate\Auth\Access\AuthorizationException
264
     */
265
    public function getStatus(Server $server)
266
    {
267
        $this->authorize(ServerPermissionHelper::CONTROL_ABILITY, $server);
268
269
        return [
270
            'processActive' => $server->processActive(),
271
        ];
272
    }
273
274
    /**
275
     * @param Server $server
276
     * @return array
277
     *
278
     * @throws \Illuminate\Auth\Access\AuthorizationException
279
     */
280
    public function query(Server $server)
281
    {
282
        $this->authorize(ServerPermissionHelper::CONTROL_ABILITY, $server);
283
284
        $query = $this->serverService->query($server);
285
286
        return $query;
287
    }
288
289
    /**
290
     * @param Server $server
291
     * @return array
292
     *
293
     * @throws \Illuminate\Auth\Access\AuthorizationException
294
     */
295
    public function consoleLog(Server $server)
296
    {
297
        $this->authorize(ServerPermissionHelper::CONTROL_ABILITY, $server);
298
        $this->authorize(ServerPermissionHelper::CONSOLE_VIEW_ABILITY, $server);
299
300
        return [
301
            'console' => $this->serverService->getConsoleLog($server),
302
        ];
303
    }
304
305
    /**
306
     * @param ServerConsoleCommandRequest $request
307
     * @param Server $server
308
     * @return array
309
     *
310
     * @throws \Illuminate\Auth\Access\AuthorizationException
311
     */
312
    public function sendCommand(ServerConsoleCommandRequest $request, Server $server)
313
    {
314
        $this->authorize(ServerPermissionHelper::CONTROL_ABILITY, $server);
315
        $this->authorize(ServerPermissionHelper::CONSOLE_SEND_ABILITY, $server);
316
317
        $command = $request->input('command');
318
        $this->serverService->sendConsoleCommand($server, $command);
319
320
        return ['message' => 'success'];
321
    }
322
323
    public function search(Request $request)
324
    {
325
        $query = $request->input('q');
326
        return $this->repository->search($query);
327
    }
328
329
    public function getList()
330
    {
331
        /** @var User $currentUser */
332
        $currentUser = $this->authFactory->guard()->user();
333
334
        if ($currentUser->can(PermissionHelper::ADMIN_PERMISSIONS)) {
335
            $collection = $this->repository->getAllServers()->collect();
336
        } else {
337
            $collection = $this->repository->getServersForUser($currentUser->id);
338
        }
339
340
        return $collection->map(function ($item) {
341
            return $item->only([
342
                'id',
343
                'uuid',
344
                'uuid_short',
345
                'enabled',
346
                'installed',
347
                'blocked',
348
                'name',
349
                'ds_id',
350
                'game_id',
351
                'game_mod_id',
352
                'server_ip',
353
                'server_port',
354
                'query_port',
355
                'rcon_port',
356
                'game',
357
                'online'
358
            ]);
359
        });
360
    }
361
362
    public function store(SaveServerRequest $request, CreateGameServer $createGameServer): array
363
    {
364
        /** @var CreateGameServerCommand $command */
365
        $command = $this->serializer->denormalize(
366
            $request->all(),
367
            CreateGameServerCommand::class,
368
        );
369
370
        $result = $createGameServer($command);
371
372
        return ['message' => 'success', 'result' => $result];
373
    }
374
375
    public function save(int $id, SaveServerRequest $request, EditGameServer $saveGameServer): array
376
    {
377
        /** @var EditGameServerCommand $command */
378
        $command = $this->serializer->denormalize(
379
            $request->all(),
380
            EditGameServerCommand::class,
381
        );
382
383
        $command->id = $id;
384
385
        $result = $saveGameServer($command);
386
387
        return ['message' => 'success', 'result' => $result->id];
388
    }
389
390
    public function destroy(ServerDestroyRequest $request, Server $server)
391
    {
392
        if ($request->input('delete_files')) {
393
            try {
394
                $this->gdaemonTaskRepository->addServerDelete($server);
395
            } catch (RecordExistExceptions $e) {
396
                // Nothing
397
            }
398
399
            $server->delete();
400
        } else {
401
            $server->forceDelete();
402
        }
403
404
        return ['message' => 'success'];
405
    }
406
407
    /**
408
     * @param Exception $exception
409
     *
410
     * @return \Illuminate\Http\JsonResponse
411
     */
412
    private function handleException(\Throwable $exception)
413
    {
414
        if (Auth::user()->can(PermissionHelper::ADMIN_PERMISSIONS)) {
415
            $extraMessage = $this->getDocMessage($exception);
416
        } else {
417
            $extraMessage = (string)__('main.common_admin_error');
418
        }
419
420
        return $this->makeErrorResponse($exception->getMessage() . $extraMessage);
421
    }
422
423
    /**
424
     * @param Exception $exception
425
     * @return string
426
     */
427
    private function getDocMessage(\Throwable $exception)
428
    {
429
        $msg = '';
430
431
        if ($exception instanceof EmptyServerStartCommandException) {
432
            $msg = __('gdaemon_tasks.empty_server_start_command_doc');
433
        }
434
435
        return is_string($msg) ? $msg : '';
436
    }
437
438
    /**
439
     * @param $message
440
     * @param int $code
441
     * @return \Illuminate\Http\JsonResponse
442
     */
443
    private function makeErrorResponse($message, $code = Response::HTTP_UNPROCESSABLE_ENTITY)
444
    {
445
        return response()->json([
446
            'message'   => $message,
447
            'http_code' => $code,
448
        ], $code);
449
    }
450
}
451