Skip to content

Commit

Permalink
Session management rewrite
Browse files Browse the repository at this point in the history
  • Loading branch information
xtrime-ru committed Jan 19, 2020
1 parent f666cbd commit 4058eb5
Show file tree
Hide file tree
Showing 12 changed files with 157 additions and 181 deletions.
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ Fast, simple, async php telegram api server:
## Advanced features
* CombinedAPI (multiple sessions) support.
* Multiple sessions support.
When running multiple sessions, need to define which session to use for request.
Each session is stored in `sessions/{$session}.madeline`. Nested folders supported.
**Examples:**
Expand All @@ -107,16 +107,16 @@ Fast, simple, async php telegram api server:
Session can be added and removed while server is running.
**Examples:**
* Adding session: `http://127.0.0.1:9503/combinedApi/addInstance?session=users/xtrime`
* Adding session: `http://127.0.0.1:9503/combinedApi/addInstance?session=users/xtrime`
* Adding session: `http://127.0.0.1:9503/system/addInstance?session=users/xtrime`
* Removing session: `http://127.0.0.1:9503/system/removeInstance?session=users/xtrime`
If there is no authorization in session, or session file is blank, authorization required:
User:
* `http://127.0.0.1:9503/combinedApi/phoneLogin?phone=+7123...`
* `http://127.0.0.1:9503/combinedApi/completePhoneLogin?code=123456`
* (optional) `http://127.0.0.1:9503/combinedApi/complete2falogin?password=123456`
* (optional) `http://127.0.0.1:9503/combinedApi/completeSignup?firstName=MyExampleName`
* `http://127.0.0.1:9503/api/users/xtrime/phoneLogin?phone=+7123...`
* `http://127.0.0.1:9503/api/users/xtrime/completePhoneLogin?code=123456`
* (optional) `http://127.0.0.1:9503/api/users/xtrime/complete2falogin?password=123456`
* (optional) `http://127.0.0.1:9503/api/users/xtrime/completeSignup?firstName=MyExampleName`
Bot:
* `http://127.0.0.1:9503/combinedApi/botLogin?token=34298141894:aflknsaflknLKNFS`
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"amphp/http-server": "^2",
"amphp/http-server-router": "^1",
"amphp/websocket-server": "^2",
"amphp/websocket-client": "dev-master#53f7883b325b09864095300ec8ff81e84e772c3b",
"vlucas/phpdotenv": "^4",
"danog/madelineproto":"^5"
},
Expand Down
16 changes: 8 additions & 8 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion server.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,5 +73,5 @@
}
}

$client = new TelegramApiServer\Client($sessionFiles);
$client = new TelegramApiServer\Client(array_keys($sessionFiles));
new TelegramApiServer\Server\Server($client, $options);
89 changes: 41 additions & 48 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,18 @@ class Client
{
public static string $sessionExtension = '.madeline';
public static string $sessionFolder = 'sessions';
private ?MadelineProto\CombinedAPI $MadelineProtoCombined = null;
/** @var MadelineProto\API[] */
public array $instances = [];
private array $sessionsFiles;

/**
* Client constructor.
*
* @param array $sessions
*/
public function __construct(array $sessions)
public function __construct(array $sessionsFiles)
{
$settings = (array) Config::getInstance()->get('telegram');

foreach ($sessions as &$session) {
$session = $settings;
}
unset($session);

$this->connect($sessions);
$this->sessionsFiles = $sessionsFiles;
}

/**
Expand Down Expand Up @@ -71,42 +66,47 @@ public static function checkOrCreateSessionFolder($session, $rootDir): void
}
}

/**
* @param array $sessions
*/
public function connect(array $sessions): void
public function connect(): void
{
//При каждой инициализации настройки обновляются из массива $config
echo PHP_EOL . 'Starting MadelineProto...' . PHP_EOL;
$time = microtime(true);

$this->MadelineProtoCombined = new MadelineProto\CombinedAPI('combined_session.madeline', $sessions);
//В сессии могут быть ссылки на несуществующие классы после обновления кода. Она нам не нужна.
$this->MadelineProtoCombined->session = null;
foreach ($this->sessionsFiles as $file) {
$session = static::getSessionName($file);
$this->addSession($session);
}

$this->MadelineProtoCombined->async(true);
$this->MadelineProtoCombined->loop(
function() use ($sessions) {
$promises = [];
foreach (array_keys($sessions) as $session) {
MadelineProto\Logger::log("Starting session: {$session}", MadelineProto\Logger::WARNING);
$promises[] = $this->MadelineProtoCombined->instances[$session]->start();
}
yield $this->MadelineProtoCombined::all($promises);
$time = round(microtime(true) - $time, 3);
$sessionsCount = count($this->sessionsFiles);

echo
"\nTelegramApiServer ready."
. "\nNumber of sessions: {$sessionsCount}."
. "\nElapsed time: {$time} sec.\n"
;
}

}
);
public function addSession($session): void
{
$settings = (array) Config::getInstance()->get('telegram');
$file = static::getSessionFile($session);
$instance = new MadelineProto\API($file, $settings);
$instance->async(true);
$instance->setEventHandler(EventHandler::class);
$this->instances[$session] = $instance;
Loop::defer(static function() use($instance) {
$instance->loop(['async' => true]);
});
}

public function removeSession($session) {
if (empty($this->instances[$session])) {
throw new \InvalidArgumentException('Instance not found');
}

$time = round(microtime(true) - $time, 3);
$sessionsCount = count($sessions);
MadelineProto\Logger::log(
"\nTelegramApiServer ready."
. "\nNumber of sessions: {$sessionsCount}."
. "\nElapsed time: {$time} sec.\n",
MadelineProto\Logger::WARNING
);
$this->instances[$session]->stop();
unset($this->instances[$session]);
}

/**
Expand All @@ -116,30 +116,23 @@ function() use ($sessions) {
*/
public function getInstance(?string $session = null): MadelineProto\API
{
if (!$this->MadelineProtoCombined->instances) {
if (!$this->instances) {
throw new \RuntimeException('No sessions available. Use combinedApi or restart server with --session option');
}

if (!$session) {
if (count($this->MadelineProtoCombined->instances) === 1) {
$session = (string) array_key_first($this->MadelineProtoCombined->instances);
if (count($this->instances) === 1) {
$session = (string) array_key_first($this->instances);
} else {
throw new \InvalidArgumentException('Multiple sessions detected. Specify which session to use. See README for examples.');
}
} else {
$session = static::getSessionFile($session);
}

if (empty($this->MadelineProtoCombined->instances[$session])) {
if (empty($this->instances[$session])) {
throw new \InvalidArgumentException('Session not found.');
}

return $this->MadelineProtoCombined->instances[$session];
}

public function getCombinedInstance(): MadelineProto\CombinedAPI
{
return $this->MadelineProtoCombined;
return $this->instances[$session];
}

}
6 changes: 3 additions & 3 deletions src/Controllers/AbstractApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
use danog\MadelineProto\TON\API as TonAPI;
use TelegramApiServer\Client;
use TelegramApiServer\MadelineProtoExtensions\ApiExtensions;
use TelegramApiServer\MadelineProtoExtensions\CombinedApiExtensions;
use TelegramApiServer\MadelineProtoExtensions\SystemApiExtensions;

abstract class AbstractApiController
{
Expand All @@ -36,7 +36,7 @@ abstract class AbstractApiController
abstract protected function resolvePath(array $path);
abstract protected function callApi();

public static function getRouterCallback($client, $extensionClass): CallableRequestHandler
public static function getRouterCallback(Client $client, $extensionClass): CallableRequestHandler
{
return new CallableRequestHandler(
static function (Request $request) use($client, $extensionClass) {
Expand Down Expand Up @@ -145,7 +145,7 @@ protected function callApiCommon($madelineProto)
{
$pathCount = count($this->api);
if ($pathCount === 1 && is_callable([$this->extensionClass,$this->api[0]])) {
/** @var ApiExtensions|CombinedApiExtensions $madelineProtoExtensions */
/** @var ApiExtensions|SystemApiExtensions $madelineProtoExtensions */
$madelineProtoExtensions = new $this->extensionClass($madelineProto);
$result = $madelineProtoExtensions->{$this->api[0]}(...$this->parameters);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@

use Amp\Promise;

class CombinedApiController extends AbstractApiController
class SystemController extends AbstractApiController
{

/**
* Получаем параметры из uri
*
Expand All @@ -24,8 +23,9 @@ protected function resolvePath(array $path): void
*/
protected function callApi()
{
$madelineProto = $this->client->getCombinedInstance();
return $this->callApiCommon($madelineProto);
$madelineProtoExtensions = new $this->extensionClass($this->client);
$result = $madelineProtoExtensions->{$this->api[0]}(...$this->parameters);
return $result;
}

}
7 changes: 4 additions & 3 deletions src/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ public static function getInstance(): Logger
{
if (!static::$instanse) {
$settings = Config::getInstance()->get('telegram');
MadelineProto\Logger::$default = null;
MadelineProto\Logger::constructorFromSettings($settings);
//MadelineProto\Logger::$default = null;
//MadelineProto\Logger::constructorFromSettings($settings);

$conversionTable = array_flip(static::$madelineLevels);
$loggerLevel = $conversionTable[$settings['logger']['logger_level']];
Expand Down Expand Up @@ -107,7 +107,8 @@ public function log($level, $message, array $context = []): void

$formatter = $this->formatter;

MadelineProto\Logger::log($formatter($level, $message, $context), static::$madelineLevels[$level]);
echo $formatter($level, $message, $context) . PHP_EOL;
//MadelineProto\Logger::log($formatter($level, $message, $context), static::$madelineLevels[$level]);
}

private function format(string $level, string $message, array $context): string
Expand Down
Loading

0 comments on commit 4058eb5

Please sign in to comment.