|
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 Message |
|
34
|
|
|
*/ |
|
35
|
|
|
public function handle(Message $message) |
|
36
|
|
|
{ |
|
37
|
|
|
$query = $this->getGoogleQuery($message); |
|
38
|
|
|
|
|
39
|
|
|
if ($query) { |
|
40
|
|
|
$search = ''; |
|
41
|
|
|
|
|
42
|
|
|
try { |
|
43
|
|
|
$search = $this->search->searchGetMessage($query); |
|
44
|
|
|
} catch (\Throwable $e) { |
|
|
|
|
|
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
$hasMentions = count($message->mentions); |
|
48
|
|
|
$mention = null; |
|
49
|
|
|
|
|
50
|
|
|
if ($hasMentions) { |
|
51
|
|
|
$mention = $message->mentions[0]->isBot() |
|
52
|
|
|
? $message->user |
|
53
|
|
|
: $message->mentions[0]; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
if (count($message->mentions)) { |
|
57
|
|
|
return $message->answer( |
|
58
|
|
|
trans('google.personal', [ |
|
59
|
|
|
'user' => $mention->login, |
|
60
|
|
|
'query' => urlencode($query), |
|
61
|
|
|
]) . |
|
62
|
|
|
PHP_EOL . $search |
|
63
|
|
|
); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return $message->answer( |
|
67
|
|
|
trans('google.common', ['query' => urlencode($query)]) . |
|
68
|
|
|
PHP_EOL . $search |
|
69
|
|
|
); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
return $message; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
/** |
|
76
|
|
|
* @param Message $message |
|
77
|
|
|
* |
|
78
|
|
|
* @return string |
|
79
|
|
|
*/ |
|
80
|
|
|
private function getGoogleQuery(Message $message) : string |
|
81
|
|
|
{ |
|
82
|
|
|
$words = (new Collection(trans('google.queries')))->map('preg_quote')->implode('|'); |
|
83
|
|
|
$pattern = sprintf('/^(?:@.*?\s)?(?:%s)\s(.*?)$/isu', $words); |
|
84
|
|
|
$found = preg_match($pattern, $message->text_without_special_chars, $matches); |
|
85
|
|
|
if ($found) { |
|
86
|
|
|
return trim($matches[1]); |
|
87
|
|
|
} |
|
88
|
|
|
|
|
89
|
|
|
return ''; |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
|