From 5809ab36751e0d4bc2e4e6877f49ab78b4400363 Mon Sep 17 00:00:00 2001 From: Daniil Gentili Date: Sun, 22 Jan 2023 14:27:16 +0100 Subject: [PATCH] More settings fixes --- src/danog/MadelineProto/InternalDoc.php | 17 +-- .../MadelineProto/Loop/Update/UpdateLoop.php | 2 +- src/danog/MadelineProto/MTProto.php | 119 ++++++------------ .../MTProtoSession/ResponseHandler.php | 2 +- .../MadelineProto/MTProtoTools/Files.php | 8 +- .../MTProtoTools/PeerHandler.php | 2 +- .../MTProtoTools/UpdateHandler.php | 2 +- src/danog/MadelineProto/Settings.php | 26 ---- .../MadelineProto/Settings/Connection.php | 31 ----- src/danog/MadelineProto/Settings/TLSchema.php | 4 + src/danog/MadelineProto/Wrappers/Login.php | 17 +-- 11 files changed, 55 insertions(+), 175 deletions(-) diff --git a/src/danog/MadelineProto/InternalDoc.php b/src/danog/MadelineProto/InternalDoc.php index 77470e657..6deac53e3 100644 --- a/src/danog/MadelineProto/InternalDoc.php +++ b/src/danog/MadelineProto/InternalDoc.php @@ -6771,24 +6771,20 @@ class InternalDoc extends APIFactory } /** * Store RSA keys for CDN datacenters. - * - * @param int $datacenter DC ID */ - public function getCdnConfig(int $datacenter): void + public function getCdnConfig(): void { - $this->__call(__FUNCTION__, [$datacenter]); + $this->__call(__FUNCTION__, []); } /** * Get cached (or eventually re-fetch) server-side config. * * @param array $config Current config - * @param array $options Options for method call */ public function getConfig(array $config = [ - ], array $options = [ ]) { - return $this->__call(__FUNCTION__, [$config, $options]); + return $this->__call(__FUNCTION__, [$config]); } /** * Get async DNS client. @@ -7242,13 +7238,6 @@ class InternalDoc extends APIFactory { $this->__call(__FUNCTION__, [$param, $level, $file]); } - /** - * Log out currently logged in user. - */ - public function logout(array $extra = []) - { - return $this->__call(__FUNCTION__, [$extra]); - } /** * Start MadelineProto's update handling loop, or run the provided async callable. * diff --git a/src/danog/MadelineProto/Loop/Update/UpdateLoop.php b/src/danog/MadelineProto/Loop/Update/UpdateLoop.php index d7016485d..6eba51a68 100644 --- a/src/danog/MadelineProto/Loop/Update/UpdateLoop.php +++ b/src/danog/MadelineProto/Loop/Update/UpdateLoop.php @@ -160,7 +160,7 @@ final class UpdateLoop extends ResumableSignalLoop } } else { $API->logger->logger('Resumed and fetching normal difference...', Logger::ULTRA_VERBOSE); - $difference = $API->methodCallAsyncRead('updates.getDifference', ['pts' => $state->pts(), 'date' => $state->date(), 'qts' => $state->qts()], $API->settings->getDefaultDcParams()); + $difference = $API->methodCallAsyncRead('updates.getDifference', ['pts' => $state->pts(), 'date' => $state->date(), 'qts' => $state->qts()], ['datacenter' => $API->authorized_dc]); $API->logger->logger('Got '.$difference['_'], Logger::ULTRA_VERBOSE); switch ($difference['_']) { case 'updates.differenceEmpty': diff --git a/src/danog/MadelineProto/MTProto.php b/src/danog/MadelineProto/MTProto.php index 8bc99b59f..270eba7b6 100644 --- a/src/danog/MadelineProto/MTProto.php +++ b/src/danog/MadelineProto/MTProto.php @@ -604,7 +604,7 @@ final class MTProto implements TLCallback, LoggerGetter // Initialize needed stuffs Magic::start(); // Parse and store settings - $this->updateSettingsInternal($settings); + $this->updateSettingsInternal($settings, false); // Actually instantiate needed classes like a boss $this->cleanupProperties(); // Start IPC server @@ -653,7 +653,7 @@ final class MTProto implements TLCallback, LoggerGetter $nearest_dc = $this->methodCallAsyncRead('help.getNearestDc', []); $this->logger->logger(\sprintf(Lang::$current_lang['nearest_dc'], $nearest_dc['country'], $nearest_dc['nearest_dc']), Logger::NOTICE); if ($nearest_dc['nearest_dc'] != $nearest_dc['this_dc']) { - $this->settings->setDefaultDc($this->datacenter->currentDatacenter= (int) $nearest_dc['nearest_dc']); + $this->authorized_dc = $this->datacenter->currentDatacenter = (int) $nearest_dc['nearest_dc']; } } catch (RPCErrorException $e) { if ($e->rpc !== 'BOT_METHOD_INVALID') { @@ -661,7 +661,7 @@ final class MTProto implements TLCallback, LoggerGetter } } } - $this->getConfig([]); + $this->getConfig(); $this->startUpdateSystem(true); $this->v = self::V; @@ -1103,7 +1103,7 @@ final class MTProto implements TLCallback, LoggerGetter // Reset MTProto session (not related to user session) $this->resetMTProtoSession(); // Update settings from constructor - $this->updateSettingsInternal($settings); + $this->updateSettings($settings); // Session update process for BC $forceDialogs = false; if (!isset($this->v) @@ -1233,31 +1233,13 @@ final class MTProto implements TLCallback, LoggerGetter public function updateSettings(SettingsAbstract $settings): void { $this->updateSettingsInternal($settings); - - if ($this->settings->getDb()->hasChanged()) { - $this->initDb($this); - $this->settings->getDb()->applyChanges(); - } - if ($this->settings->getIpc()->hasChanged()) { - $this->ipcServer->setSettings($this->settings->getIpc()->applyChanges()); - } - if ($this->settings->getSerialization()->hasChanged()) { - $this->serializeLoop->signal(true); - $this->serializeLoop = new PeriodicLoopInternal($this, [$this, 'serialize'], 'serialize', $this->settings->getSerialization()->applyChanges()->getInterval() * 1000); - } - if ($this->settings->getAuth()->hasChanged() - || $this->settings->getConnection()->hasChanged() - || $this->settings->getSchema()->hasChanged() - || $this->settings->getSchema()->needsUpgrade()) { - $this->initialize($this->settings); - } } /** * Parse, update and store settings. * * @param SettingsAbstract $settings Settings */ - private function updateSettingsInternal(SettingsAbstract $settings): void + private function updateSettingsInternal(SettingsAbstract $settings, bool $recurse = true): void { if ($settings instanceof SettingsEmpty) { if (!isset($this->settings)) { @@ -1285,6 +1267,33 @@ final class MTProto implements TLCallback, LoggerGetter if ($this->settings->getLogger()->hasChanged() || !isset($this->logger)) { $this->setupLogger(); } + + if ($this->settings->getDb()->hasChanged()) { + $this->logger->logger("The database settings have changed!", Logger::WARNING); + $this->cleanupProperties(); + $this->settings->getDb()->applyChanges(); + } + if ($this->settings->getIpc()->hasChanged()) { + $this->logger->logger("The IPC settings have changed!", Logger::WARNING); + if (isset($this->ipcServer)) { + $this->ipcServer->setSettings($this->settings->getIpc()->applyChanges()); + } + } + if ($this->settings->getSerialization()->hasChanged()) { + $this->logger->logger("The serialization settings have changed!", Logger::WARNING); + if (isset($this->serializeLoop)) { + $this->serializeLoop->signal(true); + } + $this->serializeLoop = new PeriodicLoopInternal($this, [$this, 'serialize'], 'serialize', $this->settings->getSerialization()->applyChanges()->getInterval() * 1000); + $this->serializeLoop->start(); + } + if ($recurse && ($this->settings->getAuth()->hasChanged() + || $this->settings->getConnection()->hasChanged() + || $this->settings->getSchema()->hasChanged() + || $this->settings->getSchema()->needsUpgrade())) { + $this->logger->logger("Generic settings have changed!", Logger::WARNING); + $this->initialize($this->settings); + } } /** * Return current settings. @@ -1403,55 +1412,6 @@ final class MTProto implements TLCallback, LoggerGetter $this->parseConfig(); $this->getPhoneConfig(); } - /** - * Clean up MadelineProto session after logout. - * - * @internal - */ - public function resetSession(): void - { - if (isset($this->seqUpdater)) { - $this->seqUpdater->signal(true); - unset($this->seqUpdater); - } - $channelIds = []; - foreach ($this->channels_state->get() as $state) { - $channelIds[] = $state->getChannel(); - } - \sort($channelIds); - foreach ($channelIds as $channelId) { - if (isset($this->feeders[$channelId])) { - $this->feeders[$channelId]->signal(true); - unset($this->feeders[$channelId]); - } - if (isset($this->updaters[$channelId])) { - $this->updaters[$channelId]->signal(true); - unset($this->updaters[$channelId]); - } - } - foreach ($this->datacenter->getDataCenterConnections() as $socket) { - $socket->authorized(false); - } - $this->channels_state = new CombinedUpdatesState(); - $this->got_state = false; - $this->msg_ids = []; - $this->authorized = self::NOT_LOGGED_IN; - $this->authorized_dc = -1; - $this->authorization = null; - $this->updates = []; - $this->secret_chats = []; - - $this->initDb($this, true); - - $this->tos = ['expires' => 0, 'accepted' => true]; - $this->dialog_params = ['_' => 'MadelineProto.dialogParams', 'limit' => 0, 'offset_date' => 0, 'offset_id' => 0, 'offset_peer' => ['_' => 'inputPeerEmpty'], 'count' => 0]; - - $this->referenceDatabase = new ReferenceDatabase($this); - $this->referenceDatabase->init(); - - $this->minDatabase = new MinDatabase($this); - $this->minDatabase->init(); - } /** * Reset the update state and fetch all updates from the beginning. */ @@ -1552,20 +1512,18 @@ final class MTProto implements TLCallback, LoggerGetter if ($this->authorized === self::LOGGED_IN && \class_exists(VoIPServerConfigInternal::class) && !$this->authorization['user']['bot'] - && $this->datacenter->getDataCenterConnection($this->settings->getDefaultDc())->hasTempAuthKey()) { + && $this->datacenter->getDataCenterConnection($this->authorized_dc)->hasTempAuthKey()) { $this->logger->logger('Fetching phone config...'); - VoIPServerConfig::updateDefault($this->methodCallAsyncRead('phone.getCallConfig', [], $this->settings->getDefaultDcParams())); + VoIPServerConfig::updateDefault($this->methodCallAsyncRead('phone.getCallConfig', [])); } } /** * Store RSA keys for CDN datacenters. - * - * @param int $datacenter DC ID */ - public function getCdnConfig(int $datacenter): void + public function getCdnConfig(): void { try { - foreach (($this->methodCallAsyncRead('help.getCdnConfig', [], ['datacenter' => $datacenter]))['public_keys'] as $curkey) { + foreach (($this->methodCallAsyncRead('help.getCdnConfig', [], ['datacenter' => $this->authorized_dc]))['public_keys'] as $curkey) { $curkey = RSA::load($this->TL, $curkey['public_key']); $this->cdn_rsa_keys[$curkey->fp] = $curkey; } @@ -1584,14 +1542,13 @@ final class MTProto implements TLCallback, LoggerGetter * Get cached (or eventually re-fetch) server-side config. * * @param array $config Current config - * @param array $options Options for method call */ - public function getConfig(array $config = [], array $options = []): array + public function getConfig(array $config = []): array { if ($this->config['expires'] > \time()) { return $this->config; } - $this->config = empty($config) ? $this->methodCallAsyncRead('help.getConfig', $config, $options ?: $this->settings->getDefaultDcParams()) : $config; + $this->config = empty($config) ? $this->methodCallAsyncRead('help.getConfig', $config) : $config; $this->parseConfig(); $this->logger->logger(Lang::$current_lang['config_updated'], Logger::NOTICE); $this->logger->logger($this->config, Logger::NOTICE); diff --git a/src/danog/MadelineProto/MTProtoSession/ResponseHandler.php b/src/danog/MadelineProto/MTProtoSession/ResponseHandler.php index 8966a08dd..98c51eeed 100644 --- a/src/danog/MadelineProto/MTProtoSession/ResponseHandler.php +++ b/src/danog/MadelineProto/MTProtoSession/ResponseHandler.php @@ -302,7 +302,7 @@ trait ResponseHandler $datacenter = -$datacenter; } if ($request->isUserRelated()) { - $this->API->settings->setDefaultDc($this->API->authorized_dc = $this->API->datacenter->currentDatacenter); + $this->API->authorized_dc = $this->API->datacenter->currentDatacenter; } EventLoop::queue($this->methodRecall(...), ['message_id' => $request->getMsgId(), 'datacenter' => $datacenter]); return null; diff --git a/src/danog/MadelineProto/MTProtoTools/Files.php b/src/danog/MadelineProto/MTProtoTools/Files.php index c3111c442..2249f83de 100644 --- a/src/danog/MadelineProto/MTProtoTools/Files.php +++ b/src/danog/MadelineProto/MTProtoTools/Files.php @@ -134,7 +134,7 @@ trait Files }); }; } - $datacenter = $this->settings->getDefaultDc(); + $datacenter = $this->authorized_dc; if ($this->datacenter->has(-$datacenter)) { $datacenter = -$datacenter; } @@ -855,7 +855,7 @@ trait Files } $part_size = $part_size ?? 1024 * 1024; $parallel_chunks = $this->settings->getFiles()->getDownloadParallelChunks(); - $datacenter = $messageMedia['InputFileLocation']['dc_id'] ?? $this->settings->getDefaultDc(); + $datacenter = $messageMedia['InputFileLocation']['dc_id'] ?? $this->authorized_dc; if ($this->datacenter->has(-$datacenter)) { $datacenter = -$datacenter; } @@ -1010,13 +1010,13 @@ trait Files $datacenter = $res['dc_id']; if (!$this->datacenter->has($datacenter)) { $this->config['expires'] = -1; - $this->getConfig([]); + $this->getConfig(); } $this->logger->logger(Lang::$current_lang['stored_on_cdn'], Logger::NOTICE); continue; } elseif ($res['_'] === 'upload.cdnFileReuploadNeeded') { $this->logger->logger(Lang::$current_lang['cdn_reupload'], Logger::NOTICE); - $this->getConfig([]); + $this->getConfig(); try { $this->addCdnHashes($messageMedia['file_token'], $this->methodCallAsyncRead('upload.reuploadCdnFile', ['file_token' => $messageMedia['file_token'], 'request_token' => $res['request_token']], ['heavy' => true, 'datacenter' => $old_dc])); } catch (RPCErrorException $e) { diff --git a/src/danog/MadelineProto/MTProtoTools/PeerHandler.php b/src/danog/MadelineProto/MTProtoTools/PeerHandler.php index 8af3f513c..0d27a4085 100644 --- a/src/danog/MadelineProto/MTProtoTools/PeerHandler.php +++ b/src/danog/MadelineProto/MTProtoTools/PeerHandler.php @@ -645,7 +645,7 @@ trait PeerHandler } if ($id === 'support') { if (!$this->supportUser) { - $this->methodCallAsyncRead('help.getSupport', [], $this->settings->getDefaultDcParams()); + $this->methodCallAsyncRead('help.getSupport', []); } return $this->getInfo($this->supportUser, $type); } diff --git a/src/danog/MadelineProto/MTProtoTools/UpdateHandler.php b/src/danog/MadelineProto/MTProtoTools/UpdateHandler.php index dab66d9db..5194ad50c 100644 --- a/src/danog/MadelineProto/MTProtoTools/UpdateHandler.php +++ b/src/danog/MadelineProto/MTProtoTools/UpdateHandler.php @@ -270,7 +270,7 @@ trait UpdateHandler public function getUpdatesState() { $data = $this->methodCallAsyncRead('updates.getState', []); - $this->getCdnConfig($this->settings->getDefaultDc()); + $this->getCdnConfig(); return $data; } /** diff --git a/src/danog/MadelineProto/Settings.php b/src/danog/MadelineProto/Settings.php index 570fffcc5..dd45d83ee 100644 --- a/src/danog/MadelineProto/Settings.php +++ b/src/danog/MadelineProto/Settings.php @@ -247,32 +247,6 @@ final class Settings extends SettingsAbstract } } - /** - * Get default DC ID. - */ - public function getDefaultDc(): int - { - return $this->connection->getDefaultDc(); - } - /** - * Get default DC params. - */ - public function getDefaultDcParams(): array - { - return $this->connection->getDefaultDcParams(); - } - - /** - * Set default DC ID. - * - * @param int $dc DC ID - */ - public function setDefaultDc(int $dc): self - { - $this->connection->setDefaultDc($dc); - return $this; - } - /** * Get app information. */ diff --git a/src/danog/MadelineProto/Settings/Connection.php b/src/danog/MadelineProto/Settings/Connection.php index f463cf3be..510dea45b 100644 --- a/src/danog/MadelineProto/Settings/Connection.php +++ b/src/danog/MadelineProto/Settings/Connection.php @@ -40,10 +40,6 @@ final class Connection extends SettingsAbstract * Robin period (seconds). */ protected int $robinPeriod = 10; - /** - * Default DC ID. - */ - protected int $defaultDc = 2; /** * Protocol identifier. * @@ -402,33 +398,6 @@ final class Connection extends SettingsAbstract return $this; } - /** - * Get default DC ID. - */ - public function getDefaultDc(): int - { - return $this->defaultDc; - } - /** - * Get default DC params. - */ - public function getDefaultDcParams(): array - { - return ['datacenter' => $this->defaultDc]; - } - - /** - * Set default DC ID. - * - * @param int $defaultDc Default DC ID. - */ - public function setDefaultDc(int $defaultDc): self - { - $this->defaultDc = $defaultDc; - - return $this; - } - /** * Get proxy identifiers. * diff --git a/src/danog/MadelineProto/Settings/TLSchema.php b/src/danog/MadelineProto/Settings/TLSchema.php index 6409e621b..2591c3f0f 100644 --- a/src/danog/MadelineProto/Settings/TLSchema.php +++ b/src/danog/MadelineProto/Settings/TLSchema.php @@ -35,6 +35,10 @@ final class TLSchema extends SettingsAbstract * Whether the scheme was upgraded. */ private bool $wasUpgraded = true; + public function __sleep() + { + return \array_merge(['wasUpgraded'], parent::__sleep()); + } public function mergeArray(array $settings): void { $settings = $settings['tl_schema'] ?? []; diff --git a/src/danog/MadelineProto/Wrappers/Login.php b/src/danog/MadelineProto/Wrappers/Login.php index 2e54e7102..d23d9a58e 100644 --- a/src/danog/MadelineProto/Wrappers/Login.php +++ b/src/danog/MadelineProto/Wrappers/Login.php @@ -36,17 +36,6 @@ use danog\MadelineProto\Settings; */ trait Login { - /** - * Log out currently logged in user. - */ - public function logout() - { - $this->methodCallAsyncRead('auth.logOut', []); - $this->resetSession(); - $this->logger->logger(Lang::$current_lang['logout_ok'], Logger::NOTICE); - $this->startUpdateSystem(); - return true; - } /** * Login as bot. * @@ -85,8 +74,7 @@ trait Login public function phoneLogin(string $number, int $sms_type = 5) { if ($this->authorized === MTProto::LOGGED_IN) { - $this->logger->logger(Lang::$current_lang['already_loggedIn'], Logger::NOTICE); - $this->logout(); + throw new Exception(Lang::$current_lang['already_loggedIn']); } $this->logger->logger(Lang::$current_lang['login_code_sending'], Logger::NOTICE); $this->authorization = $this->methodCallAsyncRead( @@ -164,8 +152,7 @@ trait Login public function importAuthorization(array $authorization, int $mainDcID) { if ($this->authorized === MTProto::LOGGED_IN) { - $this->logger->logger(Lang::$current_lang['already_loggedIn'], Logger::NOTICE); - $this->logout(); + throw new Exception(Lang::$current_lang['already_loggedIn']); } $this->logger->logger(Lang::$current_lang['login_auth_key'], Logger::NOTICE); foreach ($this->datacenter->getDataCenterConnections() as $connection) {