|
1
|
|
|
<?php |
|
2
|
|
|
namespace Domains\Bot\Middlewares; |
|
3
|
|
|
|
|
4
|
|
|
use Domains\Message; |
|
5
|
|
|
use Domains\Middleware\MiddlewareInterface; |
|
6
|
|
|
use Illuminate\Config\Repository; |
|
7
|
|
|
use Illuminate\Support\Collection; |
|
8
|
|
|
use Interfaces\Google\GoogleSearch; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Class GoogleSearchMiddleware |
|
12
|
|
|
*/ |
|
13
|
|
|
class NewGoogleSearchMiddleware implements MiddlewareInterface |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @var GoogleSearch |
|
17
|
|
|
*/ |
|
18
|
|
|
private $search; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* GoogleSearchMiddleware constructor. |
|
22
|
|
|
* |
|
23
|
|
|
* @param Repository $config |
|
24
|
|
|
*/ |
|
25
|
|
|
public function __construct(Repository $config) |
|
26
|
|
|
{ |
|
27
|
|
|
$this->search = new GoogleSearch($config); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @param Message $message |
|
32
|
|
|
* |
|
33
|
|
|
* @return array |
|
34
|
|
|
*/ |
|
35
|
|
|
public function handle(Message $message) |
|
36
|
|
|
{ |
|
37
|
|
|
$query = $this->getGoogleQuery($message); |
|
38
|
|
|
if ($query) { |
|
39
|
|
|
$search = ''; |
|
40
|
|
|
try { |
|
41
|
|
|
$search = $this->search->searchGetMessage($query); |
|
42
|
|
|
} catch (\Throwable $e) { |
|
|
|
|
|
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
$hasMentions = count($message->mentions); |
|
46
|
|
|
$mention = null; |
|
47
|
|
|
|
|
48
|
|
View Code Duplication |
if ($hasMentions) { |
|
|
|
|
|
|
49
|
|
|
$mention = $message->mentions[0]->login === \Auth::user()->login ? $message->user : $message->mentions[0]; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
if (count($message->mentions)) { |
|
53
|
|
|
$answerTo = $message->user; |
|
|
|
|
|
|
54
|
|
|
|
|
55
|
|
|
$message->answer(trans('google.personal', [ |
|
56
|
|
|
'user' => $mention->login, |
|
57
|
|
|
'query' => urlencode($query), |
|
58
|
|
|
]).PHP_EOL.$search); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
$message->answer(trans('google.common', [ |
|
62
|
|
|
'query' => urlencode($query), |
|
63
|
|
|
]).PHP_EOL.$search); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return $message; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* @param Message $message |
|
71
|
|
|
* |
|
72
|
|
|
* @return string |
|
73
|
|
|
*/ |
|
74
|
|
|
private function getGoogleQuery(Message $message) : string |
|
75
|
|
|
{ |
|
76
|
|
|
$words = (new Collection(trans('google.queries')))->map('preg_quote')->implode('|'); |
|
77
|
|
|
$pattern = sprintf('/^(?:@.*?\s)?(?:%s)\s(.*?)$/isu', $words); |
|
78
|
|
|
$found = preg_match($pattern, $message->text, $matches); |
|
79
|
|
|
if ($found) { |
|
80
|
|
|
return trim($matches[1]); |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
return ''; |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|