Skip to content

Commit

Permalink
[notification] Implements message firebase notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
LaercioSantana committed Jul 22, 2016
1 parent 62366c0 commit 3012a6c
Show file tree
Hide file tree
Showing 6 changed files with 161 additions and 15 deletions.
11 changes: 6 additions & 5 deletions application/config/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,13 @@
$route['routes/(:num)/buses/(:num)/positions']['delete'] = 'bus/deleteLocalizations/$1/$2';

/*
Notifications
Messages
*/
$route['routes/(:num)/notifications']['post'] = 'messages/addMessage/$1/$2';
$route['routes/(:num)/notifications']['get'] = 'messages/getMessages/$1/$2';
$route['routes/(:num)/buses/(:num)/notifications']['post'] = 'messages/addMessage/$1/$2';
$route['routes/(:num)/buses/(:num)/notifications']['get'] = 'messages/getMessages/$1/$2';
$route['routes/(:num)/messages']['post'] = 'messages/addMessage/$1/$2';
$route['routes/(:num)/messages']['get'] = 'messages/getMessages/$1/$2';
$route['routes/(:num)/messages/register']['post'] = 'messages/registerNotification/$1';
$route['routes/(:num)/buses/(:num)/messages']['post'] = 'messages/addMessage/$1/$2';
$route['routes/(:num)/buses/(:num)/messages']['get'] = 'messages/getMessages/$1/$2';

/*
Users
Expand Down
95 changes: 89 additions & 6 deletions application/controllers/Messages.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
require APPPATH.'/libraries/Jsv4/Validator.php';
require APPPATH.'/libraries/Jsv4/ValidationException.php';
include( APPPATH.'controllers/Authentication.php' );
include( APPPATH.'third_party/FirebaseUtil.php' );
/**
* @apiDefine tokenParam
* @apiHeader {String} Token Token do usuario que realizara a ação.
*/
class Messages extends Authentication {
/**
* @api {post} /routes/:idRoute/buses/:idBus/notifications Adicionar uma mensagem a um onibus
* @api {post} /routes/:idRoute/buses/:idBus/messages Adicionar uma mensagem a um onibus
* @apiName PostBusMessage
* @apiGroup Messages
* @apiPermission tracker
Expand Down Expand Up @@ -46,7 +47,7 @@ class Messages extends Authentication {
* }
*/
/**
* @api {post} /routes/:idRoute/notifications Adicionar uma mensagem a uma rota
* @api {post} /routes/:idRoute/messages Adicionar uma mensagem a uma rota
* @apiName PostRouteMessage
* @apiGroup Messages
* @apiPermission tracker
Expand Down Expand Up @@ -98,18 +99,23 @@ function addMessage($idRoute, $idBus){
if(empty($idBus))
unset($notification->id_bus);

$this->notify($this->messages_model->getNotificationRegistration($idRoute), $notification);

return $this->makeJsonRespose($notification, 201);
}else
return $this->makeJsonRespose($validator->errors, 400);
}
private function notify($listenersFirebaseIds, $notification){
FirebaseUtil::sendMessageMulticast($listenersFirebaseIds, $notification);
}
/**
* @api {get} /routes/:idRoute/notifications Requisitar mensagens de uma rota
* @api {get} /routes/:idRoute/messages Requisitar mensagens de uma rota
* @apiName GetRoutesMessages
* @apiGroup Messages
* @apiPermission client
*
* @apiExample Exemplo de uso:
* curl -i http://host/BusTrackerAPI/index.php/routes/86/notifications?buses=true
* curl -i http://host/BusTrackerAPI/index.php/routes/86/messages?buses=true
*
* @apiUse tokenParam
*
Expand Down Expand Up @@ -165,13 +171,13 @@ function addMessage($idRoute, $idBus){
* ]
*/
/**
* @api {get} /routes/:idRoute/buses/:idBus/notifications Requisitar mensagens de um onibus
* @api {get} /routes/:idRoute/buses/:idBus/messages Requisitar mensagens de um onibus
* @apiName GetBusMessages
* @apiGroup Messages
* @apiPermission client
*
* @apiExample Exemplo de uso:
* curl -i http://host/BusTrackerAPI/index.php/routes/86/buses/1/notifications
* curl -i http://host/BusTrackerAPI/index.php/routes/86/buses/1/messages
*
* @apiUse tokenParam
*
Expand Down Expand Up @@ -213,6 +219,83 @@ function getMessages($idRoutes, $idBus){

return $this->makeJsonRespose($notifications, 200);
}
/**
* @api {post} /routes/:idRoute/messages Registrar um usuário firebase para receber mensagens(Android)
* @apiName RegisterNotificationMessages
* @apiGroup Messages
* @apiPermission client
*
* @apiDescription Use esta requisição para registrar um usuario firebase nas notificações de mensagens de uma rota. Após
* registrado, o usuário receberá mensagens pelo firebase como as mensagens abaixo:
*
*<pre><code>
* {//mensagem de uma rota<br/>
* "title": "Onibus",<br/>
* "message": "O esse onibus eh bom :)",<br/>
* "id_routes": 86,<br/>
* "id": 47<br/>
* }<br/>
*</code></pre>
*<pre><code>
* {//mensagem de um onibus pq tem id onibus<br/>
* "title": "Onibus",<br/>
* "message": "O esse onibus eh bom :)",<br/>
* "id_routes": 86,<br/>
* "id_bus": 1,<br/>
* "id": 48<br/>
* }
*</code></pre>
*
* @apiUse tokenParam
*
* @apiParam (BodyParam) {String} registration_token_firebase Token firebase do usuário. Veja [aqui](https://firebase.google.com/docs/cloud-messaging/android/client#sample-register)
* como adquirir em android.
*
* @apiError 404 RouteNotFound
* @apiError 401 InvalidToken
* @apiError 409 ExistingRegistry
* @apiError (400 - InvalidJSON) root O json enviado é invalido. Isso pode ocorrer por falta de parametros, erros de tipos e erros de sintaxe.
*
*
* @apiSuccessExample Exemplo de respota com sucesso:
* HTTP/1.1 201 OK
* {
* "registration_token_firebase": "dIqrrKgmq40:APA91bGFbK1eLFjHJrVPxiQpuu_WUOoB6ZLkl8XxkEAbmf1jKrthc9_sZfWEqViVzhoqjYgstKpr4RjCvr4eV30dgJnQJO6YmBqT2jg-ME4q0M5dGPu3Uez1vo3aX0xuzdMgT0epj3tz",
* "id_routes": 86,
* "email": "santana@email.com"
* }
*
*/
function registerNotification($idRoute){
$token = $this->authenticate();
if(!$token->valid(Authentication::CLIENT_PERMISSION))
return $this->makeUnauthorizedResponse();

$validator = $this->validateJson($this->input->raw_input_stream, APPPATH.'/controllers/Schemas/NotificationRegistryAdd.json');
if($validator->valid){
$registry = json_decode($this->input->raw_input_stream);

//check route exist
$this->load->model('routes_model', '', TRUE);
if(!$this->routes_model->existRoute($idRoute))
return $this->makeJsonRespose(["error" => "NOT_FOUND_ROUTE"], 404);

$user = parent::getUser();
if($user == null)
return $this->makeJsonRespose(["error" => "INVALID_TOKEN"], 401);

$registry->id_routes = $idRoute;
$registry->email = $user->email;
$this->loadModel();
$result = $this->messages_model->insertNotificationRegistration($registry);

if(!$result)//exist conflict registry
return $this->makeJsonRespose(["error" => "CONFLICT"], 409);

return $this->makeJsonRespose($registry, 201);
}else
return $this->makeJsonRespose($validator->errors, 400);
}
function loadModel(){
$this->load->model('messages_model', '', TRUE);
}
Expand Down
12 changes: 12 additions & 0 deletions application/controllers/Schemas/NotificationRegistryAdd.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"registration_token_firebase": {
"type": "string"
}
},
"required": [
"registration_token_firebase"
]
}
28 changes: 24 additions & 4 deletions application/models/Messages_model.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ class Messages_model extends CI_Model{
public $id_routes;
public $date;
const table = 'messages';
const pointsTable = 'points_route';
const busTable = 'bus';
const notificationPositionTable = 'notifications_update_position';
public static $google_routes_path;
const registeredNotificationsTable = 'registered_notifications_messages';

public function __construct(){
parent::__construct();
Expand All @@ -38,5 +35,28 @@ public function insert($notification){

return $id;
}
public function insertNotificationRegistration($notificationRegistration){
$registry = new stdClass();
$registry->email = $notificationRegistration->email;
$registry->id_routes = $notificationRegistration->id_routes;
$registry->registration_token_firebase = $notificationRegistration->registration_token_firebase;

$this->db->insert(self::registeredNotificationsTable, $registry);

if($this->db->affected_rows() < 1)
return false;

return true;

}
public function getNotificationRegistration($idRoute){
$result = $this->db->select("registration_token_firebase")
->from(self::registeredNotificationsTable)
->where("id_routes = ".$idRoute)->get()->result();
$arrayIds = [];
foreach ($result as $row ) {
$arrayIds[] = $row->registration_token_firebase;
}
return $arrayIds;
}
}
30 changes: 30 additions & 0 deletions application/third_party/FirebaseUtil.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class FirebaseUtil{
public static function sendMessageMulticast($ids, $data){
$key = "key=".FirebaseUtil::GOOGLE_SERVER_KEY();

$cURL = curl_init('https://fcm.googleapis.com/fcm/send');
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

$body = [
"registration_ids" => $ids,
"data" => $data
];

curl_setopt($cURL, CURLOPT_POST, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, ["Content-Type:application/json", "Authorization:{$key}"]);
curl_setopt($cURL, CURLOPT_POSTFIELDS, json_encode($body));
curl_setopt($cURL, CURLOPT_SSL_VERIFYPEER, false);//adds this to work com google security

$result = curl_exec($cURL);
curl_close($cURL);

return $result;
}
private static function GOOGLE_SERVER_KEY(){
global $BusTrackerConfig;
return $BusTrackerConfig["GOOGLE_SERVER_KEY"];
}
}
Binary file modified database/database.mwb
Binary file not shown.

0 comments on commit 3012a6c

Please sign in to comment.