Skip to content

Commit

Permalink
better push notification
Browse files Browse the repository at this point in the history
  • Loading branch information
Ubuntu committed Mar 1, 2014
1 parent a478393 commit 5cbceb2
Show file tree
Hide file tree
Showing 6 changed files with 243 additions and 166 deletions.
11 changes: 11 additions & 0 deletions etc/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
)
));


$app->register(new Spika\Provider\SpikaDbServiceProvider(), array(
));

Expand All @@ -65,6 +66,16 @@
$app->register(new Silex\Provider\SessionServiceProvider(), array(
));

$app->register(new Spika\Provider\PushNotificationProvider(), array(
'pushnotification.options' => array (
'GCMAPIKey' => GCM_API_KEY,
'APNProdPem' => __DIR__.'/../'.APN_DEV_CERT_PATH,
'APNDevPem' => __DIR__.'/../'.APN_DEV_CERT_PATH
)
));



$app['adminBeforeTokenChecker'] = $app->share(function () use ($app) {
return new Spika\Middleware\AdminChecker(
$app
Expand Down
210 changes: 54 additions & 156 deletions src/Spika/Controller/AsyncTaskController.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ public function connect(Application $app)
return $self->returnErrorResponse("invalid access to internal API");
}


$requestBody = $request->getContent();
$requestData = json_decode($requestBody,true);

Expand All @@ -56,27 +55,15 @@ public function connect(Application $app)

// send iOS push notification
if(!empty($toUser['ios_push_token'])){
$body = array();
$body['aps'] = array('alert' => $pushnotificationMessage, 'badge' => 0, 'sound' => 'default', 'value' => "");
$body['data'] =array('from' => $fromUserId);
$payload = json_encode($body);

$iosDevCertPath = __DIR__.'/../../../'.APN_DEV_CERT_PATH;

if(file_exists($iosDevCertPath)){

$body = array();
$body['aps'] = array('alert' => $pushnotificationMessage, 'badge' => 0, 'sound' => 'default', 'value' => "");
$body['data'] =array('from' => $fromUserId);
$payload = json_encode($body);

$result = $self->sendAPNDev($toUser['ios_push_token'],$payload,$app);
$result = $self->sendAPNProd($toUser['ios_push_token'],$payload,$app);

}else{
// dev push is disabled
}

$app['sendDevAPN'](array($toUser['ios_push_token']),$payload);
$app['sendProdAPN'](array($toUser['ios_push_token']),$payload);
}

$app['monolog']->addDebug(print_r($toUser,true));

// send Android push notification
if(!empty($toUser['android_push_token'])){

Expand All @@ -94,8 +81,7 @@ public function connect(Application $app)
);

$payload = json_encode($fields);
$result = $self->sendGCM($payload,$app);

$app['sendGCM']($payload,$app);
}

return "";
Expand All @@ -117,9 +103,55 @@ public function connect(Application $app)

$messageId = $requestData['messageId'];
$message = $app['spikadb']->findMessageById($messageId);

$app['spikadb']->updateActivitySummaryByGroupMessage($message['to_group_id'],$message['from_user_id']);

// send pushnotification too all subscribed members

$users = $app['spikadb']->getAllUsersByGroupId($message['to_group_id']);
$iosTokens = array();
$androidTokens = array();

foreach($users as $user){

if(!empty($user['ios_push_token']))
$iosTokens[] = $user['ios_push_token'];

if(!empty($user['android_push_token']))
$androidTokens[] = $user['android_push_token'];

}

$app['monolog']->addDebug(print_r($androidTokens,true));

$fromUserData = $app['spikadb']->findUserById($message['from_user_id']);
$toGroupData = $app['spikadb']->findGroupById($message['to_group_id']);
$pushMessage = sprintf(GROUPMESSAGE_NOTIFICATION_MESSAGE . " test ",$fromUserData['name'],$toGroupData['name']);

$fields = array(
'registration_ids' => $androidTokens,
'data' => array(
"message" => $pushMessage,
"fromUser" => $message['from_user_id'],
"fromUserName"=>$fromUserData['name'],
"type" => "group",
"groupId" => $message['to_group_id']
),
);

$payload = json_encode($fields);
$app['sendGCM']($payload,$app);

$body = array();
$body['aps'] = array('alert' => $pushMessage, 'badge' => 0, 'sound' => 'default', 'value' => "");
$body['data'] =array('type' => 'group','to_group' => $message['to_group_id']);
$payload = json_encode($body);

$app['sendDevAPN']($iosTokens,$payload);
$app['sendProdAPN']($iosTokens,$payload);



return "";

});
Expand All @@ -128,110 +160,6 @@ public function connect(Application $app)

}


function sendAPNProd($deviceToken, $json) {
$filePath = __DIR__.'/../../../'.APN_PROD_CERT_PATH;
return $this->sendAPN($deviceToken,$json,$filePath,'ssl://gateway.push.apple.com:2195');
}

function sendAPNDev($deviceToken, $json, $app = null) {
$filePath = __DIR__.'/../../../'.APN_DEV_CERT_PATH;
return $this->sendAPN($deviceToken,$json,$filePath,'ssl://gateway.sandbox.push.apple.com:2195',$app);
}


function sendAPN($deviceToken, $json,$cert,$host,$app = null){

$apn_status = array(
'0' => "No errors encountered",
'1' => "Processing error",
'2' => "Missing device token",
'3' => "Missing topic",
'4' => "Missing payload",
'5' => "Invalid token size",
'6' => "Invalid topic size",
'7' => "Invalid payload size",
'8' => "Invalid token",
'255' => "unknown"
);

if(strlen($deviceToken) == 0) return;

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $cert);

$fp = stream_socket_client($host, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);

if (!$fp) {
$app['monolog']->addDebug("Failed to connect $err $errstr");
return;
}
else {
stream_set_blocking($fp, 0);
}

$identifiers = array();
for ($i = 0; $i < 4; $i++) {
$identifiers[$i] = rand(1, 100);
}

$msg = chr(1) . chr($identifiers[0]) . chr($identifiers[1]) . chr($identifiers[2]) . chr($identifiers[3]) . pack('N', time() + 3600)
. chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",strlen($json)) . $json;

stream_set_timeout($fp,SP_TIMEOUT);
$result = fwrite($fp, $msg);

if(!$result){

}else{

$read = array($fp);
$null = null;
$changedStreams = stream_select($read, $null, $null, 0, 1000000);

if ($changedStreams === false) {
$app['monolog']->addDebug("Error: Unabled to wait for a stream availability");
return false;

} elseif ($changedStreams > 0) {

$responseBinary = fread($fp, 6);

if ($responseBinary !== false || strlen($responseBinary) == 6) {

$response = unpack('Ccommand/Cstatus_code/Nidentifier', $responseBinary);
$response['error_message'] = $apn_status[$response['status_code']];
$result = json_encode($response);

}

} else {
$result = "succeed";
}

}

fclose($fp);

return $result;

}

function getAPNResult($response){

if($response === false)
return false;

$responseAry = json_decode($response,true);

if(isset($responseAry['status_code']) && $responseAry['status_code'] != 0){
return false;
}

return true;

}

function generatePushNotificationMessage($fromUser,$toUser){

$message = "You got message from {$fromUser['name']}";
Expand All @@ -240,36 +168,6 @@ function generatePushNotificationMessage($fromUser,$toUser){

}

function sendGCM($json, $app = null) {

$apiKey = GCM_API_KEY;

// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';

$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();

// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $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);
curl_setopt( $ch, CURLOPT_TIMEOUT,SP_TIMEOUT);

// Execute post
$result = curl_exec($ch);

curl_close($ch);

return $result;

}
}

?>
1 change: 0 additions & 1 deletion src/Spika/Controller/MessageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,6 @@ function ($id) use ($app,$self) {
return $self->returnErrorResponse("failed to get message");

//$result = $self->fileterMessage($result,$app['spikadb']);
$app['monolog']->addDebug(print_r($result,true));
$result = $this->fileterOneMessage($result);

return json_encode($result);
Expand Down
8 changes: 2 additions & 6 deletions src/Spika/Db/DbInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,32 +52,28 @@ public function clearActivitySummary($toUserId, $type, $fieldKey);
public function addPassworResetRequest($toUserId);
public function getPassworResetRequest($requestCode);
public function changePassword($userId,$newPassword);

public function findUserCount();
public function findAllUsersWithPaging($offect,$count);
public function deleteUser($id);

public function createGroupCategory($title,$picture);
public function findAllGroupCategoryWithPaging($offect,$count);
public function findGroupCategoryCount();
public function findGroupCategoryById($id);
public function updateGroupCategory($id,$title,$picture);
public function deleteGroupCategory($id);

public function createEmoticon($identifier,$picture);
public function findAllEmoticonsWithPaging($offect,$count);
public function findEmoticonCount();
public function findEmoticonById($id);
public function updateEmoticon($id,$title,$picture);
public function deleteEmoticon($id);

public function getMessageCount();
public function getLastLoginedUsersCount();

public function setMessageDelete($messageId,$deleteType,$deleteAt,$deleteAfterShownFlag);
public function deleteMessage($messageId);

public function getConversationHistory($user,$offset = 0,$count);
public function getConversationHistoryCount($user);
public function updateReadAt($messageId);
public function getAllUsersByGroupId($groupId);

}
10 changes: 7 additions & 3 deletions src/Spika/Db/MySql.php
Original file line number Diff line number Diff line change
Expand Up @@ -346,9 +346,7 @@ public function getActivitySummary($user_id)
left join user on notification.from_user_id = user._id
where user_id = ?
order by modified desc',array($user_id));

$this->logger->addDebug(print_r($myNotifications,true));


$directMessages = array();
$groupMessages = array();

Expand Down Expand Up @@ -1914,4 +1912,10 @@ public function deleteStory($storyId){
);
}

public function getAllUsersByGroupId($groupId){
$users = $this->DB->fetchAll('select * from user where _id in (select user_id from user_group where group_id = ?)',
array($groupId));

return $users;
}
}
Loading

0 comments on commit 5cbceb2

Please sign in to comment.