mirror of
https://github.com/danog/TelegramApiServer.git
synced 2024-11-30 04:19:13 +01:00
cs-fix
This commit is contained in:
parent
2871122256
commit
0580754d62
@ -37,6 +37,9 @@
|
|||||||
"danog/madelineproto": "dev-v8_fix_cleanup",
|
"danog/madelineproto": "dev-v8_fix_cleanup",
|
||||||
"amphp/dns": "2.x-dev"
|
"amphp/dns": "2.x-dev"
|
||||||
},
|
},
|
||||||
|
"require-dev": {
|
||||||
|
"amphp/php-cs-fixer-config": "^2.0.1"
|
||||||
|
},
|
||||||
"suggest": {
|
"suggest": {
|
||||||
"ext-pcntl": "Install pcintl for propper signal handling and healthcheck (enabled in .env)"
|
"ext-pcntl": "Install pcintl for propper signal handling and healthcheck (enabled in .env)"
|
||||||
},
|
},
|
||||||
@ -57,5 +60,8 @@
|
|||||||
"allow-plugins": {
|
"allow-plugins": {
|
||||||
"symfony/thanks": false
|
"symfony/thanks": false
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"cs-fix": "PHP_CS_FIXER_IGNORE_ENV=1 php -d pcre.jit=0 vendor/bin/php-cs-fixer fix -v"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
2385
composer.lock
generated
2385
composer.lock
generated
File diff suppressed because it is too large
Load Diff
@ -1,7 +1,7 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all updates from MadelineProto EventHandler running inside TelegramApiServer via websocket
|
* Get all updates from MadelineProto EventHandler running inside TelegramApiServer via websocket.
|
||||||
* @see \TelegramApiServer\Controllers\EventsController
|
* @see \TelegramApiServer\Controllers\EventsController
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@ -13,7 +13,6 @@ use function Amp\Websocket\Client\connect;
|
|||||||
|
|
||||||
require 'vendor/autoload.php';
|
require 'vendor/autoload.php';
|
||||||
|
|
||||||
|
|
||||||
$shortopts = 'u::';
|
$shortopts = 'u::';
|
||||||
$longopts = [
|
$longopts = [
|
||||||
'url::',
|
'url::',
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer;
|
namespace TelegramApiServer;
|
||||||
|
|
||||||
@ -12,7 +12,6 @@ use InvalidArgumentException;
|
|||||||
use Psr\Log\LogLevel;
|
use Psr\Log\LogLevel;
|
||||||
use ReflectionProperty;
|
use ReflectionProperty;
|
||||||
use RuntimeException;
|
use RuntimeException;
|
||||||
use TelegramApiServer\EventObservers\EventHandler;
|
|
||||||
use TelegramApiServer\EventObservers\EventObserver;
|
use TelegramApiServer\EventObservers\EventObserver;
|
||||||
|
|
||||||
final class Client
|
final class Client
|
||||||
@ -41,7 +40,7 @@ final class Client
|
|||||||
|
|
||||||
$this->startNotLoggedInSessions();
|
$this->startNotLoggedInSessions();
|
||||||
|
|
||||||
$sessionsCount = count($sessionFiles);
|
$sessionsCount = \count($sessionFiles);
|
||||||
warning(
|
warning(
|
||||||
"\nTelegramApiServer ready."
|
"\nTelegramApiServer ready."
|
||||||
. "\nNumber of sessions: {$sessionsCount}."
|
. "\nNumber of sessions: {$sessionsCount}."
|
||||||
@ -63,7 +62,7 @@ final class Client
|
|||||||
if ($settings) {
|
if ($settings) {
|
||||||
Files::saveSessionSettings($session, $settings);
|
Files::saveSessionSettings($session, $settings);
|
||||||
}
|
}
|
||||||
$settings = array_replace_recursive(
|
$settings = \array_replace_recursive(
|
||||||
(array) Config::getInstance()->get('telegram'),
|
(array) Config::getInstance()->get('telegram'),
|
||||||
Files::getSessionSettings($session),
|
Files::getSessionSettings($session),
|
||||||
);
|
);
|
||||||
@ -92,14 +91,9 @@ final class Client
|
|||||||
$instance->unsetEventHandler();
|
$instance->unsetEventHandler();
|
||||||
}
|
}
|
||||||
unset($instance);
|
unset($instance);
|
||||||
gc_collect_cycles();
|
\gc_collect_cycles();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @param string|null $session
|
|
||||||
*
|
|
||||||
* @return API
|
|
||||||
*/
|
|
||||||
public function getSession(?string $session = null): API
|
public function getSession(?string $session = null): API
|
||||||
{
|
{
|
||||||
if (!$this->instances) {
|
if (!$this->instances) {
|
||||||
@ -109,8 +103,8 @@ final class Client
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!$session) {
|
if (!$session) {
|
||||||
if (count($this->instances) === 1) {
|
if (\count($this->instances) === 1) {
|
||||||
$session = (string)array_key_first($this->instances);
|
$session = (string) \array_key_first($this->instances);
|
||||||
} else {
|
} else {
|
||||||
throw new InvalidArgumentException(
|
throw new InvalidArgumentException(
|
||||||
'Multiple sessions detected. Specify which session to use. See README for examples.'
|
'Multiple sessions detected. Specify which session to use. See README for examples.'
|
||||||
@ -165,9 +159,10 @@ final class Client
|
|||||||
return $wrapper;
|
return $wrapper;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static function getSettingsFromArray(string $session, array $settings, SettingsAbstract $settingsObject = new Settings()): SettingsAbstract {
|
private static function getSettingsFromArray(string $session, array $settings, SettingsAbstract $settingsObject = new Settings()): SettingsAbstract
|
||||||
|
{
|
||||||
foreach ($settings as $key => $value) {
|
foreach ($settings as $key => $value) {
|
||||||
if (is_array($value) && $key !== 'proxies') {
|
if (\is_array($value) && $key !== 'proxies') {
|
||||||
if ($key === 'db' && isset($value['type'])) {
|
if ($key === 'db' && isset($value['type'])) {
|
||||||
$type = match ($value['type']) {
|
$type = match ($value['type']) {
|
||||||
'memory' => new Settings\Database\Memory(),
|
'memory' => new Settings\Database\Memory(),
|
||||||
@ -185,23 +180,22 @@ final class Client
|
|||||||
}
|
}
|
||||||
|
|
||||||
unset($value[$value['type']], $value['type'],);
|
unset($value[$value['type']], $value['type'],);
|
||||||
if (count($value) === 0) {
|
if (\count($value) === 0) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$method = 'get' . ucfirst(str_replace('_', '', ucwords($key, '_')));
|
$method = 'get' . \ucfirst(\str_replace('_', '', \ucwords($key, '_')));
|
||||||
self::getSettingsFromArray($session, $value, $settingsObject->$method());
|
self::getSettingsFromArray($session, $value, $settingsObject->$method());
|
||||||
} else {
|
} else {
|
||||||
if ($key === 'serializer' && is_string($value)) {
|
if ($key === 'serializer' && \is_string($value)) {
|
||||||
$value = SerializerType::from($value);
|
$value = SerializerType::from($value);
|
||||||
}
|
}
|
||||||
$method = 'set' . ucfirst(str_replace('_', '', ucwords($key, '_')));
|
$method = 'set' . \ucfirst(\str_replace('_', '', \ucwords($key, '_')));
|
||||||
$settingsObject->$method($value);
|
$settingsObject->$method($value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return $settingsObject;
|
return $settingsObject;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,7 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
|
||||||
namespace TelegramApiServer;
|
namespace TelegramApiServer;
|
||||||
|
|
||||||
|
|
||||||
final class Config
|
final class Config
|
||||||
{
|
{
|
||||||
private static ?Config $instance = null;
|
private static ?Config $instance = null;
|
||||||
@ -20,7 +18,7 @@ final class Config
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* is not allowed to call from outside to prevent from creating multiple instances,
|
* is not allowed to call from outside to prevent from creating multiple instances,
|
||||||
* to use the singleton, you have to obtain the instance from Singleton::getInstance() instead
|
* to use the singleton, you have to obtain the instance from Singleton::getInstance() instead.
|
||||||
*/
|
*/
|
||||||
private function __construct()
|
private function __construct()
|
||||||
{
|
{
|
||||||
@ -40,11 +38,11 @@ final class Config
|
|||||||
private function findByKey($key)
|
private function findByKey($key)
|
||||||
{
|
{
|
||||||
$key = (string) $key;
|
$key = (string) $key;
|
||||||
$path = explode('.', $key);
|
$path = \explode('.', $key);
|
||||||
|
|
||||||
$value = &$this->config;
|
$value = &$this->config;
|
||||||
foreach ($path as $pathKey) {
|
foreach ($path as $pathKey) {
|
||||||
if (!is_array($value) || !array_key_exists($pathKey, $value)) {
|
if (!\is_array($value) || !\array_key_exists($pathKey, $value)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
$value = &$value[$pathKey];
|
$value = &$value[$pathKey];
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\Controllers;
|
namespace TelegramApiServer\Controllers;
|
||||||
|
|
||||||
@ -18,8 +18,6 @@ use TelegramApiServer\MadelineProtoExtensions\ApiExtensions;
|
|||||||
use TelegramApiServer\MadelineProtoExtensions\SystemApiExtensions;
|
use TelegramApiServer\MadelineProtoExtensions\SystemApiExtensions;
|
||||||
use Throwable;
|
use Throwable;
|
||||||
use UnexpectedValueException;
|
use UnexpectedValueException;
|
||||||
use function Amp\delay;
|
|
||||||
use function mb_strpos;
|
|
||||||
|
|
||||||
abstract class AbstractApiController
|
abstract class AbstractApiController
|
||||||
{
|
{
|
||||||
@ -29,7 +27,6 @@ abstract class AbstractApiController
|
|||||||
protected ?StreamedField $file = null;
|
protected ?StreamedField $file = null;
|
||||||
protected string $extensionClass;
|
protected string $extensionClass;
|
||||||
|
|
||||||
|
|
||||||
public array $page = [
|
public array $page = [
|
||||||
'headers' => self::JSON_HEADER,
|
'headers' => self::JSON_HEADER,
|
||||||
'success' => false,
|
'success' => false,
|
||||||
@ -83,7 +80,7 @@ abstract class AbstractApiController
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Получаем параметры из GET и POST
|
* Получаем параметры из GET и POST.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
private function resolveRequest(): void
|
private function resolveRequest(): void
|
||||||
@ -91,11 +88,11 @@ abstract class AbstractApiController
|
|||||||
$query = $this->request->getUri()->getQuery();
|
$query = $this->request->getUri()->getQuery();
|
||||||
$contentType = (string) $this->request->getHeader('Content-Type');
|
$contentType = (string) $this->request->getHeader('Content-Type');
|
||||||
|
|
||||||
parse_str($query, $get);
|
\parse_str($query, $get);
|
||||||
|
|
||||||
switch (true) {
|
switch (true) {
|
||||||
case $contentType === 'application/x-www-form-urlencoded':
|
case $contentType === 'application/x-www-form-urlencoded':
|
||||||
case mb_strpos($contentType, 'multipart/form-data') !== false:
|
case \mb_strpos($contentType, 'multipart/form-data') !== false:
|
||||||
$form = (new StreamingFormParser())->parseForm($this->request);
|
$form = (new StreamingFormParser())->parseForm($this->request);
|
||||||
$post = [];
|
$post = [];
|
||||||
|
|
||||||
@ -107,27 +104,27 @@ abstract class AbstractApiController
|
|||||||
//We need to break loop without getting file
|
//We need to break loop without getting file
|
||||||
//All other post field will be omitted, hope we dont need them :)
|
//All other post field will be omitted, hope we dont need them :)
|
||||||
break;
|
break;
|
||||||
} else {
|
|
||||||
$post[$field->getName()] = $field->buffer();
|
|
||||||
}
|
}
|
||||||
|
$post[$field->getName()] = $field->buffer();
|
||||||
|
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case $contentType === 'application/json':
|
case $contentType === 'application/json':
|
||||||
$body = $this->request->getBody()->buffer();
|
$body = $this->request->getBody()->buffer();
|
||||||
$post = json_decode($body, 1);
|
$post = \json_decode($body, 1);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
$body = $this->request->getBody()->buffer();
|
$body = $this->request->getBody()->buffer();
|
||||||
parse_str($body, $post);
|
\parse_str($body, $post);
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->parameters = array_merge((array)$post, $get);
|
$this->parameters = \array_merge((array) $post, $get);
|
||||||
$this->parameters = array_values($this->parameters);
|
$this->parameters = \array_values($this->parameters);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Получает посты для формирования ответа
|
* Получает посты для формирования ответа.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
private function generateResponse(): void
|
private function generateResponse(): void
|
||||||
@ -159,16 +156,16 @@ abstract class AbstractApiController
|
|||||||
|
|
||||||
protected function callApiCommon(API $madelineProto)
|
protected function callApiCommon(API $madelineProto)
|
||||||
{
|
{
|
||||||
$pathCount = count($this->api);
|
$pathCount = \count($this->api);
|
||||||
if ($pathCount === 1 && method_exists($this->extensionClass, $this->api[0])) {
|
if ($pathCount === 1 && \method_exists($this->extensionClass, $this->api[0])) {
|
||||||
/** @var ApiExtensions|SystemApiExtensions $madelineProtoExtensions */
|
/** @var ApiExtensions|SystemApiExtensions $madelineProtoExtensions */
|
||||||
$madelineProtoExtensions = new $this->extensionClass($madelineProto, $this->request, $this->file);
|
$madelineProtoExtensions = new $this->extensionClass($madelineProto, $this->request, $this->file);
|
||||||
$result = $madelineProtoExtensions->{$this->api[0]}(...$this->parameters);
|
$result = $madelineProtoExtensions->{$this->api[0]}(...$this->parameters);
|
||||||
} else {
|
} else {
|
||||||
if ($this->api[0] === 'API') {
|
if ($this->api[0] === 'API') {
|
||||||
$madelineProto = Client::getWrapper($madelineProto)->getAPI();
|
$madelineProto = Client::getWrapper($madelineProto)->getAPI();
|
||||||
array_shift($this->api);
|
\array_shift($this->api);
|
||||||
$pathCount = count($this->api);
|
$pathCount = \count($this->api);
|
||||||
}
|
}
|
||||||
//Проверяем нет ли в MadilineProto такого метода.
|
//Проверяем нет ли в MadilineProto такого метода.
|
||||||
switch ($pathCount) {
|
switch ($pathCount) {
|
||||||
@ -190,9 +187,7 @@ abstract class AbstractApiController
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param Throwable $e
|
|
||||||
*
|
*
|
||||||
* @return AbstractApiController
|
|
||||||
* @throws Throwable
|
* @throws Throwable
|
||||||
*/
|
*/
|
||||||
private function setError(Throwable $e): self
|
private function setError(Throwable $e): self
|
||||||
@ -210,9 +205,8 @@ abstract class AbstractApiController
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Кодирует ответ в нужный формат: json
|
* Кодирует ответ в нужный формат: json.
|
||||||
*
|
*
|
||||||
* @return Response|string
|
|
||||||
* @throws JsonException
|
* @throws JsonException
|
||||||
*/
|
*/
|
||||||
private function getResponse(): string|Response
|
private function getResponse(): string|Response
|
||||||
@ -221,7 +215,7 @@ abstract class AbstractApiController
|
|||||||
return $this->page['response'];
|
return $this->page['response'];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!is_array($this->page['response']) && !is_scalar($this->page['response'])) {
|
if (!\is_array($this->page['response']) && !\is_scalar($this->page['response'])) {
|
||||||
$this->page['response'] = null;
|
$this->page['response'] = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -234,7 +228,7 @@ abstract class AbstractApiController
|
|||||||
$data['success'] = true;
|
$data['success'] = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
$result = json_encode(
|
$result = \json_encode(
|
||||||
$data,
|
$data,
|
||||||
JSON_THROW_ON_ERROR |
|
JSON_THROW_ON_ERROR |
|
||||||
JSON_INVALID_UTF8_SUBSTITUTE |
|
JSON_INVALID_UTF8_SUBSTITUTE |
|
||||||
@ -248,11 +242,9 @@ abstract class AbstractApiController
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Устанавливает http код ответа (200, 400, 404 и тд.)
|
* Устанавливает http код ответа (200, 400, 404 и тд.).
|
||||||
*
|
*
|
||||||
* @param int $code
|
|
||||||
*
|
*
|
||||||
* @return AbstractApiController
|
|
||||||
*/
|
*/
|
||||||
private function setPageCode(int $code): self
|
private function setPageCode(int $code): self
|
||||||
{
|
{
|
||||||
|
@ -1,19 +1,10 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\Controllers;
|
namespace TelegramApiServer\Controllers;
|
||||||
|
|
||||||
use Amp\Sync\LocalKeyedMutex;
|
|
||||||
use Amp\Sync\LocalMutex;
|
|
||||||
use Amp\Sync\StaticKeyMutex;
|
|
||||||
use Amp\Sync\SyncException;
|
|
||||||
use Exception;
|
use Exception;
|
||||||
use Revolt\EventLoop;
|
|
||||||
use TelegramApiServer\Client;
|
use TelegramApiServer\Client;
|
||||||
use TelegramApiServer\Config;
|
use TelegramApiServer\Config;
|
||||||
use TelegramApiServer\Logger;
|
|
||||||
use function Amp\async;
|
|
||||||
use function Amp\delay;
|
|
||||||
use function Amp\Future\awaitAll;
|
|
||||||
|
|
||||||
final class ApiController extends AbstractApiController
|
final class ApiController extends AbstractApiController
|
||||||
{
|
{
|
||||||
@ -21,15 +12,14 @@ final class ApiController extends AbstractApiController
|
|||||||
private ?string $session = '';
|
private ?string $session = '';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Получаем параметры из uri
|
* Получаем параметры из uri.
|
||||||
*
|
*
|
||||||
* @param array $path
|
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
protected function resolvePath(array $path): void
|
protected function resolvePath(array $path): void
|
||||||
{
|
{
|
||||||
$this->session = $path['session'] ?? null;
|
$this->session = $path['session'] ?? null;
|
||||||
$this->api = explode('.', $path['method'] ?? '');
|
$this->api = \explode('.', $path['method'] ?? '');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -1,11 +1,11 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\Controllers;
|
namespace TelegramApiServer\Controllers;
|
||||||
|
|
||||||
|
use Amp\Http\HttpStatus;
|
||||||
use Amp\Http\Server\Request;
|
use Amp\Http\Server\Request;
|
||||||
use Amp\Http\Server\Response;
|
use Amp\Http\Server\Response;
|
||||||
use Amp\Http\Server\Router;
|
use Amp\Http\Server\Router;
|
||||||
use Amp\Http\HttpStatus;
|
|
||||||
use Amp\Http\Server\SocketHttpServer;
|
use Amp\Http\Server\SocketHttpServer;
|
||||||
use Amp\Websocket\Server\Rfc6455Acceptor;
|
use Amp\Websocket\Server\Rfc6455Acceptor;
|
||||||
use Amp\Websocket\Server\Websocket as WebsocketServer;
|
use Amp\Websocket\Server\Websocket as WebsocketServer;
|
||||||
@ -104,7 +104,7 @@ final class EventsController implements WebsocketClientHandler, WebsocketAccepto
|
|||||||
];
|
];
|
||||||
|
|
||||||
$this->gateway->multicastText(
|
$this->gateway->multicastText(
|
||||||
json_encode(
|
\json_encode(
|
||||||
$update,
|
$update,
|
||||||
JSON_THROW_ON_ERROR |
|
JSON_THROW_ON_ERROR |
|
||||||
JSON_INVALID_UTF8_SUBSTITUTE |
|
JSON_INVALID_UTF8_SUBSTITUTE |
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\Controllers;
|
namespace TelegramApiServer\Controllers;
|
||||||
|
|
||||||
@ -90,7 +90,7 @@ final class LogController implements WebsocketClientHandler, WebsocketAcceptor
|
|||||||
];
|
];
|
||||||
|
|
||||||
$this->gateway->multicastText(
|
$this->gateway->multicastText(
|
||||||
json_encode(
|
\json_encode(
|
||||||
$update,
|
$update,
|
||||||
JSON_THROW_ON_ERROR |
|
JSON_THROW_ON_ERROR |
|
||||||
JSON_INVALID_UTF8_SUBSTITUTE |
|
JSON_INVALID_UTF8_SUBSTITUTE |
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\Controllers;
|
namespace TelegramApiServer\Controllers;
|
||||||
|
|
||||||
@ -8,18 +8,16 @@ use TelegramApiServer\Client;
|
|||||||
final class SystemController extends AbstractApiController
|
final class SystemController extends AbstractApiController
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Получаем параметры из uri
|
* Получаем параметры из uri.
|
||||||
*
|
*
|
||||||
* @param array $path
|
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
protected function resolvePath(array $path): void
|
protected function resolvePath(array $path): void
|
||||||
{
|
{
|
||||||
$this->api = explode('.', $path['method'] ?? '');
|
$this->api = \explode('.', $path['method'] ?? '');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @return mixed
|
|
||||||
* @throws Exception
|
* @throws Exception
|
||||||
*/
|
*/
|
||||||
protected function callApi()
|
protected function callApi()
|
||||||
|
@ -1,8 +1,7 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\EventObservers;
|
namespace TelegramApiServer\EventObservers;
|
||||||
|
|
||||||
|
|
||||||
use danog\MadelineProto\APIWrapper;
|
use danog\MadelineProto\APIWrapper;
|
||||||
use ReflectionProperty;
|
use ReflectionProperty;
|
||||||
use TelegramApiServer\Client;
|
use TelegramApiServer\Client;
|
||||||
@ -43,7 +42,7 @@ final class EventObserver
|
|||||||
{
|
{
|
||||||
$sessions = [];
|
$sessions = [];
|
||||||
if ($requestedSession === null) {
|
if ($requestedSession === null) {
|
||||||
$sessions = array_keys(Client::getInstance()->instances);
|
$sessions = \array_keys(Client::getInstance()->instances);
|
||||||
} else {
|
} else {
|
||||||
$sessions[] = $requestedSession;
|
$sessions[] = $requestedSession;
|
||||||
}
|
}
|
||||||
@ -74,7 +73,7 @@ final class EventObserver
|
|||||||
{
|
{
|
||||||
$sessions = [];
|
$sessions = [];
|
||||||
if ($requestedSession === null) {
|
if ($requestedSession === null) {
|
||||||
$sessions = array_keys(Client::getInstance()->instances);
|
$sessions = \array_keys(Client::getInstance()->instances);
|
||||||
} else {
|
} else {
|
||||||
$sessions[] = $requestedSession;
|
$sessions[] = $requestedSession;
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\EventObservers;
|
namespace TelegramApiServer\EventObservers;
|
||||||
|
|
||||||
@ -18,22 +18,22 @@ final class LogObserver
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @param mixed|array|string $message
|
* @param mixed|array|string $message
|
||||||
* @param int $level
|
|
||||||
*/
|
*/
|
||||||
public static function log($message, int $level)
|
public static function log($message, int $level)
|
||||||
{
|
{
|
||||||
if (is_scalar($message)) {
|
if (\is_scalar($message)) {
|
||||||
Logger::getInstance()->log(Logger::$madelineLevels[$level], (string) $message);
|
Logger::getInstance()->log(Logger::$madelineLevels[$level], (string) $message);
|
||||||
} else {
|
} else {
|
||||||
if ($message instanceof Throwable) {
|
if ($message instanceof Throwable) {
|
||||||
$message = Logger::getExceptionAsArray($message);
|
$message = Logger::getExceptionAsArray($message);
|
||||||
}
|
}
|
||||||
if (is_array($message)) {
|
if (\is_array($message)) {
|
||||||
Logger::getInstance()->log(Logger::$madelineLevels[$level], '', $message);
|
Logger::getInstance()->log(Logger::$madelineLevels[$level], '', $message);
|
||||||
} else {
|
} else {
|
||||||
Logger::getInstance()->log(
|
Logger::getInstance()->log(
|
||||||
Logger::$madelineLevels[$level],
|
Logger::$madelineLevels[$level],
|
||||||
json_encode($message,
|
\json_encode(
|
||||||
|
$message,
|
||||||
JSON_UNESCAPED_UNICODE |
|
JSON_UNESCAPED_UNICODE |
|
||||||
JSON_PRETTY_PRINT |
|
JSON_PRETTY_PRINT |
|
||||||
JSON_INVALID_UTF8_SUBSTITUTE |
|
JSON_INVALID_UTF8_SUBSTITUTE |
|
||||||
|
@ -1,8 +1,7 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\EventObservers;
|
namespace TelegramApiServer\EventObservers;
|
||||||
|
|
||||||
|
|
||||||
trait ObserverTrait
|
trait ObserverTrait
|
||||||
{
|
{
|
||||||
/** @var callable[] */
|
/** @var callable[] */
|
||||||
@ -18,7 +17,7 @@ trait ObserverTrait
|
|||||||
{
|
{
|
||||||
notice("Removing listener: {$clientId}");
|
notice("Removing listener: {$clientId}");
|
||||||
unset(self::$subscribers[$clientId]);
|
unset(self::$subscribers[$clientId]);
|
||||||
$listenersCount = count(self::$subscribers);
|
$listenersCount = \count(self::$subscribers);
|
||||||
notice("Event listeners left: {$listenersCount}");
|
notice("Event listeners left: {$listenersCount}");
|
||||||
if ($listenersCount === 0) {
|
if ($listenersCount === 0) {
|
||||||
self::$subscribers = [];
|
self::$subscribers = [];
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\Exceptions;
|
namespace TelegramApiServer\Exceptions;
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\Exceptions;
|
namespace TelegramApiServer\Exceptions;
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer;
|
namespace TelegramApiServer;
|
||||||
|
|
||||||
@ -13,11 +13,11 @@ final class Files
|
|||||||
|
|
||||||
public static function checkOrCreateSessionFolder(string $session): void
|
public static function checkOrCreateSessionFolder(string $session): void
|
||||||
{
|
{
|
||||||
$directory = dirname($session);
|
$directory = \dirname($session);
|
||||||
if ($directory && $directory !== '.' && !is_dir($directory)) {
|
if ($directory && $directory !== '.' && !\is_dir($directory)) {
|
||||||
$parentDirectoryPermissions = fileperms(ROOT_DIR);
|
$parentDirectoryPermissions = \fileperms(ROOT_DIR);
|
||||||
if (!mkdir($directory, $parentDirectoryPermissions, true) && !is_dir($directory)) {
|
if (!\mkdir($directory, $parentDirectoryPermissions, true) && !\is_dir($directory)) {
|
||||||
throw new RuntimeException(sprintf('Directory "%s" was not created', $directory));
|
throw new RuntimeException(\sprintf('Directory "%s" was not created', $directory));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -28,7 +28,7 @@ final class Files
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
preg_match(
|
\preg_match(
|
||||||
'~' . self::SESSION_FOLDER . "/(?'sessionName'.*?)" . self::SESSION_EXTENSION . '~',
|
'~' . self::SESSION_FOLDER . "/(?'sessionName'.*?)" . self::SESSION_EXTENSION . '~',
|
||||||
$sessionFile,
|
$sessionFile,
|
||||||
$matches
|
$matches
|
||||||
@ -37,21 +37,14 @@ final class Files
|
|||||||
return $matches['sessionName'] ?? null;
|
return $matches['sessionName'] ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* @param string|null $session
|
|
||||||
*
|
|
||||||
* @param string $extension
|
|
||||||
*
|
|
||||||
* @return string|null
|
|
||||||
*/
|
|
||||||
public static function getSessionFile(?string $session, string $extension = self::SESSION_EXTENSION): ?string
|
public static function getSessionFile(?string $session, string $extension = self::SESSION_EXTENSION): ?string
|
||||||
{
|
{
|
||||||
if (!$session) {
|
if (!$session) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
$session = trim(trim($session), '/');
|
$session = \trim(\trim($session), '/');
|
||||||
$session = self::SESSION_FOLDER . '/' . $session . $extension;
|
$session = self::SESSION_FOLDER . '/' . $session . $extension;
|
||||||
$session = str_replace('//', '/', $session);
|
$session = \str_replace('//', '/', $session);
|
||||||
return $session;
|
return $session;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -59,9 +52,9 @@ final class Files
|
|||||||
{
|
{
|
||||||
$settingsFile = self::getSessionFile($session, self::SETTINGS_EXTENSION);
|
$settingsFile = self::getSessionFile($session, self::SETTINGS_EXTENSION);
|
||||||
$settings = [];
|
$settings = [];
|
||||||
if (file_exists($settingsFile)) {
|
if (\file_exists($settingsFile)) {
|
||||||
$settings = json_decode(
|
$settings = \json_decode(
|
||||||
file_get_contents($settingsFile),
|
\file_get_contents($settingsFile),
|
||||||
true,
|
true,
|
||||||
10,
|
10,
|
||||||
JSON_THROW_ON_ERROR
|
JSON_THROW_ON_ERROR
|
||||||
@ -74,9 +67,9 @@ final class Files
|
|||||||
public static function saveSessionSettings(string $session, array $settings = []): void
|
public static function saveSessionSettings(string $session, array $settings = []): void
|
||||||
{
|
{
|
||||||
$settingsFile = self::getSessionFile($session, self::SETTINGS_EXTENSION);
|
$settingsFile = self::getSessionFile($session, self::SETTINGS_EXTENSION);
|
||||||
file_put_contents(
|
\file_put_contents(
|
||||||
$settingsFile,
|
$settingsFile,
|
||||||
json_encode(
|
\json_encode(
|
||||||
$settings,
|
$settings,
|
||||||
JSON_THROW_ON_ERROR |
|
JSON_THROW_ON_ERROR |
|
||||||
JSON_INVALID_UTF8_SUBSTITUTE |
|
JSON_INVALID_UTF8_SUBSTITUTE |
|
||||||
@ -89,9 +82,9 @@ final class Files
|
|||||||
|
|
||||||
public static function globRecursive($pattern, $flags = 0): array
|
public static function globRecursive($pattern, $flags = 0): array
|
||||||
{
|
{
|
||||||
$files = glob($pattern, $flags) ?: [];
|
$files = \glob($pattern, $flags) ?: [];
|
||||||
foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
|
foreach (\glob(\dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
|
||||||
$files = [...$files, ...self::globRecursive($dir . '/' . basename($pattern), $flags)];
|
$files = [...$files, ...self::globRecursive($dir . '/' . \basename($pattern), $flags)];
|
||||||
}
|
}
|
||||||
return $files;
|
return $files;
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* This file is part of the Symfony package.
|
* This file is part of the Symfony package.
|
||||||
@ -21,13 +21,10 @@ use Psr\Log\LogLevel;
|
|||||||
use TelegramApiServer\EventObservers\LogObserver;
|
use TelegramApiServer\EventObservers\LogObserver;
|
||||||
use Throwable;
|
use Throwable;
|
||||||
|
|
||||||
|
use const PHP_EOL;
|
||||||
use function Amp\async;
|
use function Amp\async;
|
||||||
use function Amp\ByteStream\getStdout;
|
use function Amp\ByteStream\getStdout;
|
||||||
use function Amp\ByteStream\pipe;
|
use function Amp\ByteStream\pipe;
|
||||||
use function get_class;
|
|
||||||
use function gettype;
|
|
||||||
use function is_object;
|
|
||||||
use const PHP_EOL;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Minimalist PSR-3 logger designed to write in stderr or any other stream.
|
* Minimalist PSR-3 logger designed to write in stderr or any other stream.
|
||||||
@ -68,7 +65,7 @@ final class Logger extends AbstractLogger
|
|||||||
*/
|
*/
|
||||||
private static array $closePromises = [];
|
private static array $closePromises = [];
|
||||||
|
|
||||||
protected function __construct(string $minLevel = LogLevel::WARNING, \Closure $formatter = null)
|
protected function __construct(string $minLevel = LogLevel::WARNING, ?\Closure $formatter = null)
|
||||||
{
|
{
|
||||||
if (null === $minLevel) {
|
if (null === $minLevel) {
|
||||||
if (isset($_ENV['SHELL_VERBOSITY']) || isset($_SERVER['SHELL_VERBOSITY'])) {
|
if (isset($_ENV['SHELL_VERBOSITY']) || isset($_SERVER['SHELL_VERBOSITY'])) {
|
||||||
@ -91,10 +88,10 @@ final class Logger extends AbstractLogger
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!isset(self::$levels[$minLevel])) {
|
if (!isset(self::$levels[$minLevel])) {
|
||||||
throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $minLevel));
|
throw new InvalidArgumentException(\sprintf('The log level "%s" does not exist.', $minLevel));
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->minLevelIndex = min(self::$levels[$minLevel], self::$levels[self::$madelineLevels[MadelineProto\Logger::VERBOSE]]);
|
$this->minLevelIndex = \min(self::$levels[$minLevel], self::$levels[self::$madelineLevels[MadelineProto\Logger::VERBOSE]]);
|
||||||
$this->formatter = $formatter ?: $this->format(...);
|
$this->formatter = $formatter ?: $this->format(...);
|
||||||
$pipe = new Pipe(PHP_INT_MAX);
|
$pipe = new Pipe(PHP_INT_MAX);
|
||||||
$this->stdout = $pipe->getSink();
|
$this->stdout = $pipe->getSink();
|
||||||
@ -103,10 +100,10 @@ final class Logger extends AbstractLogger
|
|||||||
try {
|
try {
|
||||||
pipe($source, getStdout());
|
pipe($source, getStdout());
|
||||||
} finally {
|
} finally {
|
||||||
unset(self::$closePromises[spl_object_id($promise)]);
|
unset(self::$closePromises[\spl_object_id($promise)]);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
self::$closePromises[spl_object_id($promise)] = [$this->stdout, $promise];
|
self::$closePromises[\spl_object_id($promise)] = [$this->stdout, $promise];
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function getInstance(): Logger
|
public static function getInstance(): Logger
|
||||||
@ -127,7 +124,7 @@ final class Logger extends AbstractLogger
|
|||||||
public function log($level, $message, array $context = []): void
|
public function log($level, $message, array $context = []): void
|
||||||
{
|
{
|
||||||
if (!isset(self::$levels[$level])) {
|
if (!isset(self::$levels[$level])) {
|
||||||
throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level));
|
throw new InvalidArgumentException(\sprintf('The log level "%s" does not exist.', $level));
|
||||||
}
|
}
|
||||||
|
|
||||||
LogObserver::notify($level, $message, $context);
|
LogObserver::notify($level, $message, $context);
|
||||||
@ -137,7 +134,8 @@ final class Logger extends AbstractLogger
|
|||||||
}
|
}
|
||||||
|
|
||||||
$formatter = $this->formatter;
|
$formatter = $this->formatter;
|
||||||
$data = $formatter($level, $message, $context);;
|
$data = $formatter($level, $message, $context);
|
||||||
|
;
|
||||||
try {
|
try {
|
||||||
$this->stdout->write($data);
|
$this->stdout->write($data);
|
||||||
} catch (\Throwable) {
|
} catch (\Throwable) {
|
||||||
@ -158,38 +156,38 @@ final class Logger extends AbstractLogger
|
|||||||
|
|
||||||
private function format(string $level, string $message, array $context): string
|
private function format(string $level, string $message, array $context): string
|
||||||
{
|
{
|
||||||
if (false !== strpos($message, '{')) {
|
if (false !== \strpos($message, '{')) {
|
||||||
$replacements = [];
|
$replacements = [];
|
||||||
foreach ($context as $key => $val) {
|
foreach ($context as $key => $val) {
|
||||||
if ($val instanceof Throwable) {
|
if ($val instanceof Throwable) {
|
||||||
$context[$key] = self::getExceptionAsArray($val);
|
$context[$key] = self::getExceptionAsArray($val);
|
||||||
}
|
}
|
||||||
if (null === $val || is_scalar($val) || (is_object($val) && method_exists($val, '__toString'))) {
|
if (null === $val || \is_scalar($val) || (\is_object($val) && \method_exists($val, '__toString'))) {
|
||||||
$replacements["{{$key}}"] = $val;
|
$replacements["{{$key}}"] = $val;
|
||||||
} else {
|
} else {
|
||||||
if ($val instanceof DateTimeInterface) {
|
if ($val instanceof DateTimeInterface) {
|
||||||
$replacements["{{$key}}"] = $val->format(self::$dateTimeFormat);
|
$replacements["{{$key}}"] = $val->format(self::$dateTimeFormat);
|
||||||
} else {
|
} else {
|
||||||
if (is_object($val)) {
|
if (\is_object($val)) {
|
||||||
$replacements["{{$key}}"] = '[object ' . get_class($val) . ']';
|
$replacements["{{$key}}"] = '[object ' . \get_class($val) . ']';
|
||||||
} else {
|
} else {
|
||||||
$replacements["{{$key}}"] = '[' . gettype($val) . ']';
|
$replacements["{{$key}}"] = '[' . \gettype($val) . ']';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$message = strtr($message, $replacements);
|
$message = \strtr($message, $replacements);
|
||||||
}
|
}
|
||||||
|
|
||||||
return sprintf(
|
return \sprintf(
|
||||||
'[%s] [%s] %s %s',
|
'[%s] [%s] %s %s',
|
||||||
date(self::$dateTimeFormat),
|
\date(self::$dateTimeFormat),
|
||||||
$level,
|
$level,
|
||||||
$message,
|
$message,
|
||||||
$context ?
|
$context ?
|
||||||
"\n" .
|
"\n" .
|
||||||
json_encode(
|
\json_encode(
|
||||||
$context,
|
$context,
|
||||||
JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_PRETTY_PRINT | JSON_UNESCAPED_LINE_TERMINATORS | JSON_UNESCAPED_SLASHES
|
JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_PRETTY_PRINT | JSON_UNESCAPED_LINE_TERMINATORS | JSON_UNESCAPED_SLASHES
|
||||||
)
|
)
|
||||||
@ -200,12 +198,12 @@ final class Logger extends AbstractLogger
|
|||||||
public static function getExceptionAsArray(Throwable $exception)
|
public static function getExceptionAsArray(Throwable $exception)
|
||||||
{
|
{
|
||||||
return [
|
return [
|
||||||
'exception' => get_class($exception),
|
'exception' => \get_class($exception),
|
||||||
'message' => $exception->getMessage(),
|
'message' => $exception->getMessage(),
|
||||||
'file' => $exception->getFile(),
|
'file' => $exception->getFile(),
|
||||||
'line' => $exception->getLine(),
|
'line' => $exception->getLine(),
|
||||||
'code' => $exception->getCode(),
|
'code' => $exception->getCode(),
|
||||||
'backtrace' => array_slice($exception->getTrace(), 0, 3),
|
'backtrace' => \array_slice($exception->getTrace(), 0, 3),
|
||||||
'previous exception' => $exception->getPrevious(),
|
'previous exception' => $exception->getPrevious(),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,7 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
|
|
||||||
namespace TelegramApiServer\MadelineProtoExtensions;
|
namespace TelegramApiServer\MadelineProtoExtensions;
|
||||||
|
|
||||||
|
|
||||||
use Amp\Http\Server\FormParser\StreamedField;
|
use Amp\Http\Server\FormParser\StreamedField;
|
||||||
use Amp\Http\Server\Request;
|
use Amp\Http\Server\Request;
|
||||||
use Amp\Http\Server\Response;
|
use Amp\Http\Server\Response;
|
||||||
@ -43,12 +41,9 @@ final class ApiExtensions
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Проверяет есть ли подходящие медиа у сообщения
|
* Проверяет есть ли подходящие медиа у сообщения.
|
||||||
*
|
*
|
||||||
* @param array $message
|
|
||||||
* @param bool $allowWebPage
|
|
||||||
*
|
*
|
||||||
* @return bool
|
|
||||||
*/
|
*/
|
||||||
private static function hasMedia(array $message = [], bool $allowWebPage = false): bool
|
private static function hasMedia(array $message = [], bool $allowWebPage = false): bool
|
||||||
{
|
{
|
||||||
@ -90,10 +85,10 @@ final class ApiExtensions
|
|||||||
$text = StrTools::mbSubstr($message, $entity['offset'], $entity['length']);
|
$text = StrTools::mbSubstr($message, $entity['offset'], $entity['length']);
|
||||||
|
|
||||||
$template = $html[$entity['_']];
|
$template = $html[$entity['_']];
|
||||||
if (in_array($entity['_'], ['messageEntityTextUrl', 'messageEntityMention', 'messageEntityUrl'])) {
|
if (\in_array($entity['_'], ['messageEntityTextUrl', 'messageEntityMention', 'messageEntityUrl'])) {
|
||||||
$textFormated = sprintf($template, strip_tags($entity['url'] ?? $text), $text);
|
$textFormated = \sprintf($template, \strip_tags($entity['url'] ?? $text), $text);
|
||||||
} else {
|
} else {
|
||||||
$textFormated = sprintf($template, $text);
|
$textFormated = \sprintf($template, $text);
|
||||||
}
|
}
|
||||||
|
|
||||||
$message = self::substringReplace($message, $textFormated, $entity['offset'], $entity['length']);
|
$message = self::substringReplace($message, $textFormated, $entity['offset'], $entity['length']);
|
||||||
@ -105,7 +100,7 @@ final class ApiExtensions
|
|||||||
}
|
}
|
||||||
if ($nextEntity['offset'] < ($entity['offset'] + $entity['length'])) {
|
if ($nextEntity['offset'] < ($entity['offset'] + $entity['length'])) {
|
||||||
$nextEntity['offset'] += StrTools::mbStrlen(
|
$nextEntity['offset'] += StrTools::mbStrlen(
|
||||||
preg_replace('~(\>).*<\/.*$~', '$1', $textFormated)
|
\preg_replace('~(\>).*<\/.*$~', '$1', $textFormated)
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
$nextEntity['offset'] += StrTools::mbStrlen($textFormated) - StrTools::mbStrlen($text);
|
$nextEntity['offset'] += StrTools::mbStrlen($textFormated) - StrTools::mbStrlen($text);
|
||||||
@ -115,7 +110,7 @@ final class ApiExtensions
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
unset($entity);
|
unset($entity);
|
||||||
$message = nl2br($message);
|
$message = \nl2br($message);
|
||||||
return $message;
|
return $message;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -127,7 +122,7 @@ final class ApiExtensions
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Пересылает сообщения без ссылки на оригинал
|
* Пересылает сообщения без ссылки на оригинал.
|
||||||
*
|
*
|
||||||
* @param array $data
|
* @param array $data
|
||||||
* <pre>
|
* <pre>
|
||||||
@ -141,7 +136,7 @@ final class ApiExtensions
|
|||||||
*/
|
*/
|
||||||
public function copyMessages(array $data)
|
public function copyMessages(array $data)
|
||||||
{
|
{
|
||||||
$data = array_merge(
|
$data = \array_merge(
|
||||||
[
|
[
|
||||||
'from_peer' => '',
|
'from_peer' => '',
|
||||||
'to_peer' => '',
|
'to_peer' => '',
|
||||||
@ -157,7 +152,7 @@ final class ApiExtensions
|
|||||||
]
|
]
|
||||||
);
|
);
|
||||||
$result = [];
|
$result = [];
|
||||||
if (!$response || !is_array($response) || !array_key_exists('messages', $response)) {
|
if (!$response || !\is_array($response) || !\array_key_exists('messages', $response)) {
|
||||||
return $result;
|
return $result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -174,7 +169,7 @@ final class ApiExtensions
|
|||||||
$result[] = $this->madelineProto->messages->sendMessage(...$messageData);
|
$result[] = $this->madelineProto->messages->sendMessage(...$messageData);
|
||||||
}
|
}
|
||||||
if ($key > 0) {
|
if ($key > 0) {
|
||||||
delay(random_int(300, 2000) / 1000);
|
delay(\random_int(300, 2000) / 1000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -182,14 +177,13 @@ final class ApiExtensions
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Загружает медиафайл из указанного сообщения в поток
|
* Загружает медиафайл из указанного сообщения в поток.
|
||||||
*
|
*
|
||||||
* @param array $data
|
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public function getMedia(array $data): Response
|
public function getMedia(array $data): Response
|
||||||
{
|
{
|
||||||
$data = array_merge(
|
$data = \array_merge(
|
||||||
[
|
[
|
||||||
'peer' => '',
|
'peer' => '',
|
||||||
'id' => [0],
|
'id' => [0],
|
||||||
@ -222,17 +216,16 @@ final class ApiExtensions
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return $this->downloadToResponse($info);
|
return $this->downloadToResponse($info);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Загружает превью медиафайла из указанного сообщения в поток
|
* Загружает превью медиафайла из указанного сообщения в поток.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public function getMediaPreview(array $data): Response
|
public function getMediaPreview(array $data): Response
|
||||||
{
|
{
|
||||||
$data = array_merge(
|
$data = \array_merge(
|
||||||
[
|
[
|
||||||
'peer' => '',
|
'peer' => '',
|
||||||
'id' => [0],
|
'id' => [0],
|
||||||
@ -250,7 +243,7 @@ final class ApiExtensions
|
|||||||
throw new NoMediaException('Message has no media');
|
throw new NoMediaException('Message has no media');
|
||||||
}
|
}
|
||||||
|
|
||||||
$media = $message['media'][array_key_last($message['media'])];
|
$media = $message['media'][\array_key_last($message['media'])];
|
||||||
$thumb = null;
|
$thumb = null;
|
||||||
switch (true) {
|
switch (true) {
|
||||||
case isset($media['sizes']):
|
case isset($media['sizes']):
|
||||||
@ -308,7 +301,7 @@ final class ApiExtensions
|
|||||||
public function getMessages(array $data): array
|
public function getMessages(array $data): array
|
||||||
{
|
{
|
||||||
$peerInfo = $this->madelineProto->getInfo($data['peer']);
|
$peerInfo = $this->madelineProto->getInfo($data['peer']);
|
||||||
if (in_array($peerInfo['type'], ['channel', 'supergroup'])) {
|
if (\in_array($peerInfo['type'], ['channel', 'supergroup'])) {
|
||||||
$response = $this->madelineProto->channels->getMessages(
|
$response = $this->madelineProto->channels->getMessages(
|
||||||
[
|
[
|
||||||
'channel' => $data['peer'],
|
'channel' => $data['peer'],
|
||||||
@ -328,7 +321,6 @@ final class ApiExtensions
|
|||||||
* @param array $info
|
* @param array $info
|
||||||
* Any downloadable array: message, media etc...
|
* Any downloadable array: message, media etc...
|
||||||
*
|
*
|
||||||
* @return Response
|
|
||||||
*/
|
*/
|
||||||
public function downloadToResponse(array $info): Response
|
public function downloadToResponse(array $info): Response
|
||||||
{
|
{
|
||||||
@ -336,7 +328,7 @@ final class ApiExtensions
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Адаптер для стандартного метода
|
* Адаптер для стандартного метода.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public function downloadToBrowser(array $info): Response
|
public function downloadToBrowser(array $info): Response
|
||||||
@ -361,7 +353,7 @@ final class ApiExtensions
|
|||||||
$this->file->getMimeType(),
|
$this->file->getMimeType(),
|
||||||
$this->file->getFilename()
|
$this->file->getFilename()
|
||||||
);
|
);
|
||||||
$inputFile['id'] = unpack('P', $inputFile['id'])['1'];
|
$inputFile['id'] = \unpack('P', $inputFile['id'])['1'];
|
||||||
return [
|
return [
|
||||||
'media' => [
|
'media' => [
|
||||||
'_' => 'inputMediaUploadedDocument',
|
'_' => 'inputMediaUploadedDocument',
|
||||||
@ -384,7 +376,6 @@ final class ApiExtensions
|
|||||||
Client::getWrapper($this->madelineProto)->serialize();
|
Client::getWrapper($this->madelineProto)->serialize();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public function getUpdates(array $params): array
|
public function getUpdates(array $params): array
|
||||||
{
|
{
|
||||||
foreach ($params as $key => $value) {
|
foreach ($params as $key => $value) {
|
||||||
@ -410,12 +401,13 @@ final class ApiExtensions
|
|||||||
Client::getWrapper($this->madelineProto)->serialize();
|
Client::getWrapper($this->madelineProto)->serialize();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function unsubscribeFromUpdates(?string $channel = null): array {
|
public function unsubscribeFromUpdates(?string $channel = null): array
|
||||||
|
{
|
||||||
$inputChannelId = null;
|
$inputChannelId = null;
|
||||||
if ($channel) {
|
if ($channel) {
|
||||||
$id = (string) $this->madelineProto->getId($channel);
|
$id = (string) $this->madelineProto->getId($channel);
|
||||||
|
|
||||||
$inputChannelId = (int)str_replace(['-100', '-'], '', $id);
|
$inputChannelId = (int) \str_replace(['-100', '-'], '', $id);
|
||||||
if (!$inputChannelId) {
|
if (!$inputChannelId) {
|
||||||
throw new InvalidArgumentException('Invalid id');
|
throw new InvalidArgumentException('Invalid id');
|
||||||
}
|
}
|
||||||
@ -438,10 +430,9 @@ final class ApiExtensions
|
|||||||
$counter++;
|
$counter++;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'disabled_update_loops' => $counter,
|
'disabled_update_loops' => $counter,
|
||||||
'current_update_loops' => count(Client::getWrapper($this->madelineProto)->getAPI()->feeders),
|
'current_update_loops' => \count(Client::getWrapper($this->madelineProto)->getAPI()->feeders),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\MadelineProtoExtensions;
|
namespace TelegramApiServer\MadelineProtoExtensions;
|
||||||
|
|
||||||
@ -75,7 +75,7 @@ final class SystemApiExtensions
|
|||||||
foreach ($this->client->instances as $session => $instance) {
|
foreach ($this->client->instances as $session => $instance) {
|
||||||
$authorized = $instance->getAuthorization();
|
$authorized = $instance->getAuthorization();
|
||||||
switch ($authorized) {
|
switch ($authorized) {
|
||||||
case API::NOT_LOGGED_IN;
|
case API::NOT_LOGGED_IN:
|
||||||
$status = 'NOT_LOGGED_IN';
|
$status = 'NOT_LOGGED_IN';
|
||||||
break;
|
break;
|
||||||
case API::WAITING_CODE:
|
case API::WAITING_CODE:
|
||||||
@ -107,7 +107,7 @@ final class SystemApiExtensions
|
|||||||
|
|
||||||
return [
|
return [
|
||||||
'sessions' => $sessions,
|
'sessions' => $sessions,
|
||||||
'memory' => $this->bytesToHuman(memory_get_usage(true)),
|
'memory' => $this->bytesToHuman(\memory_get_usage(true)),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -115,9 +115,9 @@ final class SystemApiExtensions
|
|||||||
{
|
{
|
||||||
$file = Files::getSessionFile($session);
|
$file = Files::getSessionFile($session);
|
||||||
|
|
||||||
if (is_file($file)) {
|
if (\is_file($file)) {
|
||||||
$futures = [];
|
$futures = [];
|
||||||
foreach (glob("$file*") as $file) {
|
foreach (\glob("$file*") as $file) {
|
||||||
$futures[] = async(fn () => deleteFile($file));
|
$futures[] = async(fn () => deleteFile($file));
|
||||||
}
|
}
|
||||||
awaitAll($futures);
|
awaitAll($futures);
|
||||||
@ -140,7 +140,7 @@ final class SystemApiExtensions
|
|||||||
public function unlinkSessionSettings($session): string
|
public function unlinkSessionSettings($session): string
|
||||||
{
|
{
|
||||||
$settings = Files::getSessionFile($session, Files::SETTINGS_EXTENSION);
|
$settings = Files::getSessionFile($session, Files::SETTINGS_EXTENSION);
|
||||||
if (is_file($settings)) {
|
if (\is_file($settings)) {
|
||||||
deleteFile($settings);
|
deleteFile($settings);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -159,6 +159,6 @@ final class SystemApiExtensions
|
|||||||
for ($i = 0; $bytes > 1024; $i++) {
|
for ($i = 0; $bytes > 1024; $i++) {
|
||||||
$bytes /= 1024;
|
$bytes /= 1024;
|
||||||
}
|
}
|
||||||
return round($bytes, 2) . ' ' . $units[$i];
|
return \round($bytes, 2) . ' ' . $units[$i];
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\Migrations;
|
namespace TelegramApiServer\Migrations;
|
||||||
|
|
||||||
@ -8,7 +8,7 @@ final class StartUpFixes
|
|||||||
{
|
{
|
||||||
public static function fix(): void
|
public static function fix(): void
|
||||||
{
|
{
|
||||||
define('MADELINE_WORKER_TYPE', 'madeline-ipc');
|
\define('MADELINE_WORKER_TYPE', 'madeline-ipc');
|
||||||
Magic::$isIpcWorker = true;
|
Magic::$isIpcWorker = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\Server;
|
namespace TelegramApiServer\Server;
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\Server;
|
namespace TelegramApiServer\Server;
|
||||||
|
|
||||||
@ -20,7 +20,7 @@ final class Authorization implements Middleware
|
|||||||
|
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
$this->selfIp = ip2long(getHostByName(php_uname('n')));
|
$this->selfIp = \ip2long(\getHostByName(\php_uname('n')));
|
||||||
$this->ipWhitelist = (array) Config::getInstance()->get('api.ip_whitelist', []);
|
$this->ipWhitelist = (array) Config::getInstance()->get('api.ip_whitelist', []);
|
||||||
$this->passwords = Config::getInstance()->get('api.passwords', []);
|
$this->passwords = Config::getInstance()->get('api.passwords', []);
|
||||||
if (!$this->ipWhitelist && !$this->passwords) {
|
if (!$this->ipWhitelist && !$this->passwords) {
|
||||||
@ -39,9 +39,9 @@ final class Authorization implements Middleware
|
|||||||
if ($this->passwords) {
|
if ($this->passwords) {
|
||||||
$header = (string) $request->getHeader('Authorization');
|
$header = (string) $request->getHeader('Authorization');
|
||||||
if ($header) {
|
if ($header) {
|
||||||
sscanf($header, "Basic %s", $encodedPassword);
|
\sscanf($header, "Basic %s", $encodedPassword);
|
||||||
[$username, $password] = explode(':', base64_decode($encodedPassword), 2);
|
[$username, $password] = \explode(':', \base64_decode($encodedPassword), 2);
|
||||||
if (array_key_exists($username, $this->passwords) && $this->passwords[$username] === $password) {
|
if (\array_key_exists($username, $this->passwords) && $this->passwords[$username] === $password) {
|
||||||
return $requestHandler->handleRequest($request);
|
return $requestHandler->handleRequest($request);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -59,21 +59,21 @@ final class Authorization implements Middleware
|
|||||||
private function isIpAllowed(string $host): bool
|
private function isIpAllowed(string $host): bool
|
||||||
{
|
{
|
||||||
|
|
||||||
|
if ($this->ipWhitelist && !\in_array($host, $this->ipWhitelist, true)) {
|
||||||
if ($this->ipWhitelist && !in_array($host, $this->ipWhitelist, true)) {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function isLocal(string $host): bool {
|
private function isLocal(string $host): bool
|
||||||
|
{
|
||||||
if ($host === '127.0.0.1' || $host === 'localhost') {
|
if ($host === '127.0.0.1' || $host === 'localhost') {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
global $options;
|
global $options;
|
||||||
if ($options['docker']) {
|
if ($options['docker']) {
|
||||||
$isSameNetwork = abs(ip2long($host) - $this->selfIp) < 256;
|
$isSameNetwork = \abs(\ip2long($host) - $this->selfIp) < 256;
|
||||||
if ($isSameNetwork) {
|
if ($isSameNetwork) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\Server;
|
namespace TelegramApiServer\Server;
|
||||||
|
|
||||||
@ -8,17 +8,15 @@ use TelegramApiServer\Controllers\AbstractApiController;
|
|||||||
final class ErrorResponses
|
final class ErrorResponses
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @param int $status
|
|
||||||
* @param string|array $message
|
* @param string|array $message
|
||||||
*
|
*
|
||||||
* @return Response
|
|
||||||
*/
|
*/
|
||||||
public static function get(int $status, $message): Response
|
public static function get(int $status, $message): Response
|
||||||
{
|
{
|
||||||
return new Response(
|
return new Response(
|
||||||
$status,
|
$status,
|
||||||
AbstractApiController::JSON_HEADER,
|
AbstractApiController::JSON_HEADER,
|
||||||
json_encode(
|
\json_encode(
|
||||||
[
|
[
|
||||||
'success' => false,
|
'success' => false,
|
||||||
'errors' => [
|
'errors' => [
|
||||||
|
@ -1,12 +1,12 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\Server;
|
namespace TelegramApiServer\Server;
|
||||||
|
|
||||||
|
use Amp\Http\HttpStatus;
|
||||||
use Amp\Http\Server\ErrorHandler;
|
use Amp\Http\Server\ErrorHandler;
|
||||||
use Amp\Http\Server\Request;
|
use Amp\Http\Server\Request;
|
||||||
use Amp\Http\Server\RequestHandler\ClosureRequestHandler;
|
use Amp\Http\Server\RequestHandler\ClosureRequestHandler;
|
||||||
use Amp\Http\Server\SocketHttpServer;
|
use Amp\Http\Server\SocketHttpServer;
|
||||||
use Amp\Http\HttpStatus;
|
|
||||||
use TelegramApiServer\Controllers\ApiController;
|
use TelegramApiServer\Controllers\ApiController;
|
||||||
use TelegramApiServer\Controllers\EventsController;
|
use TelegramApiServer\Controllers\EventsController;
|
||||||
use TelegramApiServer\Controllers\LogController;
|
use TelegramApiServer\Controllers\LogController;
|
||||||
@ -70,5 +70,4 @@ final class Router
|
|||||||
$this->router->addRoute('GET', '/log/{level:.*?[^/]}[/]', $logHandler);
|
$this->router->addRoute('GET', '/log/{level:.*?[^/]}[/]', $logHandler);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
@ -1,4 +1,4 @@
|
|||||||
<?php
|
<?php declare(strict_types=1);
|
||||||
|
|
||||||
namespace TelegramApiServer\Server;
|
namespace TelegramApiServer\Server;
|
||||||
|
|
||||||
@ -14,7 +14,6 @@ use Revolt\EventLoop;
|
|||||||
use TelegramApiServer\Client;
|
use TelegramApiServer\Client;
|
||||||
use TelegramApiServer\Config;
|
use TelegramApiServer\Config;
|
||||||
use TelegramApiServer\Logger;
|
use TelegramApiServer\Logger;
|
||||||
use function sprintf;
|
|
||||||
use const SIGINT;
|
use const SIGINT;
|
||||||
use const SIGTERM;
|
use const SIGTERM;
|
||||||
|
|
||||||
@ -23,8 +22,6 @@ final class Server
|
|||||||
/**
|
/**
|
||||||
* Server constructor.
|
* Server constructor.
|
||||||
*
|
*
|
||||||
* @param array $options
|
|
||||||
* @param array|null $sessionFiles
|
|
||||||
*/
|
*/
|
||||||
public function __construct(array $options, ?array $sessionFiles)
|
public function __construct(array $options, ?array $sessionFiles)
|
||||||
{
|
{
|
||||||
@ -51,7 +48,6 @@ final class Server
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stop the server gracefully when SIGINT is received.
|
* Stop the server gracefully when SIGINT is received.
|
||||||
* This is technically optional, but it is best to call Server::stop().
|
* This is technically optional, but it is best to call Server::stop().
|
||||||
@ -60,10 +56,10 @@ final class Server
|
|||||||
*/
|
*/
|
||||||
private static function registerShutdown(SocketHttpServer $server)
|
private static function registerShutdown(SocketHttpServer $server)
|
||||||
{
|
{
|
||||||
if (defined('SIGINT')) {
|
if (\defined('SIGINT')) {
|
||||||
// Await SIGINT or SIGTERM to be received.
|
// Await SIGINT or SIGTERM to be received.
|
||||||
$signal = Amp\trapSignal([SIGINT, SIGTERM]);
|
$signal = Amp\trapSignal([SIGINT, SIGTERM]);
|
||||||
info(sprintf("Received signal %d, stopping HTTP server", $signal));
|
info(\sprintf("Received signal %d, stopping HTTP server", $signal));
|
||||||
$server->stop();
|
$server->stop();
|
||||||
} else {
|
} else {
|
||||||
EventLoop::run();
|
EventLoop::run();
|
||||||
@ -74,16 +70,14 @@ final class Server
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Установить конфигурацию для http-сервера
|
* Установить конфигурацию для http-сервера.
|
||||||
*
|
*
|
||||||
* @param array $config
|
|
||||||
* @return array
|
|
||||||
*/
|
*/
|
||||||
private function getConfig(array $config = []): array
|
private function getConfig(array $config = []): array
|
||||||
{
|
{
|
||||||
$config = array_filter($config);
|
$config = \array_filter($config);
|
||||||
|
|
||||||
$config = array_merge(
|
$config = \array_merge(
|
||||||
Config::getInstance()->get('server', []),
|
Config::getInstance()->get('server', []),
|
||||||
$config
|
$config
|
||||||
);
|
);
|
||||||
@ -97,18 +91,18 @@ final class Server
|
|||||||
if ($realIpHeader) {
|
if ($realIpHeader) {
|
||||||
$remote = $request->getHeader($realIpHeader);
|
$remote = $request->getHeader($realIpHeader);
|
||||||
if (!$remote) {
|
if (!$remote) {
|
||||||
GOTO DIRECT;
|
goto DIRECT;
|
||||||
}
|
}
|
||||||
$tmp = explode(',', $remote);
|
$tmp = \explode(',', $remote);
|
||||||
$remote = trim(end($tmp));
|
$remote = \trim(\end($tmp));
|
||||||
} else {
|
} else {
|
||||||
DIRECT:
|
DIRECT:
|
||||||
$remote = $request->getClient()->getRemoteAddress()->toString();
|
$remote = $request->getClient()->getRemoteAddress()->toString();
|
||||||
$hostArray = explode(':', $remote);
|
$hostArray = \explode(':', $remote);
|
||||||
if (count($hostArray) >= 2) {
|
if (\count($hostArray) >= 2) {
|
||||||
$port = (int)array_pop($hostArray);
|
$port = (int) \array_pop($hostArray);
|
||||||
if ($port > 0 && $port <= 65353) {
|
if ($port > 0 && $port <= 65353) {
|
||||||
$remote = implode(':', $hostArray);
|
$remote = \implode(':', $hostArray);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user