Code Style

This commit is contained in:
Alexander Pankratov 2019-03-19 02:36:20 +03:00
parent d0c4a19139
commit b6d12bead9
7 changed files with 196 additions and 185 deletions

View File

@ -9,6 +9,6 @@ if (!class_exists('TelegramSwooleClient')) {
chdir($root);
}
//Check if root env file hash been loaded (in case plugin installed in existing project)
if (!getenv('SWOOLE_SERVER_ADDRESS')){
if (!getenv('SWOOLE_SERVER_ADDRESS')) {
(new Dotenv\Dotenv($root))->load();
}

View File

@ -3,12 +3,12 @@
return [
'swoole' => [
'server' => [
'address' => (string) getenv('SWOOLE_SERVER_ADDRESS'),
'port' => (string) getenv('SWOOLE_SERVER_PORT'),
'address' => (string)getenv('SWOOLE_SERVER_ADDRESS'),
'port' => (string)getenv('SWOOLE_SERVER_PORT'),
],
'options'=> [
'worker_num' => (int) getenv('SWOOLE_WORKER_NUM'),
'http_compression' => (bool) getenv('SWOOLE_HTTP_COMPRESSION'),
'options' => [
'worker_num' => (int)getenv('SWOOLE_WORKER_NUM'),
'http_compression' => (bool)getenv('SWOOLE_HTTP_COMPRESSION'),
]
],
'telegram' => [
@ -45,7 +45,7 @@ return [
]
],
'api' => [
'ip_whitelist' => json_decode(getenv('API_CLIENT_WHITELIST'),true),
'ip_whitelist' => json_decode(getenv('API_CLIENT_WHITELIST'), true),
'index_message' => getenv('API_INDEX_MESSAGE'),
],
];

View File

@ -2,12 +2,14 @@
namespace TelegramSwooleClient;
use \danog\MadelineProto;
use danog\MadelineProto;
class Client {
class Client
{
public $MadelineProto;
private $sessionFile;
/**
* Client constructor.
*/
@ -23,7 +25,8 @@ class Client {
$this->connect();
}
public function connect() {
public function connect()
{
//При каждой инициализации настройки обновляются из массива $config
echo PHP_EOL . 'Starting telegram client ...' . PHP_EOL;
$time = microtime(true);
@ -80,25 +83,26 @@ class Client {
* </pre>
* @return array
*/
public function copyMessages($data):array {
public function copyMessages($data): array
{
$data = array_merge([
'from_peer' => '',
'to_peer' => '',
'id' => [],
],$data);
], $data);
$response = $this->MadelineProto->channels->getMessages([
'channel' => $data['from_peer'],
'id' => $data['id'],
]);
$result = [];
if (!$response || !is_array($response) || !array_key_exists('messages', $response)){
if (!$response || !is_array($response) || !array_key_exists('messages', $response)) {
return $result;
}
foreach ($response['messages'] as $message) {
usleep(mt_rand(300,2000)*1000);
usleep(mt_rand(300, 2000) * 1000);
$messageData = [
'message' => $message['message'] ?? '',
'peer' => $data['to_peer'],
@ -137,7 +141,7 @@ class Client {
'offset_id' => 0,
'offset_date' => 0,
'limit' => 10,
],$data);
], $data);
return $this->MadelineProto->messages->searchGlobal($data);
}
@ -199,13 +203,14 @@ class Client {
* @param $data
* @return array
*/
public function getMedia($data) {
public function getMedia($data)
{
$data = array_merge([
'channel' =>'',
'channel' => '',
'id' => [0],
'message' => [],
'size_limit' => 0,
],$data);
], $data);
if (!$data['message']) {
@ -233,9 +238,9 @@ class Client {
$this->MadelineProto->download_to_file($message, $file);
return [
'headers'=> [
['Content-Length',$info['size']],
['Content-Type',$info['mime']]
'headers' => [
['Content-Length', $info['size']],
['Content-Type', $info['mime']]
],
'file' => $file,
];
@ -248,12 +253,13 @@ class Client {
* @param array $data
* @return array
*/
public function getMediaPreview(array $data){
public function getMediaPreview(array $data)
{
$data = array_merge([
'channel' =>'',
'channel' => '',
'id' => [0],
'message' => [],
],$data);
], $data);
if (!$data['message']) {
$response = $this->MadelineProto->channels->getMessages($data);
@ -289,7 +295,7 @@ class Client {
$this->MadelineProto->download_to_file($thumb, $file);
return [
'headers'=> [
'headers' => [
['Content-Length', $info['size']],
['Content-Type', $info['mime']],
],
@ -302,12 +308,13 @@ class Client {
* @param array $message
* @return bool
*/
private static function hasMedia($message = [], $useWebPage = true){
private static function hasMedia($message = [], $useWebPage = true)
{
$media = $message['media'] ?? [];
if (empty($media['_'])) {
return false;
}
if ($media['_'] == 'messageMediaWebPage'){
if ($media['_'] == 'messageMediaWebPage') {
return $useWebPage;
}
return true;

View File

@ -50,17 +50,19 @@ class Config
* @param null $default
* @return mixed|null
*/
public function get($key = '', $default = null) {
public function get($key = '', $default = null)
{
return $this->findByKey($key) ?? $default;
}
private function findByKey($key) {
$key = (string) $key;
private function findByKey($key)
{
$key = (string)$key;
$path = explode('.', $key);
$value = &$this->config;
foreach($path as $pathKey) {
if (!is_array($value) || !array_key_exists($pathKey,$value)) {
foreach ($path as $pathKey) {
if (!is_array($value) || !array_key_exists($pathKey, $value)) {
return;
}
$value = &$value[$pathKey];

View File

@ -35,8 +35,8 @@ class RequestCallback
*/
public function __construct(\Swoole\Http\Request $request, \Swoole\Http\Response $response, Client $client, $http_server)
{
$this->ipWhiteList = (array) Config::getInstance()->get('api.ip_whitelist', []);
$this->indexMessage = (string) Config::getInstance()->get('api.index_message', 'Welcome to telegram client!');
$this->ipWhiteList = (array)Config::getInstance()->get('api.ip_whitelist', []);
$this->indexMessage = (string)Config::getInstance()->get('api.index_message', 'Welcome to telegram client!');
$this->client = $client;
$this->server = $http_server;
$this->parsePost($request)
@ -63,7 +63,7 @@ class RequestCallback
$this->path = array_values(array_filter(explode('/', $uri)));
if (!$this->path || $this->path[0] !== 'api') {
$this->page['response'] = $this->indexMessage;
} elseif (!in_array($this->path[0],self::PAGES, true)) {
} elseif (!in_array($this->path[0], self::PAGES, true)) {
$this->setPageCode(404);
$this->page['errors'][] = 'Incorrect path';
}
@ -76,7 +76,8 @@ class RequestCallback
* @param array $post
* @return RequestCallback
*/
private function resolveRequest(array $get, array $post):self {
private function resolveRequest(array $get, array $post): self
{
$this->parameters = array_values(array_merge($get, $post));
$this->api = $this->path[1] ?? '';
return $this;
@ -103,18 +104,19 @@ class RequestCallback
return $this;
}
private function callApi(\Swoole\Http\Request $request){
private function callApi(\Swoole\Http\Request $request)
{
if (!in_array($request->server['remote_addr'], $this->ipWhiteList, true)) {
throw new \Exception('API not available');
}
if (method_exists($this->client,$this->api)){
if (method_exists($this->client, $this->api)) {
return $this->client->{$this->api}(...$this->parameters);
}
//Проверяем нет ли в MadilineProto такого метода.
$this->api = explode('.', $this->api);
switch (count($this->api)){
switch (count($this->api)) {
case 1:
return $this->client->MadelineProto->{$this->api[0]}(...$this->parameters);
break;
@ -133,8 +135,9 @@ class RequestCallback
* @param \Throwable $e
* @return RequestCallback
*/
private function setError(\Throwable $e):self {
if ($e instanceof \Error){
private function setError(\Throwable $e): self
{
if ($e instanceof \Error) {
//Это критическая ошибка соедниения. Необходим полный перезапуск.
$this->setPageCode(400);
$this->page['errors'][] = [

View File

@ -23,8 +23,7 @@ class Server
$http_server->set($this->config['options']);
$http_server->on('request', function(\Swoole\Http\Request $request, \Swoole\Http\Response $response) use($client, $http_server)
{
$http_server->on('request', function (\Swoole\Http\Request $request, \Swoole\Http\Response $response) use ($client, $http_server) {
//На каждый запрос должны создаваться новые экземпляры классов парсера и коллбеков,
//иначе их данные будут в области видимости всех запросов.
@ -44,10 +43,10 @@ class Server
private function setConfig(array $config = []): self
{
$config = [
'server'=> array_filter($config)
'server' => array_filter($config)
];
foreach (['server','options'] as $key) {
foreach (['server', 'options'] as $key) {
$this->config[$key] = array_merge(
Config::getInstance()->get("swoole.{$key}", []),
$config[$key] ?? []