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:
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'
MYSQL_CACHE_TTL="+5 minutes"

View File

@ -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'
MYSQL_CACHE_TTL="+5 minutes"

View File

@ -27,4 +27,4 @@ RUN touch '/app/sessions/.env.docker' && \
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
```
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:

View File

@ -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
]);

View File

@ -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
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:
php server.php

View File

@ -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++) {