Implementacion de la notificacion para android y ios

add method

add endpoints to api.ini

change message in send notification

change .pem and conf

PM-3587 Cambiar el texto de notificaciones
This commit is contained in:
Ronald Quenta
2015-09-07 18:13:08 -04:00
parent 9fa3c2d2bf
commit 3a6c82801a
17 changed files with 2571 additions and 1 deletions

View File

@@ -0,0 +1,243 @@
<?php
namespace ProcessMaker\BusinessModel\Light;
use G;
class NotificationDevice
{
/**
* Post Create register device with userUid
*
* @param array $request_data
* @param string $use_uid
* @author Ronald Quenta <ronald.quenta@processmaker.com>
*
*/
public function saveDevice($use_uid, $request_data)
{
$arrayData = array();
$arrayData['USR_UID'] = $use_uid;
$arrayData['DEV_REG_ID'] = $request_data['deviceIdToken'];
$arrayData['SYS_LANG'] = $request_data['sysLanguage'];
$arrayData['DEV_TYPE'] = $request_data['deviceType'];
$arrayData['DEV_STATUS'] = 'active';
$oNoti = new \NotificationDevice();
$devices = $oNoti->loadByDeviceId($request_data['deviceIdToken']);
$response = array();
if (!$devices){
if($oNoti->create($arrayData)){
$response["devUid"] = $oNoti->getDevUid();
$response["message"] = G:: LoadTranslation("ID_RECORD_SAVED_SUCCESFULLY");
G::auditLog("Create", "Device Save: Device ID (".$oNoti->getDevUid().") ");
}
} else {
$response["devUid"] = $devices[0]['DEV_UID'];
$response["message"] = G:: LoadTranslation("ID_RECORD_EXISTS_IN_TABLE",array($devices[0]['DEV_UID'], "NOTIFICATION_DEVICE"));
//throw new \Exception(G::LoadTranslation("ID_RECORD_CANNOT_BE_CREATED"));
}
return $response;
}
/**
* Update register device with userUid
*
* @param array $request_data
* @param string $dev_uid
* @param string $use_uid
* @author Ronald Quenta <ronald.quenta@processmaker.com>
*
*/
public function updateDevice($dev_uid, $use_uid, $request_data)
{
$arrayData = array();
$arrayData['USR_UID'] = $use_uid;
$arrayData['DEV_UID'] = $dev_uid;
if(isset($request_data['deviceIdToken'])){
$arrayData['DEV_REG_ID'] = $request_data['deviceIdToken'];
}
if(isset($request_data['sysLanguage'])) {
$arrayData['SYS_LANG'] = $request_data['sysLanguage'];
}
if(isset($request_data['deviceType'])) {
$arrayData['DEV_TYPE'] = $request_data['deviceType'];
}
$oNoti = new \NotificationDevice();
$response = array();
if($oNoti->update($arrayData)){
$response["message"] = G:: LoadTranslation("ID_RECORD_SAVED_SUCCESFULLY");
G::auditLog("Create", "Device Save: Device ID (".$oNoti->getDevUid().") ");
}
return $response;
}
/**
* Send Message each user id
*
* @param array $request_data
* @author Ronald Quenta <ronald.quenta@processmaker.com>
*
*/
public function sendMessage($userIds, $message, $data = null)
{
try {
$oNoti = new \NotificationDevice();
$devices = array();
if (is_array($userIds)){
foreach ($userIds as $id) {
$deviceUser = $oNoti->loadByUsersId($id);
$devices = array_merge($devices, $deviceUser);
}
} else {
$devices = $oNoti->loadByUsersId($userIds);
}
$devicesAndroidIds = array();
$devicesAppleIds = array();
foreach ($devices as $dev) {
switch ($dev['DEV_TYPE']) {
case "apple":
$devicesAppleIds[] = $dev['DEV_REG_ID'];
break;
case "android":
$devicesAndroidIds[] = $dev['DEV_REG_ID'];
break;
}
}
if (count($devicesAppleIds) > 0) {
$oNotification = new PushMessageIOS();
$oNotification->setSettingNotification();
$oNotification->setDevices($devicesAppleIds);
$response['android'] = $oNotification->send($message, $data);
}
if (count($devicesAndroidIds) > 0) {
$oNotification = new PushMessageAndroid();
$oNotification->setSettingNotification();
$oNotification->setDevices($devicesAndroidIds);
$response['apple'] = $oNotification->send($message, $data);
}
} catch (\Exception $e) {
throw new \Exception(\Api::STAT_APP_EXCEPTION, $e->getMessage());
}
return $response;
}
/**
* Send Message each user id
*
* @param array $request_data
* @author Ronald Quenta <ronald.quenta@processmaker.com>
*
*/
public function routeCaseNotification($currentUserId, $processId, $currentTaskId, $appFields, $aTasks, $nextIndex)
{
try {
$oUser = new \Users();
$aUser = $oUser->load( $currentUserId );
$response = array();
$task = new \Tasks();
$group = new \Groups();
foreach ($aTasks as $aTask) {
$arrayTaskUser = array();
switch ($aTask["TAS_ASSIGN_TYPE"]) {
case "SELF_SERVICE":
if (isset($aTask["TAS_UID"]) && !empty($aTask["TAS_UID"])) {
$arrayAux1 = $task->getGroupsOfTask($aTask["TAS_UID"], 1);
foreach ($arrayAux1 as $arrayGroup) {
$arrayAux2 = $group->getUsersOfGroup($arrayGroup["GRP_UID"]);
foreach ($arrayAux2 as $arrayUser) {
$arrayTaskUser[] = $arrayUser["USR_UID"];
}
}
$arrayAux1 = $task->getUsersOfTask($aTask["TAS_UID"], 1);
foreach ($arrayAux1 as $arrayUser) {
$arrayTaskUser[] = $arrayUser["USR_UID"];
}
}
break;
default:
if (isset($aTask["USR_UID"]) && !empty($aTask["USR_UID"])) {
$arrayTaskUser = $aTask["USR_UID"];
}
break;
}
// $oTask = new \Task();
// $currentTask = $oTask->load($aTask['TAS_UID']);
$delIndex = null;
foreach ($nextIndex as $nIndex) {
if($aTask['TAS_UID'] == $nIndex['TAS_UID']){
$delIndex = $nIndex['DEL_INDEX'];
break;
}
}
$userIds = $arrayTaskUser;
$message = '#'. $appFields['APP_NUMBER'] . ' : '.$appFields['APP_TITLE'];
$data = array(
'processId' => $processId,
'taskId' => $aTask["TAS_UID"],
'caseId' => $appFields['APP_UID'],
'caseTitle' => $appFields['APP_TITLE'],
'delIndex' => $delIndex,
'typeList' => 'todo'
);
if ($userIds) {
$oNoti = new \NotificationDevice();
$devices = array();
if (is_array($userIds)){
foreach ($userIds as $id) {
$deviceUser = $oNoti->loadByUsersId($id);
$devices = array_merge($devices, $deviceUser);
}
} else {
$devices = $oNoti->loadByUsersId($userIds);
$lists = new \ProcessMaker\BusinessModel\Lists();
$counter = $lists->getCounters($userIds);
$light = new \ProcessMaker\Services\Api\Light();
$result = $light->parserCountersCases($counter);
$data['counters'] = $result;
}
$devicesAndroidIds = array();
$devicesAppleIds = array();
foreach ($devices as $dev) {
switch ($dev['DEV_TYPE']) {
case "apple":
$devicesAppleIds[] = $dev['DEV_REG_ID'];
break;
case "android":
$devicesAndroidIds[] = $dev['DEV_REG_ID'];
break;
}
}
if (count($devicesAppleIds) > 0) {
$oNotification = new PushMessageIOS();
$oNotification->setSettingNotification();
$oNotification->setDevices($devicesAppleIds);
$response['apple'] = $oNotification->send($message, $data);
}
if (count($devicesAndroidIds) > 0) {
$oNotification = new PushMessageAndroid();
$oNotification->setSettingNotification();
$oNotification->setDevices($devicesAndroidIds);
$response['android'] = $oNotification->send($message, $data);
}
}
}
} catch (\Exception $e) {
throw new \Exception(\Api::STAT_APP_EXCEPTION, $e->getMessage());
}
return $response;
}
}

View File

@@ -0,0 +1,123 @@
<?php
/**
* Class PushMessageAndroid
* Class to send push notifications using Google Cloud Messaging for Android
* Example usage
*
* $an = new PushMessageAndroid();
* $an->setKey($apiKey);
* $an->setDevices($devices);
* $response = $an->send($message);
*
*/
namespace ProcessMaker\BusinessModel\Light;
class PushMessageAndroid
{
var $url = 'https://android.googleapis.com/gcm/send';
var $serverApiKey = "AIzaSyBO-VLXGhjf0PPlwmPFTPQEKIBfVDydLAk";
var $devices = array();
/**
* @param $url string the url server
*/
function setUrl($url){
$this->$url = $url;
}
/**
* @param $apiKeyIn string the server API key
*/
function setKey($apiKeyIn){
$this->serverApiKey = $apiKeyIn;
}
/**
* Set the devices to send to
* @param $deviceIds string or array of device tokens to send
*/
function setDevices($deviceIds)
{
if(is_array($deviceIds)){
$this->devices = $deviceIds;
} else {
$this->devices = array($deviceIds);
}
}
/**
* Set the setting value config
*/
public function setSettingNotification()
{
$conf = \System::getSystemConfiguration( PATH_CONFIG . 'mobile.ini' );
$this->setUrl($conf['android']['url']);
$this->setKey($conf['android']['serverApiKey']);
}
/**
* Send the message to the device
* @param $message string the message to send
* @param $data array send extra information for app
* @return mixed
*/
function send($message, $data)
{
if(!is_array($this->devices) || count($this->devices) == 0){
$this->error("No devices set");
}
if(strlen($this->serverApiKey) < 8){
$this->error("Server API Key not set");
}
if (!is_null($data)) {
$fields = array(
'registration_ids' => $this->devices,
'data' => array(
"message" => $message,
"data" => $data
),
);
} else {
$fields = array(
'registration_ids' => $this->devices,
'data' => array( "message" => $message ),
);
}
$headers = array(
'Authorization: key=' . $this->serverApiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $this->url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Avoids problem with https certificate
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false);
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
return $result;
}
function error($msg)
{
echo "Android send notification failed with error:";
echo "\t" . $msg;
exit(1);
}
}

View File

@@ -0,0 +1,145 @@
<?php
/**
* Class PushMessageIOS
* Class to send push notifications for iOS
* Example usage
*
* $ios = new PushMessageIOS($passphrase);
* $ios->setDevices($devicesToken);
* $response = $an->send($message);
*
*/
namespace ProcessMaker\BusinessModel\Light;
class PushMessageIOS
{
var $url = 'ssl://gateway.sandbox.push.apple.com:2195';
var $passphrase = "sample";
var $pemFile;
var $devices = array();
var $response = array();
/**
* @param $url string the url server
*/
function setUrl($url){
$this->url = $url;
}
/**
* Constructor
* @param $passphrase update your private key's
*/
function setKey($passphrase){
$this->passphrase = $passphrase;
}
/**
* Set the devices token to send to
* @param $deviceIds array of device tokens to send to
*/
function setDevices($devicesToken)
{
if(is_array($devicesToken)){
$this->devices = $devicesToken;
} else {
$this->devices = array($devicesToken);
}
}
/**
* Set the setting value config
*/
public function setSettingNotification()
{
$conf = \System::getSystemConfiguration( PATH_CONFIG . 'mobile.ini' );
$this->setUrl($conf['apple']['url']);
$this->setKey($conf['apple']['passphrase']);
}
/**
* Send the message to the device
* @param $message the message to send
* @return mixed
*/
function send($message, $data)
{
if(!is_array($this->devices) || count($this->devices) == 0){
$this->error("No devices set");
}
if(strlen($this->passphrase) < 8){
$this->error("Server API Key not set");
}
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', PATH_CONFIG . 'mobileios.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $this->passphrase);
// Open a connection to the APNS server
// $fp = stream_socket_client(
// $this->url, $err,
// $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
// if (!$fp)
// exit("Failed to connect: $err $errstr" . PHP_EOL);
// Create the payload body
if (!is_null($data)) {
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'data' => $data
);
} else {
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
}
// Encode the payload as JSON
$payload = json_encode($body);
// // Build the binary notification
// $msg = chr(0) . pack('n', 32) . pack('H*', $this->devices) . pack('n', strlen($payload)) . $payload;
//
// // Send it to the server
// $result = fwrite($fp, $msg, strlen($msg));
// fclose($fp);
foreach ($this->devices as $item) {
// Open a connection to the APNS server
$fp = stream_socket_client($this->url, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp) {
throw (new \Exception( G::LoadTranslation( 'ID_FAILED' ).': ' ."$err $errstr"));
} else {
//echo 'Apple service is online. ' . '<br />';
}
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $item) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result) {
$this->response['undelivered'][] = 'Undelivered message count: ' . $item;
} else {
$this->response['delivered'][] = 'Delivered message count: ' . $item;
}
if ($fp) {
fclose($fp);
//echo 'The connection has been closed by the client' . '<br />';
}
}
return $this->response;
}
function error($msg){
echo "Android send notification failed with error:";
echo "\t" . $msg;
}
}