forked from danog/MadelineProto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EventHandler.php
490 lines (463 loc) · 17.7 KB
/
EventHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
<?php
declare(strict_types=1);
/**
* EventHandler module.
*
* This file is part of MadelineProto.
* MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU General Public License along with MadelineProto.
* If not, see <http://www.gnu.org/licenses/>.
*
* @author Daniil Gentili <daniil@daniil.it>
* @copyright 2016-2023 Daniil Gentili <daniil@daniil.it>
* @license https://opensource.org/licenses/AGPL-3.0 AGPLv3
* @link https://docs.madelineproto.xyz MadelineProto documentation
*/
namespace danog\MadelineProto;
use Amp\DeferredFuture;
use Amp\Future;
use Amp\Sync\LocalMutex;
use AssertionError;
use Closure;
use danog\Loop\PeriodicLoop;
use danog\MadelineProto\Db\DbPropertiesTrait;
use danog\MadelineProto\EventHandler\Attributes\Cron;
use danog\MadelineProto\EventHandler\Attributes\Handler;
use danog\MadelineProto\EventHandler\Filter\Combinator\FiltersAnd;
use danog\MadelineProto\EventHandler\Filter\Filter;
use danog\MadelineProto\EventHandler\Filter\FilterAllowAll;
use danog\MadelineProto\EventHandler\Update;
use Generator;
use PhpParser\Node\Name;
use ReflectionAttribute;
use ReflectionClass;
use ReflectionMethod;
use Revolt\EventLoop;
use Webmozart\Assert\Assert;
use function Amp\File\isDirectory;
use function Amp\File\isFile;
use function Amp\File\listFiles;
/**
* Event handler.
*/
abstract class EventHandler extends AbstractAPI
{
use DbPropertiesTrait {
DbPropertiesTrait::initDb as private internalInitDb;
}
protected function getDbPrefix(): string
{
return $this->wrapper->getAPI()->getDbPrefix();
}
private static bool $includingPlugins = false;
/**
* Start MadelineProto and the event handler.
*
* Also initializes error reporting, catching and reporting all errors surfacing from the event loop.
*
* @param string $session Session name
* @param ?SettingsAbstract $settings Settings
*/
final public static function startAndLoop(string $session, ?SettingsAbstract $settings = null): void
{
if (self::$includingPlugins) {
return;
}
self::cachePlugins(static::class);
$settings ??= new SettingsEmpty;
$API = new API($session, $settings);
$API->startAndLoopInternal(static::class);
}
/**
* Start MadelineProto as a bot and the event handler.
*
* Also initializes error reporting, catching and reporting all errors surfacing from the event loop.
*
* @param string $session Session name
* @param string $token Bot token
* @param ?SettingsAbstract $settings Settings
*/
final public static function startAndLoopBot(string $session, string $token, ?SettingsAbstract $settings = null): void
{
if (self::$includingPlugins) {
return;
}
self::cachePlugins(static::class);
$settings ??= new SettingsEmpty;
$API = new API($session, $settings);
$API->botLogin($token);
$API->startAndLoopInternal(static::class);
}
/** @internal */
final protected function reconnectFull(): bool
{
return true;
}
/**
* Whether the event handler was started.
*/
private bool $startedInternal = false;
private ?LocalMutex $startMutex = null;
private ?DeferredFuture $startDeferred = null;
/**
* @var array<PeriodicLoop>
*/
private array $periodicLoops = [];
/**
* Start method handler.
*
* @internal
*/
final public function internalStart(APIWrapper $MadelineProto, array $pluginsPrev, array &$pluginsNew, bool $main = true): ?array
{
if ($this->startedInternal) {
return null;
}
$this->startMutex ??= new LocalMutex;
$this->startDeferred ??= new DeferredFuture;
$startDeferred = $this->startDeferred;
$lock = $this->startMutex->acquire();
try {
if ($this->startedInternal) {
return null;
}
$this->wrapper = $MadelineProto;
$this->exportNamespaces();
if (isset(static::$dbProperties)) {
$this->internalInitDb($this->wrapper->getAPI());
}
if ($main) {
$this->setReportPeers($this->getReportPeers());
}
if (method_exists($this, 'onStart')) {
$r = $this->onStart();
if ($r instanceof Generator) {
throw new AssertionError("Yield cannot be used in onStart!");
}
if ($r instanceof Future) {
$r = $r->await();
}
}
if ($main) {
$this->setReportPeers($this->getReportPeers());
}
if ($this instanceof PluginEventHandler && !$this->isPluginEnabled()) {
return [[], []];
}
$constructors = $this->getTL()->getConstructors();
$methods = [];
$handlers = [];
$has_any = false;
$basic_handler = static function (array $update, Closure $closure): void {
$closure($update);
};
foreach ((new ReflectionClass($this))->getMethods(ReflectionMethod::IS_PUBLIC) as $methodRefl) {
$method = $methodRefl->getName();
if ($method === 'onAny') {
$has_any = true;
continue;
}
$closure = $this->$method(...);
$method_name = lcfirst(substr($method, 2));
if ((
($constructor = $constructors->findByPredicate($method_name)) && $constructor['type'] === 'Update'
)
|| $method_name === 'updateBroadcastProgress'
|| $method_name === 'updateNewOutgoingEncryptedMessage'
) {
$methods[$method_name] = [
static function (array $update) use ($basic_handler, $closure): void {
EventLoop::queue($basic_handler, $update, $closure);
}
];
continue;
}
array_map(fn (ReflectionAttribute $attribute) => $attribute->newInstance(), $methodRefl->getAttributes());
if ($periodic = $methodRefl->getAttributes(Cron::class)) {
if (!$this instanceof SimpleEventHandler) {
throw new AssertionError("Please extend SimpleEventHandler to use crons!");
}
$periodic = $periodic[0]->newInstance();
$this->periodicLoops[$method] = new PeriodicLoop(
static function (PeriodicLoop $loop) use ($closure): bool {
return $closure($loop) ?? false;
},
$method,
$periodic->period
);
$this->periodicLoops[$method]->start();
continue;
}
$filter = $methodRefl->getAttributes(
Filter::class,
ReflectionAttribute::IS_INSTANCEOF
)[0] ?? null;
if (!$filter) {
if (!($handler = $methodRefl->getAttributes(Handler::class))) {
continue;
}
$filter = new FilterAllowAll;
} else {
$filter = $filter->newInstance();
}
$filter = new FiltersAnd(
$filter,
Filter::fromReflectionType($methodRefl->getParameters()[0]->getType())
);
$filter = $filter->initialize($this);
if (!$this instanceof SimpleEventHandler) {
throw new AssertionError("Please extend SimpleEventHandler to use filters!");
}
$handlers []= static function (Update $update) use ($closure, $filter): void {
EventLoop::queue(static function () use ($closure, $filter, $update): void {
if ($filter->apply($update)) {
$closure($update);
}
});
};
}
if ($this instanceof SimpleEventHandler) {
$last = null;
foreach (Tools::validateEventHandlerClass(static::class) as $issue) {
if ($issue->severe) {
$last = $issue;
}
$issue->log();
}
if ($last) {
$last->throw();
}
}
if ($has_any) {
/** @psalm-suppress UndefinedMethod */
$onAny = function (array $update): void {
EventLoop::queue($this->onAny(...), $update);
};
foreach ($constructors->by_id as $constructor) {
if ($constructor['type'] === 'Update' && !isset($methods[$constructor['predicate']])) {
$methods[$constructor['predicate']] = [$onAny];
}
}
}
$plugins = self::$pluginCache[static::class];
foreach ($plugins as $class) {
$plugin = $pluginsPrev[$class] ?? $pluginsNew[$class] ?? new $class;
$pluginsNew[$class] = $plugin;
[$newMethods, $newHandlers] = $plugin->internalStart($MadelineProto, $pluginsPrev, $pluginsNew, false) ?? [];
if (!$plugin->isPluginEnabled()) {
unset($pluginsNew[$class]);
continue;
}
foreach ($newMethods as $update => $method) {
$methods[$update] = array_merge($method, $methods[$update] ?? []);
}
$handlers = array_merge($handlers, $newHandlers);
}
$this->startedInternal = true;
return [$methods, $handlers];
} finally {
$this->startDeferred = null;
$startDeferred->complete();
EventLoop::queue($lock->release(...));
}
}
/**
* Obtain a PeriodicLoop instance created by the Cron attribute.
*
* @param string $name Method name
*/
final public function getPeriodicLoop(string $name): PeriodicLoop
{
return $this->periodicLoops[$name];
}
/**
* Obtain all PeriodicLoop instances created by the Cron attribute.
*
* @return array<string, PeriodicLoop>
*/
final public function getPeriodicLoops(): array
{
return $this->periodicLoops;
}
/**
* @internal
*/
final public function waitForInternalStart(): ?Future
{
if (!$this->startedInternal && !$this->startDeferred) {
$this->startDeferred = new DeferredFuture;
}
return $this->startDeferred?->getFuture();
}
/**
* Get peers where to send error reports.
*
* @return string|int|array<string|int>
*/
public function getReportPeers()
{
return [];
}
/**
* Obtain a path or a list of paths that will be recursively searched for plugins.
*
* Plugin filenames end with Plugin.php, and will be included automatically.
*
* @return non-empty-string|non-empty-list<non-empty-string>|null
*/
public static function getPluginPaths(): string|array|null
{
return null;
}
/**
* Obtain a list of plugin event handlers to use, in addition with those found by getPluginPath.
*
* @return array<class-string<EventHandler>>
*/
public static function getPlugins(): array
{
return [];
}
/** @var array<class-string<EventHandler>, list<class-string<PluginEventHandler>>> */
private static array $pluginCache = [];
/**
* Cache a list of plugin event handlers.
*
* @internal
*
* @param class-string<EventHandler> $class
*/
final public static function cachePlugins(string $class): void
{
if (isset(self::$pluginCache[$class])) {
return;
}
$plugins = $class::getPlugins();
$plugins = array_values(array_unique($plugins, SORT_REGULAR));
$plugins = array_merge($plugins, self::internalGetDirectoryPlugins($class));
foreach ($plugins as $plugin) {
Assert::classExists($plugin);
Assert::true(is_subclass_of($plugin, PluginEventHandler::class), "$plugin must extend ".PluginEventHandler::class);
Assert::notEq($plugin, PluginEventHandler::class);
Assert::true(str_contains(ltrim($plugin, '\\'), '\\'), "$plugin must be in a namespace!");
$last = null;
foreach (Tools::validateEventHandlerClass($plugin) as $issue) {
if ($issue->severe) {
$last = $issue;
}
$issue->log();
}
if ($last) {
$last->throw();
}
}
self::$pluginCache[$class] = $plugins;
foreach ($plugins as $plugin) {
self::cachePlugins($plugin);
}
}
private static array $checkedPaths = [];
/**
* Cache a list of plugin event handlers.
*
* @param class-string<EventHandler> $class
*/
private static function internalGetDirectoryPlugins(string $class): array
{
if (is_subclass_of($class, PluginEventHandler::class)) {
return [];
}
$paths = $class::getPluginPaths();
if (\is_string($paths)) {
$paths = [$paths];
} elseif ($paths === null) {
$paths = [];
} else {
$paths = array_values($paths);
}
foreach ($paths as $k => &$path) {
$pathNew = realpath($path);
if ($pathNew === false) {
$pathNew = realpath(\dirname((new ReflectionClass($class))->getFileName()).DIRECTORY_SEPARATOR.$path);
if ($pathNew === false) {
unset($paths[$k]);
Logger::log(sprintf(Lang::$current_lang['plugin_path_does_not_exist'], $path), Logger::FATAL_ERROR);
continue;
}
}
$path = $pathNew;
}
if (!$paths) {
return [];
}
$pluginsTemp = [];
$recurse = static function (string $path, string $namespace = 'MadelinePlugin') use (&$recurse, &$pluginsTemp): void {
foreach (listFiles($path) as $file) {
$file = $path.DIRECTORY_SEPARATOR.$file;
if (isDirectory($file)) {
$recurse($file, $namespace.'\\'.basename($file));
} elseif (isFile($file) && str_ends_with($file, ".php")) {
$file = realpath($file);
$fileName = basename($file, '.php');
if ($fileName === 'functions') {
require $file;
continue;
}
if (str_contains($fileName, '.')) {
continue;
}
$class = $namespace.'\\'.$fileName;
$refl = new ReflectionClass($class);
if ($refl->getFileName() !== $file) {
throw new AssertionError("$class was not defined when including $file, the same plugin is present in multiple plugin paths/composer!");
}
if (class_exists($class)
&& !$refl->isAbstract()
&& is_subclass_of($class, PluginEventHandler::class)
) {
self::cachePlugins($class);
$pluginsTemp []= $class;
}
}
}
};
$plugins = [];
try {
self::$includingPlugins = true;
foreach ($paths as $p) {
if (isset(self::$checkedPaths[$p])) {
$plugins = array_merge($plugins, self::$checkedPaths[$p]);
continue;
}
spl_autoload_register(static function (string $class) use ($p): void {
if (!str_starts_with($class, 'MadelinePlugin\\')) {
return;
}
// Has leading /
$file = $p.str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 14)).'.php';
if (file_exists($file)) {
require $file;
if (!class_exists($class) && !interface_exists($class) && !trait_exists($class) && !enum_exists($class)) {
throw new AssertionError("$class was not defined when including $file!");
}
}
});
$recurse($p);
self::$checkedPaths[$p] = $pluginsTemp;
$plugins = array_merge($plugins, $pluginsTemp);
$pluginsTemp = [];
}
} finally {
self::$includingPlugins = false;
}
return $plugins;
}
public function __destruct()
{
if (method_exists($this, 'onStop')) {
$this->onStop();
}
}
}