forked from danog/MadelineProto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAPI.php
466 lines (441 loc) · 15.4 KB
/
API.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
<?php
declare(strict_types=1);
/**
* API 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 <[email protected]>
* @copyright 2016-2023 Daniil Gentili <[email protected]>
* @license https://opensource.org/licenses/AGPL-3.0 AGPLv3
* @link https://docs.madelineproto.xyz MadelineProto documentation
*/
namespace danog\MadelineProto;
use Amp\CancelledException;
use Amp\DeferredFuture;
use Amp\Future;
use Amp\Future\UnhandledFutureError;
use Amp\Ipc\Sync\ChannelledSocket;
use Amp\SignalException;
use Amp\TimeoutException;
use danog\MadelineProto\ApiWrappers\Start;
use danog\MadelineProto\Ipc\Client;
use danog\MadelineProto\Ipc\Server;
use danog\MadelineProto\Settings\Ipc as SettingsIpc;
use danog\MadelineProto\Settings\Logger as SettingsLogger;
use Revolt\EventLoop;
use Revolt\EventLoop\UncaughtThrowable;
use Throwable;
use Webmozart\Assert\Assert;
use function Amp\async;
use function Amp\Future\await;
use function Amp\Future\awaitFirst;
/**
* Main API wrapper for MadelineProto.
*/
final class API extends AbstractAPI
{
/**
* Release version.
*
* @var string
*/
public const RELEASE = '8.3.2';
/**
* We're not logged in.
*
* @var int
*/
public const NOT_LOGGED_IN = 0;
/**
* We're waiting for the login code.
*
* @var int
*/
public const WAITING_CODE = 1;
/**
* We're waiting for parameters to sign up.
*
* @var int
*/
public const WAITING_SIGNUP = -1;
/**
* We're waiting for the 2FA password.
*
* @var int
*/
public const WAITING_PASSWORD = 2;
/**
* We're logged in.
*
* @var int
*/
public const LOGGED_IN = 3;
/**
* We're logged out, the session will be deleted ASAP.
*
* @var int
*/
public const LOGGED_OUT = 4;
/**
* This peer is a user.
*
* @var string
*/
public const PEER_TYPE_USER = 'user';
/**
* This peer is a bot.
*
* @var string
*/
public const PEER_TYPE_BOT = 'bot';
/**
* This peer is a normal group.
*
* @var string
*/
public const PEER_TYPE_GROUP = 'chat';
/**
* This peer is a supergroup.
*
* @var string
*/
public const PEER_TYPE_SUPERGROUP = 'supergroup';
/**
* This peer is a channel.
*
* @var string
*/
public const PEER_TYPE_CHANNEL = 'channel';
/**
* Whether to generate only peer information.
*/
public const INFO_TYPE_PEER = 0;
/**
* Whether to generate only constructor information.
*/
public const INFO_TYPE_CONSTRUCTOR = 1;
/**
* Whether to generate only ID information.
*/
public const INFO_TYPE_ID = 2;
/**
* Whether to generate all information.
*/
public const INFO_TYPE_ALL = 3;
/**
* Whether to generate all usernames.
*/
public const INFO_TYPE_USERNAMES = 4;
/**
* Whether to generate just type info.
*/
public const INFO_TYPE_TYPE = 5;
use Start;
/**
* Session paths.
*
* @internal
*/
private SessionPaths $session;
/**
* Unlock callback.
*
* @var ?callable
*/
private $unlock = null;
/**
* Obtain the API ID UI template.
*/
public function getWebAPITemplate(): string
{
return $this->wrapper->getWebApiTemplate();
}
/**
* Set the API ID UI template.
*/
public function setWebApiTemplate(string $template): void
{
$this->wrapper->setWebApiTemplate($template);
}
/**
* Constructor function.
*
* @param string $session Session name
* @param SettingsAbstract $settings Settings
*/
public function __construct(string $session, ?SettingsAbstract $settings = null)
{
Magic::start(light: true);
$settings ??= new SettingsEmpty;
$this->session = new SessionPaths($session);
$this->wrapper = new APIWrapper($this->session);
$this->exportNamespaces();
Logger::constructorFromSettings($settings instanceof Settings
? $settings->getLogger()
: ($settings instanceof SettingsLogger ? $settings : new SettingsLogger));
if ($this->connectToMadelineProto($settings)) {
if (!$settings instanceof SettingsEmpty) {
EventLoop::queue($this->updateSettings(...), $settings);
}
return; // OK
}
if (!$settings instanceof Settings) {
$newSettings = new Settings;
$newSettings->merge($settings);
$settings = $newSettings;
}
$appInfo = $settings->getAppInfo();
if (!$appInfo->hasApiInfo()) {
if (!$appInfo->getShowPrompt()) {
throw new Exception("No API ID or API hash was provided, please specify them in the settings!");
}
$app = $this->APIStart($settings);
if (!$app) {
die();
}
$appInfo->setApiId($app['api_id']);
$appInfo->setApiHash($app['api_hash']);
}
$this->wrapper->setAPI(new MTProto($settings, $this->wrapper));
$this->wrapper->logger('Prompting initial serialization...');
$this->wrapper->serialize();
$this->wrapper->logger('Done initial serialization!');
$this->destruct();
if (!$this->connectToMadelineProto($settings)) {
throw new Exception("Could not start IPC server!");
}
$this->wrapper->logger(Lang::$current_lang['madelineproto_ready'], Logger::NOTICE);
}
/**
* Reconnect to full instance.
*/
protected function reconnectFull(): bool
{
if ($this->wrapper->getAPI() instanceof Client) {
$this->wrapper->logger('Restarting to full instance...');
try {
if (!isset($_GET['MadelineSelfRestart']) && (($this->hasEventHandler()) || !($this->isIpcWorker()))) {
$this->wrapper->logger('Restarting to full instance: the bot is already running!');
Tools::closeConnection($this->getWebMessage(Lang::$current_lang['botAlreadyRunning']));
return false;
}
$this->wrapper->logger('Restarting to full instance: stopping IPC server...');
$this->wrapper->getAPI()->stopIpcServer();
} catch (SecurityException|SignalException $e) {
throw $e;
} catch (Throwable $e) {
if ($e instanceof UncaughtThrowable) {
$e = $e->getPrevious();
if ($e instanceof SecurityException || $e instanceof SignalException) {
throw $e;
}
}
$this->wrapper->logger("Restarting to full instance: error $e");
}
$this->wrapper->logger('Restarting to full instance: reconnecting...');
$cancel = new DeferredFuture;
$cb = function () use ($cancel, &$cb): void {
[$result] = Serialization::tryConnect($this->session->getIpcPath(), $cancel->getFuture());
if ($result instanceof ChannelledSocket) {
try {
if (!$this->wrapper->getAPI() instanceof Client) {
$this->wrapper->logger('Restarting to full instance (again): the bot is already running!');
$result->disconnect();
return;
}
$this->wrapper->logger('Restarting to full instance (again): sending shutdown signal!');
$result->send(Server::SHUTDOWN);
$result->disconnect();
} catch (SecurityException|SignalException $e) {
throw $e;
} catch (Throwable $e) {
if ($e instanceof UncaughtThrowable) {
$e = $e->getPrevious();
if ($e instanceof SecurityException || $e instanceof SignalException) {
throw $e;
}
}
$this->wrapper->logger("Restarting to full instance: error in stop loop $e");
}
EventLoop::queue($cb);
}
};
EventLoop::queue($cb);
$this->connectToMadelineProto(new SettingsEmpty, true);
$cancel->complete(new Exception('Connected!'));
}
return true;
}
/**
* Connect to MadelineProto.
*
* @param SettingsAbstract $settings Settings
* @param bool $forceFull Whether to force full initialization
*/
protected function connectToMadelineProto(SettingsAbstract $settings, bool $forceFull = false, bool $tryReconnect = true): bool
{
if ($settings instanceof SettingsIpc) {
$forceFull = $forceFull || $settings->getSlow();
} elseif ($settings instanceof Settings) {
$forceFull = $forceFull || $settings->getIpc()->getSlow();
}
$forceFull = $forceFull || isset($_GET['MadelineSelfRestart']) || Magic::$altervista;
try {
[$unserialized, $this->unlock] = async(
Serialization::unserialize(...),
$this->session,
$settings,
$forceFull
)->await(Tools::getTimeoutCancellation(30.0));
} catch (CancelledException $e) {
if (!$e->getPrevious() instanceof TimeoutException) {
throw $e;
}
[$unserialized, $this->unlock] = [0, null];
}
if ($unserialized === 0) {
// Timeout
throw new Exception(Lang::$current_lang['could_not_connect_to_MadelineProto']);
} elseif ($unserialized instanceof Throwable) {
// IPC server error
throw $unserialized;
} elseif ($unserialized instanceof ChannelledSocket) {
// Success, IPC client
$this->wrapper->setAPI(new Client($unserialized, $this->session, Logger::$default));
return true;
} elseif ($unserialized) {
// Success, full session
$this->wrapper->getAPI()?->unreference();
$this->wrapper = $unserialized;
$this->wrapper->setSession($this->session);
$this->exportNamespaces();
if ($this->wrapper->getAPI()) {
unset($unserialized);
if ($settings instanceof SettingsIpc) {
$settings = new SettingsEmpty;
}
$this->wrapper->getAPI()->wakeup($settings, $this->wrapper);
$this->wrapper->logger(Lang::$current_lang['madelineproto_ready'], Logger::NOTICE);
return true;
}
}
return false;
}
/**
* Wakeup function.
*/
public function __wakeup(): void
{
$this->__construct($this->session->getSessionDirectoryPath());
}
public function __sleep(): array
{
return ['session'];
}
/**
* @var array<Future<null>>
*/
private static array $destructors = [];
/**
* @internal
*/
public static function finalize(): void
{
if (self::$destructors) {
await(self::$destructors);
}
}
private function destruct(int|null $id = null): void
{
$this->wrapper->logger('Shutting down MadelineProto ('.static::class.')');
$this->wrapper->getAPI()?->unreference();
if (isset($this->wrapper)) {
$this->wrapper->logger('Prompting final serialization...');
$this->wrapper->serialize();
$this->wrapper->logger('Done final serialization!');
}
if ($this->unlock) {
($this->unlock)();
}
if ($id !== null) {
unset(self::$destructors[$id]);
}
}
/**
* Destruct function.
*
* @internal
*/
public function __destruct()
{
$id = \count(self::$destructors);
self::$destructors[$id] = async($this->destruct(...), $id);
}
/**
* Start multiple instances of MadelineProto and the event handlers (enables async).
*
* @param array<API> $instances Instances of madeline
* @param array<class-string<EventHandler>>|class-string<EventHandler> $eventHandler Event handler(s)
*/
public static function startAndLoopMulti(array $instances, array|string $eventHandler): void
{
if (\is_string($eventHandler)) {
Assert::classExists($eventHandler);
$eventHandler::cachePlugins($eventHandler);
$eventHandler = array_fill_keys(array_keys($instances), $eventHandler);
} else {
Assert::notEmpty($eventHandler);
Assert::allClassExists($eventHandler);
foreach ($eventHandler as $c) {
$c::cachePlugins($c);
}
}
$errors = [];
$started = array_fill_keys(array_keys($instances), false);
$instanceOne = array_values($instances)[0];
$prev = EventLoop::getErrorHandler();
EventLoop::setErrorHandler(
$cb = static function (Throwable $e) use ($instanceOne, &$errors, &$started, $eventHandler): void {
if ($e instanceof UnhandledFutureError) {
$e = $e->getPrevious();
}
if ($e instanceof SecurityException || $e instanceof SignalException) {
throw $e;
}
if (str_starts_with($e->getMessage(), 'Could not connect to DC ')) {
throw $e;
}
$t = time();
$errors = [$t => $errors[$t] ?? 0];
$errors[$t]++;
if ($errors[$t] > 10 && array_sum($started) !== \count($eventHandler)) {
$instanceOne->wrapper->logger('More than 10 errors in a second and not inited, exiting!', Logger::FATAL_ERROR);
return;
}
echo $e;
$instanceOne->wrapper->logger((string) $e, Logger::FATAL_ERROR);
$instanceOne->report("Surfaced: $e");
}
);
try {
$promises = [];
foreach ($instances as $k => $instance) {
$instance->start();
$promises []= async(static function () use ($k, $instance, $eventHandler, &$started): void {
$instance->startAndLoopLogic($eventHandler[$k], $started[$k]);
});
}
awaitFirst($promises);
} finally {
if (EventLoop::getErrorHandler() === $cb) {
EventLoop::setErrorHandler($prev);
}
}
}
}