From d45d2d887e57b8ba3a96e0381725e9632c8d9f60 Mon Sep 17 00:00:00 2001 From: marcosramirezaranda Date: Fri, 16 Mar 2018 11:10:22 -0300 Subject: [PATCH] add HTTP Proxy Support (#335) * Add support for HTTP Proxy * fix small typo * forgot git add ... * reverts to use numeric protocol in HTTPProxy::__construct --- src/HTTPProxy.php | 191 +++++++++++++++++ src/Socket.php | 17 +- src/danog/MadelineProto/Connection.php | 17 +- src/danog/MadelineProto/Proxy.php | 4 + tests/testing-proxy.php | 272 +++++++++++++++++++++++++ 5 files changed, 496 insertions(+), 5 deletions(-) create mode 100644 src/HTTPProxy.php create mode 100644 tests/testing-proxy.php diff --git a/src/HTTPProxy.php b/src/HTTPProxy.php new file mode 100644 index 00000000..36f0c891 --- /dev/null +++ b/src/HTTPProxy.php @@ -0,0 +1,191 @@ + 0, 'usec' => 0]; + private $domain; + private $type; + private $options = []; + private $use_connect = false; + private $use_ssl = false; + + public function __construct($domain, $type, $protocol) + { + $this->domain = $domain; + $this->type = $type; + $this->protocol = $protocol === PHP_INT_MAX ? 'tls' : 'tcp'; + + if ($protocol === PHP_INT_MAX) { /* https */ + $this->use_connect = $this->use_ssl = true; + } elseif ($protocol !== PHP_INT_MAX - 1) { /* http */ + $this->use_connect = true; + } + } + + public function __destruct() + { + if ($this->sock !== null) { + fclose($this->sock); + $this->sock = NULL; + } + } + + public function accept() + { + throw new \danog\MadelineProto\Exception('Not supported'); + } + + public function bind($address, $port = 0) + { + throw new \danog\MadelineProto\Exception('Not supported'); + } + + public function close() + { + fclose($this->sock); + $this->sock = null; + } + + public function connect($address, $port = 0) + { + $errno = 0; + $errstr = ''; + + if (isset($this->options['host']) && isset($this->options['port'])) { + $this->sock = @fsockopen($this->options['host'], $this->options['port'], $errno, $errstr, $this->timeout['sec'] + ($this->timeout['usec'] / 1000000)); + } else { + $this->sock = @fsockopen($address, $port, $errno, $errstr, $this->timeout['sec'] + ($this->timeout['usec'] / 1000000)); + } + stream_set_timeout($this->sock, $this->timeout['sec'], $this->timeout['usec']); + + if (isset($this->options['host']) && isset($this->options['port']) && + true === $this->use_connect) { + if ($this->domain === AF_INET6 && strpos($address, ':') !== false) { + $address = '[' . $address . ']'; + } + fwrite($this->sock, "CONNECT " . $address . ":" . $port . " HTTP/1.1\r\n" . + "Accept: */*\r\n" . + "Host: " . $address . ":" . $port . "\r\n" . + $this->getProxyAuthHeader() . + "connection: keep-Alive\r\n" . + "\r\n"); + + $response = ''; + $status = false; + while ($line = @fgets($this->sock)) { + $status = $status || (strpos($line, 'HTTP') !== false); + if ($status) { + $response .= $line; + if (!chop($line)) + break; + } + } + if (substr($response, 0, 13) !== "HTTP/1.1 200 ") + return false; + } + + if (true === $this->use_ssl) { + $modes = array( + STREAM_CRYPTO_METHOD_TLS_CLIENT, + STREAM_CRYPTO_METHOD_SSLv3_CLIENT, + STREAM_CRYPTO_METHOD_SSLv23_CLIENT, + STREAM_CRYPTO_METHOD_SSLv2_CLIENT + ); + + $contextOptions = array( + 'ssl' => array( + 'verify_peer' => false, + 'verify_peer_name' => false, + ), + ); + stream_context_set_option($this->sock, $contextOptions); + + $success = false; + foreach ($modes as $mode) + { + $success = stream_socket_enable_crypto($this->sock, true, $mode); + if ($success) + return true; + } + return false; + } + return true; + } + + public function getOption($level, $name) + { + throw new \danog\MadelineProto\Exception('Not supported'); + } + + public function getPeerName($port = true) + { + throw new \danog\MadelineProto\Exception('Not supported'); + } + + public function getSockName($port = true) + { + throw new \danog\MadelineProto\Exception('Not supported'); + } + + public function listen($backlog = 0) + { + throw new \danog\MadelineProto\Exception('Not supported'); + } + + public function read($length, $flags = 0) + { + return stream_get_contents($this->sock, $length); + } + + public function select(array &$read, array &$write, array &$except, $tv_sec, $tv_usec = 0) + { + return stream_select($read, $write, $except, $tv_sec, $tv_usec); + } + + public function send($data, $length, $flags) + { + throw new \danog\MadelineProto\Exception('Not supported'); + } + + public function setBlocking($blocking) + { + return stream_set_blocking($this->sock, $blocking); + } + + public function setOption($level, $name, $value) + { + if (in_array($name, [\SO_RCVTIMEO, \SO_SNDTIMEO])) { + $this->timeout = ['sec' => (int) $value, 'usec' => (int) (($value - (int) $value) * 1000000)]; + + return true; + } + throw new \danog\MadelineProto\Exception('Not supported'); + } + + public function write($buffer, $length = -1) + { + return $length === -1 ? fwrite($this->sock, $buffer) : fwrite($this->sock, $buffer, $length); + } + + private function getProxyAuthHeader() + { + if (!isset($this->options['user']) || !isset($this->options['pass'])) { + return ''; + } + return "Proxy-Authorization: Basic " . base64_encode($this->options['user'] . ":" . $this->options['pass']) . "\r\n"; + } + + public function getProxyHeaders() + { + return ($this->use_connect === true) ? '' : $this->getProxyAuthHeader(); + } + + public function setExtra(array $extra = []) + { + $this->options = $extra; + } + +} diff --git a/src/Socket.php b/src/Socket.php index cd2c4d05..6e27bdd9 100644 --- a/src/Socket.php +++ b/src/Socket.php @@ -22,7 +22,7 @@ If not, see . { $this->domain = $domain; $this->type = $type; - $this->protocol = $protocol === PHP_INT_MAX ? 'tls' : getprotobynumber($protocol); + $this->protocol = $protocol === PHP_INT_MAX ? 'tls' : ($protocol === PHP_INT_MAX - 1 ? 'tcp' : getprotobynumber($protocol)); } public function __destruct() @@ -116,6 +116,16 @@ If not, see . { throw new \danog\MadelineProto\Exception('Not supported'); } + + public function setExtra(array $extra = []) + { + + } + + public function getProxyHeaders() + { + return ''; + } } if (!extension_loaded('pthreads')) { @@ -225,6 +235,11 @@ if (!extension_loaded('pthreads')) { return $port ? ['host' => $address, 'port' => $port] : ['host' => $address]; } + + public function getProxyHeaders() + { + return ''; + } } class Socket extends SocketBase { diff --git a/src/danog/MadelineProto/Connection.php b/src/danog/MadelineProto/Connection.php index 2557f690..b88ac11c 100644 --- a/src/danog/MadelineProto/Connection.php +++ b/src/danog/MadelineProto/Connection.php @@ -151,9 +151,18 @@ class Connection if (strpos($this->protocol, 'https') === 0 && $proxy === '\\Socket') { $proxy = '\\FSocket'; } - $this->sock = new $proxy($ipv6 ? \AF_INET6 : \AF_INET, \SOCK_STREAM, strpos($this->protocol, 'https') === 0 ? PHP_INT_MAX : getprotobyname('tcp')); - if ($has_proxy && $this->extra !== []) { - $this->sock->setExtra($this->extra); + $this->sock = new $proxy($ipv6 ? \AF_INET6 : \AF_INET, \SOCK_STREAM, strpos($this->protocol, 'https') === 0 ? PHP_INT_MAX : ($has_proxy ? PHP_INT_MAX - 1 : getprotobyname('tcp'))); + if ($has_proxy ) { + if ($this->extra !== []) { + $this->sock->setExtra($this->extra); + } + if ($this->protocol === 'http') { + $this->parsed['path'] = $this->parsed['scheme'] . '://' . $this->parsed['host'] . + $this->parsed['path']; + $port = 80; + } elseif ($this->protocol === 'https') { + $port = 443; + } } $this->sock->setOption(\SOL_SOCKET, \SO_RCVTIMEO, $timeout); $this->sock->setOption(\SOL_SOCKET, \SO_SNDTIMEO, $timeout); @@ -352,7 +361,7 @@ class Connection break; case 'http': case 'https': - $this->write('POST '.$this->parsed['path']." HTTP/1.1\r\nHost: ".$this->parsed['host'].':'.$this->port."\r\nContent-Type: application/x-www-form-urlencoded\r\nConnection: keep-alive\r\nKeep-Alive: timeout=100000, max=10000000\r\nContent-Length: ".strlen($message)."\r\n\r\n".$message); + $this->write('POST '.$this->parsed['path']." HTTP/1.1\r\nHost: ".$this->parsed['host'].':'.$this->port."\r\n" . $this->sock->getProxyHeaders() . "Content-Type: application/x-www-form-urlencoded\r\nConnection: keep-alive\r\nKeep-Alive: timeout=100000, max=10000000\r\nContent-Length: ".strlen($message)."\r\n\r\n".$message); break; case 'udp': throw new Exception(\danog\MadelineProto\Lang::$current_lang['protocol_not_implemented']); diff --git a/src/danog/MadelineProto/Proxy.php b/src/danog/MadelineProto/Proxy.php index 706a6e87..a3ab66a6 100644 --- a/src/danog/MadelineProto/Proxy.php +++ b/src/danog/MadelineProto/Proxy.php @@ -44,4 +44,8 @@ interface Proxy public function getPeerName($port = true); public function getSockName($port = true); + + public function getProxyHeaders(); + + public function setExtra(array $extra = []); } diff --git a/tests/testing-proxy.php b/tests/testing-proxy.php new file mode 100644 index 00000000..e2daaab0 --- /dev/null +++ b/tests/testing-proxy.php @@ -0,0 +1,272 @@ +#!/usr/bin/env php +. +*/ +set_include_path(get_include_path().':'.realpath(dirname(__FILE__).'/../').':'.realpath(dirname(__FILE__).'/../MadelineProto/')); +chdir(dirname(__FILE__).'/../'); +if (!file_exists('vendor/autoload.php')) { + die('You did not run composer update'); +} +require_once 'vendor/autoload.php'; +//include 'SocksProxy.php'; +if (!function_exists('readline')) { + function readline($prompt = null) + { + if ($prompt) { + echo $prompt; + } + $fp = fopen('php://stdin', 'r'); + $line = rtrim(fgets($fp, 1024)); + + return $line; + } +} + +if (file_exists('web_data.php')) { + require_once 'web_data.php'; +} + + +/** + * Set default context proxy for file_get_contents + * + */ + +$default_opts = array( + 'http' => array( + 'proxy' => "tcp://host:port", + 'request_fulluri' => true, + /* Only if your proxy requires authentication */ + 'header' => array( + "Proxy-Authorization: Basic " . base64_encode("proxy_user:proxy_pass") + ) + ), + 'https' => array( + 'proxy' => "tcp://host:port", + 'request_fulluri' => true, + /* Only if your proxy requires authentication */ + 'header' => array( + "Proxy-Authorization: Basic " . base64_encode("proxy_user:proxy_pass") + ) + ), + 'tls' => array( + 'proxy' => "tcp://host:port", + 'request_fulluri' => true, + /* Only if your proxy requires authentication */ + 'header' => array( + "Proxy-Authorization: Basic " . base64_encode("proxy_user:proxy_pass") + ) + ) +); + +$default = stream_context_set_default($default_opts); + + +echo 'Deserializing MadelineProto from testing.madeline...'.PHP_EOL; +$MadelineProto = false; + +try { + $MadelineProto = new \danog\MadelineProto\API('testing.madeline'); +} catch (\danog\MadelineProto\Exception $e) { + \danog\MadelineProto\Logger::log($e->getMessage()); +} +if (file_exists('.env')) { + echo 'Loading .env...'.PHP_EOL; + $dotenv = new Dotenv\Dotenv(getcwd()); + $dotenv->load(); +} +if (getenv('TEST_SECRET_CHAT') == '') { + die('TEST_SECRET_CHAT is not defined in .env, please define it.'.PHP_EOL); +} +echo 'Loading settings...'.PHP_EOL; +\danog\MadelineProto\Logger::log(getenv('MTPROTO_SETTINGS')); +$settings = json_decode(getenv('MTPROTO_SETTINGS'), true) ?: []; +$settings['connection_settings']['all']['proxy'] = '\HTTPProxy'; +$settings['connection_settings']['all']['proxy_extra'] = ['host' => '127.0.0.1', 'port' => 3218 /* 'user' => 'proxy_user', 'pass'=> 'proxy_pass' */]; + +\danog\MadelineProto\Logger::log($settings); +if ($MadelineProto === false) { + echo 'Loading MadelineProto...'.PHP_EOL; + $MadelineProto = new \danog\MadelineProto\API($settings); + if (getenv('TRAVIS_COMMIT') == '') { + $sentCode = $MadelineProto->phone_login(readline('Enter your phone number: ')); + \danog\MadelineProto\Logger::log($sentCode, \danog\MadelineProto\Logger::NOTICE); + echo 'Enter the code you received: '; + $code = fgets(STDIN, (isset($sentCode['type']['length']) ? $sentCode['type']['length'] : 5) + 1); + $authorization = $MadelineProto->complete_phone_login($code); + \danog\MadelineProto\Logger::log($authorization, \danog\MadelineProto\Logger::NOTICE); + if ($authorization['_'] === 'account.noPassword') { + throw new \danog\MadelineProto\Exception('2FA is enabled but no password is set!'); + } + if ($authorization['_'] === 'account.password') { + \danog\MadelineProto\Logger::log('2FA is enabled', \danog\MadelineProto\Logger::NOTICE); + $authorization = $MadelineProto->complete_2fa_login(readline('Please enter your password (hint '.$authorization['hint'].'): ')); + } + if ($authorization['_'] === 'account.needSignup') { + \danog\MadelineProto\Logger::log('Registering new user', \danog\MadelineProto\Logger::NOTICE); + $authorization = $MadelineProto->complete_signup(readline('Please enter your first name: '), readline('Please enter your last name (can be empty): ')); + } + } else { + $MadelineProto->bot_login(getenv('BOT_TOKEN')); + } +} +$MadelineProto->session = 'testing.madeline'; +\danog\MadelineProto\Logger::log('hey', \danog\MadelineProto\Logger::ULTRA_VERBOSE); +\danog\MadelineProto\Logger::log('hey', \danog\MadelineProto\Logger::VERBOSE); +\danog\MadelineProto\Logger::log('hey', \danog\MadelineProto\Logger::NOTICE); +\danog\MadelineProto\Logger::log('hey', \danog\MadelineProto\Logger::WARNING); +\danog\MadelineProto\Logger::log('hey', \danog\MadelineProto\Logger::ERROR); +\danog\MadelineProto\Logger::log('hey', \danog\MadelineProto\Logger::FATAL_ERROR); +//$MadelineProto->phone->createGroupCall(['channel' => -1001333587884 + +$message = (getenv('TRAVIS_COMMIT') == '') ? 'I iz works always (io laborare sembre) (yo lavorar siempre) (mi labori ĉiam) (я всегда работать) (Ik werkuh altijd) (Ngimbonga ngaso sonke isikhathi ukusebenza)' : ('Travis ci tests in progress: commit '.getenv('TRAVIS_COMMIT').', job '.getenv('TRAVIS_JOB_NUMBER').', PHP version: '.getenv('TRAVIS_PHP_VERSION')); + +echo 'Serializing MadelineProto to testing.madeline...'.PHP_EOL; echo 'Wrote '.\danog\MadelineProto\Serialization::serialize('testing.madeline', $MadelineProto).' bytes'.PHP_EOL; +/* +$m = new \danog\MadelineProto\API($settings); +$m->import_authorization($MadelineProto->export_authorization()); +*/ +if (stripos(readline('Do you want to make a call? (y/n): '), 'y') !== false) { + $controller = $MadelineProto->request_call(getenv('TEST_SECRET_CHAT'))->play('input.raw')->then('input.raw')->playOnHold(['input.raw'])->setOutputFile('output.raw'); + while ($controller->getCallState() < \danog\MadelineProto\VoIP::CALL_STATE_READY) { + $MadelineProto->get_updates(); + } + //$MadelineProto->messages->sendMessage(['peer' => $controller->getOtherID(), 'message' => 'Emojis: '.implode('', $controller->getVisualization())]); + \danog\MadelineProto\Logger::log($controller->configuration); + while ($controller->getCallState() < \danog\MadelineProto\VoIP::CALL_STATE_ENDED) { + $MadelineProto->get_updates(); + } +} +if (stripos(readline('Do you want to handle incoming calls? (y/n): '), 'y') !== false) { + $howmany = readline('How many calls would you like me to handle? '); + $offset = 0; + while ($howmany > 0) { + $updates = $MadelineProto->get_updates(['offset' => $offset, 'limit' => 50, 'timeout' => 0]); // Just like in the bot API, you can specify an offset, a limit and a timeout + foreach ($updates as $update) { + \danog\MadelineProto\Logger::log($update); + $offset = $update['update_id'] + 1; // Just like in the bot API, the offset must be set to the last update_id + switch ($update['update']['_']) { + case 'updatePhoneCall': + if (is_object($update['update']['phone_call']) && $update['update']['phone_call']->getCallState() === \danog\MadelineProto\VoIP::CALL_STATE_INCOMING) { + $update['update']['phone_call']->accept()->play('input.raw')->then('input.raw')->playOnHold(['input.raw'])->setOutputFile('output.raw'); + $howmany--; + } + } + } + //echo 'Wrote '.\danog\MadelineProto\Serialization::serialize('testing.madeline', $MadelineProto).' bytes'.PHP_EOL; + } +} +if (stripos(readline('Do you want to make the secret chat tests? (y/n): '), 'y') !== false) { + $secret = $MadelineProto->API->request_secret_chat(getenv('TEST_SECRET_CHAT')); + echo 'Waiting for '.getenv('TEST_SECRET_CHAT').' (secret chat id '.$secret.') to accept the secret chat...'.PHP_EOL; + while ($MadelineProto->secret_chat_status($secret) !== 2) { + $MadelineProto->get_updates(); + } + $offset = 0; + + $InputEncryptedChat = $MadelineProto->get_secret_chat($secret)['InputEncryptedChat']; + $sentMessage = $MadelineProto->messages->sendEncrypted(['peer' => $InputEncryptedChat, 'message' => ['_' => 'decryptedMessage', 'media' => ['_' => 'decryptedMessageMediaEmpty'], 'ttl' => 10, 'message' => $message, 'entities' => [['_' => 'messageEntityCode', 'offset' => 0, 'length' => mb_strlen($message)]]]]); // should work with all layers + \danog\MadelineProto\Logger::log($sentMessage, \danog\MadelineProto\Logger::NOTICE); + /* + while (true) { + $updates = $MadelineProto->get_updates(['offset' => $offset, 'limit' => 50, 'timeout' => 0]); // Just like in the bot API, you can specify an offset, a limit and a timeout + //\danog\MadelineProto\Logger::log($updates); + foreach ($updates as $update) { + $offset = $update['update_id'] + 1; // Just like in the bot API, the offset must be set to the last update_id + switch ($update['update']['_']) { + case 'updateNewEncryptedMessage': + \danog\MadelineProto\Logger::log($update); + } + echo 'Wrote '.\danog\MadelineProto\Serialization::serialize('testing.madeline', $MadelineProto).' bytes'.PHP_EOL; + } + }*/ + + $secret_media = []; + + // Photo uploaded as document, secret chat + $inputEncryptedFile = $MadelineProto->upload_encrypted('tests/faust.jpg', 'fausticorn.jpg'); // This gets an inputFile object with file name magic + $secret_media['document_photo'] = ['peer' => $secret, 'file' => $inputEncryptedFile, 'message' => ['_' => 'decryptedMessage', 'ttl' => 0, 'message' => '', 'media' => ['_' => 'decryptedMessageMediaDocument', 'thumb' => file_get_contents('tests/faust.preview.jpg'), 'thumb_w' => 90, 'thumb_h' => 90, 'mime_type' => mime_content_type('tests/faust.jpg'), 'caption' => 'This file was uploaded using MadelineProto', 'key' => $inputEncryptedFile['key'], 'iv' => $inputEncryptedFile['iv'], 'file_name' => 'faust.jpg', 'size' => filesize('tests/faust.jpg'), 'attributes' => [['_' => 'documentAttributeImageSize', 'w' => 1280, 'h' => 914]]]]]; + + // Photo, secret chat + $secret_media['photo'] = ['peer' => $secret, 'file' => $inputEncryptedFile, 'message' => ['_' => 'decryptedMessage', 'ttl' => 0, 'message' => '', 'media' => ['_' => 'decryptedMessageMediaPhoto', 'thumb' => file_get_contents('tests/faust.preview.jpg'), 'thumb_w' => 90, 'thumb_h' => 90, 'caption' => 'This file was uploaded using MadelineProto', 'key' => $inputEncryptedFile['key'], 'iv' => $inputEncryptedFile['iv'], 'size' => filesize('tests/faust.jpg'), 'w' => 1280, 'h' => 914]]]; + + // GIF, secret chat + $inputEncryptedFile = $MadelineProto->upload_encrypted('tests/pony.mp4'); + $secret_media['gif'] = ['peer' => $secret, 'file' => $inputEncryptedFile, 'message' => ['_' => 'decryptedMessage', 'ttl' => 0, 'message' => '', 'media' => ['_' => 'decryptedMessageMediaDocument', 'thumb' => file_get_contents('tests/pony.preview.jpg'), 'thumb_w' => 90, 'thumb_h' => 90, 'mime_type' => mime_content_type('tests/pony.mp4'), 'caption' => 'test', 'key' => $inputEncryptedFile['key'], 'iv' => $inputEncryptedFile['iv'], 'file_name' => 'pony.mp4', 'size' => filesize('tests/faust.jpg'), 'attributes' => [['_' => 'documentAttributeAnimated']]]]]; + + // Sticker, secret chat + $inputEncryptedFile = $MadelineProto->upload_encrypted('tests/lel.webp'); + $secret_media['sticker'] = ['peer' => $secret, 'file' => $inputEncryptedFile, 'message' => ['_' => 'decryptedMessage', 'ttl' => 0, 'message' => '', 'media' => ['_' => 'decryptedMessageMediaDocument', 'thumb' => file_get_contents('tests/lel.preview.jpg'), 'thumb_w' => 90, 'thumb_h' => 90, 'mime_type' => mime_content_type('tests/lel.webp'), 'caption' => 'test', 'key' => $inputEncryptedFile['key'], 'iv' => $inputEncryptedFile['iv'], 'file_name' => 'lel.webp', 'size' => filesize('tests/lel.webp'), 'attributes' => [['_' => 'documentAttributeSticker', 'alt' => 'LEL', 'stickerset' => ['_' => 'inputStickerSetEmpty']]]]]]; + + // Document, secrey chat + $time = time(); + $inputEncryptedFile = $MadelineProto->upload_encrypted('tests/60', 'magic'); // This gets an inputFile object with file name magic + \danog\MadelineProto\Logger::log(time() - $time); + $secret_media['document'] = ['peer' => $secret, 'file' => $inputEncryptedFile, 'message' => ['_' => 'decryptedMessage', 'ttl' => 0, 'message' => '', 'media' => ['_' => 'decryptedMessageMediaDocument', 'thumb' => file_get_contents('tests/faust.preview.jpg'), 'thumb_w' => 90, 'thumb_h' => 90, 'mime_type' => 'magic/magic', 'caption' => 'test', 'key' => $inputEncryptedFile['key'], 'iv' => $inputEncryptedFile['iv'], 'file_name' => 'magic.magic', 'size' => filesize('tests/60'), 'attributes' => [['_' => 'documentAttributeFilename', 'file_name' => 'fairy']]]]]; + + // Video, secret chat + $inputEncryptedFile = $MadelineProto->upload_encrypted('tests/swing.mp4'); + $secret_media['video'] = ['peer' => $secret, 'file' => $inputEncryptedFile, 'message' => ['_' => 'decryptedMessage', 'ttl' => 0, 'message' => '', 'media' => ['_' => 'decryptedMessageMediaDocument', 'thumb' => file_get_contents('tests/swing.preview.jpg'), 'thumb_w' => 90, 'thumb_h' => 90, 'mime_type' => mime_content_type('tests/swing.mp4'), 'caption' => 'test', 'key' => $inputEncryptedFile['key'], 'iv' => $inputEncryptedFile['iv'], 'file_name' => 'swing.mp4', 'size' => filesize('tests/swing.mp4'), 'attributes' => [['_' => 'documentAttributeVideo', 'duration' => 5, 'w' => 1280, 'h' => 720]]]]]; + + // audio, secret chat + $inputEncryptedFile = $MadelineProto->upload_encrypted('tests/mosconi.mp3'); + $secret_media['audio'] = ['peer' => $secret, 'file' => $inputEncryptedFile, 'message' => ['_' => 'decryptedMessage', 'ttl' => 0, 'message' => '', 'media' => ['_' => 'decryptedMessageMediaDocument', 'thumb' => file_get_contents('tests/faust.preview.jpg'), 'thumb_w' => 90, 'thumb_h' => 90, 'mime_type' => mime_content_type('tests/mosconi.mp3'), 'caption' => 'test', 'key' => $inputEncryptedFile['key'], 'iv' => $inputEncryptedFile['iv'], 'file_name' => 'mosconi.mp3', 'size' => filesize('tests/mosconi.mp3'), 'attributes' => [['_' => 'documentAttributeAudio', 'voice' => false, 'duration' => 1, 'title' => 'AH NON LO SO IO', 'performer' => 'IL DIO GERMANO MOSCONI']]]]]; + + $secret_media['voice'] = ['peer' => $secret, 'file' => $inputEncryptedFile, 'message' => ['_' => 'decryptedMessage', 'ttl' => 0, 'message' => '', 'media' => ['_' => 'decryptedMessageMediaDocument', 'thumb' => file_get_contents('tests/faust.preview.jpg'), 'thumb_w' => 90, 'thumb_h' => 90, 'mime_type' => mime_content_type('tests/mosconi.mp3'), 'caption' => 'test', 'key' => $inputEncryptedFile['key'], 'iv' => $inputEncryptedFile['iv'], 'file_name' => 'mosconi.mp3', 'size' => filesize('tests/mosconi.mp3'), 'attributes' => [['_' => 'documentAttributeAudio', 'voice' => true, 'duration' => 1, 'title' => 'AH NON LO SO IO', 'performer' => 'IL DIO GERMANO MOSCONI']]]]]; + + foreach ($secret_media as $type => $smessage) { + $type = $MadelineProto->messages->sendEncryptedFile($smessage); + } +} + +$mention = $MadelineProto->get_info(getenv('TEST_USERNAME')); // Returns an array with all of the constructors that can be extracted from a username or an id +$mention = $mention['user_id']; // Selects only the numeric user id +$media = []; + +// Sticker +$inputFile = $MadelineProto->upload('tests/lel.webp'); +\danog\MadelineProto\Logger::log($inputFile); +$media['sticker'] = ['_' => 'inputMediaUploadedDocument', 'file' => $inputFile, 'mime_type' => mime_content_type('tests/lel.webp'), 'caption' => 'test', 'attributes' => [['_' => 'documentAttributeSticker', 'alt' => 'LEL', 'stickerset' => ['_' => 'inputStickerSetEmpty']]]]; + +// Video +$inputFile = $MadelineProto->upload('tests/swing.mp4'); +$media['video'] = ['_' => 'inputMediaUploadedDocument', 'file' => $inputFile, 'mime_type' => mime_content_type('tests/swing.mp4'), 'caption' => 'test', 'attributes' => [['_' => 'documentAttributeVideo', 'duration' => 5, 'w' => 1280, 'h' => 720]]]; + +// audio +$inputFile = $MadelineProto->upload('tests/mosconi.mp3'); +$media['audio'] = ['_' => 'inputMediaUploadedDocument', 'file' => $inputFile, 'mime_type' => mime_content_type('tests/mosconi.mp3'), 'caption' => 'test', 'attributes' => [['_' => 'documentAttributeAudio', 'voice' => false, 'duration' => 1, 'title' => 'AH NON LO SO IO', 'performer' => 'IL DIO GERMANO MOSCONI']]]; + +// voice +$media['voice'] = ['_' => 'inputMediaUploadedDocument', 'file' => $inputFile, 'mime_type' => mime_content_type('tests/mosconi.mp3'), 'caption' => 'test', 'attributes' => [['_' => 'documentAttributeAudio', 'voice' => true, 'duration' => 1, 'title' => 'AH NON LO SO IO', 'performer' => 'IL DIO GERMANO MOSCONI']]]; + +// Document +$time = time(); +$inputFile = $MadelineProto->upload('tests/60', 'magic'); // This gets an inputFile object with file name magic +\danog\MadelineProto\Logger::log(time() - $time); +$media['document'] = ['_' => 'inputMediaUploadedDocument', 'file' => $inputFile, 'mime_type' => 'magic/magic', 'caption' => 'This file was uploaded using MadelineProto', 'attributes' => [['_' => 'documentAttributeFilename', 'file_name' => 'magic.magic']]]; + +$message = 'yay'; +$mention = $MadelineProto->get_info(getenv('TEST_USERNAME')); // Returns an array with all of the constructors that can be extracted from a username or an id +$mention = $mention['user_id']; // Selects only the numeric user id + +foreach (json_decode(getenv('TEST_DESTINATION_GROUPS'), true) as $peer) { + $sentMessage = $MadelineProto->messages->sendMessage(['peer' => $peer, 'message' => $message, 'entities' => [['_' => 'inputMessageEntityMentionName', 'offset' => 0, 'length' => mb_strlen($message), 'user_id' => $mention]]]); + \danog\MadelineProto\Logger::log($sentMessage, \danog\MadelineProto\Logger::NOTICE); + + foreach ($media as $type => $inputMedia) { + $type = $MadelineProto->messages->sendMedia(['peer' => $peer, 'media' => $inputMedia, 'message' => '['.$message.'](mention:'.$mention.')', 'parse_mode' => 'markdown']); + } +} + +foreach (json_decode(getenv('TEST_DESTINATION_GROUPS'), true) as $peer) { + $sentMessage = $MadelineProto->messages->sendMessage(['peer' => $peer, 'message' => $message, 'entities' => [['_' => 'inputMessageEntityMentionName', 'offset' => 0, 'length' => mb_strlen($message), 'user_id' => $mention]]]); + \danog\MadelineProto\Logger::log($sentMessage, \danog\MadelineProto\Logger::NOTICE); +}