cron: vk sms checker

This commit is contained in:
Evgeny Zinoviev 2022-05-26 03:14:50 +03:00
parent 997c6da6c4
commit c3ed2483ea
9 changed files with 187 additions and 4 deletions

3
.gitignore vendored
View File

@ -9,4 +9,5 @@ __pycache__
/localwebsite/vendor
/localwebsite/.debug.log
/localwebsite/config.local.php
/localwebsite/cache
/localwebsite/cache
/localwebsite/test.php

View File

@ -176,8 +176,10 @@ class E3372
$messages = [];
foreach ($xml->Messages->Message as $message) {
$dt = DateTime::createFromFormat("Y-m-d H:i:s", (string)$message->Date);
$messages[] = [
'date' => (string)$message->Date,
'timestamp' => $dt->getTimestamp(),
'phone' => (string)$message->Phone,
'content' => (string)$message->Content
];

View File

@ -0,0 +1,37 @@
<?php
class TelegramBotClient {
protected string $token;
public function __construct(string $token) {
$this->token = $token;
}
public function sendMessage(int $chat_id, string $text): bool {
$ch = curl_init();
$url = 'https://api.telegram.org/bot'.$this->token.'/sendMessage';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'chat_id' => $chat_id,
'text' => $text,
'parse_mode' => 'html',
'disable_web_page_preview' => 1
]);
$body = curl_exec($ch);
curl_close($ch);
$resp = jsonDecode($body);
if (!$resp['ok']) {
debugError(__METHOD__ . ': ' . $body);
return false;
}
return true;
}
}

View File

@ -8,7 +8,8 @@
"ext-simplexml": "*",
"ext-curl": "*",
"ext-json": "*",
"ext-gmp": "*"
"ext-gmp": "*",
"ext-sqlite3": "*"
},
"license": "MIT"
}

View File

@ -61,5 +61,13 @@ return [
'cam_hls_host' => '192.168.1.1',
'cam_list' => [
// fill me with names
]
],
'vk_sms_checker' => [
'telegram_token' => '',
'telegram_chat_id' => '',
'modem_name' => '', // reference to the 'modems' array
],
'database_path' => getenv('HOME').'/.config/homekit.localwebsite.sqlite3',
];

View File

@ -0,0 +1,44 @@
#!/usr/bin/env php
<?php
// this scripts pulls recent inbox from e3372 modem,
// looks for new messages from vk and re-sends them
// to the telegram group
require_once __DIR__.'/../init.php';
global $config;
$cfg = $config['modems'][$config['vk_sms_checker']['modem_name']];
$e3372 = new E3372($cfg['ip'], $cfg['legacy_token_auth']);
$db = getDB();
$last_processed = $db->querySingle("SELECT last_message_time FROM vk_processed");
$new_last_processed = 0;
$messages = $e3372->getSMSList();
$messages = array_reverse($messages);
$results = [];
if (!empty($messages)) {
foreach ($messages as $m) {
if ($m['timestamp'] <= $last_processed)
continue;
$new_last_processed = $m['timestamp'];
if (preg_match('/^vk/i', $m['phone']) || preg_match('/vk/i', $m['content']))
$results[] = $m;
}
}
if (!empty($results)) {
$t = new TelegramBotClient($config['vk_sms_checker']['telegram_token']);
foreach ($results as $m) {
$text = '<b>'.htmlescape($m['phone']).'</b> ('.$m['date'].')';
$text .= "\n".htmlescape($m['content']);
$t->sendMessage($config['vk_sms_checker']['telegram_chat_id'], $text);
}
}
if ($new_last_processed != 0)
$db->exec("UPDATE vk_processed SET last_message_time=?", $new_last_processed);

View File

@ -0,0 +1,80 @@
<?php
class database {
const SCHEMA_VERSION = 2;
protected SQLite3 $link;
public function __construct(string $db_path) {
$this->link = new SQLite3($db_path);
$this->link->enableExceptions(true);
$this->upgradeSchema();
}
protected function upgradeSchema() {
$cur = $this->getSchemaVersion();
if ($cur < 1) {
$this->link->exec("CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT,
password TEXT
)");
}
if ($cur < 2) {
$this->link->exec("CREATE TABLE vk_processed (
last_message_time INTEGER
)");
$this->link->exec("INSERT INTO vk_processed (last_message_time) VALUES (0)");
}
$this->syncSchemaVersion();
}
protected function getSchemaVersion() {
return $this->link->query("PRAGMA user_version")->fetchArray()[0];
}
protected function syncSchemaVersion() {
$this->link->exec("PRAGMA user_version=".self::SCHEMA_VERSION);
}
protected function prepareQuery(string $sql): string {
if (func_num_args() > 1) {
$mark_count = substr_count($sql, '?');
$positions = array();
$last_pos = -1;
for ($i = 0; $i < $mark_count; $i++) {
$last_pos = strpos($sql, '?', $last_pos + 1);
$positions[] = $last_pos;
}
for ($i = $mark_count - 1; $i >= 0; $i--) {
$arg_val = func_get_arg($i + 1);
if (is_null($arg_val)) {
$v = 'NULL';
} else {
$v = '\''.$this->link->escapeString($arg_val) . '\'';
}
$sql = substr_replace($sql, $v, $positions[$i], 1);
}
}
return $sql;
}
public function query(string $sql, ...$params): SQLite3Result {
return $this->link->query($this->prepareQuery($sql, ...$params));
}
public function exec(string $sql, ...$params) {
return $this->link->exec($this->prepareQuery($sql, ...$params));
}
public function querySingle(string $sql, ...$params) {
return $this->link->querySingle($this->prepareQuery($sql, ...$params));
}
public function querySingleRow(string $sql, ...$params) {
return $this->link->querySingle($this->prepareQuery($sql, ...$params), true);
}
}

View File

@ -252,4 +252,14 @@ function append_shutdown_function(callable $f) {
function prepend_shutdown_function(callable $f) {
global $ShutdownFunctions;
array_unshift($ShutdownFunctions, $f);
}
function getDB(): database {
global $config;
static $link = null;
if (is_null($link))
$link = new database($config['database_path']);
return $link;
}

View File

@ -19,7 +19,7 @@ spl_autoload_register(function($class) {
$path = ROOT.'/handlers/'.$class.'.php';
// engine classes
else if (in_array($class, ['request_handler', 'router', 'model', 'debug']))
else if (in_array($class, ['request_handler', 'router', 'model', 'debug', 'database']))
$path = ROOT.'/engine/'.$class.'.php';
else if ($class == 'Lang')