From e5f1fc61d6620def1194dc948577bc22fc38a0d6 Mon Sep 17 00:00:00 2001 From: JonatanRek Date: Tue, 8 Oct 2019 16:49:08 +0200 Subject: [PATCH] Push Messages #2 --- app/class/AutomationManager.php | 45 ++++++++++++------ app/class/NotificationManager.php | 77 +++++++++++++++++++++++++++++++ app/templates/home.phtml | 16 ++++--- app/templates/js/script.js | 19 ++++++++ app/views/Ajax.php | 2 + serviceWorker.js | 75 ++++++++++++------------------ 6 files changed, 168 insertions(+), 66 deletions(-) create mode 100644 app/class/NotificationManager.php diff --git a/app/class/AutomationManager.php b/app/class/AutomationManager.php index 6a64924..f1b8717 100644 --- a/app/class/AutomationManager.php +++ b/app/class/AutomationManager.php @@ -51,10 +51,12 @@ class AutomationManager{ $run = false; $restart = false; - if ($automation['active'] != 0){ + if ($automation['active'] == 1){ + + + if (in_array($dayNameNow, $actionDays)){ if (in_array($onValue['type'], ['sunSet', 'sunRise', 'time','now'])) { - if ($onValue['type'] == 'sunSet') { $value = date_sunset($value, SUNFUNCS_RET_TIMESTAMP, 50.0755381 , 14.4378005, 90); } else if ($onValue['type'] == 'sunRise') { @@ -65,13 +67,6 @@ class AutomationManager{ $onValue = $today->setTime($onValue[0], $onValue[1]); $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 ($automation['executed'] == 0){ $run = true; @@ -109,19 +104,33 @@ class AutomationManager{ } else if ($membersHome > 0 && $automation['executed'] == 0){ $run = true; } - /*echo "Someone Home". '
'; - echo "at home" . $membersHome. '
'; - echo "run" . $run. '
'; - echo "restart" . $restart. '
';*/ - } //finalization if ($run) { + $serverKey = 'AAAAFcN4elo:APA91bG4GViYbiwDHhNgkcOc3DpCYHW_4dpj9F-nQ-v5yiRcps9iENT6CmVAi8Qxxyjid5mrsMAqib9YSyObBOEJLg-Q9gsD5MnVaJjjTYggwyeyJEgFLM5wQNPeqQDPvIecXS9sbib4'; + $body = ''; + $sceneDoArray = json_decode($sceneDoJson); foreach ($sceneDoArray as $deviceId => $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"); Db::edit('automation', array('executed' => 1), 'WHERE automation_id = ?', array($automation['automation_id'])); } else if ($restart) { @@ -129,7 +138,15 @@ class AutomationManager{ Db::edit('automation', array('executed' => 0), 'WHERE automation_id = ?', array($automation['automation_id'])); } } + + + + } } } + + + + } diff --git a/app/class/NotificationManager.php b/app/class/NotificationManager.php new file mode 100644 index 0000000..4aa94cc --- /dev/null +++ b/app/class/NotificationManager.php @@ -0,0 +1,77 @@ + $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; + } +} diff --git a/app/templates/home.phtml b/app/templates/home.phtml index d265683..baf3a5c 100644 --- a/app/templates/home.phtml +++ b/app/templates/home.phtml @@ -29,14 +29,16 @@ } ?> - + + $room) { + if ($room['device_count'] > 0) { ?> + + - - + +
$room) { ?> $device) { ?> diff --git a/app/templates/js/script.js b/app/templates/js/script.js index d150873..343607c 100644 --- a/app/templates/js/script.js +++ b/app/templates/js/script.js @@ -25,12 +25,31 @@ if ('serviceWorker' in navigator) { }) .then(function(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) { console.log("Unable to get permission to notify.", err); }); messaging.onMessage(function(payload) { console.log("Message received. ", payload); + var notification = new Notification('hello', { + body: "Hey there!", + }); + notification.onclick = function () { + window.open("http://google.com"); + }; }); }) .catch(err => { diff --git a/app/views/Ajax.php b/app/views/Ajax.php index 0ece2a7..ea4ac51 100644 --- a/app/views/Ajax.php +++ b/app/views/Ajax.php @@ -136,6 +136,8 @@ class Ajax extends Template }else { echo SceneManager::execScene($sceneId); } + } else if (isset($_POST['token'])) { + NotificationManager::addSubscriber($_SESSION['user']['id'], $_POST['token']); } die(); diff --git a/serviceWorker.js b/serviceWorker.js index e6cc4ec..cd7d70c 100644 --- a/serviceWorker.js +++ b/serviceWorker.js @@ -25,55 +25,40 @@ var CACHE_FILES = [ 'assets/logo.svg' ]; -this.addEventListener('install', function(event) { -}); +self.addEventListener('install', function(event) { + console.info('Installed'); +}); self.addEventListener('push', function(event) { console.log('Received a push message', event); - if (!firebase.apps.length) { - firebase.initializeApp({ - 'messagingSenderId': '93473765978' - }); -} - - const messaging = firebase.messaging(); - 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'); - - }); - - self.addEventListener('fetch', function (event) { - - }); - - self.addEventListener("online", 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. + if (event && event.data) { + var data = event.data.json(); + data = JSON.parse(data.data.notification); + console.log(data); + event.waitUntil(self.registration.showNotification(data.title, { + body: data.body, + icon: data.icon || null + })); + } +}); + +self.addEventListener('sync', function(event) { + console.info('Event: Sync'); +}); + +self.addEventListener('fetch', function (event) { +}); + +self.addEventListener("online", function (event) { +}); + +self.addEventListener("offline", function (event) { +}); + +self.addEventListener('notificationclick', function(e) { +}); +