diff --git a/assets/js/common/ws.js b/assets/js/common/ws.js index 8eccb6fd..35a73b03 100644 --- a/assets/js/common/ws.js +++ b/assets/js/common/ws.js @@ -3,6 +3,20 @@ * * @author Pierre HUBERT */ + + +class WsMessage { + constructor(info) { + this.title = info.title + this.id = info.id + this.data = info.data + } + + get hasId() { + return this.id.length > 0 + } +} + class UserWebSocket { /** @@ -31,7 +45,7 @@ class UserWebSocket { // Handle incoming messages this.ws.addEventListener("message", (e) => { - this.ProcessMessage(JSON.parse(e.data)); + this.ProcessMessage(new WsMessage(JSON.parse(e.data))); }) } catch(e) { @@ -83,9 +97,36 @@ class UserWebSocket { /** * Process an incoming message * - * @param {any} msg The incoming message + * @param {WsMessage} msg The incoming message */ static async ProcessMessage(msg) { - console.error("WS message", msg) + + // Check if the message is not associated if any request + if(!msg.hasId) + this.ProcessDetachedMessage(msg) + + else + throw Error("Attached message to request are not supported yet!"); + + } + + /** + * Process detached message + * @param {WsMessage} msg Incoming message + */ + static async ProcessDetachedMessage(msg) { + + switch(msg.title) { + + case "number_notifs": + SendEvent("newNumberNotifs", msg.data) + break; + + case "number_unread_conversations": + SendEvent("newNumberUnreadConvs", msg.data) + break; + + } + } } \ No newline at end of file diff --git a/assets/js/components/notifications/service.js b/assets/js/components/notifications/service.js index b0951651..ac499595 100644 --- a/assets/js/components/notifications/service.js +++ b/assets/js/components/notifications/service.js @@ -25,7 +25,7 @@ ComunicWeb.components.notifications.service = { */ init: async function(target, auto_hide, target_conversations){ - processResponse = () => { + const processResponse = () => { if(!target.isConnected || this.count_unread_notifications < 0 || this.count_unread_conv < 0) return; @@ -74,6 +74,17 @@ ComunicWeb.components.notifications.service = { console.error("Could not get the number of unread notifications!") console.error(e); } + + // Register to events + document.addEventListener("newNumberNotifs", e => { + this.count_unread_notifications = e.detail; + processResponse(); + }); + + document.addEventListener("newNumberUnreadConvs", e => { + this.count_unread_conv = e.detail; + processResponse(); + }); }, } \ No newline at end of file