Added first alpha of web version and fixed bugs

This commit is contained in:
danogentili 2017-01-01 17:13:59 +03:00
parent 2f8149c4d9
commit 378dd9ac1d
7 changed files with 428 additions and 0 deletions

3
dummy_db_connect.php Normal file
View File

@ -0,0 +1,3 @@
<?php
$db_settings = ['connection' => 'mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=MadelineProto', 'user' => 'user', 'password' => 'password'];

48
index.php Normal file
View File

@ -0,0 +1,48 @@
<?php
ini_set('log_errors', 1);
ini_set('error_log', '/tmp/php-Madeline-errors.log');
require 'vendor/autoload.php';
require 'db_connect.php';
$settings = [
'db' => $db_settings,
'workers' => [
'serialization_interval' => 120,
'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
],
];
try {
$web_API = new \danog\MadelineProto\WebAPI($settings);
echo json_encode($web_API->run());
} catch (\danog\MadelineProto\ResponseException $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());
error_log($e->getTraceAsString());
} catch (\danog\MadelineProto\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());
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: '.$e->getMessage());
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());
error_log($e->getTraceAsString());
} catch (\PDOException $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());
error_log($e->getTraceAsString());
}

View File

@ -0,0 +1,90 @@
<?php
/*
Copyright 2016 Daniil Gentili
(https://daniil.it)
This file is part of MadelineProto.
MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License along with MadelineProto.
If not, see <http://www.gnu.org/licenses/>.
*/
namespace danog\MadelineProto;
class WebAPI
{
use \danog\MadelineProto\Worker\Worker;
use \danog\MadelineProto\Worker\WorkerTools;
use \danog\MadelineProto\Worker\Tools;
public $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);
foreach ($this->settings['other']['params'] as &$param) {
$new_param = json_decode($param, true);
if (is_array($new_param)) $param = $new_param;
}
}
public function run() {
switch ($this->token) {
case 'new_token':
$token = '';
while ($token === '' || file_exists($this->sessions_dir.$token)) {
for ($len = 0; $len < rand($this->settings['token']['min_length'], $this->settings['token']['min_length']); $len++) {
$token .= $this->base_64[rand(0, 63)];
}
}
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'];
}
switch ($this->method) {
case 'start_worker_sync':
return $this->start_worker_sync($this->token);
case 'start_worker':
case 'start_worker_async':
return $this->start_worker_async($this->token);
case 'check_worker':
return $this->check_worker($this->token);
default:
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'])]);
$id = $this->pdo->lastInsertId();
$request_count = 0;
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 = $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];
$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]);
return $res;
}
}
return ['ok' => false, 'error_code' => 400, 'error_description' => 'Timeout while fetching result, request id '.$id];
}
}
}

View File

@ -0,0 +1,39 @@
<?php
/*
Copyright 2016 Daniil Gentili
(https://daniil.it)
This file is part of MadelineProto.
MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License along with MadelineProto.
If not, see <http://www.gnu.org/licenses/>.
*/
namespace danog\MadelineProto\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 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;
}
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 send_buffer() {
ob_flush();
flush();
}
}

View File

@ -0,0 +1,142 @@
<?php
/*
Copyright 2016 Daniil Gentili
(https://daniil.it)
This file is part of MadelineProto.
MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License along with MadelineProto.
If not, see <http://www.gnu.org/licenses/>.
*/
namespace danog\MadelineProto\Worker;
/**
* worker
*/
trait Worker
{
public $last_serialization = 0;
public function start_worker_sync($worker)
{
$this->db_connect();
set_time_limit(0);
ignore_user_abort(1);
$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)) {
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"];
}
// Deserialize contents if needed
fseek($this->lock_file, 0);
$result = stream_get_contents($this->lock_file);
if ($result !== '') {
try {
$this->MadelineProto = unserialize($result);
} catch (\danog\MadelineProto\Exception $e) {
error_log('An error occurred while deserializing '.$worker);
$this->MadelineProto = new \danog\MadelineProto\API(['logger' => ['logger' => 2, 'logger_param' => $this->sessions_dir.$worker.'.log']]);
}
} else {
$this->MadelineProto = new \danog\MadelineProto\API(['logger' => ['logger' => 2, 'logger_param' => $this->sessions_dir.$worker.'.log']]);
}
$this->serialize_worker();
$stop = false;
/*
echo json_encode(['ok' => true, 'result' => 'Worker started successfully!']);
*/
while (true) {
$actions = $this->pdo->prepare('SELECT * FROM worker_jobs WHERE worker = ? AND processed = ?');
$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'];
$params = json_decode($action['params']);
try {
switch ($action['method']) {
case 'stop_worker':
$stop = true;
$result = ['ok' => true, 'result' => 'Worker stopped'];
break;
case 'bot_login':
$result = ['ok' => true, 'result' => $this->MadelineProto->bot_login($settings['other']['params']['token'])];
break;
case 'phone_login':
$result = ['ok' => true, 'result' => $this->MadelineProto->phone_login($settings['other']['params']['number'])];
break;
case 'complete_phone_login':
$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'])];
}
}
} catch (\danog\MadelineProto\ResponseException $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());
} catch (\danog\MadelineProto\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());
} 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());
} 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']]);
}
try {
$this->MadelineProto->API->recv_message();
} catch (\danog\MadelineProto\ResponseException $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());
} catch (\danog\MadelineProto\Exception $e) {
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());
} 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;
}
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;
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

@ -0,0 +1,51 @@
<?php
/*
Copyright 2016 Daniil Gentili
(https://daniil.it)
This file is part of MadelineProto.
MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License along with MadelineProto.
If not, see <http://www.gnu.org/licenses/>.
*/
namespace danog\MadelineProto\Worker;
/**
* Tools for the worker
*/
trait WorkerTools
{
public function check_all_workers() {
$result = ['ok' => true, 'result' => []];
foreach (glob($this->sessions_dir.'*') as $session) {
if (stripos($session, '.log') !== false) continue;
$session = basename($session);
$result['result'][] = $this->check_worker($session);
}
return $result;
}
public function start_worker_async($worker, $recursive = true)
{
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) {
$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)) {
return ['ok' => false, 'error_code' => 400, "Couldn't open/lock session file"];
}
if (!$got_lock && $wouldblock) {
return ['ok' => true, 'result' => ['active' => true]];
}
if ($recursive) { // If worker is turned off and $recursive
return $this->start_worker_async($worker, false);
}
return ['ok' => true, 'result' => ['active' => false]];
}
}

55
web_api.sql Normal file
View File

@ -0,0 +1,55 @@
-- MySQL dump 10.13 Distrib 5.7.16, for Linux (x86_64)
--
-- Host: localhost Database: MadelineProto
-- ------------------------------------------------------
-- Server version 5.7.16-0ubuntu0.16.04.1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `worker_jobs`
--
DROP TABLE IF EXISTS `worker_jobs`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `worker_jobs` (
`worker` varchar(255) NOT NULL,
`method` text NOT NULL,
`params` longtext NOT NULL,
`response` longtext,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`request_id` int(11) NOT NULL AUTO_INCREMENT,
`processed` tinyint(1) DEFAULT '0',
PRIMARY KEY (`request_id`)
) ENGINE=InnoDB AUTO_INCREMENT=112 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `worker_jobs`
--
LOCK TABLES `worker_jobs` WRITE;
/*!40000 ALTER TABLE `worker_jobs` DISABLE KEYS */;
/*!40000 ALTER TABLE `worker_jobs` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2017-01-01 17:05:27