Completed
Push — master ( 56815b...e9534a )
by Ehsan
12:27
created

Slackbot::setCommands()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Botonomous;
4
5
use Botonomous\listener\EventListener;
6
use Botonomous\plugin\AbstractPlugin;
7
8
/**
9
 * Class Botonomous.
10
 */
11
class Slackbot extends AbstractBot
12
{
13
    private $commands;
14
    private $lastError;
15
    private $currentCommand;
16
17
    /**
18
     * Botonomous constructor.
19
     *
20
     * @param Config|null $config
21
     *
22
     * @throws \Exception
23
     */
24 35
    public function __construct(Config $config = null)
25
    {
26 35
        if ($config !== null) {
27 4
            $this->setConfig($config);
28
        }
29
30
        // set timezone
31 35
        date_default_timezone_set($this->getConfig()->get('timezone'));
32 35
    }
33
34
    /**
35
     * @param null|string $key
36
     *
37
     * @return mixed
38
     */
39 8
    public function getRequest($key = null)
40
    {
41 8
        return $this->getListener()->getRequest($key);
42
    }
43
44
    /**
45
     * @return string|null
46
     */
47 7
    private function determineAction()
48
    {
49 7
        $utility = $this->getRequestUtility();
50 7
        $getRequest = $utility->getGet();
51
52 7
        if (!empty($getRequest['action'])) {
53 2
            return strtolower($getRequest['action']);
54
        }
55
56 5
        $request = $utility->getPostedBody();
57
58 5
        if (isset($request['type']) && $request['type'] === 'url_verification') {
59 1
            return 'url_verification';
60
        }
61 4
    }
62
63
    /**
64
     * @return null|AbstractBaseSlack
65
     */
66 1
    private function handleMessageActions()
67
    {
68 1
        $post = $this->getRequestUtility()->getPost();
69
70
        // ignore if payload is not set
71 1
        if (!isset($post['payload'])) {
72
            /* @noinspection PhpInconsistentReturnPointsInspection */
73 1
            return;
74
        }
75
76
        // posted payload is in JSON
77 1
        $payload = json_decode($post['payload'], true);
78
79 1
        return (new MessageAction())->load($payload);
80
    }
81
82
    /**
83
     * @throws \Exception
84
     */
85 4
    private function handleSendResponse()
86
    {
87
        // 1. Start listening
88 4
        $this->getListener()->listen();
89
90
        // 2. verify the request
91
        try {
92 4
            $verificationResult = $this->verifyRequest();
93
94 4
            if ($verificationResult['success'] !== true) {
95 4
                throw new \Exception($verificationResult['message']);
96
            }
97 1
        } catch (\Exception $e) {
98 1
            throw $e;
99
        }
100
101
        // 3. pre process the request
102 3
        $this->preProcessRequest();
103
104
        // 4. check access control
105 3
        if ($this->checkAccessControl() !== true) {
106 2
            return;
107
        }
108
109
        // 5. set the current command
110 1
        $message = $this->getMessage();
111 1
        $this->setCurrentCommand($this->getMessageUtility()->extractCommandName($message));
112
113
        // 6. log the message
114 1
        if (empty($this->getRequest('debug'))) {
115 1
            $this->getLoggerUtility()->logRaw($this->getFormattingUtility()->newLine());
116 1
            $this->getLoggerUtility()->logChat(__METHOD__, $message);
117
        }
118
119 1
        $this->getLoggerUtility()->logRaw($this->getRequestUtility()->getContent());
120
121
        // 7. send confirmation message if is enabled
122 1
        $this->sendConfirmation();
123
124
        // 8. And send the response to the channel, only if the response is not empty
125 1
        $response = $this->respond($message);
126
127 1
        if (!empty($response)) {
128 1
            $this->getSender()->send($response);
129
        }
130 1
    }
131
132
    /**
133
     * @return bool
134
     */
135 3
    private function checkAccessControl()
136
    {
137
        // if accessControlEnabled is not set true ignore the check and return true
138 3
        if ($this->getConfig()->get('accessControlEnabled') !== true) {
139 1
            return true;
140
        }
141
142 2
        if ($this->getBlackList()->isBlackListed() !== false) {
143
            // found in blacklist
144 1
            $this->getSender()->send($this->getConfig()->get('blacklistedMessage'));
145
146 1
            return false;
147
        }
148
149 1
        if ($this->getWhiteList()->isWhiteListed() !== true) {
150
            // not found in whitelist
151 1
            $this->getSender()->send($this->getConfig()->get('whitelistedMessage'));
152
153 1
            return false;
154
        }
155
156
        return true;
157
    }
158
159
    /**
160
     * @throws \Exception
161
     */
162 7
    public function run()
163
    {
164 7
        switch ($this->determineAction()) {
165 7
            case 'oauth':
166 1
                return $this->handleOAuth();
167 6
            case 'message_actions':
168 1
                return $this->handleMessageActions();
169 5
            case 'url_verification':
170 1
                return $this->handleUrlVerification();
171
            default:
172 4
                return $this->handleSendResponse();
173
        }
174
    }
175
176
    /**
177
     * handle OAuth.
178
     */
179 1
    private function handleOAuth()
180
    {
181 1
        return $this->getOauth()->doOauth();
182
    }
183
184
    /**
185
     * @throws \Exception
186
     *
187
     * @return mixed
188
     */
189 1
    private function handleUrlVerification()
190
    {
191 1
        $request = $this->getRequestUtility()->getPostedBody();
192
193 1
        if (empty($request['challenge'])) {
194
            throw new \Exception('Challenge is missing for URL verification');
195
        }
196
197 1
        echo $request['challenge'];
198 1
    }
199
200
    /**
201
     * Send confirmation.
202
     */
203 1
    private function sendConfirmation()
204
    {
205 1
        $userId = $this->getRequest('user_id');
206
207 1
        $user = '';
208 1
        if (!empty($userId)) {
209 1
            $user = $this->getMessageUtility()->linkToUser($userId).' ';
210
        }
211
212 1
        $confirmMessage = $this->getConfig()->get('confirmReceivedMessage', ['user' => $user]);
213
214 1
        if (!empty($confirmMessage)) {
215 1
            $this->getSender()->send($confirmMessage);
216
        }
217 1
    }
218
219
    /**
220
     * Pre-process the request.
221
     */
222 3
    private function preProcessRequest()
223
    {
224 3
        $request = $this->getListener()->getRequest();
225
226
        // remove the trigger_word from beginning of the message
227 3
        if (!empty($request['trigger_word'])) {
228 3
            $request['text'] = $this->getMessageUtility()->removeTriggerWord(
229 3
                $request['text'],
230 3
                $request['trigger_word']
231
            );
232
233 3
            $this->getListener()->setRequest($request);
234
        }
235 3
    }
236
237
    /**
238
     * @param null $message
239
     *
240
     * @throws \Exception
241
     *
242
     * @return mixed
243
     */
244 4
    public function respond($message = null)
245
    {
246
        try {
247 4
            $command = $this->getCommandByMessage($message);
248
249 4
            if (!$command instanceof Command) {
250
                // something went wrong, error will tell us!
251 2
                return $this->getLastError();
252
            }
253
254
            // create the class
255 3
            $pluginClassFile = $command->getClass();
256 3
            $pluginClass = new $pluginClassFile($this);
257
258
            // check class is valid
259 3
            if (!$pluginClass instanceof AbstractPlugin) {
260
                throw new \Exception("Couldn't create class: '{$pluginClassFile}'");
261
            }
262
263
            // check action exists
264 3
            $action = $command->getAction();
265 3
            if (!method_exists($pluginClass, $action)) {
266 1
                throw new \Exception("Action / function: '{$action}' does not exist in '{$pluginClassFile}'");
267
            }
268
269 2
            return $pluginClass->$action();
270 1
        } catch (\Exception $e) {
271 1
            throw $e;
272
        }
273
    }
274
275
    /**
276
     * @param null $message
277
     *
278
     * @throws \Exception
279
     *
280
     * @return bool|Command
281
     */
282 7
    public function getCommandByMessage($message = null)
283
    {
284
        // If message is not set, get it from the current request
285 7
        if ($message === null) {
286 4
            $message = $this->getMessage();
287
        }
288
289 7
        if (empty($message)) {
290 1
            $this->setLastError('Message is empty');
291
292 1
            return false;
293
        }
294
295
        /**
296
         * Process the message.
297
         */
298 6
        $command = $this->getMessageUtility()->extractCommandName($message);
299
300 6
        $config = $this->getConfig();
301
302
        // check command name
303 6
        if (empty($command)) {
304
            // get the default command if no command is find in the message
305 2
            $command = $config->get('defaultCommand');
306
307 2
            if (empty($command)) {
308 2
                $this->setLastError($config->get('noCommandMessage'));
309
310 2
                return false;
311
            }
312
        }
313
314 4
        $commandObject = $this->getCommandContainer()->getAsObject($command);
315
316
        // check command details
317 4
        if (empty($commandObject)) {
318 1
            $this->setLastError($config->get('unknownCommandMessage', ['command' => $command]));
319
320 1
            return false;
321
        }
322
323 4
        if (!$commandObject instanceof Command) {
324
            throw new \Exception('Command is not an object');
325
        }
326
327
        // check the plugin for the command
328 4
        if (empty($commandObject->getPlugin())) {
329
            throw new \Exception('Plugin is not set for this command');
330
        }
331
332 4
        return $commandObject;
333
    }
334
335
    /**
336
     * @throws \Exception
337
     *
338
     * @return array<string,boolean|string>
339
     */
340 4
    private function verifyRequest()
341
    {
342 4
        $originCheck = $this->getListener()->verifyOrigin();
343
344 4
        if (!isset($originCheck['success'])) {
345
            throw new \Exception('Success must be provided in verifyOrigin response');
346
        }
347
348 4
        if ($originCheck['success'] !== true) {
349
            return [
350
                'success' => false,
351
                'message' => $originCheck['message'],
352
            ];
353
        }
354
355 4
        if ($this->getListener()->isThisBot() !== false) {
356
            return [
357 1
                'success' => false,
358
                'message' => 'Request comes from the bot',
359
            ];
360
        }
361
362
        return [
363 3
            'success' => true,
364
            'message' => 'Yay!',
365
        ];
366
    }
367
368
    /**
369
     * @return array
370
     */
371 2
    public function getCommands()
372
    {
373 2
        if (!isset($this->commands)) {
374 1
            $this->setCommands($this->getCommandContainer()->getAllAsObject());
375
        }
376
377 2
        return $this->commands;
378
    }
379
380
    /**
381
     * @param array $commands
382
     */
383 2
    public function setCommands(array $commands)
384
    {
385 2
        $this->commands = $commands;
386 2
    }
387
388
    /**
389
     * @return string
390
     */
391 4
    public function getLastError()
392
    {
393 4
        return $this->lastError;
394
    }
395
396
    /**
397
     * @param string $lastError
398
     */
399 4
    public function setLastError($lastError)
400
    {
401 4
        $this->lastError = $lastError;
402 4
    }
403
404
    /**
405
     * @return string
406
     */
407 1
    public function getCurrentCommand()
408
    {
409 1
        return $this->currentCommand;
410
    }
411
412
    /**
413
     * @param string $currentCommand
414
     */
415 2
    public function setCurrentCommand($currentCommand)
416
    {
417 2
        $this->currentCommand = $currentCommand;
418 2
    }
419
420
    /**
421
     * Return message based on the listener
422
     * If listener is event and event text is empty, fall back to request text.
423
     *
424
     * @return mixed|string
425
     */
426 11
    public function getMessage()
427
    {
428 11
        $listener = $this->getListener();
429 11
        if ($listener instanceof EventListener && $listener->getEvent() instanceof Event) {
430 1
            $message = $listener->getEvent()->getText();
431
432 1
            if (!empty($message)) {
433 1
                return $message;
434
            }
435
        }
436
437 10
        return $listener->getRequest('text');
438
    }
439
440
    /**
441
     * Determine if bot user id is mentioned in the message.
442
     *
443
     * @return bool
444
     */
445 1
    public function youTalkingToMe()
446
    {
447 1
        $message = $this->getMessage();
448
449 1
        if (empty($message)) {
450 1
            return false;
451
        }
452
453 1
        if ($this->getMessageUtility()->isBotMentioned($message) === true) {
454 1
            return true;
455
        }
456
457 1
        $listener = $this->getListener();
458
        // check direct messages
459 1
        return $listener instanceof EventListener && $listener->getEvent()->isDirectMessage() === true;
460
    }
461
}
462