Handle incoming message and delivered datetime

This commit is contained in:
Benjamin Renard 2017-11-19 20:01:49 +01:00
parent df18ea284b
commit 70e9b346ae
7 changed files with 228 additions and 25 deletions

View file

@ -13,6 +13,8 @@ use GetOptionKit\OptionPrinter\ConsoleOptionPrinter;
$specs = new OptionCollection;
$specs->add('done', 'Show done queue.' );
$specs->add('incoming', 'Show incoming queue.' );
$specs->add('incoming-done', 'Show incomingi done queue.' );
$specs->add('h|help', 'Show this help message.' );
$specs->add('v|verbose', 'Enable verbose mode.' );
$specs->add('d|debug', 'Enable debug mode.' );
@ -178,6 +180,9 @@ if (!empty($subcommandOptions)) {
logging('DEBUG', 'Handle outgoing pending messages');
if (handle_outgoing_msgs() !== True)
logging('ERROR', 'Error handling outgoing pending messages');
logging('DEBUG', 'Handle incoming pending messages');
if (handle_incoming_msgs() !== True)
logging('ERROR', 'Error handling incoming pending messages');
exit(0);
break;
case 'check-gateway':
@ -192,8 +197,11 @@ if (!empty($subcommandOptions)) {
$uuid=$subcommandArgs[$subcmd][0];
$msg=get_outgoing_msg($uuid);
if (!$msg) {
echo "Message $uuid not found.\n";
exit(1);
$msg=get_incoming_msg($uuid);
if (!$msg) {
echo "Message $uuid not found.\n";
exit(1);
}
}
echo "Message $uuid :\n";
echo "----------------------------------------------\n";
@ -204,6 +212,8 @@ if (!empty($subcommandOptions)) {
echo "Unique SMS gateway message ID : ".$msg['uniqueid']."\n";
if ($msg['nbfrag'])
echo "Number of fragment(s) : ".$msg['nbfrag']."\n";
if ($msg['delivered_datetime'] && $msg['delivered_datetime']!='0000-00-00 00:00:00')
echo "Delivered at : ".$msg['delivered_datetime']."\n";
echo "Last update : ".$msg['lastupdate']."\n";
echo "\nText :\n------\n";
echo preg_replace('/(^|\n)/',"\n ",wordwrap($msg['text'], 70, "\n", true));
@ -228,15 +238,26 @@ if (!empty($subcommandOptions)) {
$uuid=$subcommandArgs[$subcmd][0];
$msg=get_outgoing_msg($uuid);
if (!$msg) {
echo "Message $uuid not found.\n";
$msg=get_incoming_msg($uuid);
if (!$msg) {
echo "Message $uuid not found.\n";
exit(1);
}
if (handle_incoming_msg($msg)===True) {
echo "Incoming SMS forwarded\n";
exit(0);
}
echo "An error occured forwarding incoming SMS. Please see log file for more informations.\n";
exit(1);
}
if (handle_outgoing_msg($msg)===True) {
echo "Message push on SMS gateway\n";
exit(0);
else {
if (handle_outgoing_msg($msg)===True) {
echo "Message push on SMS gateway\n";
exit(0);
}
echo "An error occured sending message on SMS gateway. Please see log file for more informations.\n";
exit(1);
}
echo "An error occured sending message on SMS gateway. Please see log file for more informations.\n";
exit(1);
break;
case 'delete':
$uuid=$subcommandArgs[$subcmd][0];
@ -259,10 +280,16 @@ if (!empty($subcommandOptions)) {
// Main command
// Format messages queue output
function show_queue($q) {
function show_queue($q, $done=false) {
$tbl = new Console_Table();
$tbl->setHeaders(
array('Id', 'Date', 'Recipient', 'Status', 'Text')
array(
'Id',
'Date',
'Number',
($done?'Delivered date':'Status'),
'Text'
)
);
foreach($q as $msg) {
$tbl->addRow(
@ -270,7 +297,7 @@ function show_queue($q) {
$msg['uuid'],
$msg['datetime'],
$msg['number'],
$msg['status'],
($done?$msg['delivered_datetime']:$msg['status']),
(strlen($msg['text'])>40?substr($msg['text'],0,37)."...":$msg['text'])
)
);
@ -286,7 +313,29 @@ if (array_key_exists('done', $app_options->keys)) {
echo "SMS done queue is empty.\n";
exit(0);
}
show_queue($q, true);
echo count($q)." message(s) in done queue\n";
}
elseif (array_key_exists('incoming', $app_options->keys)) {
$q = get_incoming_msgs('pending');
if (!is_array($q))
die("Invalid get_incoming_msgs() result !\n");
if (empty($q)) {
echo "SMS incoming queue is empty.\n";
exit(0);
}
show_queue($q);
echo count($q)." message(s) in queue\n";
}
elseif (array_key_exists('incoming-done', $app_options->keys)) {
$q = get_incoming_msgs('delivered');
if (!is_array($q))
die("Invalid get_incoming_msgs() result !\n");
if (empty($q)) {
echo "SMS incoming done queue is empty.\n";
exit(0);
}
show_queue($q, true);
echo count($q)." message(s) in done queue\n";
}
else {

View file

@ -8,7 +8,7 @@ SET time_zone = "+00:00";
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `smsgw`
-- Database: `smsq`
--
-- --------------------------------------------------------
@ -18,11 +18,14 @@ SET time_zone = "+00:00";
--
CREATE TABLE `incoming_msg` (
`datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`uuid` varchar(40) NOT NULL,
`number` text NOT NULL,
`text` text NOT NULL,
`timestampms` int(11) NOT NULL,
`status` varchar(20) NOT NULL
`timestampms` bigint(20) NOT NULL,
`status` varchar(20) NOT NULL DEFAULT 'pending',
`lastupdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`delivered_datetime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
@ -39,7 +42,8 @@ CREATE TABLE `outgoing_msg` (
`uniqueid` bigint(11) UNSIGNED NOT NULL,
`nbfrag` int(11) NOT NULL,
`status` varchar(30) NOT NULL DEFAULT 'pending',
`lastupdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
`lastupdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`delivered_datetime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------

View file

@ -29,6 +29,9 @@ $db_options=array();
* Config Mail
*/
// Forward incoming SMS destination (mail address)
$forward_incoming_sms_to="user@domain.tld";
$phpmail_path="Mail.php";
/*

View file

@ -20,3 +20,4 @@ require_once('sms_gw_api.php');
$smsgw = new sms_gw_api($smsgw_url, $smsgw_ssl_verify, $smsgw_ws_connect_timeout, $smsgw_ws_timeout);
require('db.php');
require('mail.php');

View file

@ -44,6 +44,21 @@ function get_incoming_msg($uuid) {
return -1;
}
function get_incoming_msgs($status=false) {
global $fpdo;
$where=array();
if ($status)
$where['status']=$status;
$result = $fpdo -> from('incoming_msg')
-> where($where)
-> execute();
if ($result !== false) {
return $result -> fetchAll();
}
return -1;
}
function create_incoming_msg($number, $text, $timestampms) {
global $fpdo;
@ -62,6 +77,76 @@ function create_incoming_msg($number, $text, $timestampms) {
return $uuid;
}
function handle_incoming_msg($msg) {
global $fpdo, $mail_sender, $forward_incoming_sms_to;
if (!is_array($msg))
$msg=get_outgoing_msg($msg);
if (is_array($msg)) {
if ($msg['status']=='pending') {
/*
var_dump($msg);
array(6) {
["datetime"]=>
string(19) "2017-11-19 19:05:26"
["uuid"]=>
string(36) "c87e8945-94fd-45db-a32c-e5bf7f42fc28"
["number"]=>
string(12) "+33612345678"
["text"]=>
string(4) "test"
["timestampms"]=>
string(13) "1511112645376"
["status"]=>
string(7) "pending"
}
*/
$subject = "SMS from ".$msg['number'];
$body = "SMS received from ".$msg['number']." at ".$msg['datetime']."\n\n";
$body .= "Text :\n";
$body .= "------\n";
$body .= wordwrap($msg['text'], 70, "\n", true);
$headers = array (
'X-SMS-UUID' => $msg['uuid'],
);
if (send_mail($mail_sender ,$forward_incoming_sms_to ,$subject, $body, $headers) !== True) {
return -1;
}
$result = $fpdo -> update('incoming_msg')
-> set(
array (
'status' => 'delivered',
'lastupdate' => db_now(),
'delivered_datetime' => db_now(),
)
)
-> where(
array (
'uuid' => $msg['uuid'],
)
)
-> execute();
if ($result === false)
return -1;
}
return True;
}
return -1;
}
function handle_incoming_msgs() {
$msgs=get_incoming_msgs('pending');
if (!is_array($msgs))
return -1;
foreach($msgs as $msg) {
if (handle_incoming_msg($msg) !== True)
return -1;
}
return True;
}
function get_outgoing_msg($uuid, $status=false) {
global $fpdo;
$where=array();
@ -287,13 +372,15 @@ function get_outgoing_msg_status_from_frags($msg) {
function update_outgoing_msg_status($uuid, $status) {
global $fpdo;
$changes=array (
'status' => $status,
'lastupdate' => db_now(),
);
if ($status=='delivered') {
$changes['delivered_datetime'] = db_now();
}
$result = $fpdo -> update('outgoing_msg')
-> set(
array (
'status' => $status,
'lastupdate' => db_now(),
)
)
-> set($changes)
-> where(
array (
'uuid' => $uuid,
@ -314,7 +401,7 @@ function create_outgoing_msg_frag($msguid, $fragid, $status=false) {
);
if ($status)
$values['status']=strtolower($status);
$result = $fpdo -> insertInto('outgoing_msg_frag',$values)
-> execute();
if ($result === false)

53
includes/mail.php Normal file
View file

@ -0,0 +1,53 @@
<?php
require $phpmail_path;
function send_mail($from,$to,$subject,$msg,$headers=array()) {
global $mail_send_method, $mail_hearders, $mail_send_params, $mail_sender, $mail_catch;
$mail_obj = & Mail::factory($mail_send_method, $mail_send_params);
if(is_array($mail_hearders)) {
$headers = array_merge($headers,$mail_hearders);
}
if ($subject) {
$headers["Subject"] = $subject;
}
if ($from) {
$headers['From'] = $from;
}
else {
$headers['From'] = $mail_sender;
}
if ($mail_catch) {
$headers["To"] = $mail_catch;
$headers["X-Orig-To"] = $to;
$to=$mail_catch;
}
else {
$headers["To"] = $to;
}
$to = array (
'To' => $to
);
foreach(array_keys($headers) as $header) {
if(strtoupper($header) == 'BCC') {
$to['BCC'] = $headers[$header];
}
elseif(strtoupper($header) == 'CC') {
$to['CC'] = $headers[$header];
}
}
$ret = $mail_obj -> send($to,$headers,$msg);
if ($ret instanceof PEAR_Error) {
logging('ERROR',"Error sending email to $to : ".$ret -> getMessage());
return -1;
}
return true;
}

View file

@ -6,6 +6,7 @@ $go=false;
if (isset($_REQUEST['go'])) {
$go=$_REQUEST['go'];
}
logging('DEBUG',"Request (Go : $go) : ".print_r($_REQUEST,1));
$post_body=file_get_contents('php://input');
if ($post_body) {
@ -80,9 +81,14 @@ switch($go) {
*/
if (is_array($post_body) && check_phone_number($post_body['number']) && check_sms_text($post_body['text']) && check_integer($post_body['timestampMillis'])) {
logging('INFO','Incoming SMS from '.$post_body['number']);
$msg=create_incoming_msg($post_body['number'], $post_body['text'], $post_body['timestampMillis']);
if (is_array($msg)) {
$data['status']='ok';
$uuid=create_incoming_msg($post_body['number'], $post_body['text'], $post_body['timestampMillis']);
if (check_uuid($uuid)) {
if(handle_incoming_msg($uuid)===True) {
$data['status']='delivered';
}
else {
$data['status']='pending';
}
}
else {
$data['status']='error';