Jelajahi Sumber

use self object to persist xmppjs connection

Dele Olajide 4 tahun lalu
induk
melakukan
2a54af4c39
3 mengubah file dengan 47 tambahan dan 40 penghapusan
  1. 18 13
      packages/offline-reply/offline-reply.js
  2. 1 1
      packages/offline-reply/readme.md
  3. 28 26
      serviceworker.js

+ 18 - 13
packages/offline-reply/offline-reply.js

@@ -63,7 +63,7 @@
                             avatar = "data:" + image_type + ";base64," + _converse.xmppstatus.vcard.get('image');
                         }
 
-                        const payload = {msgBody: data.get('message'), msgTo: jid, msgFrom: _converse.bare_jid, msgType: 'chat', avatar: avatar, fullname: fullname, domain: _converse.connection.domain, password: _converse.connection.pass, ws: _converse.api.settings.get("websocket_url"), username: Strophe.getNodeFromJid(_converse.bare_jid)};
+                        const payload = {msgBody: data.get('message'), msgFrom: _converse.bare_jid, msgType: 'chat', avatar: avatar, fullname: fullname};
                         window.WebPushLib.setVapidDetails('xmpp:' + _converse.bare_jid, secret.publicKey, secret.privateKey);
 
                         window.WebPushLib.sendNotification(secret.subscription, JSON.stringify(payload), {TTL: 60}).then(response => {
@@ -152,24 +152,29 @@
         }, "http://jabber.org/protocol/pubsub#event", 'message');
 
 
-        if ('serviceWorker' in navigator && 'PushManager' in window) navigator.serviceWorker.onmessage = function(event)
+        if ('serviceWorker' in navigator && 'PushManager' in window)
         {
-            console.debug("Broadcasted from service worker : ", event.data);
+            navigator.serviceWorker.controller.postMessage({ domain: _converse.connection.domain, password: _converse.connection.pass, ws: _converse.api.settings.get("websocket_url"), username: Strophe.getNodeFromJid(_converse.bare_jid) });
 
-            if (event.data.msgFrom)     // notification
+            navigator.serviceWorker.onmessage = function(event)
             {
-                if (event.data.msgType == "chat") _converse.api.chats.open(event.data.msgFrom);
+                console.debug("Broadcasted from service worker : ", event.data);
+
+                if (event.data.msgFrom)     // notification
+                {
+                    if (event.data.msgType == "chat") _converse.api.chats.open(event.data.msgFrom);
+                    else
+                    if (event.data.msgType == "room") _converse.api.rooms.open(event.data.msgFrom);
+                }
                 else
-                if (event.data.msgType == "room") _converse.api.rooms.open(event.data.msgFrom);
-            }
-            else
 
-            if (event.data.options)    // subscription renewal.
-            {
-                makeSubscription(function(err, subscription, keys)
+                if (event.data.options)    // subscription renewal.
                 {
-                    if (!err) handleSubscription(subscription, keys);
-                })
+                    makeSubscription(function(err, subscription, keys)
+                    {
+                        if (!err) handleSubscription(subscription, keys);
+                    })
+                }
             }
         }
     }

+ 1 - 1
packages/offline-reply/readme.md

@@ -14,4 +14,4 @@ Any messages typed will be sent to the XMPP server to to be action as offline me
 The recieving user can reply inline or open ConverseJS to have a full blown chat conversation.
 
 ## Warning
-This plugin is experimental and was created to explore peer-to-peer web push notifications across the different browser platforms. In order to reply a message, user credentials are included in the encrypted web push message. Use at own risk.
+This plugin is experimental and was created to explore peer-to-peer web push notifications across the different browser platforms and investigate sending xmpp messages in a service worker. Use at own risk.

+ 28 - 26
serviceworker.js

@@ -86,8 +86,25 @@ self.addEventListener('notificationclose', function(e) {
 
 self.addEventListener('message', function (evt) {
   console.log('service worker postMessage received', evt.data);
+
+  if (evt.data.domain && evt.data.ws && evt.data.username && evt.data.password)
+  {
+    self.xmpp = clientXmpp({ service: evt.data.ws, domain: evt.data.domain, username: evt.data.username, password: evt.data.password });
+    console.log('service worker creating xmpp client', self.xmpp);
+
+    self.xmpp.on("online", async (address) => {
+      console.debug("online - sending message", address, self.xmpp_data);
+
+      const body = ">" + self.xmpp_data.msgBody + "\n\n" + self.xmpp_data.reply;
+      const message = xml("message", {type: self.xmpp_data.msgType, to: jid(self.xmpp_data.msgFrom) }, xml("body", {}, body));
+      await self.xmpp.send(message);
+      await self.xmpp.send(xml("presence", { type: "unavailable" }));
+      await self.xmpp.stop();
+    });
+  }
 })
 
+
 self.addEventListener('notificationclick', function(event) {
     console.debug('notificationclick', event);
 
@@ -95,32 +112,17 @@ self.addEventListener('notificationclick', function(event) {
 
     if (event.action === 'open' || event.reply)
     {
-        event.notification.data.reply = event.reply;
-
-        event.waitUntil(clients.matchAll({type: "window"}).then(function(clientList)
+        if (event.reply && event.reply != "" && self.xmpp)
         {
-            if (event.reply && event.reply != "")
+            self.xmpp_data = event.notification.data;
+            self.xmpp_data.reply = event.reply;
+
+            self.xmpp.start().catch(console.error);
+        }
+        else {
+
+            event.waitUntil(clients.matchAll({type: "window"}).then(function(clientList)
             {
-                const xmpp = clientXmpp({
-                  service: event.notification.data.ws,
-                  domain: event.notification.data.domain,
-                  username: event.notification.data.username,
-                  password: event.notification.data.password
-                });
-
-                xmpp.on("online", async (address) => {
-                  console.debug("online", address);
-
-                  const body = ">" + event.notification.data.msgBody + "\n\n" + event.reply;
-                  const message = xml("message", { from: event.notification.data.msgTo, type: event.notification.data.msgType, to: jid(event.notification.data.msgFrom) }, xml("body", {}, body));
-                  await xmpp.send(message);
-                  await xmpp.send(xml("presence", { type: "unavailable" }));
-                  await xmpp.stop();
-                });
-
-                xmpp.start().catch(console.error);
-            }
-            else {
                 const url = event.notification.data.url;
 
                 for (var i = 0; i < clientList.length; i++) {
@@ -134,7 +136,7 @@ self.addEventListener('notificationclick', function(event) {
                 if (clients.openWindow) {
                     return clients.openWindow(event.notification.data.url);
                 }
-            }
-        }));
+            }));
+        }
     }
 }, false);