Ability to redefine env file path

This commit is contained in:
Alexander Pankratov 2020-06-25 01:33:18 +03:00
parent 3c6d7e0184
commit be5d7e2749
7 changed files with 51 additions and 33 deletions

View File

@ -37,12 +37,12 @@ TELEGRAM_PROXY_PASSWORD=
# Change this type to convert session: # Change this type to convert session:
DB_TYPE=mysql DB_TYPE=mysql
# MYSQL Settings. Required, when DB_TYPE=mysql # MYSQL Settings. Required, when DB_TYPE=mysql
MYSQL_HOST='mysql' MYSQL_HOST=mysql
MYSQL_PORT=3306 MYSQL_PORT=3306
MYSQL_USER='root' MYSQL_USER=root
MYSQL_PASSWORD='' MYSQL_PASSWORD=
MYSQL_DATABASE='MadelineProto' MYSQL_DATABASE=MadelineProto
MYSQL_MAX_CONNECTIONS=10 MYSQL_MAX_CONNECTIONS=10
MYSQL_IDLE_TIMEOUT=60 MYSQL_IDLE_TIMEOUT=60
# Recent data will be stored in memory this amount of time: # Recent data will be stored in memory this amount of time:
MYSQL_CACHE_TTL='+5 minutes' MYSQL_CACHE_TTL="+5 minutes"

View File

@ -37,12 +37,12 @@ TELEGRAM_PROXY_PASSWORD=
# Change this type to convert session: # Change this type to convert session:
DB_TYPE=memory DB_TYPE=memory
# MYSQL Settings. Required, when DB_TYPE=mysql # MYSQL Settings. Required, when DB_TYPE=mysql
MYSQL_HOST='127.0.0.1' MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306 MYSQL_PORT=3306
MYSQL_USER='root' MYSQL_USER=root
MYSQL_PASSWORD='' MYSQL_PASSWORD=
MYSQL_DATABASE='MadelineProto' MYSQL_DATABASE=MadelineProto
MYSQL_MAX_CONNECTIONS=10 MYSQL_MAX_CONNECTIONS=10
MYSQL_IDLE_TIMEOUT=60 MYSQL_IDLE_TIMEOUT=60
# Recent data will be stored in memory this amount of time: # Recent data will be stored in memory this amount of time:
MYSQL_CACHE_TTL='+5 minutes' MYSQL_CACHE_TTL="+5 minutes"

View File

@ -27,4 +27,4 @@ RUN touch '/app/sessions/.env.docker' && \
EXPOSE 9503 EXPOSE 9503
ENTRYPOINT docker-compose-wait && php server.php --docker -s=* ENTRYPOINT docker-compose-wait && php server.php -e=.env.docker --docker -s=*

View File

@ -57,7 +57,7 @@ Fast, simple, async php telegram api server:
1. Run server/parser 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: Options:
--help Show this message --help Show this message
@ -70,11 +70,16 @@ Fast, simple, async php telegram api server:
-s --session Name for session file (optional) -s --session Name for session file (optional)
Multiple sessions can be specified: "--session=user --session=bot" 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. Nested folders supported.
See README for more examples. 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. 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 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. When running multiple sessions, need to define which session to use for request.
Each session stored in `sessions/{$session}.madeline`. Nested folders supported. 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=*` 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. * `--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 ### Session management
**Examples:** **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` * 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` * [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` * 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` * Remove session file: `http://127.0.0.1:9503/system/unlinkSessionFile?session=users/xtrime`
Don`t forget to logout first! Don`t forget to logout and call removeSession first!
If there is no authorization in session, or session file is blank, authorization required: If there is no authorization in session, or session file is blank, authorization required:

View File

@ -23,15 +23,17 @@ const ENV_VERSION='1';
//Config init //Config init
{ {
if (!getenv('SERVER_ADDRESS')) { if (!getenv('SERVER_ADDRESS')) {
$envFile = '.env'; $envFile = $options['env'];
if ($options['docker']) { if (empty($envFile)) {
$envFile .= '.docker'; throw new InvalidArgumentException('Env file not defined');
} }
$envPath = ROOT_DIR . '/' . $envFile; $envPath = ROOT_DIR . '/' . $envFile;
$envPathExample = $envPath . '.example'; $envPathExample = $envPath . '.example';
if (!is_file($envPath) || filesize($envPath) === 0) { 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 //Dont use copy because of docker symlinks
$envContent = file_get_contents($envPathExample); $envContent = file_get_contents($envPathExample);
file_put_contents($envPath, $envContent); file_put_contents($envPath, $envContent);
@ -40,7 +42,7 @@ const ENV_VERSION='1';
Dotenv\Dotenv::createImmutable(ROOT_DIR, $envFile)->load(); Dotenv\Dotenv::createImmutable(ROOT_DIR, $envFile)->load();
if (getenv('VERSION') !== ENV_VERSION) { 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'), 'VERSION in .env' => getenv('VERSION'),
'required' => ENV_VERSION 'required' => ENV_VERSION
]); ]);

View File

@ -8,12 +8,13 @@ if (PHP_SAPI !== 'cli') {
throw new RuntimeException('Start in CLI'); throw new RuntimeException('Start in CLI');
} }
$shortopts = 'a::p::s::'; $shortopts = 'a::p::s::e::';
$longopts = [ $longopts = [
'address::', // ip адресс сервера, необязательное значение 'address::', // ip адресс сервера
'port::', // порт сервера, необязательное значение 'port::', // порт сервера
'session::', //префикс session файла 'session::', //префикс session файла
'docker::', //сгенерировать docker-совместимый .env 'env::', //путь до .env файла
'docker::', //включить настройки для запуска внутри docker
'help', //нужна ли справка? 'help', //нужна ли справка?
]; ];
$options = getopt($shortopts, $longopts); $options = getopt($shortopts, $longopts);
@ -21,6 +22,7 @@ $options = [
'address' => $options['address'] ?? $options['a'] ?? '', 'address' => $options['address'] ?? $options['a'] ?? '',
'port' => $options['port'] ?? $options['p'] ?? '', 'port' => $options['port'] ?? $options['p'] ?? '',
'session' => (array) ($options['session'] ?? $options['s'] ?? []), 'session' => (array) ($options['session'] ?? $options['s'] ?? []),
'env' => $options['env'] ?? $options['e'] ?? '.env',
'docker' => isset($options['docker']), 'docker' => isset($options['docker']),
'help' => isset($options['help']), 'help' => isset($options['help']),
]; ];
@ -28,7 +30,7 @@ $options = [
if ($options['help']) { if ($options['help']) {
$help = 'Fast, simple, async php telegram parser: MadelineProto + Swoole Server $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: Options:
--help Show this message --help Show this message
@ -45,9 +47,12 @@ Options:
Nested folders supported. Nested folders supported.
See README for more examples. 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
Also all options can be set in .env file (see .env.example) --docker Apply some settings for docker: add docker network to whitelist.
Also some options can be set in .env file (see .env.example)
Example: Example:
php server.php php server.php

View File

@ -2,7 +2,6 @@
namespace TelegramApiServer\MadelineProtoExtensions; namespace TelegramApiServer\MadelineProtoExtensions;
use Amp\Delayed;
use Amp\Promise; use Amp\Promise;
use danog\MadelineProto; use danog\MadelineProto;
use danog\MadelineProto\MTProto; use danog\MadelineProto\MTProto;
@ -32,6 +31,7 @@ class SystemApiExtensions
!Client::isSessionLoggedIn($instance) !Client::isSessionLoggedIn($instance)
) { ) {
$this->removeSession($session); $this->removeSession($session);
$this->unlinkSessionFile($session);
throw new \RuntimeException('No api_id or api_hash provided'); throw new \RuntimeException('No api_id or api_hash provided');
} }
yield $this->client->startLoggedInSession($session); 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) { return call(static function() use($session) {
$file = Files::getSessionFile($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']; $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
for ($i = 0; $bytes > 1024; $i++) { for ($i = 0; $bytes > 1024; $i++) {