From be5d7e27495fbde023a0c62d816ba1e8997653c6 Mon Sep 17 00:00:00 2001 From: Alexander Pankratov Date: Thu, 25 Jun 2020 01:33:18 +0300 Subject: [PATCH] Ability to redefine env file path --- .env.docker.example | 10 ++++---- .env.example | 10 ++++---- Dockerfile | 2 +- README.md | 25 +++++++++++++------ bootstrap.php | 12 +++++---- server.php | 19 ++++++++------ .../SystemApiExtensions.php | 6 ++--- 7 files changed, 51 insertions(+), 33 deletions(-) diff --git a/.env.docker.example b/.env.docker.example index 537fb3c..c70e043 100644 --- a/.env.docker.example +++ b/.env.docker.example @@ -37,12 +37,12 @@ TELEGRAM_PROXY_PASSWORD= # Change this type to convert session: DB_TYPE=mysql # MYSQL Settings. Required, when DB_TYPE=mysql -MYSQL_HOST='mysql' +MYSQL_HOST=mysql MYSQL_PORT=3306 -MYSQL_USER='root' -MYSQL_PASSWORD='' -MYSQL_DATABASE='MadelineProto' +MYSQL_USER=root +MYSQL_PASSWORD= +MYSQL_DATABASE=MadelineProto MYSQL_MAX_CONNECTIONS=10 MYSQL_IDLE_TIMEOUT=60 # Recent data will be stored in memory this amount of time: -MYSQL_CACHE_TTL='+5 minutes' \ No newline at end of file +MYSQL_CACHE_TTL="+5 minutes" \ No newline at end of file diff --git a/.env.example b/.env.example index 2f3c343..20beeb5 100644 --- a/.env.example +++ b/.env.example @@ -37,12 +37,12 @@ TELEGRAM_PROXY_PASSWORD= # Change this type to convert session: DB_TYPE=memory # MYSQL Settings. Required, when DB_TYPE=mysql -MYSQL_HOST='127.0.0.1' +MYSQL_HOST=127.0.0.1 MYSQL_PORT=3306 -MYSQL_USER='root' -MYSQL_PASSWORD='' -MYSQL_DATABASE='MadelineProto' +MYSQL_USER=root +MYSQL_PASSWORD= +MYSQL_DATABASE=MadelineProto MYSQL_MAX_CONNECTIONS=10 MYSQL_IDLE_TIMEOUT=60 # Recent data will be stored in memory this amount of time: -MYSQL_CACHE_TTL='+5 minutes' \ No newline at end of file +MYSQL_CACHE_TTL="+5 minutes" \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 6f0e602..b8a6593 100644 --- a/Dockerfile +++ b/Dockerfile @@ -27,4 +27,4 @@ RUN touch '/app/sessions/.env.docker' && \ EXPOSE 9503 -ENTRYPOINT docker-compose-wait && php server.php --docker -s=* \ No newline at end of file +ENTRYPOINT docker-compose-wait && php server.php -e=.env.docker --docker -s=* \ No newline at end of file diff --git a/README.md b/README.md index 49dea6a..3803136 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ Fast, simple, async php telegram api server: 1. Run server/parser ``` - usage: php server.php [--help] [-a=|--address=127.0.0.1] [-p=|--port=9503] [-s=|--session=] + usage: php server.php [--help] [-a=|--address=127.0.0.1] [-p=|--port=9503] [-s=|--session=] [-e=|--env=.env] [--docker] Options: --help Show this message @@ -70,11 +70,16 @@ Fast, simple, async php telegram api server: -s --session Name for session file (optional) Multiple sessions can be specified: "--session=user --session=bot" - Each session is stored in `sessions/%session%.madeline`. + Each session is stored in `sessions/{$session}.madeline`. Nested folders supported. See README for more examples. - - Also options can be set in .env file (see .env.example) + + -e --env .env file name. (default: .env). + Helpful when need multiple instances with different settings + + --docker Apply some settings for docker: add docker network to whitelist. + + Also some options can be set in .env file (see .env.example) ``` 1. Access Telegram API with simple GET/POST requests. @@ -206,7 +211,7 @@ curl --location --request POST '127.0.0.1:9503/api/downloadToResponse' \ Also see: https://docs.madelineproto.xyz/docs/FILES.html#downloading-files -### Multiple sessions support. +### Multiple sessions support When running multiple sessions, need to define which session to use for request. Each session stored in `sessions/{$session}.madeline`. Nested folders supported. @@ -220,6 +225,12 @@ Each session stored in `sessions/{$session}.madeline`. Nested folders supported. * `--session=*` to use all `sessions/*.madeline` files (in subfolders too). * `--session=users/* --session=bots/*` to use all session files from `sessions/bots` and `sessions/users` folders. +### Different settings for sessions +Use `--env` argument to define the relative path to env file. +Example: ```php server.php --env=.env```, ```php server.php --env=sessions/.env.session``` +This is helpful to define unique settings for different instances of TelegramApiServer. +You can start multiple instances of TelegramApiServer with different sessions on different ports with their own settings. + ### Session management **Examples:** @@ -227,8 +238,8 @@ Each session stored in `sessions/{$session}.madeline`. Nested folders supported. * Adding session: `http://127.0.0.1:9503/system/addSession?session=users/xtrime` * [optional] Adding session with custom settings: `http://127.0.0.1:9503/system/addSession?session=users/xtrime&settings[app_info][app_id]=xxx&&settings[app_info][app_hash]=xxx` * Removing session (session file will remain): `http://127.0.0.1:9503/system/removeSession?session=users/xtrime` -* Remove session file: `http://127.0.0.1:9503/system/removeSessionFile?session=users/xtrime` - Don`t forget to logout first! +* Remove session file: `http://127.0.0.1:9503/system/unlinkSessionFile?session=users/xtrime` + Don`t forget to logout and call removeSession first! If there is no authorization in session, or session file is blank, authorization required: diff --git a/bootstrap.php b/bootstrap.php index 15eeeea..136b96b 100644 --- a/bootstrap.php +++ b/bootstrap.php @@ -23,15 +23,17 @@ const ENV_VERSION='1'; //Config init { if (!getenv('SERVER_ADDRESS')) { - $envFile = '.env'; - if ($options['docker']) { - $envFile .= '.docker'; + $envFile = $options['env']; + if (empty($envFile)) { + throw new InvalidArgumentException('Env file not defined'); } - $envPath = ROOT_DIR . '/' . $envFile; $envPathExample = $envPath . '.example'; if (!is_file($envPath) || filesize($envPath) === 0) { + if (!is_file($envPathExample) || filesize($envPathExample) === 0) { + throw new InvalidArgumentException("Env files not found or empty: {$envPath}, {$envPathExample}"); + } //Dont use copy because of docker symlinks $envContent = file_get_contents($envPathExample); file_put_contents($envPath, $envContent); @@ -40,7 +42,7 @@ const ENV_VERSION='1'; Dotenv\Dotenv::createImmutable(ROOT_DIR, $envFile)->load(); if (getenv('VERSION') !== ENV_VERSION) { - Logger::getInstance()->critical('Env version mismatch. Update .env from .env.example.', [ + Logger::getInstance()->critical("Env version mismatch. Update {$envPath} from {$envPathExample}", [ 'VERSION in .env' => getenv('VERSION'), 'required' => ENV_VERSION ]); diff --git a/server.php b/server.php index a2f10df..1295871 100644 --- a/server.php +++ b/server.php @@ -8,12 +8,13 @@ if (PHP_SAPI !== 'cli') { throw new RuntimeException('Start in CLI'); } -$shortopts = 'a::p::s::'; +$shortopts = 'a::p::s::e::'; $longopts = [ - 'address::', // ip адресс сервера, необязательное значение - 'port::', // порт сервера, необязательное значение + 'address::', // ip адресс сервера + 'port::', // порт сервера 'session::', //префикс session файла - 'docker::', //сгенерировать docker-совместимый .env + 'env::', //путь до .env файла + 'docker::', //включить настройки для запуска внутри docker 'help', //нужна ли справка? ]; $options = getopt($shortopts, $longopts); @@ -21,6 +22,7 @@ $options = [ 'address' => $options['address'] ?? $options['a'] ?? '', 'port' => $options['port'] ?? $options['p'] ?? '', 'session' => (array) ($options['session'] ?? $options['s'] ?? []), + 'env' => $options['env'] ?? $options['e'] ?? '.env', 'docker' => isset($options['docker']), 'help' => isset($options['help']), ]; @@ -28,7 +30,7 @@ $options = [ if ($options['help']) { $help = 'Fast, simple, async php telegram parser: MadelineProto + Swoole Server -usage: php server.php [--help] [-a=|--address=127.0.0.1] [-p=|--port=9503] [-s=|--session=] +usage: php server.php [--help] [-a=|--address=127.0.0.1] [-p=|--port=9503] [-s=|--session=] [-e=|--env=.env] [--docker] Options: --help Show this message @@ -45,9 +47,12 @@ Options: Nested folders supported. See README for more examples. - --docker Modify/Generate Docker compatible .env at first run + -e --env .env file name. (default: .env). + Helpful when need multiple instances with different settings + + --docker Apply some settings for docker: add docker network to whitelist. -Also all options can be set in .env file (see .env.example) +Also some options can be set in .env file (see .env.example) Example: php server.php diff --git a/src/MadelineProtoExtensions/SystemApiExtensions.php b/src/MadelineProtoExtensions/SystemApiExtensions.php index 3151d52..1d4e1ce 100644 --- a/src/MadelineProtoExtensions/SystemApiExtensions.php +++ b/src/MadelineProtoExtensions/SystemApiExtensions.php @@ -2,7 +2,6 @@ namespace TelegramApiServer\MadelineProtoExtensions; -use Amp\Delayed; use Amp\Promise; use danog\MadelineProto; use danog\MadelineProto\MTProto; @@ -32,6 +31,7 @@ class SystemApiExtensions !Client::isSessionLoggedIn($instance) ) { $this->removeSession($session); + $this->unlinkSessionFile($session); throw new \RuntimeException('No api_id or api_hash provided'); } yield $this->client->startLoggedInSession($session); @@ -88,7 +88,7 @@ class SystemApiExtensions ]; } - public function removeSessionFile($session) + public function unlinkSessionFile($session): Promise { return call(static function() use($session) { $file = Files::getSessionFile($session); @@ -99,7 +99,7 @@ class SystemApiExtensions }); } - private function bytesToHuman($bytes) + private function bytesToHuman($bytes): string { $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; for ($i = 0; $bytes > 1024; $i++) {