1
0
mirror of https://github.com/danog/MadelineProto.git synced 2024-11-27 03:14:39 +01:00

More settings fixes

This commit is contained in:
Daniil Gentili 2023-01-22 14:27:16 +01:00
parent 583a400723
commit 5809ab3675
11 changed files with 55 additions and 175 deletions

View File

@ -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.
*

View File

@ -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':

View File

@ -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);

View File

@ -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;

View File

@ -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) {

View File

@ -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);
}

View File

@ -270,7 +270,7 @@ trait UpdateHandler
public function getUpdatesState()
{
$data = $this->methodCallAsyncRead('updates.getState', []);
$this->getCdnConfig($this->settings->getDefaultDc());
$this->getCdnConfig();
return $data;
}
/**

View File

@ -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.
*/

View File

@ -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.
*

View File

@ -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'] ?? [];

View File

@ -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) {