Push Messages #2

This commit is contained in:
JonatanRek 2019-10-08 16:49:08 +02:00
parent 1f456aaaac
commit e5f1fc61d6
6 changed files with 168 additions and 66 deletions

View File

@ -51,10 +51,12 @@ class AutomationManager{
$run = false; $run = false;
$restart = false; $restart = false;
if ($automation['active'] != 0){ if ($automation['active'] == 1){
if (in_array($dayNameNow, $actionDays)){ if (in_array($dayNameNow, $actionDays)){
if (in_array($onValue['type'], ['sunSet', 'sunRise', 'time','now'])) { if (in_array($onValue['type'], ['sunSet', 'sunRise', 'time','now'])) {
if ($onValue['type'] == 'sunSet') { if ($onValue['type'] == 'sunSet') {
$value = date_sunset($value, SUNFUNCS_RET_TIMESTAMP, 50.0755381 , 14.4378005, 90); $value = date_sunset($value, SUNFUNCS_RET_TIMESTAMP, 50.0755381 , 14.4378005, 90);
} else if ($onValue['type'] == 'sunRise') { } else if ($onValue['type'] == 'sunRise') {
@ -65,13 +67,6 @@ class AutomationManager{
$onValue = $today->setTime($onValue[0], $onValue[1]); $onValue = $today->setTime($onValue[0], $onValue[1]);
$value = $today->getTimestamp(); $value = $today->getTimestamp();
} }
/*
Echo "Spouštění Automatizace";
echo "Aktual" . date( "HH:mm", strtotime(time()));
echo "Run At" . date( "HH:mm", strtotime($value));
*/
if (time() > $value){ if (time() > $value){
if ($automation['executed'] == 0){ if ($automation['executed'] == 0){
$run = true; $run = true;
@ -109,19 +104,33 @@ class AutomationManager{
} else if ($membersHome > 0 && $automation['executed'] == 0){ } else if ($membersHome > 0 && $automation['executed'] == 0){
$run = true; $run = true;
} }
/*echo "Someone Home". '<br>';
echo "at home" . $membersHome. '<br>';
echo "run" . $run. '<br>';
echo "restart" . $restart. '<br>';*/
} }
//finalization //finalization
if ($run) { if ($run) {
$serverKey = 'AAAAFcN4elo:APA91bG4GViYbiwDHhNgkcOc3DpCYHW_4dpj9F-nQ-v5yiRcps9iENT6CmVAi8Qxxyjid5mrsMAqib9YSyObBOEJLg-Q9gsD5MnVaJjjTYggwyeyJEgFLM5wQNPeqQDPvIecXS9sbib4';
$body = '';
$sceneDoArray = json_decode($sceneDoJson); $sceneDoArray = json_decode($sceneDoJson);
foreach ($sceneDoArray as $deviceId => $deviceState) { foreach ($sceneDoArray as $deviceId => $deviceState) {
RecordManager::create($deviceId, 'on/off', $deviceState); RecordManager::create($deviceId, 'on/off', $deviceState);
} }
$subscribers = NotificationManager::getSubscription();
$i = 0;
foreach ($subscribers as $key => $subscriber) {
// code...
$logManager->write("[NOTIFICATION] SENDING NOTIFICATION TO" . $subscriber['id'] . " was executed" . $i);
$title = 'Automatizace-'.$automation['automation_id']." was executed" . $i;
$bodyFinal = var_export($subscriber);;
$notification = new Notification($serverKey);
$notification->to($subscriber['token']);
$notification->notification($title, $bodyFinal , '', '');
$notification->send();
$notification = null;
}
$logManager->write("[AUTOMATIONS] automation id ". $automation['automation_id'] . " was executed"); $logManager->write("[AUTOMATIONS] automation id ". $automation['automation_id'] . " was executed");
Db::edit('automation', array('executed' => 1), 'WHERE automation_id = ?', array($automation['automation_id'])); Db::edit('automation', array('executed' => 1), 'WHERE automation_id = ?', array($automation['automation_id']));
} else if ($restart) { } else if ($restart) {
@ -129,7 +138,15 @@ class AutomationManager{
Db::edit('automation', array('executed' => 0), 'WHERE automation_id = ?', array($automation['automation_id'])); Db::edit('automation', array('executed' => 0), 'WHERE automation_id = ?', array($automation['automation_id']));
} }
} }
} }
} }
} }
} }

View File

@ -0,0 +1,77 @@
<?php
/**
* Notification Manager
*/
class NotificationManager
{
function addSubscriber($userID = '', $token = ''){
$notificationSubscriber = $subDeviceId = Db::loadOne('SELECT id FROM notifications WHERE token = ?;', array($token));
if ($notificationSubscriber == ''){
$notification = array (
'user_id' => $userID,
'token' => $token,
);
Db::add ('notifications', $notification);
}
}
function getSubscription(){
return Db::loadAll('SELECT * FROM notifications;', array());
}
}
class Notification
{
public $server_key = '';
public $jsonPayload = [
"to" => '',
"data" => [
"notification" => [
"body" => '',
"title" => '',
"icon" => '',
"click_action" => '',
]
]
];
function __construct($serverKey = '')
{
$this->server_key = $serverKey;
}
function to($to = ''){
$this->jsonPayload["to"] = $to;
}
function notification($title = '', $body = '', $icon = '', $action = '')
{
$this->jsonPayload["data"]["notification"]["title"] = $title;
$this->jsonPayload["data"]["notification"]["body"] = $body;
$this->jsonPayload["data"]["notification"]["icon"] = $icon;
$this->jsonPayload["data"]["notification"]["click_action"] = $action;
}
function send(){
$data = json_encode($this->jsonPayload);
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$this->server_key,
);
$ch = curl_init();
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_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if ($result === FALSE) {
die('Oops! FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
}

View File

@ -29,7 +29,8 @@
} }
?> ?>
</div> </div>
<select class="select m-1" name="room"> <div class="m-1">
<select class="select" name="room">
<option value="all">All</option> <option value="all">All</option>
<?php foreach ($ROOMS as $key => $room) { <?php foreach ($ROOMS as $key => $room) {
if ($room['device_count'] > 0) { ?> if ($room['device_count'] > 0) { ?>
@ -37,6 +38,7 @@
<?php } ?> <?php } ?>
<?php } ?> <?php } ?>
</select> </select>
</div>
<div class="row no-gutters"> <div class="row no-gutters">
<?php foreach ($DATA as $roomId => $room) { ?> <?php foreach ($DATA as $roomId => $room) { ?>
<?php foreach ($room['devices'] as $deviceId => $device) { ?> <?php foreach ($room['devices'] as $deviceId => $device) { ?>

View File

@ -25,12 +25,31 @@ if ('serviceWorker' in navigator) {
}) })
.then(function(token) { .then(function(token) {
console.log("token is : " + token); console.log("token is : " + token);
$.ajax({
url: 'ajax',
type: 'POST',
data: {
"token": token
},
success: function(data){
console.log('saved', data);
},
error: function (request, status, error) {
console.log("ERROR ", request, error);
}
});
}) })
.catch(function (err) { .catch(function (err) {
console.log("Unable to get permission to notify.", err); console.log("Unable to get permission to notify.", err);
}); });
messaging.onMessage(function(payload) { messaging.onMessage(function(payload) {
console.log("Message received. ", payload); console.log("Message received. ", payload);
var notification = new Notification('hello', {
body: "Hey there!",
});
notification.onclick = function () {
window.open("http://google.com");
};
}); });
}) })
.catch(err => { .catch(err => {

View File

@ -136,6 +136,8 @@ class Ajax extends Template
}else { }else {
echo SceneManager::execScene($sceneId); echo SceneManager::execScene($sceneId);
} }
} else if (isset($_POST['token'])) {
NotificationManager::addSubscriber($_SESSION['user']['id'], $_POST['token']);
} }
die(); die();

View File

@ -25,55 +25,40 @@ var CACHE_FILES = [
'assets/logo.svg' 'assets/logo.svg'
]; ];
this.addEventListener('install', function(event) {
});
self.addEventListener('install', function(event) {
console.info('Installed');
});
self.addEventListener('push', function(event) { self.addEventListener('push', function(event) {
console.log('Received a push message', event); console.log('Received a push message', event);
if (!firebase.apps.length) { if (event && event.data) {
firebase.initializeApp({ var data = event.data.json();
'messagingSenderId': '93473765978' data = JSON.parse(data.data.notification);
}); console.log(data);
} event.waitUntil(self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon || null
}));
}
});
const messaging = firebase.messaging(); self.addEventListener('sync', function(event) {
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/itwonders-web-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
});
self.addEventListener('sync', function(event) {
console.info('Event: Sync'); console.info('Event: Sync');
});
}); self.addEventListener('fetch', function (event) {
self.addEventListener('fetch', function (event) { });
}); self.addEventListener("online", function (event) {
self.addEventListener("online", function (event) { });
}); self.addEventListener("offline", function (event) {
});
self.addEventListener("offline", function (event) {
});
self.addEventListener('notificationclick', function(e) {
});
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
self.addEventListener('notificationclick', function(e) {
});