Continue refactoring

This commit is contained in:
Daniil Gentili 2019-11-01 12:45:15 +01:00
parent c16e174db2
commit 883d09eccf
Signed by: danog
GPG Key ID: 8C1BE3B34B230CA7
10 changed files with 67 additions and 66 deletions

View File

@ -22,7 +22,7 @@
/* /*
* Various ways to load MadelineProto * Various ways to load MadelineProto
*/ */
if (\file_exists(__DIR__.'/vendor/autoload.php')) { if (\file_exists('vendor/autoload.php')) {
include 'vendor/autoload.php'; include 'vendor/autoload.php';
} else { } else {
if (!\file_exists('madeline.php')) { if (!\file_exists('madeline.php')) {

View File

@ -227,7 +227,7 @@ class DataCenter
if ($reconnectAll || $changedSettings || !$this->CookieJar) { if ($reconnectAll || $changedSettings || !$this->CookieJar) {
$this->CookieJar = $jar ?? new ArrayCookieJar; $this->CookieJar = $jar ?? new ArrayCookieJar;
$this->HTTPClient = new DefaultClient($this->CookieJar, new HttpSocketPool(new ProxySocketPool([$this, 'rawConnectAsync']))); $this->HTTPClient = new DefaultClient($this->CookieJar, new HttpSocketPool(new ProxySocketPool([$this, 'rawConnect'])));
$DoHHTTPClient = new DefaultClient( $DoHHTTPClient = new DefaultClient(
$this->CookieJar, $this->CookieJar,
@ -433,7 +433,7 @@ class DataCenter
} }
// The following hack looks like the only way to detect connection refused errors with PHP's stream sockets. // The following hack looks like the only way to detect connection refused errors with PHP's stream sockets.
if (\stream_socket_getName($socket, true) === false) { if (\stream_socket_get_name($socket, true) === false) {
\fclose($socket); \fclose($socket);
throw new ConnectException(\sprintf( throw new ConnectException(\sprintf(
"Connection to %s refused%s", "Connection to %s refused%s",

View File

@ -241,7 +241,7 @@ class ReadLoop extends SignalLoop
return -404; return -404;
} }
$deserialized = $API->deserialize($message_data, ['type' => '', 'connection' => $connection]); $deserialized = $API->getTL()->deserialize($message_data, ['type' => '', 'connection' => $connection]);
$API->referenceDatabase->reset(); $API->referenceDatabase->reset();
$connection->incoming_messages[$message_id]['content'] = $deserialized; $connection->incoming_messages[$message_id]['content'] = $deserialized;

View File

@ -94,7 +94,7 @@ class WriteLoop extends ResumableSignalLoop
$connection->writing(true); $connection->writing(true);
try { try {
$please_wait = yield $this->{$shared->hasTempAuthKey() ? 'encryptedWriteLoopAsync' : 'unencryptedWriteLoopAsync'}(); $please_wait = yield $this->{$shared->hasTempAuthKey() ? 'encryptedWriteLoop' : 'unencryptedWriteLoop'}();
} catch (StreamException $e) { } catch (StreamException $e) {
if ($connection->shouldReconnect()) { if ($connection->shouldReconnect()) {
return; return;

View File

@ -189,7 +189,7 @@ trait CallHandler
$aargs, $aargs,
[ [
'_' => $method, '_' => $method,
'type' => $this->API->methods->findByMethod($method)['type'], 'type' => $this->API->getTL()->getMethods()->findByMethod($method)['type'],
'contentRelated' => $this->contentRelated($method), 'contentRelated' => $this->contentRelated($method),
'promise' => $deferred, 'promise' => $deferred,
'method' => true, 'method' => true,

View File

@ -27,6 +27,7 @@ use danog\MadelineProto\MTProto;
*/ */
trait ResponseHandler trait ResponseHandler
{ {
public function sendMsgsStateInfo($req_msg_id, $msg_ids) public function sendMsgsStateInfo($req_msg_id, $msg_ids)
{ {
$this->logger->logger('Sending state info for '.\count($msg_ids).' message IDs'); $this->logger->logger('Sending state info for '.\count($msg_ids).' message IDs');
@ -258,7 +259,7 @@ trait ResponseHandler
$this->checkInSeqNo($current_msg_id); $this->checkInSeqNo($current_msg_id);
$this->ackIncomingMessageId($current_msg_id); $this->ackIncomingMessageId($current_msg_id);
// Acknowledge that I received the server's response // Acknowledge that I received the server's response
$response_type = $this->API->constructors->findByPredicate($this->incoming_messages[$current_msg_id]['content']['_'])['type']; $response_type = $this->API->getTL()->getConstructors()->findByPredicate($this->incoming_messages[$current_msg_id]['content']['_'])['type'];
switch ($response_type) { switch ($response_type) {
case 'Updates': case 'Updates':
@ -579,7 +580,7 @@ trait ResponseHandler
return; return;
} }
$botAPI = isset($request['botAPI']) && $request['botAPI']; $botAPI = isset($request['botAPI']) && $request['botAPI'];
if (isset($response['_']) && !$this->isCdn() && $this->API->constructors->findByPredicate($response['_'])['type'] === 'Updates') { if (isset($response['_']) && !$this->isCdn() && $this->API->getTL()->getConstructors()->findByPredicate($response['_'])['type'] === 'Updates') {
$response['request'] = $request; $response['request'] = $request;
\danog\MadelineProto\Tools::callForkDefer($this->API->handleUpdates($response)); \danog\MadelineProto\Tools::callForkDefer($this->API->handleUpdates($response));
} }

View File

@ -378,7 +378,7 @@ trait Files
public function genAllFile($media) public function genAllFile($media)
{ {
$res = [$this->constructors->findByPredicate($media['_'])['type'] => $media]; $res = [$this->TL->getConstructors()->findByPredicate($media['_'])['type'] => $media];
switch ($media['_']) { switch ($media['_']) {
case 'messageMediaPoll': case 'messageMediaPoll':
$res['Poll'] = $media['poll']; $res['Poll'] = $media['poll'];

View File

@ -543,7 +543,7 @@ trait PeerHandler
public function genAll($constructor, $folder_id = null) public function genAll($constructor, $folder_id = null)
{ {
$res = [$this->constructors->findByPredicate($constructor['_'])['type'] => $constructor]; $res = [$this->TL->getConstructors()->findByPredicate($constructor['_'])['type'] => $constructor];
switch ($constructor['_']) { switch ($constructor['_']) {
case 'user': case 'user':
if ($constructor['self']) { if ($constructor['self']) {

View File

@ -31,7 +31,7 @@ class TL
* *
* @var integer * @var integer
*/ */
private $encrypted_layer = -1; private $secretLayer = -1;
/** /**
* Constructors. * Constructors.
* *
@ -49,25 +49,25 @@ class TL
* *
* @var TLConstructors * @var TLConstructors
*/ */
private $td_constructors; private $tdConstructors;
/** /**
* TD Methods. * TD Methods.
* *
* @var TLMethods * @var TLMethods
*/ */
private $td_methods; private $tdMethods;
/** /**
* Descriptions. * Descriptions.
* *
* @var array * @var array
*/ */
private $td_descriptions; private $tdDescriptions;
/** /**
* TL callbacks. * TL callbacks.
* *
* @var array * @var array
*/ */
private $tl_callbacks = []; private $callbacks = [];
/** /**
* API instance. * API instance.
* *
@ -91,7 +91,7 @@ class TL
*/ */
public function getSecretLayer(): int public function getSecretLayer(): int
{ {
return $this->encrypted_layer; return $this->secretLayer;
} }
/** /**
@ -103,7 +103,7 @@ class TL
*/ */
public function getConstructors(bool $td = false): TLConstructors public function getConstructors(bool $td = false): TLConstructors
{ {
return $td ? $this->td_constructors : $this->constructors; return $td ? $this->tdConstructors : $this->constructors;
} }
/** /**
@ -115,7 +115,7 @@ class TL
*/ */
public function getMethods(bool $td = false): TLMethods public function getMethods(bool $td = false): TLMethods
{ {
return $td ? $this->td_methods : $this->methods; return $td ? $this->tdMethods : $this->methods;
} }
/** /**
@ -125,7 +125,7 @@ class TL
*/ */
public function getDescriptions(): array public function getDescriptions(): array
{ {
return $this->td_descriptions; return $this->tdDescriptions;
} }
/** /**
@ -142,9 +142,9 @@ class TL
$this->updateCallbacks($objects); $this->updateCallbacks($objects);
$this->constructors = new TLConstructors(); $this->constructors = new TLConstructors();
$this->methods = new TLMethods(); $this->methods = new TLMethods();
$this->td_constructors = new TLConstructors(); $this->tdConstructors = new TLConstructors();
$this->td_methods = new TLMethods(); $this->tdMethods = new TLMethods();
$this->td_descriptions = ['types' => [], 'constructors' => [], 'methods' => []]; $this->tdDescriptions = ['types' => [], 'constructors' => [], 'methods' => []];
foreach ($files as $scheme_type => $file) { foreach ($files as $scheme_type => $file) {
$this->API->logger->logger(\sprintf(\danog\MadelineProto\Lang::$current_lang['file_parsing'], \basename($file)), \danog\MadelineProto\Logger::VERBOSE); $this->API->logger->logger(\sprintf(\danog\MadelineProto\Lang::$current_lang['file_parsing'], \basename($file)), \danog\MadelineProto\Logger::VERBOSE);
$filec = \file_get_contents(\danog\MadelineProto\Absolute::absolute($file)); $filec = \file_get_contents(\danog\MadelineProto\Absolute::absolute($file));
@ -174,7 +174,7 @@ class TL
} }
if ($elem[0] === 'description') { if ($elem[0] === 'description') {
if (!\is_null($class)) { if (!\is_null($class)) {
$this->td_descriptions['types'][$class] = $elem[1]; $this->tdDescriptions['types'][$class] = $elem[1];
$class = null; $class = null;
} else { } else {
$e = $elem[1]; $e = $elem[1];
@ -224,7 +224,7 @@ class TL
$id = $nid; $id = $nid;
} }
if (!\is_null($e)) { if (!\is_null($e)) {
$this->td_descriptions[$type][$name] = ['description' => $e, 'params' => $dparams]; $this->tdDescriptions[$type][$name] = ['description' => $e, 'params' => $dparams];
$e = null; $e = null;
$dparams = []; $dparams = [];
} }
@ -267,7 +267,7 @@ class TL
$this->API->logger->logger(\danog\MadelineProto\Lang::$current_lang['translating_obj'], \danog\MadelineProto\Logger::ULTRA_VERBOSE); $this->API->logger->logger(\danog\MadelineProto\Lang::$current_lang['translating_obj'], \danog\MadelineProto\Logger::ULTRA_VERBOSE);
foreach ($TL_dict['constructors'] as $elem) { foreach ($TL_dict['constructors'] as $elem) {
if ($scheme_type === 'secret') { if ($scheme_type === 'secret') {
$this->encrypted_layer = \max($this->encrypted_layer, $elem['layer']); $this->secretLayer = \max($this->secretLayer, $elem['layer']);
} }
$this->{($scheme_type === 'td' ? 'td_' : '').'constructors'}->add($elem, $scheme_type); $this->{($scheme_type === 'td' ? 'td_' : '').'constructors'}->add($elem, $scheme_type);
} }
@ -275,31 +275,31 @@ class TL
foreach ($TL_dict['methods'] as $elem) { foreach ($TL_dict['methods'] as $elem) {
$this->{($scheme_type === 'td' ? 'td_' : '').'methods'}->add($elem); $this->{($scheme_type === 'td' ? 'td_' : '').'methods'}->add($elem);
if ($scheme_type === 'secret') { if ($scheme_type === 'secret') {
$this->encrypted_layer = \max($this->encrypted_layer, $elem['layer']); $this->secretLayer = \max($this->secretLayer, $elem['layer']);
} }
} }
} }
if (isset($files['td']) && isset($files['telegram'])) { if (isset($files['td']) && isset($files['telegram'])) {
foreach ($this->td_constructors->by_id as $id => $data) { foreach ($this->tdConstructors->by_id as $id => $data) {
$name = $data['predicate']; $name = $data['predicate'];
if ($this->constructors->findById($id) === false) { if ($this->constructors->findById($id) === false) {
unset($this->td_descriptions['constructors'][$name]); unset($this->tdDescriptions['constructors'][$name]);
} else { } else {
if (!\count($this->td_descriptions['constructors'][$name]['params'])) { if (!\count($this->tdDescriptions['constructors'][$name]['params'])) {
continue; continue;
} }
foreach ($this->td_descriptions['constructors'][$name]['params'] as $k => $param) { foreach ($this->tdDescriptions['constructors'][$name]['params'] as $k => $param) {
$this->td_descriptions['constructors'][$name]['params'][$k] = \str_replace('nullable', 'optional', $param); $this->tdDescriptions['constructors'][$name]['params'][$k] = \str_replace('nullable', 'optional', $param);
} }
} }
} }
foreach ($this->td_methods->by_id as $id => $data) { foreach ($this->tdMethods->by_id as $id => $data) {
$name = $data['method']; $name = $data['method'];
if ($this->methods->findById($id) === false) { if ($this->methods->findById($id) === false) {
unset($this->td_descriptions['methods'][$name]); unset($this->tdDescriptions['methods'][$name]);
} else { } else {
foreach ($this->td_descriptions['methods'][$name]['params'] as $k => $param) { foreach ($this->tdDescriptions['methods'][$name]['params'] as $k => $param) {
$this->td_descriptions['constructors'][$name]['params'][$k] = \str_replace('nullable', 'optional', $param); $this->tdDescriptions['constructors'][$name]['params'][$k] = \str_replace('nullable', 'optional', $param);
} }
} }
} }
@ -341,7 +341,7 @@ class TL
*/ */
public function updateCallbacks(array $objects) public function updateCallbacks(array $objects)
{ {
$this->tl_callbacks = []; $this->callbacks = [];
foreach ($objects as $object) { foreach ($objects as $object) {
if (!isset(\class_implements(\get_class($object))[TLCallback::class])) { if (!isset(\class_implements(\get_class($object))[TLCallback::class])) {
throw new Exception('Invalid callback object provided!'); throw new Exception('Invalid callback object provided!');
@ -356,13 +356,13 @@ class TL
]; ];
foreach ($new as $type => $values) { foreach ($new as $type => $values) {
foreach ($values as $match => $callback) { foreach ($values as $match => $callback) {
if (!isset($this->tl_callbacks[$type][$match])) { if (!isset($this->callbacks[$type][$match])) {
$this->tl_callbacks[$type][$match] = []; $this->callbacks[$type][$match] = [];
} }
if (\in_array($type, [TLCallback::TYPE_MISMATCH_CALLBACK, TLCallback::CONSTRUCTOR_SERIALIZE_CALLBACK])) { if (\in_array($type, [TLCallback::TYPE_MISMATCH_CALLBACK, TLCallback::CONSTRUCTOR_SERIALIZE_CALLBACK])) {
$this->tl_callbacks[$type][$match] = $callback; $this->callbacks[$type][$match] = $callback;
} else { } else {
$this->tl_callbacks[$type][$match] = \array_merge($callback, $this->tl_callbacks[$type][$match]); $this->callbacks[$type][$match] = \array_merge($callback, $this->callbacks[$type][$match]);
} }
} }
} }
@ -528,8 +528,8 @@ class TL
if ($type['type'] === 'InputMessage' && !\is_array($object)) { if ($type['type'] === 'InputMessage' && !\is_array($object)) {
$object = ['_' => 'inputMessageID', 'id' => $object]; $object = ['_' => 'inputMessageID', 'id' => $object];
} elseif (isset($this->tl_callbacks[TLCallback::TYPE_MISMATCH_CALLBACK][$type['type']]) && (!\is_array($object) || isset($object['_']) && $this->constructors->findByPredicate($object['_'])['type'] !== $type['type'])) { } elseif (isset($this->callbacks[TLCallback::TYPE_MISMATCH_CALLBACK][$type['type']]) && (!\is_array($object) || isset($object['_']) && $this->constructors->findByPredicate($object['_'])['type'] !== $type['type'])) {
$object = yield $this->tl_callbacks[TLCallback::TYPE_MISMATCH_CALLBACK][$type['type']]($object); $object = yield $this->callbacks[TLCallback::TYPE_MISMATCH_CALLBACK][$type['type']]($object);
if (!isset($object[$type['type']])) { if (!isset($object[$type['type']])) {
throw new \danog\MadelineProto\Exception("Could not convert {$type['type']} object"); throw new \danog\MadelineProto\Exception("Could not convert {$type['type']} object");
} }
@ -543,8 +543,8 @@ class TL
$auto = true; $auto = true;
$object['_'] = $constructorData['predicate']; $object['_'] = $constructorData['predicate'];
} }
if (isset($this->tl_callbacks[TLCallback::CONSTRUCTOR_SERIALIZE_CALLBACK][$object['_']])) { if (isset($this->callbacks[TLCallback::CONSTRUCTOR_SERIALIZE_CALLBACK][$object['_']])) {
$object = yield $this->tl_callbacks[TLCallback::CONSTRUCTOR_SERIALIZE_CALLBACK][$object['_']]($object); $object = yield $this->callbacks[TLCallback::CONSTRUCTOR_SERIALIZE_CALLBACK][$object['_']]($object);
} }
$predicate = $object['_']; $predicate = $object['_'];
@ -973,8 +973,8 @@ class TL
return false; return false;
} }
$x = ['_' => $constructorData['predicate']]; $x = ['_' => $constructorData['predicate']];
if (isset($this->tl_callbacks[TLCallback::CONSTRUCTOR_BEFORE_CALLBACK][$x['_']])) { if (isset($this->callbacks[TLCallback::CONSTRUCTOR_BEFORE_CALLBACK][$x['_']])) {
foreach ($this->tl_callbacks[TLCallback::CONSTRUCTOR_BEFORE_CALLBACK][$x['_']] as $callback) { foreach ($this->callbacks[TLCallback::CONSTRUCTOR_BEFORE_CALLBACK][$x['_']] as $callback) {
$callback($x['_']); $callback($x['_']);
} }
} }
@ -1008,9 +1008,9 @@ class TL
} }
if ($x['_'] === 'rpc_result' && $arg['name'] === 'result') { if ($x['_'] === 'rpc_result' && $arg['name'] === 'result') {
if (isset($type['connection']->outgoing_messages[$x['req_msg_id']]['_']) if (isset($type['connection']->outgoing_messages[$x['req_msg_id']]['_'])
&& isset($this->tl_callbacks[TLCallback::METHOD_BEFORE_CALLBACK][$type['connection']->outgoing_messages[$x['req_msg_id']]['_']]) && isset($this->callbacks[TLCallback::METHOD_BEFORE_CALLBACK][$type['connection']->outgoing_messages[$x['req_msg_id']]['_']])
) { ) {
foreach ($this->tl_callbacks[TLCallback::METHOD_BEFORE_CALLBACK][$type['connection']->outgoing_messages[$x['req_msg_id']]['_']] as $callback) { foreach ($this->callbacks[TLCallback::METHOD_BEFORE_CALLBACK][$type['connection']->outgoing_messages[$x['req_msg_id']]['_']] as $callback) {
$callback($type['connection']->outgoing_messages[$x['req_msg_id']]['_']); $callback($type['connection']->outgoing_messages[$x['req_msg_id']]['_']);
} }
} }
@ -1054,15 +1054,15 @@ class TL
} }
} }
if (isset($this->tl_callbacks[TLCallback::CONSTRUCTOR_CALLBACK][$x['_']])) { if (isset($this->callbacks[TLCallback::CONSTRUCTOR_CALLBACK][$x['_']])) {
foreach ($this->tl_callbacks[TLCallback::CONSTRUCTOR_CALLBACK][$x['_']] as $callback) { foreach ($this->callbacks[TLCallback::CONSTRUCTOR_CALLBACK][$x['_']] as $callback) {
\danog\MadelineProto\Tools::callFork($callback($x)); \danog\MadelineProto\Tools::callFork($callback($x));
} }
} elseif ($x['_'] === 'rpc_result' } elseif ($x['_'] === 'rpc_result'
&& isset($type['connection']->outgoing_messages[$x['req_msg_id']]['_']) && isset($type['connection']->outgoing_messages[$x['req_msg_id']]['_'])
&& isset($this->tl_callbacks[TLCallback::METHOD_CALLBACK][$type['connection']->outgoing_messages[$x['req_msg_id']]['_']]) && isset($this->callbacks[TLCallback::METHOD_CALLBACK][$type['connection']->outgoing_messages[$x['req_msg_id']]['_']])
) { ) {
foreach ($this->tl_callbacks[TLCallback::METHOD_CALLBACK][$type['connection']->outgoing_messages[$x['req_msg_id']]['_']] as $callback) { foreach ($this->callbacks[TLCallback::METHOD_CALLBACK][$type['connection']->outgoing_messages[$x['req_msg_id']]['_']] as $callback) {
$callback($type['connection']->outgoing_messages[$x['req_msg_id']], $x['result']); $callback($type['connection']->outgoing_messages[$x['req_msg_id']], $x['result']);
} }
} }

View File

@ -244,11 +244,11 @@ trait Tools
/** /**
* Convert double to binary version. * Convert double to binary version.
* *
* @param double $value Value to convert * @param float $value Value to convert
* *
* @return string * @return string
*/ */
public static function packDouble(double $value): string public static function packDouble(float $value): string
{ {
$res = \pack('d', $value); $res = \pack('d', $value);
if (\strlen($res) !== 8) { if (\strlen($res) !== 8) {
@ -263,9 +263,9 @@ trait Tools
* *
* @param string $value Value to unpack * @param string $value Value to unpack
* *
* @return double * @return float
*/ */
public static function unpackDouble(string $value): double public static function unpackDouble(string $value): float
{ {
if (\strlen($value) !== 8) { if (\strlen($value) !== 8) {
throw new TL\Exception(\danog\MadelineProto\Lang::$current_lang['length_not_8']); throw new TL\Exception(\danog\MadelineProto\Lang::$current_lang['length_not_8']);
@ -419,9 +419,9 @@ trait Tools
* @param ?\Generator|Promise $actual Promise to resolve instead of $promise * @param ?\Generator|Promise $actual Promise to resolve instead of $promise
* @param string $file File * @param string $file File
* *
* @return void * @return Promise
*/ */
public static function callFork($promise, $actual = null, $file = '') public static function callFork($promise, $actual = null, $file = ''): Promise
{ {
if ($actual) { if ($actual) {
$promise = $actual; $promise = $actual;
@ -558,11 +558,11 @@ trait Tools
* *
* @param string $file File to lock * @param string $file File to lock
* @param integer $operation Locking mode * @param integer $operation Locking mode
* @param integer $polling Polling interval * @param float $polling Polling interval
* *
* @return Promise * @return Promise
*/ */
public static function flock(string $file, int $operation, $polling = 0.1): Promise public static function flock(string $file, int $operation, float $polling = 0.1): Promise
{ {
return self::call(self::flockGenerator($file, $operation, $polling)); return self::call(self::flockGenerator($file, $operation, $polling));
} }
@ -571,11 +571,11 @@ trait Tools
* *
* @param string $file File to lock * @param string $file File to lock
* @param integer $operation Locking mode * @param integer $operation Locking mode
* @param integer $polling Polling interval * @param float $polling Polling interval
* *
* @return void * @return \Generator
*/ */
private static function flockGenerator(string $file, int $operation, $polling) private static function flockGenerator(string $file, int $operation, float $polling): \Generator
{ {
if (!yield exists($file)) { if (!yield exists($file)) {
yield \touch($file); yield \touch($file);
@ -626,9 +626,9 @@ trait Tools
* *
* @param string $prompt Prompt * @param string $prompt Prompt
* *
* @return void * @return \Generator
*/ */
private static function readLineGenerator(string $prompt = '') private static function readLineGenerator(string $prompt = ''): \Generator
{ {
$stdin = getStdin(); $stdin = getStdin();
$stdout = getStdout(); $stdout = getStdout();
@ -662,7 +662,7 @@ trait Tools
* *
* @return boolean * @return boolean
*/ */
public static function isArrayOrAlike($var) public static function isArrayOrAlike($var): bool
{ {
return \is_array($var) || return \is_array($var) ||
($var instanceof ArrayAccess && ($var instanceof ArrayAccess &&