1
0
mirror of https://github.com/danog/MadelineProto.git synced 2024-11-30 08:18:59 +01:00

New event handler startAndLoop API

This commit is contained in:
Daniil Gentili 2021-12-09 13:25:14 +01:00
parent 5fc3f54ed0
commit 2c90b1d96b
Signed by: danog
GPG Key ID: 8C1BE3B34B230CA7
11 changed files with 56 additions and 136 deletions

2
docs

@ -1 +1 @@
Subproject commit ee670d480786e65caa89266bdf859c0e6ad4521e Subproject commit 989550c157c6aeb96d8dbe1ea625d61932efb993

View File

@ -19,7 +19,6 @@
* @link https://docs.madelineproto.xyz MadelineProto documentation * @link https://docs.madelineproto.xyz MadelineProto documentation
*/ */
use danog\MadelineProto\API;
use danog\MadelineProto\Db\DbArray; use danog\MadelineProto\Db\DbArray;
use danog\MadelineProto\EventHandler; use danog\MadelineProto\EventHandler;
use danog\MadelineProto\Logger; use danog\MadelineProto\Logger;
@ -142,8 +141,6 @@ $settings->getLogger()->setLevel(Logger::LEVEL_ULTRA_VERBOSE);
// $settings->setDb((new Postgres)->setDatabase('MadelineProto')->setUsername('daniil')->setPassword('pony')); // $settings->setDb((new Postgres)->setDatabase('MadelineProto')->setUsername('daniil')->setPassword('pony'));
// $settings->setDb((new Mysql)->setDatabase('MadelineProto')->setUsername('daniil')->setPassword('pony')); // $settings->setDb((new Mysql)->setDatabase('MadelineProto')->setUsername('daniil')->setPassword('pony'));
$MadelineProto = new API('uwu.madeline', $settings);
// Reduce boilerplate with new wrapper method. // Reduce boilerplate with new wrapper method.
// Also initializes error reporting, catching and reporting all errors surfacing from the event loop. // Also initializes error reporting, catching and reporting all errors surfacing from the event loop.
$MadelineProto->startAndLoop(MyEventHandler::class); MyEventHandler::startAndLoop('uwu.madeline', $settings);

View File

@ -29,6 +29,7 @@ use danog\MadelineProto\API;
use danog\MadelineProto\APIWrapper; use danog\MadelineProto\APIWrapper;
use danog\MadelineProto\MTProtoTools\Files; use danog\MadelineProto\MTProtoTools\Files;
use danog\MadelineProto\RPCErrorException; use danog\MadelineProto\RPCErrorException;
use danog\MadelineProto\Settings;
use danog\MadelineProto\Tools; use danog\MadelineProto\Tools;
use League\Uri\Contracts\UriException; use League\Uri\Contracts\UriException;
@ -237,26 +238,15 @@ class MyEventHandler extends \danog\MadelineProto\EventHandler
} }
} }
} }
$settings = [
'logger' => [
'logger_level' => 4
],
'serialization' => [
'serialization_interval' => 30
],
'connection_settings' => [
'media_socket_count' => [
'min' => 20,
'max' => 1000,
]
],
'upload' => [
'allow_automatic_upload' => false // IMPORTANT: for security reasons, upload by URL will still be allowed
],
];
$MadelineProto = new \danog\MadelineProto\API(($argv[1] ?? 'bot').'.madeline', $settings); $settings = new Settings;
$settings->getConnection()
->setMinMediaSocketCount(20)
->setMaxMediaSocketCount(1000);
// IMPORTANT: for security reasons, upload by URL will still be allowed
$settings->getFiles()->setAllowAutomaticUpload(true);
// Reduce boilerplate with new wrapper method. // Reduce boilerplate with new wrapper method.
// Also initializes error reporting, catching and reporting all errors surfacing from the event loop. // Also initializes error reporting, catching and reporting all errors surfacing from the event loop.
$MadelineProto->startAndLoop(MyEventHandler::class); MyEventHandler::startAndLoop(($argv[1] ?? 'bot').'.madeline', $settings);

View File

@ -20,6 +20,7 @@
*/ */
use danog\MadelineProto\APIWrapper; use danog\MadelineProto\APIWrapper;
use danog\MadelineProto\Settings;
/* /*
* Various ways to load MadelineProto * Various ways to load MadelineProto
@ -125,16 +126,6 @@ class SecretHandler extends \danog\MadelineProto\EventHandler
} }
} }
if (\file_exists('.env')) { $settings = new Settings;
echo 'Loading .env...'.PHP_EOL;
$dotenv = Dotenv\Dotenv::create(\getcwd());
$dotenv->load();
}
echo 'Loading settings...'.PHP_EOL; SecretHandler::startAndLoop('secret.madeline', $settings);
$settings = \json_decode(\getenv('MTPROTO_SETTINGS'), true) ?: [];
$MadelineProto = new \danog\MadelineProto\API('secret.madeline', $settings);
// Reduce boilerplate with new wrapper method
$MadelineProto->startAndLoop(SecretHandler::class);

View File

@ -40,6 +40,22 @@ abstract class EventHandler extends InternalDoc
public function __construct($API) // BC public function __construct($API) // BC
{ {
} }
/**
* Start MadelineProto and the event handler (enables async).
*
* Also initializes error reporting, catching and reporting all errors surfacing from the event loop.
*
* @param string $session Session name
* @param SettingsAbstract $settings Settings
*
* @return void
*/
final public static function startAndLoop(string $session, SettingsAbstract $settings): void
{
$API = new API($session, $settings);
$API->startAndLoop(static::class);
}
/** /**
* Internal constructor. * Internal constructor.
* *

View File

@ -175,7 +175,7 @@ class Server extends SignalLoop
return self::$shutdownDeferred->promise(); return self::$shutdownDeferred->promise();
} }
/** /**
* Shutdown * Shutdown.
* *
* @return void * @return void
*/ */

View File

@ -10,13 +10,6 @@ use danog\MadelineProto\SettingsAbstract;
*/ */
class Ipc extends SettingsAbstract class Ipc extends SettingsAbstract
{ {
/**
* Whether to force full deserialization of instance, without using the IPC server/client.
*
* WARNING: this will cause slow startup if enabled.
*/
protected bool $slow = false;
public function __construct() public function __construct()
{ {
Magic::start(true); Magic::start(true);
@ -24,7 +17,6 @@ class Ipc extends SettingsAbstract
public function mergeArray(array $settings): void public function mergeArray(array $settings): void
{ {
$this->setSlow($settings['ipc']['slow'] ?? $this->getSlow());
} }
/** /**
@ -36,20 +28,4 @@ class Ipc extends SettingsAbstract
{ {
return Magic::$isIpcWorker; return Magic::$isIpcWorker;
} }
/**
* Whether to force full deserialization of instance, without using the IPC server/client.
*
* WARNING: this will cause slow startup if enabled.
*
* @param bool $slow WARNING: this will cause slow startup if enabled.
*
* @return self
*/
public function setSlow(bool $slow): self
{
$this->slow = $slow;
return $this;
}
} }

View File

@ -19,14 +19,6 @@ class RPC extends SettingsAbstract
*/ */
protected int $floodTimeout = 10*60; protected int $floodTimeout = 10*60;
/**
* Maximum number of messages to be stored in the incoming queue.
*/
protected int $limitIncoming = 100;
/**
* Maximum number of messages to be stored in the outgoing queue.
*/
protected int $limitOutgoing = 100;
/** /**
* Maximum number of message IDs to consider when using call queues. * Maximum number of message IDs to consider when using call queues.
*/ */
@ -45,12 +37,6 @@ class RPC extends SettingsAbstract
if (isset($settings['flood_timeout']['wait_if_lt'])) { if (isset($settings['flood_timeout']['wait_if_lt'])) {
$this->setFloodTimeout($settings['flood_timeout']['wait_if_lt']); $this->setFloodTimeout($settings['flood_timeout']['wait_if_lt']);
} }
if (isset($settings['msg_array_limit']['incoming'])) {
$this->setLimitIncoming($settings['msg_array_limit']['incoming']);
}
if (isset($settings['msg_array_limit']['outgoing'])) {
$this->setLimitOutgoing($settings['msg_array_limit']['outgoing']);
}
if (isset($settings['msg_array_limit']['call_queue'])) { if (isset($settings['msg_array_limit']['call_queue'])) {
$this->setLimitCallQueue($settings['msg_array_limit']['call_queue']); $this->setLimitCallQueue($settings['msg_array_limit']['call_queue']);
} }
@ -107,54 +93,6 @@ class RPC extends SettingsAbstract
return $this; return $this;
} }
/**
* Get maximum number of messages to be stored in the incoming queue.
*
* @return int
*/
public function getLimitIncoming(): int
{
return $this->limitIncoming;
}
/**
* Set maximum number of messages to be stored in the incoming queue.
*
* @param int $limitIncoming Maximum number of messages to be stored in the incoming queue
*
* @return self
*/
public function setLimitIncoming(int $limitIncoming): self
{
$this->limitIncoming = $limitIncoming;
return $this;
}
/**
* Get maximum number of messages to be stored in the outgoing queue.
*
* @return int
*/
public function getLimitOutgoing(): int
{
return $this->limitOutgoing;
}
/**
* Set maximum number of messages to be stored in the outgoing queue.
*
* @param int $limitOutgoing Maximum number of messages to be stored in the outgoing queue
*
* @return self
*/
public function setLimitOutgoing(int $limitOutgoing): self
{
$this->limitOutgoing = $limitOutgoing;
return $this;
}
/** /**
* Get maximum number of messages to consider when using call queues. * Get maximum number of messages to consider when using call queues.
* *

View File

@ -53,7 +53,10 @@ abstract class SettingsAbstract
|| $other->{$name} !== $this->{$name} // Is equal, but current value is not the default one || $other->{$name} !== $this->{$name} // Is equal, but current value is not the default one
) )
) )
&& $other->{$name} !== $this->{$name} && (
!isset($this->{$name})
|| $other->{$name} !== $this->{$name}
)
) { ) {
$this->{"set$uc"}($other->{$name}); $this->{"set$uc"}($other->{$name});
$this->changed = true; $this->changed = true;

View File

@ -1,6 +1,8 @@
<?php <?php
use danog\MadelineProto\Logger; use danog\MadelineProto\Logger;
use danog\MadelineProto\Settings\Logger as SettingsLogger;
use danog\MadelineProto\Settings\TLSchema;
use danog\MadelineProto\TL\TL; use danog\MadelineProto\TL\TL;
/* /*
@ -15,9 +17,7 @@ If not, see <http://www.gnu.org/licenses/>.
*/ */
require 'vendor/autoload.php'; require 'vendor/autoload.php';
$param = 1; $logger = new Logger(new SettingsLogger);
\danog\MadelineProto\Logger::constructor($param);
$logger = \danog\MadelineProto\Logger::$default;
\set_error_handler(['\danog\MadelineProto\Exception', 'ExceptionErrorHandler']); \set_error_handler(['\danog\MadelineProto\Exception', 'ExceptionErrorHandler']);
@ -34,17 +34,18 @@ if ($argc !== 3) {
function getTL($layer) function getTL($layer)
{ {
$layer = __DIR__."/../schemas/TL_telegram_v$layer.tl"; $layer = __DIR__."/../schemas/TL_telegram_v$layer.tl";
$layer = new class($layer) { $layer = new class($layer) extends TL {
use TL;
public function __construct($layer) public function __construct($layer)
{ {
$this->logger = Logger::$default; $API = new class {
$this->construct_TL(['telegram' => $layer]); };
$API->logger = Logger::$default;
parent::__construct($API);
$this->init((new TLSchema)->setAPISchema($layer));
} }
}; };
return ['methods' => $layer->methods, 'constructors' => $layer->constructors]; return ['methods' => $layer->getMethods(), 'constructors' => $layer->getConstructors()];
} }
function getUrl($constructor, $type) function getUrl($constructor, $type)
{ {
@ -75,7 +76,6 @@ foreach (['methods', 'constructors'] as $type) {
$res .= "\n\nChanged ".\ucfirst($type)."\n"; $res .= "\n\nChanged ".\ucfirst($type)."\n";
foreach ($new[$type]->by_id as $constructor) { foreach ($new[$type]->by_id as $constructor) {
$name = $constructor[$key]; $name = $constructor[$key];
$constructor['id'] = $new[$type]->$finder($name)['id'];
if ($old[$type]->$finder($name)) { if ($old[$type]->$finder($name)) {
$new_args = $constructor['params']; $new_args = $constructor['params'];
$old_args = $old[$type]->$finder($name)['params']; $old_args = $old[$type]->$finder($name)['params'];
@ -112,4 +112,13 @@ foreach (['methods', 'constructors'] as $type) {
} }
} }
echo $res;
$bot = new \danog\MadelineProto\API('layer.madeline');
$bot->start();
foreach (\explode("\n\n", $res) as $chunk) {
if (!$chunk) {
continue;
}
$bot->messages->sendMessage(['peer' => 'danogentili', 'message' => $chunk, 'parse_mode' => 'markdown']);
}

View File

@ -4,7 +4,7 @@ if (\defined('MADELINE_PHP')) {
throw new \Exception('Please do not include madeline.php twice!'); throw new \Exception('Please do not include madeline.php twice!');
} }
if (!defined('MADELINE_ALLOW_COMPOSER') && \class_exists(\Composer\Autoload\ClassLoader::class)) { if (!\defined('MADELINE_ALLOW_COMPOSER') && \class_exists(\Composer\Autoload\ClassLoader::class)) {
throw new \Exception('Composer autoloader detected: madeline.php is incompatible with Composer, please require MadelineProto using composer.'); throw new \Exception('Composer autoloader detected: madeline.php is incompatible with Composer, please require MadelineProto using composer.');
} }