1
0
mirror of https://github.com/danog/MadelineProto.git synced 2025-01-22 15:31:12 +01:00
This commit is contained in:
Daniil Gentili 2020-11-25 19:36:52 +01:00
parent 5b1f0d866e
commit f56555537a
Signed by: danog
GPG Key ID: 8C1BE3B34B230CA7
9 changed files with 254 additions and 71 deletions

View File

@ -60,36 +60,23 @@ class MyEventHandler extends EventHandler
{
return [self::ADMIN];
}
/**
* Handle updates from supergroups and channels.
*
* @param array $update Update
*
* @return void
*/
public function onUpdateNewChannelMessage(array $update): \Generator
{
return $this->onUpdateNewMessage($update);
public function onStart() {
}
/**
* Handle updates from users.
*
* @param array $update Update
*
* @return \Generator
* @return void
*/
public function onUpdateNewMessage(array $update): \Generator
public function onUpdateNewMessage(array $update)
{
if ($update['message']['_'] === 'messageEmpty' || $update['message']['out'] ?? false) {
return;
}
$res = \json_encode($update, JSON_PRETTY_PRINT);
yield $this->messages->sendMessage(['peer' => $update, 'message' => "<code>$res</code>", 'reply_to_msg_id' => isset($update['message']['id']) ? $update['message']['id'] : null, 'parse_mode' => 'HTML']);
if (isset($update['message']['media']) && $update['message']['media']['_'] !== 'messageMediaGame') {
yield $this->messages->sendMedia(['peer' => $update, 'message' => $update['message']['message'], 'media' => $update]);
}
$this->logger($update);
}
public function onAny(array $update)
{
$this->logger($update);
}
}
$settings = new Settings;
@ -100,8 +87,85 @@ $settings->getLogger()->setLevel(Logger::LEVEL_ULTRA_VERBOSE);
// $settings->setDb((new Postgres)->setDatabase('MadelineProto')->setUsername('daniil')->setPassword('pony'));
// $settings->setDb((new Mysql)->setDatabase('MadelineProto')->setUsername('daniil')->setPassword('pony'));
$MadelineProto = new API('bot.madeline', $settings);
$MadelineProto = new API('aaa.madeline', $settings);
var_dump($MadelineProto->messages->sendVote(['peer' => -1001049295266, 'msg_id' => 272778]));
/*
$a = $MadelineProto->channels->getMessages([
'channel' => 'pony2jkanflk',
'id' => [6],
'offset_id' => 4200,
'offset_date' => 0,
'add_offset' => 0,
'max_id' => 0,
'min_id' => 0,
'limit' => 100
])['messages'][0];
var_dump($MadelineProto->messages->sendVote(['peer' => 'pony2jkanflk', 'msg_id' => 6, 'options' => ['0']]));
readline();
*/
//$MadelineProto->photos->uploadProfilePhoto(['video' => '../../Video/o.mp4', 'file' => 'tests/faust.jpg', 'video_start_ts' => 1]);
/*var_dumP($MadelineProto->users->getFullUser(['id' => 'me']));
var_dumP($MadelineProto->downloadToDir($MadelineProto->getPropicInfo('me'), '/tmp'));
readline();*/
//var_dump($MadelineProto->channels->getChannels(['id' => ['https://t.me/joinchat/Bgrajz6K-aJS2Dc5HJ7dsA']]));
//var_dump($MadelineProto->messages->sendMessage(['peer' => 'danogentili', 'message' => 'lmao', 'schedule_date' => time() + 11]));
/*//var_duMP($MadelineProto->channels->getMessages(['peer' => -1001218943867, 'msg_id' => 4368]));
$id = 272211;
$id = 272319;
var_dump($MadelineProto->messages->search(['peer' => -1001049295266, 'min_date' => 0, 'max_date' => 0, 'offset_id' => 0, 'limit' => 100, 'max_id' => 0, 'min_id' => 0, 'add_offset' => 0, 'top_msg_id' => 268793]));
readline();
$s = $MadelineProto->channels->getMessages(['channel' => -1001049295266, 'id' => [$id]])['messages'][0]['media']['photo'];
var_dump($s);
readline();
$s = (string) $s[0]['bytes'];
function uploadSvgPathDecode($encoded) {
$path = 'M';
$len = strlen($encoded);
for ($i = 0; $i < $len; $i++) {
$num = ord($encoded[$i]);
if ($num >= 128 + 64) {
$path .= substr('AACAAAAHAAALMAAAQASTAVAAAZaacaaaahaaalmaaaqastava.az0123456789-,', $num - 128 - 64, 1);
} else {
if ($num >= 128) {
$path .= ',';
} else if ($num >= 64) {
$path .= '-';
}
var_dump($num & 63);
$path .= $num & 63;
}
}
$path .= 'z';
return $path;
}
var_dump(uploadSvgPathDecode($s));
//var_dump($MadelineProto->stats->getBroadcastStats(['channel' => 'pony2jkanflk']));
readline();
//var_dump($MadelineProto->getFullInfo('davtur19'));
//->getMessagePublicForwards(['channel' => 'ponatqjoa', 'msg_id' => 2, 'offset_rate' => 0, 'offset_id' => 0, 'limit' => 0]));
die;*/
// Reduce boilerplate with new wrapper method.
// Also initializes error reporting, catching and reporting all errors surfacing from the event loop.
$MadelineProto->startAndLoop(MyEventHandler::class);

@ -1 +1 @@
Subproject commit 8fd40f0a4170769465e4943e4a5da37bd58f7e88
Subproject commit d0b2b612cbece1fd3dc971634326f7470dc0099b

View File

@ -576,8 +576,11 @@ class MTProto extends AsyncConstruct implements TLCallback
$this->rsa_keys[$key->fp] = $key;
}
// (re)-initialize TL
$callbacks = [$this, $this->referenceDatabase];
if (!($this->authorization['user']['bot'] ?? false)) {
$callbacks = [$this];
if ($this->settings->getDb()->getEnableFileReferenceDb()) {
$callbacks []= $this->referenceDatabase;
}
if (!($this->authorization['user']['bot'] ?? false) && $this->settings->getDb()->getEnableMinDb()) {
$callbacks[] = $this->minDatabase;
}
$this->TL->init($this->settings->getSchema(), $callbacks);

View File

@ -24,6 +24,7 @@ use danog\MadelineProto\Db\DbArray;
use danog\MadelineProto\Db\DbPropertiesTrait;
use danog\MadelineProto\Exception;
use danog\MadelineProto\MTProto;
use danog\MadelineProto\MTProto\OutgoingMessage;
use danog\MadelineProto\TL\TLCallback;
/**
@ -292,7 +293,7 @@ class ReferenceDatabase implements TLCallback
$this->API->logger->logger("Adding origin context {$originContext} for {$type}!", \danog\MadelineProto\Logger::ULTRA_VERBOSE);
$this->cacheContexts[] = $originContext;
}
public function addOriginMethod(array $data, array $res): \Generator
public function addOriginMethod(OutgoingMessage $data, array $res): \Generator
{
$key = \count($this->cacheContexts) - 1;
if ($key === -1) {
@ -300,14 +301,15 @@ class ReferenceDatabase implements TLCallback
}
$originType = \array_pop($this->cacheContexts);
if (!isset($this->cache[$key])) {
$this->API->logger->logger("Removing origin context {$originType} for {$data['_']}, nothing in the reference cache!", \danog\MadelineProto\Logger::ULTRA_VERBOSE);
$this->API->logger->logger("Removing origin context {$originType} for {$constructor}, nothing in the reference cache!", \danog\MadelineProto\Logger::ULTRA_VERBOSE);
return;
}
$cache = $this->cache[$key];
unset($this->cache[$key]);
$origin = [];
$body = $data['body'];
switch ($data['_']) {
$constructor = $data->getConstructor();
$body = $data->getBodyOrEmpty();
switch ($body ?? '') {
case 'photos.updateProfilePhoto':
$origin['max_id'] = $res['photo_id'] ?? 0;
$origin['offset'] = -1;
@ -350,18 +352,18 @@ class ReferenceDatabase implements TLCallback
}
}
}
$this->API->logger->logger("Added origin {$originType} ({$data['_']}) to {$count} references", \danog\MadelineProto\Logger::ULTRA_VERBOSE);
$this->API->logger->logger("Added origin {$originType} ($constructor) to {$count} references", \danog\MadelineProto\Logger::ULTRA_VERBOSE);
return;
case 'messages.getStickers':
$origin['emoticon'] = $body['emoticon'];
break;
default:
throw new \danog\MadelineProto\Exception("Unknown origin type provided: {$data['_']}");
throw new \danog\MadelineProto\Exception("Unknown origin type provided: {$constructor}");
}
foreach ($cache as $location => $reference) {
yield from $this->storeReference($location, $reference, $originType, $origin);
}
$this->API->logger->logger("Added origin {$originType} ({$data['_']}) to ".\count($cache).' references', \danog\MadelineProto\Logger::ULTRA_VERBOSE);
$this->API->logger->logger("Added origin {$originType} ({$constructor}) to ".\count($cache).' references', \danog\MadelineProto\Logger::ULTRA_VERBOSE);
}
public function storeReference(string $location, string $reference, int $originType, array $origin): \Generator
{

View File

@ -299,13 +299,15 @@ class Magic
self::$bigint = PHP_INT_SIZE < 8;
try {
self::$ipv6 = (bool) \strlen(@\file_get_contents('http://ipv6.google.com/', false, \stream_context_create(['http' => ['timeout' => 1]]))) > 0;
} catch (\Throwable $e) {}
} catch (\Throwable $e) {
}
try {
\preg_match('/const V = (\\d+);/', @\file_get_contents('https://raw.githubusercontent.com/danog/MadelineProto/master/src/danog/MadelineProto/MTProto.php'), $matches);
if (isset($matches[1]) && \danog\MadelineProto\MTProto::V < (int) $matches[1]) {
throw new \danog\MadelineProto\Exception(\hex2bin(\danog\MadelineProto\Lang::$current_lang['v_error']), 0, null, 'MadelineProto', 1);
}
} catch (\Throwable $e) {}
} catch (\Throwable $e) {
}
if (\class_exists('\\danog\\MadelineProto\\VoIP')) {
if (!\defined('\\danog\\MadelineProto\\VoIP::PHP_LIBTGVOIP_VERSION') || !\in_array(\danog\MadelineProto\VoIP::PHP_LIBTGVOIP_VERSION, ['1.5.0'])) {
throw new \danog\MadelineProto\Exception(\hex2bin(\danog\MadelineProto\Lang::$current_lang['v_tgerror']), 0, null, 'MadelineProto', 1);

View File

@ -9,4 +9,144 @@ use danog\MadelineProto\SettingsAbstract;
*/
abstract class DatabaseAbstract extends SettingsAbstract
{
/**
* Whether to enable the file reference database. If disabled, will break file downloads.
*/
private bool $enableFileReferenceDb = true;
/**
* Whether to enable the min database. If disabled, will break sendMessage (and other methods) in certain conditions.
*/
private bool $enableMinDb = true;
/**
* Whether to enable the username database. If disabled, will break sendMessage (and other methods) with usernames.
*/
private bool $enableUsernameDb = true;
/**
* Whether to enable the full peer info database. If disabled, will break getFullInfo.
*/
private bool $enableFullPeerDb = true;
/**
* Whether to enable the peer info database. If disabled, will break getInfo.
*/
private bool $enablePeerInfoDb = true;
/**
* Get whether to enable the file reference database. If disabled, will break file downloads.
*
* @return bool
*/
public function getEnableFileReferenceDb(): bool
{
return $this->enableFileReferenceDb;
}
/**
* Set whether to enable the file reference database. If disabled, will break file downloads.
*
* @param bool $enableFileReferenceDb Whether to enable the file reference database. If disabled, will break file downloads.
*
* @return self
*/
public function setEnableFileReferenceDb(bool $enableFileReferenceDb): self
{
$this->enableFileReferenceDb = $enableFileReferenceDb;
return $this;
}
/**
* Get whether to enable the min database. If disabled, will break sendMessage (and other methods) in certain conditions.
*
* @return bool
*/
public function getEnableMinDb(): bool
{
return $this->enableMinDb;
}
/**
* Set whether to enable the min database. If disabled, will break sendMessage (and other methods) in certain conditions.
*
* @param bool $enableMinDb Whether to enable the min database. If disabled, will break sendMessage (and other methods) in certain conditions.
*
* @return self
*/
public function setEnableMinDb(bool $enableMinDb): self
{
$this->enableMinDb = $enableMinDb;
return $this;
}
/**
* Get whether to enable the username database. If disabled, will break sendMessage (and other methods) with usernames.
*
* @return bool
*/
public function getEnableUsernameDb(): bool
{
return $this->enableUsernameDb;
}
/**
* Set whether to enable the username database. If disabled, will break sendMessage (and other methods) with usernames.
*
* @param bool $enableUsernameDb Whether to enable the username database. If disabled, will break sendMessage (and other methods) with usernames.
*
* @return self
*/
public function setEnableUsernameDb(bool $enableUsernameDb): self
{
$this->enableUsernameDb = $enableUsernameDb;
return $this;
}
/**
* Get whether to enable the full peer info database. If disabled, will break getFullInfo.
*
* @return bool
*/
public function getEnableFullPeerDb(): bool
{
return $this->enableFullPeerDb;
}
/**
* Set whether to enable the full peer info database. If disabled, will break getFullInfo.
*
* @param bool $enableFullPeerDb Whether to enable the full peer info database. If disabled, will break getFullInfo.
*
* @return self
*/
public function setEnableFullPeerDb(bool $enableFullPeerDb): self
{
$this->enableFullPeerDb = $enableFullPeerDb;
return $this;
}
/**
* Get whether to enable the peer info database. If disabled, will break getInfo.
*
* @return bool
*/
public function getEnablePeerInfoDb(): bool
{
return $this->enablePeerInfoDb;
}
/**
* Set whether to enable the peer info database. If disabled, will break getInfo.
*
* @param bool $enablePeerInfoDb Whether to enable the peer info database. If disabled, will break getInfo.
*
* @return self
*/
public function setEnablePeerInfoDb(bool $enablePeerInfoDb): self
{
$this->enablePeerInfoDb = $enablePeerInfoDb;
return $this;
}
}

View File

@ -12,7 +12,7 @@ class TLSchema extends SettingsAbstract
/**
* TL layer version.
*/
protected int $layer = 120;
protected int $layer = 121;
/**
* MTProto schema path.
*/
@ -20,7 +20,7 @@ class TLSchema extends SettingsAbstract
/**
* API schema path.
*/
protected string $APISchema = __DIR__.'/../TL_telegram_v120.tl';
protected string $APISchema = __DIR__.'/../TL_telegram_v121.tl';
/**
* Secret schema path.
*/
@ -57,7 +57,7 @@ class TLSchema extends SettingsAbstract
public function __wakeup()
{
if (!\file_exists($this->APISchema) // Scheme was upgraded
|| $this->APISchema !== __DIR__.'/../TL_telegram_v120.tl' // Session path has changed
|| $this->APISchema !== __DIR__.'/../TL_telegram_v121.tl' // Session path has changed
) {
$new = new self;
$this->setAPISchema($new->getAPISchema());

View File

@ -1,33 +1,3 @@
///////////////////////////////
/////////////////// Layer cons
///////////////////////////////
//invokeAfterMsg#cb9f372d msg_id:long query:!X = X;
//invokeAfterMsgs#3dc4b4f0 msg_ids:Vector<long> query:!X = X;
//invokeWithLayer1#53835315 query:!X = X;
//invokeWithLayer2#289dd1f6 query:!X = X;
//invokeWithLayer3#b7475268 query:!X = X;
//invokeWithLayer4#dea0d430 query:!X = X;
//invokeWithLayer5#417a57ae query:!X = X;
//invokeWithLayer6#3a64d54d query:!X = X;
//invokeWithLayer7#a5be56d3 query:!X = X;
//invokeWithLayer8#e9abd9fd query:!X = X;
//invokeWithLayer9#76715a63 query:!X = X;
//invokeWithLayer10#39620c41 query:!X = X;
//invokeWithLayer11#a6b88fdf query:!X = X;
//invokeWithLayer12#dda60d3c query:!X = X;
//invokeWithLayer13#427c8ea2 query:!X = X;
//invokeWithLayer14#2b9b08fa query:!X = X;
//invokeWithLayer15#b4418b64 query:!X = X;
//invokeWithLayer16#cf5f0987 query:!X = X;
//invokeWithLayer17#50858a19 query:!X = X;
//invokeWithLayer18#1c900537 query:!X = X;
//invokeWithLayer#da9b0d0d layer:int query:!X = X; // after 18 layer
///////////////////////////////
///////// Main application API
///////////////////////////////
boolFalse#bc799737 = Bool;
boolTrue#997275b5 = Bool;
@ -194,6 +164,7 @@ photoSize#77bfb61b type:string location:FileLocation w:int h:int size:int = Phot
photoCachedSize#e9a734fa type:string location:FileLocation w:int h:int bytes:bytes = PhotoSize;
photoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;
photoSizeProgressive#5aa86a51 type:string location:FileLocation w:int h:int sizes:Vector<int> = PhotoSize;
photoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;
geoPointEmpty#1117dd5f = GeoPoint;
geoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;
@ -902,6 +873,7 @@ account.webAuthorizations#ed56c9fc authorizations:Vector<WebAuthorization> users
inputMessageID#a676a322 id:int = InputMessage;
inputMessageReplyTo#bad88395 id:int = InputMessage;
inputMessagePinned#86872538 = InputMessage;
inputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;
inputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;
inputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;
@ -1546,5 +1518,3 @@ stats.loadAsyncGraph#621d5fa0 flags:# token:string x:flags.0?long = StatsGraph;
stats.getMegagroupStats#dcdf8607 flags:# dark:flags.0?true channel:InputChannel = stats.MegagroupStats;
stats.getMessagePublicForwards#5630281b channel:InputChannel msg_id:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;
stats.getMessageStats#b6e0a3f5 flags:# dark:flags.0?true channel:InputChannel msg_id:int = stats.MessageStats;
// LAYER 120

View File

@ -233,8 +233,10 @@ class VoIP
$this->sockets['v6 '.$endpoint['id']] = new Endpoint('['.$endpoint['ipv6'].']', $endpoint['port'], $endpoint['peer_tag'], true, $this);
$this->sockets['v4 '.$endpoint['id']] = new Endpoint($endpoint['ip'], $endpoint['port'], $endpoint['peer_tag'], true, $this);
}
foreach ($this->sockets as $socket) {
yield from $socket->connect();
foreach ($this->sockets as $k => $socket) {
try {
yield from $socket->connect();
} catch (\Throwable $e) { Logger::log($e); unset($this->sockets[$k]); }
}
$this->init_all();
Tools::callFork((function () use ($socket) {