Completed
Push — master ( 220ce5...be682d )
by
unknown
17s
created

ManiaExchange::onApplicationStop()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace eXpansion\Bundle\Maps\Plugins;
4
5
use eXpansion\Bundle\Maps\Services\JukeboxService;
6
use eXpansion\Bundle\Maps\Structure\MxInfo;
7
use eXpansion\Framework\AdminGroups\Helpers\AdminGroups;
8
use eXpansion\Framework\Core\DataProviders\Listener\ListenerInterfaceExpApplication;
9
use eXpansion\Framework\Core\Helpers\ChatNotification;
10
use eXpansion\Framework\Core\Helpers\Http;
11
use eXpansion\Framework\Core\Helpers\Structures\HttpResult;
12
use eXpansion\Framework\Core\Helpers\TMString;
13
use eXpansion\Framework\Core\Services\Console;
14
use eXpansion\Framework\Core\Storage\GameDataStorage;
15
use Maniaplanet\DedicatedServer\Connection;
16
17
class ManiaExchange implements ListenerInterfaceExpApplication
18
{
19
20
    const SITE_TM = "TM";
21
    const SITE_SM = "SM";
22
23
    /**
24
     * @var Connection
25
     */
26
    private $connection;
27
    /**
28
     * @var ChatNotification
29
     */
30
    private $chatNotification;
31
    /**
32
     * @var Http
33
     */
34
    private $http;
35
    /**
36
     * @var AdminGroups
37
     */
38
    private $adminGroups;
39
    /**
40
     * @var GameDataStorage
41
     */
42
    private $gameDataStorage;
43
    /**
44
     * @var Console
45
     */
46
    private $console;
47
    /**
48
     * @var JukeboxService
49
     */
50
    private $jukebox;
51
52
53
    /**
54
     * ManiaExchange constructor.
55
     * @param Connection $connection
56
     * @param ChatNotification $chatNotification
57
     * @param Http $http
58
     * @param AdminGroups $adminGroups
59
     * @param GameDataStorage $gameDataStorage
60
     * @param Console $console
61
     * @param JukeboxService $jukebox
62
     */
63 View Code Duplication
    public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
64
        Connection $connection,
65
        ChatNotification $chatNotification,
66
        Http $http,
67
        AdminGroups $adminGroups,
68
        GameDataStorage $gameDataStorage,
69
        Console $console,
70
        JukeboxService $jukebox
71
    ) {
72
        $this->connection = $connection;
73
        $this->chatNotification = $chatNotification;
74
        $this->http = $http;
75
        $this->adminGroups = $adminGroups;
76
        $this->gameDataStorage = $gameDataStorage;
77
        $this->console = $console;
78
        $this->jukebox = $jukebox;
79
    }
80
81
    /**
82
     * @param string $login
83
     * @param integer $id
84
     * @param string $mxsite "TM" or "SM"
85
     */
86
    public function addMap($login, $id, $mxsite)
87
    {
88
89
        if (!$this->adminGroups->hasPermission($login, "mania_exchange.add")) {
90
            $this->chatNotification->sendMessage('expansion_mx.chat.nopermission', $login);
91
92
            return;
93
        }
94
        $options = [
95
            CURLOPT_HTTPHEADER => [
96
                "Content-Type" => "application/json",
97
                "X-ManiaPlanet-ServerLogin" => $this->gameDataStorage->getSystemInfo()->serverLogin,
98
            ],
99
        ];
100
101
        if (!$mxsite) {
102
            $mxsite = "TM";
103
        }
104
105
        $group = $this->adminGroups->getLoginUserGroups($login);
106
107
        $this->chatNotification->sendMessage(
108
            'expansion_mx.chat.start',
109
            $group,
110
            ["%id%" => $id, "%site%" => $mxsite]
111
        );
112
113
        $this->http->get("https://api.mania-exchange.com/".strtolower($mxsite)."/maps?ids=".$id,
114
            [$this, 'callbackAddMap1'],
115
            ['login' => $login, 'site' => $mxsite, 'mxId' => $id], $options);
116
117
    }
118
119
120
    public function callbackAddMap1(HttpResult $result)
121
    {
122
        $additionalData = $result->getAdditionalData();
123
        $group = $this->adminGroups->getLoginUserGroups($additionalData['login']);
124
125
        $json = json_decode($result->getResponse(), true);
126
        if (isset($json['StatusCode'])) {
127
            $this->chatNotification->sendMessage(
128
                'expansion_mx.chat.apierror',
129
                $group,
130
                ["%status%" => $json['StatusCode'], "%message%" => $json['Message']]
131
            );
132
133
            return;
134
        }
135
136
        $mxInfo = new MxInfo($json);
137
        $additionalData['mxInfo'] = $mxInfo;
138
139
        if (!$result->hasError()) {
140
            $options = [
141
                CURLOPT_HTTPHEADER => [
142
                    "Content-Type" => "application/json",
143
                    "X-ManiaPlanet-ServerLogin" => $this->gameDataStorage->getSystemInfo()->serverLogin,
144
                ],
145
            ];
146
147
            $this->http->get("https://".strtolower($additionalData['site']).
148
                ".mania-exchange.com/tracks/download/".$additionalData['mxId'],
149
                [$this, 'callbackAddMap2'],
150
                $additionalData, $options);
151
        } else {
152
            $this->chatNotification->sendMessage(
153
                'expansion_mx.chat.httperror',
154
                $group,
155
                ["%status%" => $result->getHttpCode(), "%message%" => $result->getError()]
156
            );
157
        }
158
    }
159
160
    public function callbackAddMap2(HttpResult $result)
161
    {
162
        $data = $result->getAdditionalData();
163
        $group = $this->adminGroups->getLoginUserGroups($data['login']);
164
165
        if ($result->hasError()) {
166
            $this->chatNotification->sendMessage(
167
                'expansion_mx.chat.httperror',
168
                $group,
169
                ["%status%" => $result->getHttpCode(), "%message%" => $result->getError()]
170
            );
171
172
            return;
173
        }
174
175
        /** @var MxInfo $info */
176
        $info = $data['mxInfo'];
177
        $authorName = $this->cleanString($info->Username);
178
        $mapName = $this->cleanString(
179
            trim(
180
                mb_convert_encoding(
181
                    substr(TMString::trimStyles($info->GbxMapName), 0, 20),
182
                    "7bit",
183
                    "UTF-8"
184
                )
185
            )
186
        );
187
188
        $filename = $data['mxId']."-".$authorName."-".$mapName.".Map.Gbx";
189
        try {
190
            // @todo write mx info from map to database!
191
192
            $this->connection->writeFile($filename, $result->getResponse());
193
            $this->connection->addMap($filename);
194
195
            $map = $this->connection->getMapInfo($filename);
196
            $this->jukebox->addMap($map, $data['login']);
197
            $this->chatNotification->sendMessage(
198
                'expansion_mx.chat.success',
199
                null,
200
                [
201
                    "%mxid%" => $data['mxId'],
202
                    "%mapauthor%" => $map->author,
203
                    "%mapname%" => TMString::trimControls($map->name),
204
                ]
205
            );
206
        } catch (\Exception $e) {
207
            $this->chatNotification->sendMessage(
208
                'expansion_mx.chat.dedicatedexception',
209
                $group,
210
                [
211
                    "%message%" => $e->getMessage(),
212
                ]
213
            );
214
        }
215
    }
216
217
    /**
218
     * Remove special characters from map name
219
     *
220
     * @param $string
221
     * @return mixed
222
     */
223
    protected function cleanString($string)
224
    {
225
        return str_replace(array("/", "\\", ":", ".", "?", "*", '"', "|", "<", ">", "'"), "", $string);
226
    }
227
228
229
    /**
230
     * called at eXpansion init
231
     *
232
     * @return void
233
     */
234
    public function onApplicationInit()
235
    {
236
        // TODO: Implement onApplicationInit() method.
237
    }
238
239
    /**
240
     * called when init is done and callbacks are enabled
241
     *
242
     * @return void
243
     */
244
    public function onApplicationReady()
245
    {
246
247
    }
248
249
    /**
250
     * called when requesting application stop
251
     *
252
     * @return void
253
     */
254
    public function onApplicationStop()
255
    {
256
        // TODO: Implement onApplicationStop() method.
257
    }
258
}
259