Apply fixes from StyleCI

This commit is contained in:
Daniil Gentili 2017-01-01 16:14:24 +00:00 committed by StyleCI Bot
parent 378dd9ac1d
commit 64aca6040b
5 changed files with 99 additions and 54 deletions

View File

@ -7,18 +7,18 @@ ini_set('error_log', '/tmp/php-Madeline-errors.log');
require 'vendor/autoload.php';
require 'db_connect.php';
$settings = [
'db' => $db_settings,
'db' => $db_settings,
'workers' => [
'serialization_interval' => 120,
'worker_sleep' => 1
'worker_sleep' => 1,
],
'token' => ['min_length' => 30, 'max_length' => 40],
'other' => [
'homedir' => '/tmp/',
'uri' => $_SERVER['REQUEST_URI'],
'params' => $_REQUEST,
'endpoint' => 'http'.($_SERVER['SERVER_PORT'] == 443 ? 's' : '').'://'.$_SERVER['HTTP_HOST'].':'.$_SERVER['SERVER_PORT'].'/',
'response_wait' => 60
'homedir' => '/tmp/',
'uri' => $_SERVER['REQUEST_URI'],
'params' => $_REQUEST,
'endpoint' => 'http'.($_SERVER['SERVER_PORT'] == 443 ? 's' : '').'://'.$_SERVER['HTTP_HOST'].':'.$_SERVER['SERVER_PORT'].'/',
'response_wait' => 60,
],
];
@ -36,7 +36,7 @@ try {
} catch (\danog\MadelineProto\RPCErrorException $e) {
echo json_encode(['ok' => false, 'error_code' => $e->getCode(), 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())]);
error_log('Exception thrown: '.$e->getMessage());
error_log($e->getTraceAsString());
error_log($e->getTraceAsString());
} catch (\danog\MadelineProto\TL\Exception $e) {
echo json_encode(['ok' => false, 'error_code' => 400, 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())]);
error_log('Exception thrown: '.$e->getMessage());

View File

@ -12,29 +12,35 @@ If not, see <http://www.gnu.org/licenses/>.
namespace danog\MadelineProto;
class WebAPI
class WebAPI
{
use \danog\MadelineProto\Worker\Worker;
use \danog\MadelineProto\Worker\WorkerTools;
use \danog\MadelineProto\Worker\Tools;
public $settings = [];
public function __construct($settings) {
public function __construct($settings)
{
$this->settings = $settings;
set_error_handler(['\danog\MadelineProto\Exception', 'ExceptionErrorHandler']);
$uri = preg_replace(["/\?.*$/", "/^\//"], '', $settings['other']['uri'], 1);
$this->token = preg_replace('/\/.*/', '', $uri);
$this->method = strtolower(preg_replace('/.*\//', '', $uri, 1));
$this->sessions_dir = $this->settings['other']['homedir'].'/sessions/';
if (!file_exists($this->sessions_dir)) mkdir($this->sessions_dir);
if (!file_exists($this->sessions_dir)) {
mkdir($this->sessions_dir);
}
foreach ($this->settings['other']['params'] as &$param) {
$new_param = json_decode($param, true);
if (is_array($new_param)) $param = $new_param;
if (is_array($new_param)) {
$param = $new_param;
}
}
}
public function run() {
public function run()
{
switch ($this->token) {
case 'new_token':
$token = '';
@ -44,14 +50,19 @@ class WebAPI
}
}
touch($this->sessions_dir.$token);
return ['ok' => true, 'result' => ['token' => $token, 'worker_status' => $this->start_worker_async($token)]];
case 'check_all_workers':
return $this->check_all_workers();
case '':
return ['ok' => false, 'error_code' => 404, 'error_description' => 'Invalid token provided'];
default:
if (!$this->check_token($this->token)) return ['ok' => false, 'error_code' => 404, 'error_description' => 'Invalid token provided'];
if (!file_exists($this->sessions_dir.$this->token)) return ['ok' => false, 'error_code' => 404, 'error_description' => 'Invalid token provided'];
if (!$this->check_token($this->token)) {
return ['ok' => false, 'error_code' => 404, 'error_description' => 'Invalid token provided'];
}
if (!file_exists($this->sessions_dir.$this->token)) {
return ['ok' => false, 'error_code' => 404, 'error_description' => 'Invalid token provided'];
}
}
switch ($this->method) {
case 'start_worker_sync':
@ -62,8 +73,9 @@ class WebAPI
case 'check_worker':
return $this->check_worker($this->token);
default:
if (!$this->check_worker($this->token)['result']['active']) throw new Exception("Worker not active");
if (!$this->check_worker($this->token)['result']['active']) {
throw new Exception('Worker not active');
}
$this->db_connect();
$insert = $this->pdo->prepare('INSERT INTO worker_jobs (worker, method, params) VALUES (?, ?, ?);');
$insert->execute([$this->token, $this->method, json_encode($this->settings['other']['params'])]);
@ -72,19 +84,27 @@ class WebAPI
while ($request_count++ < $this->settings['other']['response_wait']) {
usleep(250000);
$select = $this->pdo->prepare('SELECT response, request_id FROM worker_jobs WHERE request_id=? AND processed = ?');
$select->execute([$id, (int)true]);
$select->execute([$id, (int) true]);
$select = $select->fetchAll();
if (count($select) > 0) {
if (count($select) > 1) return ['ok' => false, 'error_code' => 400, 'error_description' => 'Got multiple responses, request id '.$id];
if ($select[0]['request_id'] != $id) return ['ok' => false, 'error_code' => 400, 'error_description' => 'Request id mismatch: got '.$select[0]['request_id'].', actual request id '.$id];
if (count($select) > 1) {
return ['ok' => false, 'error_code' => 400, 'error_description' => 'Got multiple responses, request id '.$id];
}
if ($select[0]['request_id'] != $id) {
return ['ok' => false, 'error_code' => 400, 'error_description' => 'Request id mismatch: got '.$select[0]['request_id'].', actual request id '.$id];
}
$res = json_decode($select[0]['response'], true);
if ($res === null) return ['ok' => false, 'error_code' => 400, 'error_description' => 'Result is null, request id '.$id];
$this->pdo->prepare('DELETE FROM worker_jobs WHERE request_id = ? AND processed = ?')->execute([$id, (int)true]);
if ($res === null) {
return ['ok' => false, 'error_code' => 400, 'error_description' => 'Result is null, request id '.$id];
}
$this->pdo->prepare('DELETE FROM worker_jobs WHERE request_id = ? AND processed = ?')->execute([$id, (int) true]);
return $res;
}
}
return ['ok' => false, 'error_code' => 400, 'error_description' => 'Timeout while fetching result, request id '.$id];
}
}
}
}

View File

@ -13,27 +13,34 @@ If not, see <http://www.gnu.org/licenses/>.
namespace danog\MadelineProto\Worker;
/**
* Tools for the web API and the worker
* Tools for the web API and the worker.
*/
trait Tools
{
public $base_64 = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z", "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9","_","-"];
public $base_64 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_', '-'];
public function check_token($token) {
public function check_token($token)
{
if (strlen($token) < $this->settings['token']['min_length'] || strlen($token) > $this->settings['token']['max_length']) {
return false;
}
foreach (str_split($token) as $char) {
if (!in_array($char, $this->base_64)) return false;
if (!in_array($char, $this->base_64)) {
return false;
}
}
return true;
}
public function db_connect() {
$this->pdo = new \PDO($this->settings['db']['connection'], $this->settings['db']['user'], $this->settings['db']['password'], array(\PDO::ATTR_EMULATE_PREPARES => false, \PDO::ATTR_TIMEOUT => 2, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_WARNING));
public function db_connect()
{
$this->pdo = new \PDO($this->settings['db']['connection'], $this->settings['db']['user'], $this->settings['db']['password'], [\PDO::ATTR_EMULATE_PREPARES => false, \PDO::ATTR_TIMEOUT => 2, \PDO::ATTR_ERRMODE => \PDO::ERRMODE_WARNING]);
}
public function send_buffer() {
public function send_buffer()
{
ob_flush();
flush();
}
}
}

View File

@ -13,13 +13,13 @@ If not, see <http://www.gnu.org/licenses/>.
namespace danog\MadelineProto\Worker;
/**
* worker
* worker.
*/
trait Worker
{
public $last_serialization = 0;
public function start_worker_sync($worker)
public function start_worker_sync($worker)
{
$this->db_connect();
set_time_limit(0);
@ -30,12 +30,12 @@ trait Worker
return ['ok' => false, 'error_code' => 400, "Couldn't open/lock session file"];
}
if (!$got_lock && $wouldblock) {
return ['ok' => true, 'result' => "This worker is already running"];
return ['ok' => true, 'result' => 'This worker is already running'];
}
// Deserialize contents if needed
fseek($this->lock_file, 0);
$result = stream_get_contents($this->lock_file);
if ($result !== '') {
try {
$this->MadelineProto = unserialize($result);
@ -54,7 +54,7 @@ trait Worker
*/
while (true) {
$actions = $this->pdo->prepare('SELECT * FROM worker_jobs WHERE worker = ? AND processed = ?');
$actions->execute([$worker, (int)false]);
$actions->execute([$worker, (int) false]);
$actions = $actions->fetchAll();
foreach ($actions as $action) {
$result = ['ok' => false, 'error_code' => 404, 'error_description' => 'The method '.$this->method.' does not exist'];
@ -75,7 +75,7 @@ trait Worker
$result = ['ok' => true, 'result' => $this->MadelineProto->complete_phone_login($settings['other']['params']['code'])];
break;
default:
if ($this->MadelineProto->API->methods->find_by_method($this->method) !== false) {
$result = ['ok' => true, 'result' => $this->MadelineProto->API->method_call($this->method, $settings['other']['params'])];
}
@ -91,14 +91,14 @@ trait Worker
} catch (\danog\MadelineProto\RPCErrorException $e) {
$result = ['ok' => false, 'error_code' => $e->getCode(), 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())];
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
error_log($e->getTraceAsString());
} catch (\danog\MadelineProto\TL\Exception $e) {
$result = ['ok' => false, 'error_code' => 400, 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())];
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
}
$result['req_id'] = $action;
$this->pdo->prepare('UPDATE worker_jobs SET response=?, processed=? WHERE request_id=?')->execute([json_encode($result), (int)true, $action['request_id']]);
$this->pdo->prepare('UPDATE worker_jobs SET response=?, processed=? WHERE request_id=?')->execute([json_encode($result), (int) true, $action['request_id']]);
}
try {
$this->MadelineProto->API->recv_message();
@ -107,36 +107,47 @@ trait Worker
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
} catch (\danog\MadelineProto\Exception $e) {
if (preg_match('/Wrong length was read/', $e->getMessage())) continue;
if (preg_match('/Wrong length was read/', $e->getMessage())) {
continue;
}
echo json_encode(['ok' => false, 'error_code' => 400, 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())]);
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
} catch (\danog\MadelineProto\RPCErrorException $e) {
echo json_encode(['ok' => false, 'error_code' => $e->getCode(), 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())]);
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
error_log($e->getTraceAsString());
} catch (\danog\MadelineProto\TL\Exception $e) {
echo json_encode(['ok' => false, 'error_code' => 400, 'error_description' => $e->getMessage().' on line '.$e->getLine().' of '.basename($e->getFile())]);
error_log('Exception thrown in worker '.$worker.': '.$e->getMessage());
error_log($e->getTraceAsString());
}
$this->serialize_worker();
if (empty($actions)) usleep(250000);
if ($stop) break;
if (empty($actions)) {
usleep(250000);
}
if ($stop) {
break;
}
}
flock($this->lock_file, LOCK_UN);
fclose($this->lock_file);
return ['ok' => true, 'result' => 'Worker stopped successfully!'];
}
public function serialize_worker() {
if (time() - $this->last_serialization < $this->settings['workers']['serialization_interval']) return false;
public function serialize_worker()
{
if (time() - $this->last_serialization < $this->settings['workers']['serialization_interval']) {
return false;
}
ftruncate($this->lock_file, 0);
rewind($this->lock_file);
$serialized = serialize($this->MadelineProto);
fwrite($this->lock_file, $serialized);
$this->last_serialization = time();
return true;
}
}
}

View File

@ -13,17 +13,21 @@ If not, see <http://www.gnu.org/licenses/>.
namespace danog\MadelineProto\Worker;
/**
* Tools for the worker
* Tools for the worker.
*/
trait WorkerTools
{
public function check_all_workers() {
public function check_all_workers()
{
$result = ['ok' => true, 'result' => []];
foreach (glob($this->sessions_dir.'*') as $session) {
if (stripos($session, '.log') !== false) continue;
if (stripos($session, '.log') !== false) {
continue;
}
$session = basename($session);
$result['result'][] = $this->check_worker($session);
}
return $result;
}
@ -31,10 +35,12 @@ trait WorkerTools
{
shell_exec('curl '.escapeshellarg($this->settings['other']['endpoint'].$worker.'/start_worker_sync').' > /dev/null 2> /dev/null & ');
sleep(30);
return $this->check_worker($worker, $recursive);
}
public function check_worker($worker, $recursive = true) {
public function check_worker($worker, $recursive = true)
{
$this->lock_file = fopen($this->sessions_dir.$worker, 'c+');
$got_lock = flock($this->lock_file, LOCK_EX | LOCK_NB, $wouldblock);
if ($this->lock_file === false || (!$got_lock && !$wouldblock)) {
@ -46,6 +52,7 @@ trait WorkerTools
if ($recursive) { // If worker is turned off and $recursive
return $this->start_worker_async($worker, false);
}
return ['ok' => true, 'result' => ['active' => false]];
}
}
}