From 9fb243e9d715c0177baa2a0deb5ac6adbe9e70bf Mon Sep 17 00:00:00 2001 From: ubermanu <e.vodor@gmail.com> Date: Wed, 10 Mar 2021 18:36:11 +0100 Subject: [PATCH] format code with 2 spaces as indent size --- build-scss.js | 20 +- src/plugins/converse-rai.js | 354 ++++++++++---------- src/plugins/sib-chat-navigation.js | 94 +++--- src/plugins/sib-custom-hats.js | 34 +- src/plugins/sib-disconnected.js | 34 +- src/plugins/sib-mam-history.js | 70 ++-- src/plugins/sib-remove-notifications.js | 38 +-- src/plugins/sib-subscribe-to-rai.js | 116 +++---- src/solid-xmpp-chat.js | 418 ++++++++++++------------ src/utils.js | 16 +- 10 files changed, 597 insertions(+), 597 deletions(-) diff --git a/build-scss.js b/build-scss.js index ea8fa43..9e52edc 100644 --- a/build-scss.js +++ b/build-scss.js @@ -3,16 +3,16 @@ const sass = require('sass'); const fs = require('fs'); sass.render({ - file: 'src/styles/index.scss', - outFile: 'dist/index.css', + file: 'src/styles/index.scss', + outFile: 'dist/index.css', }, function(error, result) { - if (!error) { - if (!fs.existsSync('dist')) { - fs.mkdirSync('dist', { recursive: true }); - } - fs.writeFile('dist/index.css', String(result.css).replace(/\/lib\/solid-xmpp-chat/g, path), (e) => { - }); - } else { - console.error(error); + if (!error) { + if (!fs.existsSync('dist')) { + fs.mkdirSync('dist', { recursive: true }); } + fs.writeFile('dist/index.css', String(result.css).replace(/\/lib\/solid-xmpp-chat/g, path), (e) => { + }); + } else { + console.error(error); + } }); diff --git a/src/plugins/converse-rai.js b/src/plugins/converse-rai.js index 24ed1ad..c110906 100644 --- a/src/plugins/converse-rai.js +++ b/src/plugins/converse-rai.js @@ -1,195 +1,195 @@ (function() { - let Strophe, $iq, $msg, $pres, $build, b64_sha1, _, Backbone, dayjs, _converse; - let interestingServers = new Set(); - let subscribedServers = new Set(); - - converse.plugins.add('converse-rai', { - 'dependencies': [], - - 'initialize': function() { - _converse = this._converse; - - Strophe = converse.env.Strophe; - $iq = converse.env.$iq; - $msg = converse.env.$msg; - $pres = converse.env.$pres; - $build = converse.env.$build; - b64_sha1 = converse.env.b64_sha1; - _ = converse.env._; - Backbone = converse.env.Backbone; - dayjs = converse.env.dayjs; - - _converse.api.settings.extend({ - rai_notification: true, - rai_notification_label: 'Room Activity Indicator', - }); - - _converse.api.listen.on('connected', function() { - setupRoomActivityIndicators(); - }); - - _converse.api.listen.on('chatRoomViewInitialized', function(view) { - const jid = view.model.get('jid'); - - if (view.model.get('num_unread') > 0 || view.model.get('num_unread_general') > 0) { - emitNotification(jid); - } - }); - - _converse.api.listen.on('raiRoomsUpdated', function(rooms) { - interestingServers = new Set(rooms.filter(room => room).map(Strophe.getDomainFromJid)); - if (_converse.api.connection.connected()) { - updateSubscriptions(); - } - }); - - _converse.api.listen.on('chatBoxScrolledDown', function(view) { - const jid = view.chatbox.get('jid'); - const id_attr = 'stanza_id ' + jid; - const messages = view.chatbox.messages; - - if (!getUnreadStatus(jid)) { - return; - } - - for (let i = messages.length - 1; i >= 0; i--) { - const message = messages.at(i); - - if (message.has(id_attr)) { - let id = message.get(id_attr); - if (id != sessionStorage.getItem('rai_displayed.' + jid)) { - sessionStorage.setItem('rai_displayed.' + jid, id); - setUnreadStatus(jid, false); - setTimeout(() => sendMarker(jid, id, 'displayed'), 0); - } - break; - } - } - }); - - _converse.api.listen.on('chatBoxInsertedIntoDOM', function(view) { - const jid = view.model.get('jid'); - - if (view.model.get('num_unread') > 0) { - emitNotification(jid); - } - - }); - - _converse.api.listen.on('message', function(data) { - var chatbox = data.chatbox; - var history = data.attrs.is_archived; - var sender = data.attrs.sender; - var body = data.attrs.body; - - if (!history && body && chatbox && sender !== 'me') { - const alert = chatbox.get('num_unread') > 0; - const notify = chatbox.get('num_unread_general') > 0; - - if (alert || notify) { - emitNotification(chatbox.get('jid'), alert); - } - } - }); - }, - }); - + let Strophe, $iq, $msg, $pres, $build, b64_sha1, _, Backbone, dayjs, _converse; + let interestingServers = new Set(); + let subscribedServers = new Set(); + + converse.plugins.add('converse-rai', { + 'dependencies': [], + + 'initialize': function() { + _converse = this._converse; + + Strophe = converse.env.Strophe; + $iq = converse.env.$iq; + $msg = converse.env.$msg; + $pres = converse.env.$pres; + $build = converse.env.$build; + b64_sha1 = converse.env.b64_sha1; + _ = converse.env._; + Backbone = converse.env.Backbone; + dayjs = converse.env.dayjs; + + _converse.api.settings.extend({ + rai_notification: true, + rai_notification_label: 'Room Activity Indicator', + }); + + _converse.api.listen.on('connected', function() { + setupRoomActivityIndicators(); + }); + + _converse.api.listen.on('chatRoomViewInitialized', function(view) { + const jid = view.model.get('jid'); + + if (view.model.get('num_unread') > 0 || view.model.get('num_unread_general') > 0) { + emitNotification(jid); + } + }); - function subscribeServer(server_name) { - const id = Math.random().toString(36).substr(2, 9); - _converse.connection.send(converse.env.$pres({ - to: server_name, - id: id, - }).c('rai', { - 'xmlns': 'xmpp:prosody.im/protocol/rai', - })); - } + _converse.api.listen.on('raiRoomsUpdated', function(rooms) { + interestingServers = new Set(rooms.filter(room => room).map(Strophe.getDomainFromJid)); + if (_converse.api.connection.connected()) { + updateSubscriptions(); + } + }); - function unsubscribeServer(server_name) { - _converse.connection.send(converse.env.$pres({ - to: server_name, type: 'unavailable', - }).c('rai', { - 'xmlns': 'xmpp:prosody.im/protocol/rai', - })); - } + _converse.api.listen.on('chatBoxScrolledDown', function(view) { + const jid = view.chatbox.get('jid'); + const id_attr = 'stanza_id ' + jid; + const messages = view.chatbox.messages; - function updateSubscriptions() { - var new_servers = new Set([...interestingServers].filter(server => !subscribedServers.has(server))); - var obsolete_servers = new Set([...subscribedServers].filter(server => !interestingServers.has(server))); - for (let server of obsolete_servers) { - unsubscribeServer(server); + if (!getUnreadStatus(jid)) { + return; } - for (let server of new_servers) { - subscribeServer(server); - } - } - function setupRoomActivityIndicators() { - updateSubscriptions(); - // If we already have unread notifications stored for this session, emit them now - for (var i = 0; i < sessionStorage.length; i++) { - if (sessionStorage.key(i).indexOf('rai_notify.') == 0) { - const jid = sessionStorage.key(i).substring(11); - emitNotification(jid); + for (let i = messages.length - 1; i >= 0; i--) { + const message = messages.at(i); + + if (message.has(id_attr)) { + let id = message.get(id_attr); + if (id != sessionStorage.getItem('rai_displayed.' + jid)) { + sessionStorage.setItem('rai_displayed.' + jid, id); + setUnreadStatus(jid, false); + setTimeout(() => sendMarker(jid, id, 'displayed'), 0); } + break; + } } + }); - // Listen for incoming RAI from the server - _converse.connection.addHandler(function(message) { - const from_jid = message.attributes.from?.nodevalue; - const room_jid = from_jid?.split('/')[0]; - const room = ''; - let ignore = false; - for (let i = 0; i < _converse.chatboxes.models.length; i++) { - if (_converse.chatboxes.models[i].id === room_jid) { - room = _converse.chatboxes.models[i].id; - break; - } - } - if (room && from_jid && room_jid) { - if (from_jid === room_jid + '/' + room.get('nick')) { - ignore = true; - } - } - if (message && !ignore) - message.querySelectorAll('activity').forEach(function(activity) { - if (activity && activity.namespaceURI == 'xmpp:prosody.im/protocol/rai') { - const jid = activity.textContent; - setUnreadStatus(jid, true); - emitNotification(jid); - } - }); - return true; - }, null, 'message'); - } + _converse.api.listen.on('chatBoxInsertedIntoDOM', function(view) { + const jid = view.model.get('jid'); - function setUnreadStatus(jid, flag) { - if (flag) { - sessionStorage.setItem('rai_notify.' + jid, 'true'); - } else { - sessionStorage.removeItem('rai_notify.' + jid); + if (view.model.get('num_unread') > 0) { + emitNotification(jid); } - } - function getUnreadStatus(jid) { - return sessionStorage.getItem('rai_notify.' + jid) == 'true'; - } + }); + + _converse.api.listen.on('message', function(data) { + var chatbox = data.chatbox; + var history = data.attrs.is_archived; + var sender = data.attrs.sender; + var body = data.attrs.body; - function emitNotification(jid, alert) { - _converse.api.trigger('chatRoomActivityIndicators', jid); + if (!history && body && chatbox && sender !== 'me') { + const alert = chatbox.get('num_unread') > 0; + const notify = chatbox.get('num_unread_general') > 0; + + if (alert || notify) { + emitNotification(chatbox.get('jid'), alert); + } + } + }); + }, + }); + + + function subscribeServer(server_name) { + const id = Math.random().toString(36).substr(2, 9); + _converse.connection.send(converse.env.$pres({ + to: server_name, + id: id, + }).c('rai', { + 'xmlns': 'xmpp:prosody.im/protocol/rai', + })); + } + + function unsubscribeServer(server_name) { + _converse.connection.send(converse.env.$pres({ + to: server_name, type: 'unavailable', + }).c('rai', { + 'xmlns': 'xmpp:prosody.im/protocol/rai', + })); + } + + function updateSubscriptions() { + var new_servers = new Set([...interestingServers].filter(server => !subscribedServers.has(server))); + var obsolete_servers = new Set([...subscribedServers].filter(server => !interestingServers.has(server))); + for (let server of obsolete_servers) { + unsubscribeServer(server); + } + for (let server of new_servers) { + subscribeServer(server); + } + } + + function setupRoomActivityIndicators() { + updateSubscriptions(); + // If we already have unread notifications stored for this session, emit them now + for (var i = 0; i < sessionStorage.length; i++) { + if (sessionStorage.key(i).indexOf('rai_notify.') == 0) { + const jid = sessionStorage.key(i).substring(11); + emitNotification(jid); + } } - function sendMarker(to_jid, id, type) { - const stanza = converse.env.$msg({ - 'from': _converse.connection.jid, - 'id': Math.random().toString(36).substr(2, 9), - 'to': to_jid, - 'type': 'groupchat', - }).c(type, { - 'xmlns': converse.env.Strophe.NS.MARKERS, - 'id': id, + // Listen for incoming RAI from the server + _converse.connection.addHandler(function(message) { + const from_jid = message.attributes.from?.nodevalue; + const room_jid = from_jid?.split('/')[0]; + const room = ''; + let ignore = false; + for (let i = 0; i < _converse.chatboxes.models.length; i++) { + if (_converse.chatboxes.models[i].id === room_jid) { + room = _converse.chatboxes.models[i].id; + break; + } + } + if (room && from_jid && room_jid) { + if (from_jid === room_jid + '/' + room.get('nick')) { + ignore = true; + } + } + if (message && !ignore) + message.querySelectorAll('activity').forEach(function(activity) { + if (activity && activity.namespaceURI == 'xmpp:prosody.im/protocol/rai') { + const jid = activity.textContent; + setUnreadStatus(jid, true); + emitNotification(jid); + } }); - - _converse.api.send(stanza); + return true; + }, null, 'message'); + } + + function setUnreadStatus(jid, flag) { + if (flag) { + sessionStorage.setItem('rai_notify.' + jid, 'true'); + } else { + sessionStorage.removeItem('rai_notify.' + jid); } + } + + function getUnreadStatus(jid) { + return sessionStorage.getItem('rai_notify.' + jid) == 'true'; + } + + function emitNotification(jid, alert) { + _converse.api.trigger('chatRoomActivityIndicators', jid); + } + + function sendMarker(to_jid, id, type) { + const stanza = converse.env.$msg({ + 'from': _converse.connection.jid, + 'id': Math.random().toString(36).substr(2, 9), + 'to': to_jid, + 'type': 'groupchat', + }).c(type, { + 'xmlns': converse.env.Strophe.NS.MARKERS, + 'id': id, + }); + + _converse.api.send(stanza); + } })(); diff --git a/src/plugins/sib-chat-navigation.js b/src/plugins/sib-chat-navigation.js index 0679177..230cfcf 100644 --- a/src/plugins/sib-chat-navigation.js +++ b/src/plugins/sib-chat-navigation.js @@ -3,51 +3,51 @@ * into another component. */ converse.plugins.add('sib-chat-navigation', { - initialize() { - const _converse = this._converse; - const { api } = _converse; - - window.addEventListener('sib-change-chat', async ev => { - let { jid, is_groupchat, root } = ev.detail; - - if (!jid) { - return; - } - - jid = jid.toLowerCase(); - _converse.root = root; - - // Find the converse root - const converse_el = Array.from(document.querySelectorAll('solid-xmpp-chat')) - .map(el => el.shadowRoot.getElementById('conversejs')) - .filter(el => el) - .pop(); - - if (converse_el) { - root.appendChild(converse_el); - } - - if (is_groupchat) { - await api.rooms.open(jid, {}, true); - } else { - await api.chats.open(jid, {}, true); - } - }); - - // Get the currently used solid-xmpp-chat - const getCurrentChat = () => Array.from(document.querySelectorAll('solid-xmpp-chat')) - .filter(el => el.shadowRoot.getElementById('conversejs')) - .pop(); - - // When the a chat box is focused, send the read event - api.listen.on('chatBoxFocused', function() { - const resource = getCurrentChat()?.component.resource; - - window.dispatchEvent(new CustomEvent('read', { - detail: { - resource, - }, - })); - }); - }, + initialize() { + const _converse = this._converse; + const { api } = _converse; + + window.addEventListener('sib-change-chat', async ev => { + let { jid, is_groupchat, root } = ev.detail; + + if (!jid) { + return; + } + + jid = jid.toLowerCase(); + _converse.root = root; + + // Find the converse root + const converse_el = Array.from(document.querySelectorAll('solid-xmpp-chat')) + .map(el => el.shadowRoot.getElementById('conversejs')) + .filter(el => el) + .pop(); + + if (converse_el) { + root.appendChild(converse_el); + } + + if (is_groupchat) { + await api.rooms.open(jid, {}, true); + } else { + await api.chats.open(jid, {}, true); + } + }); + + // Get the currently used solid-xmpp-chat + const getCurrentChat = () => Array.from(document.querySelectorAll('solid-xmpp-chat')) + .filter(el => el.shadowRoot.getElementById('conversejs')) + .pop(); + + // When the a chat box is focused, send the read event + api.listen.on('chatBoxFocused', function() { + const resource = getCurrentChat()?.component.resource; + + window.dispatchEvent(new CustomEvent('read', { + detail: { + resource, + }, + })); + }); + }, }); diff --git a/src/plugins/sib-custom-hats.js b/src/plugins/sib-custom-hats.js index 334097d..f7b7871 100644 --- a/src/plugins/sib-custom-hats.js +++ b/src/plugins/sib-custom-hats.js @@ -2,22 +2,22 @@ * Transform hats to custom values. */ converse.plugins.add('sib-custom-hats', { - overrides: { - getHats: function() { - const hat_conversions = { 'admin': 'Administrateur' }; - const hats = this.__super__.getHats.apply(this, arguments); - if (!hat_conversions) { - return hats; - } else { - const role_affiliations = Object.keys(hat_conversions); - return hats.map((hat) => { - if (role_affiliations.includes(hat.title)) { - return ({ title: hat_conversions[hat.title] }); - } else { - return hat; - } - }); - } - }, + overrides: { + getHats: function() { + const hat_conversions = { 'admin': 'Administrateur' }; + const hats = this.__super__.getHats.apply(this, arguments); + if (!hat_conversions) { + return hats; + } else { + const role_affiliations = Object.keys(hat_conversions); + return hats.map((hat) => { + if (role_affiliations.includes(hat.title)) { + return ({ title: hat_conversions[hat.title] }); + } else { + return hat; + } + }); + } }, + }, }); diff --git a/src/plugins/sib-disconnected.js b/src/plugins/sib-disconnected.js index 8cb6dfe..3de3d30 100644 --- a/src/plugins/sib-disconnected.js +++ b/src/plugins/sib-disconnected.js @@ -2,23 +2,23 @@ * Initialize AUTHFAIL plugin */ converse.plugins.add('sib-disconnected', { - initialize() { - const _converse = this._converse; - const { api } = _converse; - const { Strophe } = converse.env; + initialize() { + const _converse = this._converse; + const { api } = _converse; + const { Strophe } = converse.env; - const getChats = () => Array.from(document.querySelectorAll('solid-xmpp-chat')); + const getChats = () => Array.from(document.querySelectorAll('solid-xmpp-chat')); - api.listen.on('disconnected', () => { - if (_converse.connfeedback.attributes.connection_status === Strophe.Status.AUTHFAIL) { - getChats().map(el => el.shadowRoot.innerHTML = - `<div style='margin:3em;line-height:32px;'><b style='color:red;'>Erreur d'authentification.</b><br /><i style='color:grey;'>Êtes-vous sur le Hubl affilié à votre compte ?</i></div>`, - ); - } else { - getChats().map(el => el.shadowRoot.innerHTML = - `<div style='margin:3em;line-height:32px;'><b style='color:red;'>Erreur.</b><br /><i style='color:grey;'>${_converse.connfeedback.attributes.message}</i></div>`, - ); - } - }); - }, + api.listen.on('disconnected', () => { + if (_converse.connfeedback.attributes.connection_status === Strophe.Status.AUTHFAIL) { + getChats().map(el => el.shadowRoot.innerHTML = + `<div style='margin:3em;line-height:32px;'><b style='color:red;'>Erreur d'authentification.</b><br /><i style='color:grey;'>Êtes-vous sur le Hubl affilié à votre compte ?</i></div>`, + ); + } else { + getChats().map(el => el.shadowRoot.innerHTML = + `<div style='margin:3em;line-height:32px;'><b style='color:red;'>Erreur.</b><br /><i style='color:grey;'>${_converse.connfeedback.attributes.message}</i></div>`, + ); + } + }); + }, }); diff --git a/src/plugins/sib-mam-history.js b/src/plugins/sib-mam-history.js index bffcc14..f0704e7 100644 --- a/src/plugins/sib-mam-history.js +++ b/src/plugins/sib-mam-history.js @@ -3,46 +3,46 @@ * from the setting `archived_messages_page_size`. */ converse.plugins.add('sib-mam-history', { - dependencies: [ - 'converse-mam', - ], - initialize() { - const { api } = this._converse; - let counter = 0; + dependencies: [ + 'converse-mam', + ], + initialize() { + const { api } = this._converse; + let counter = 0; - api.listen.on('MAMResult', async data => { + api.listen.on('MAMResult', async data => { - const max = +api.settings.get('archived_messages_page_size'); - const messages = await Promise.all(data.messages); + const max = +api.settings.get('archived_messages_page_size'); + const messages = await Promise.all(data.messages); - // Increase counter with the messages that contains a body - counter += messages.filter(attrs => attrs.body).length; + // Increase counter with the messages that contains a body + counter += messages.filter(attrs => attrs.body).length; - // Stop if the max value is not specified - // Stop if there are less messages available than the page size - // Stop if the counter registers more messages than the max value - if (!max || messages.length < max || counter >= max) { - counter = 0; - return; - } + // Stop if the max value is not specified + // Stop if there are less messages available than the page size + // Stop if the counter registers more messages than the max value + if (!max || messages.length < max || counter >= max) { + counter = 0; + return; + } - const is_groupchat = data.chatbox.get('type') === converse.CHATROOMS_TYPE; - const oldest_message = messages.pop(); + const is_groupchat = data.chatbox.get('type') === converse.CHATROOMS_TYPE; + const oldest_message = messages.pop(); - if (oldest_message) { - const by_jid = is_groupchat ? data.chatbox.get('jid') : converse.bare_jid; - const stanza_id = oldest_message && oldest_message['stanza_id '.concat(by_jid)]; + if (oldest_message) { + const by_jid = is_groupchat ? data.chatbox.get('jid') : converse.bare_jid; + const stanza_id = oldest_message && oldest_message['stanza_id '.concat(by_jid)]; - if (stanza_id) { - await data.chatbox.fetchArchivedMessages({ - 'before': stanza_id - }); - } else { - await data.chatbox.fetchArchivedMessages({ - 'end': oldest_message['time'] - }); - } - } - }) - } + if (stanza_id) { + await data.chatbox.fetchArchivedMessages({ + 'before': stanza_id, + }); + } else { + await data.chatbox.fetchArchivedMessages({ + 'end': oldest_message['time'], + }); + } + } + }); + }, }); diff --git a/src/plugins/sib-remove-notifications.js b/src/plugins/sib-remove-notifications.js index dd11271..b80d748 100644 --- a/src/plugins/sib-remove-notifications.js +++ b/src/plugins/sib-remove-notifications.js @@ -3,24 +3,24 @@ * so that permission request for notifications don't happen. */ converse.plugins.add('sib-remove-notifications', { - overrides: { - requestPermission: function() { - }, - showMessageNotification: function() { - }, - showChatStateNotification: function() { - }, - showContactRequestNotification: function() { - }, - showFeedbackNotification: function() { - }, - handleChatStateNotification: function() { - }, - handleMessageNotification: function() { - }, - handleContactRequestNotification: function() { - }, - handleFeedback: function() { - }, + overrides: { + requestPermission: function() { }, + showMessageNotification: function() { + }, + showChatStateNotification: function() { + }, + showContactRequestNotification: function() { + }, + showFeedbackNotification: function() { + }, + handleChatStateNotification: function() { + }, + handleMessageNotification: function() { + }, + handleContactRequestNotification: function() { + }, + handleFeedback: function() { + }, + }, }); diff --git a/src/plugins/sib-subscribe-to-rai.js b/src/plugins/sib-subscribe-to-rai.js index 634c487..51dbb91 100644 --- a/src/plugins/sib-subscribe-to-rai.js +++ b/src/plugins/sib-subscribe-to-rai.js @@ -4,67 +4,67 @@ import { store } from 'https://cdn.skypack.dev/@startinblox/core@0.15'; * Initialize rai plugin. */ converse.plugins.add('sib-subscribe-to-rai', { - dependencies: [ - 'converse-rai', - ], - async initialize() { - const _converse = this._converse; - const { api } = _converse; + dependencies: [ + 'converse-rai', + ], + async initialize() { + const _converse = this._converse; + const { api } = _converse; - const getCircles = new Promise((resolve, reject) => { - const circleInterval = setInterval(async () => { - let retry = false; - let circles = []; - const user = await document.querySelector('sib-auth').getUser(); - const userProfile = await store.getData(user['@id'], this.context); - for (let circleMembership of await userProfile['circles.ldp:contains']) { - if (circleMembership) { - circles.push(await circleMembership['circle.jabberID']); - } else { - retry = true; - } - } - if (!retry) { - clearInterval(circleInterval); - resolve(circles); - } - }, 250); - }); + const getCircles = new Promise((resolve, reject) => { + const circleInterval = setInterval(async () => { + let retry = false; + let circles = []; + const user = await document.querySelector('sib-auth').getUser(); + const userProfile = await store.getData(user['@id'], this.context); + for (let circleMembership of await userProfile['circles.ldp:contains']) { + if (circleMembership) { + circles.push(await circleMembership['circle.jabberID']); + } else { + retry = true; + } + } + if (!retry) { + clearInterval(circleInterval); + resolve(circles); + } + }, 250); + }); - const getProjects = new Promise((resolve, reject) => { - const projectInterval = setInterval(async () => { - let retry = false; - let projects = []; - const user = await document.querySelector('sib-auth').getUser(); - const userProfile = await store.getData(user['@id'], this.context); - for (let projectMembership of await userProfile['projects.ldp:contains']) { - if (projectMembership) { - projects.push(await projectMembership['project.jabberID']); - } else { - retry = true; - } - } - if (!retry) { - clearInterval(projectInterval); - resolve(projects); - } - }, 250); - }); + const getProjects = new Promise((resolve, reject) => { + const projectInterval = setInterval(async () => { + let retry = false; + let projects = []; + const user = await document.querySelector('sib-auth').getUser(); + const userProfile = await store.getData(user['@id'], this.context); + for (let projectMembership of await userProfile['projects.ldp:contains']) { + if (projectMembership) { + projects.push(await projectMembership['project.jabberID']); + } else { + retry = true; + } + } + if (!retry) { + clearInterval(projectInterval); + resolve(projects); + } + }, 250); + }); - let userRooms = (await Promise.all([ - getCircles, - getProjects, - ])).flat(); + let userRooms = (await Promise.all([ + getCircles, + getProjects, + ])).flat(); - // @MattJ Here userRooms is an array of each jabberID the user is on. - api.trigger('raiRoomsUpdated', userRooms); + // @MattJ Here userRooms is an array of each jabberID the user is on. + api.trigger('raiRoomsUpdated', userRooms); - api.listen.on('chatRoomActivityIndicators', jid => { - window.dispatchEvent(new CustomEvent('newMessage', { - detail: { - jid, - }, - })); - }); - }, + api.listen.on('chatRoomActivityIndicators', jid => { + window.dispatchEvent(new CustomEvent('newMessage', { + detail: { + jid, + }, + })); + }); + }, }); diff --git a/src/solid-xmpp-chat.js b/src/solid-xmpp-chat.js index f180e50..613139f 100644 --- a/src/solid-xmpp-chat.js +++ b/src/solid-xmpp-chat.js @@ -14,224 +14,224 @@ import './plugins/sib-remove-notifications.js'; import './plugins/sib-subscribe-to-rai.js'; export const SolidXMPPChat = { - name: 'solid-xmpp-chat', - use: [StoreMixin], - attributes: { - authentication: { - type: String, - default: 'login', - }, - autoLogin: { - type: Boolean, - default: true, - }, - i18n: { - type: String, - default: 'fr', - }, - websocketUrl: { - type: String, - default: 'wss://jabber.happy-dev.fr/xmpp-websocket', - }, - }, - - get extra_context() { - return { - 'foaf': 'http://xmlns.com/foaf/0.1/', - 'chatProfile': 'http://happy-dev.fr/owl/#chatProfile', - 'jabberID': 'foaf:jabberID', - }; - }, - - async created() { - const check_identified = await document.querySelector('sib-auth').getUserIdToken(); - if (check_identified) { - this.element.attachShadow({ mode: 'open' }); - this.importCSS(`${ComponentPath}/dist/conversejs/converse.min.css?min`); - this.importCSS(`${ComponentPath}/dist/index.css?min`); - if (typeof converse_sib === 'undefined') { - this.initializeConverse(); - } - } // Else, not logged in on page load (even if not on chat) + name: 'solid-xmpp-chat', + use: [StoreMixin], + attributes: { + authentication: { + type: String, + default: 'login', }, - - importCSS(path) { - let link = document.createElement('link'); - link.rel = 'stylesheet'; - link.href = path; - this.element.shadowRoot.append(link); + autoLogin: { + type: Boolean, + default: true, }, - - empty() { - this.element.innerHTML = 'Loading...'; + i18n: { + type: String, + default: 'fr', }, - - async populate() { - if (typeof converse_sib !== 'undefined') { - await converse_sib.loaded_deferred; - if (this.resource) { - if (await this.resource.jabberRoom) { - this.jid = await this.resource['jabberID']; - } else { - this.jid = await this.resource['chatProfile.jabberID']; - const user = await document.querySelector('sib-auth').getUser(); - const userProfile = await store.getData(user['@id'], this.context); - const contactsURL = await userProfile['contacts.@id']; - const contactInterval = setInterval(async () => { - let retry = false; - let userContacts = []; - for (let contact of await userProfile['contacts.ldp:contains']) { - if (contact) { - userContacts.push(await contact['contact.@id']); - } else { - retry = true; - } - } - if (!retry) { - clearInterval(contactInterval); - if (!userContacts.includes(this.resource['@id'])) { - store.post({ - 'contact': this.resource['@id'], - '@context': this.context, - }, contactsURL); - } - } - }, 100); - } - await converse_sib.connected_deferred; - - window.dispatchEvent(new CustomEvent('sib-change-chat', { - detail: { - jid: this.jid, - is_groupchat: await this.resource.jabberRoom, - root: this.element.shadowRoot, - }, - })); - - window.dispatchEvent(new CustomEvent('read', { - detail: { - resource: { - '@id': this.resource['@id'], - }, - }, - })); - } - } // Else, not logged in, on chat change + websocketUrl: { + type: String, + default: 'wss://jabber.happy-dev.fr/xmpp-websocket', }, - - removeConverseDatabase() { - for (let key in sessionStorage) { - if (sessionStorage.hasOwnProperty(key) && /converse/.test(key)) { - sessionStorage.removeItem(key); + }, + + get extra_context() { + return { + 'foaf': 'http://xmlns.com/foaf/0.1/', + 'chatProfile': 'http://happy-dev.fr/owl/#chatProfile', + 'jabberID': 'foaf:jabberID', + }; + }, + + async created() { + const check_identified = await document.querySelector('sib-auth').getUserIdToken(); + if (check_identified) { + this.element.attachShadow({ mode: 'open' }); + this.importCSS(`${ComponentPath}/dist/conversejs/converse.min.css?min`); + this.importCSS(`${ComponentPath}/dist/index.css?min`); + if (typeof converse_sib === 'undefined') { + this.initializeConverse(); + } + } // Else, not logged in on page load (even if not on chat) + }, + + importCSS(path) { + let link = document.createElement('link'); + link.rel = 'stylesheet'; + link.href = path; + this.element.shadowRoot.append(link); + }, + + empty() { + this.element.innerHTML = 'Loading...'; + }, + + async populate() { + if (typeof converse_sib !== 'undefined') { + await converse_sib.loaded_deferred; + if (this.resource) { + if (await this.resource.jabberRoom) { + this.jid = await this.resource['jabberID']; + } else { + this.jid = await this.resource['chatProfile.jabberID']; + const user = await document.querySelector('sib-auth').getUser(); + const userProfile = await store.getData(user['@id'], this.context); + const contactsURL = await userProfile['contacts.@id']; + const contactInterval = setInterval(async () => { + let retry = false; + let userContacts = []; + for (let contact of await userProfile['contacts.ldp:contains']) { + if (contact) { + userContacts.push(await contact['contact.@id']); + } else { + retry = true; + } } - } - for (let key in localStorage) { - if (localStorage.hasOwnProperty(key) && /converse/.test(key)) { - localStorage.removeItem(key); + if (!retry) { + clearInterval(contactInterval); + if (!userContacts.includes(this.resource['@id'])) { + store.post({ + 'contact': this.resource['@id'], + '@context': this.context, + }, contactsURL); + } } + }, 100); } - indexedDB.deleteDatabase('converse-persistent'); - }, - - initializeConverse() { - window.converse_sib = {}; - - // Deferred resolved at the end of this function - converse_sib.loaded_deferred = new Deferred(); - - // Deferred resolved after converse.initialize - converse_sib.connected_deferred = new Deferred(); - - this.removeConverseDatabase(); - - // Initialize deferred resolution plugin - setTimeout(async () => { - - // Initialize deferred resolution plugin - converse.plugins.add('sib-connected', { - initialize() { - const { api } = this._converse; - api.listen.on('connectionInitialized', converse_sib.connected_deferred.resolve); - }, - }); - - const user = await document.querySelector('sib-auth').getUser(); - const userProfile = await store.getData(user['@id'], this.context); - const jabberID = await userProfile['chatProfile.jabberID']; + await converse_sib.connected_deferred; + + window.dispatchEvent(new CustomEvent('sib-change-chat', { + detail: { + jid: this.jid, + is_groupchat: await this.resource.jabberRoom, + root: this.element.shadowRoot, + }, + })); + + window.dispatchEvent(new CustomEvent('read', { + detail: { + resource: { + '@id': this.resource['@id'], + }, + }, + })); + } + } // Else, not logged in, on chat change + }, + + removeConverseDatabase() { + for (let key in sessionStorage) { + if (sessionStorage.hasOwnProperty(key) && /converse/.test(key)) { + sessionStorage.removeItem(key); + } + } + for (let key in localStorage) { + if (localStorage.hasOwnProperty(key) && /converse/.test(key)) { + localStorage.removeItem(key); + } + } + indexedDB.deleteDatabase('converse-persistent'); + }, + + initializeConverse() { + window.converse_sib = {}; + + // Deferred resolved at the end of this function + converse_sib.loaded_deferred = new Deferred(); + + // Deferred resolved after converse.initialize + converse_sib.connected_deferred = new Deferred(); + + this.removeConverseDatabase(); + + // Initialize deferred resolution plugin + setTimeout(async () => { + + // Initialize deferred resolution plugin + converse.plugins.add('sib-connected', { + initialize() { + const { api } = this._converse; + api.listen.on('connectionInitialized', converse_sib.connected_deferred.resolve); + }, + }); - if (this.resource) { - if (await this.resource.jabberRoom) { - this.jid = await this.resource['jabberID']; - } else { - this.jid = await this.resource['chatProfile.jabberID']; - } - } else { - this.jid = jabberID; - } + const user = await document.querySelector('sib-auth').getUser(); + const userProfile = await store.getData(user['@id'], this.context); + const jabberID = await userProfile['chatProfile.jabberID']; - const idToken = await document.querySelector('sib-auth').getUserIdToken(); - - converse.initialize({ - 'assets_path': (/skypack/.test(ComponentPath) ? ComponentPath.replace('cdn.skypack.dev', 'unpkg.com') : ComponentPath) + '/dist/conversejs/', - 'authentication': this.element.dataset.authentication || 'login', - 'password': idToken, - 'allow_bookmarks': false, - 'allow_chat_pending_contacts': true, - 'allow_message_retraction': 'moderator', - 'allow_non_roster_messaging': true, - 'allow_dragresize': false, - 'allow_logout': false, - 'archived_messages_page_size': '30', - 'auto_list_rooms': true, - 'auto_login': this.element.dataset.autoLogin === 'true', - 'auto_join_on_invite': true, - 'auto_reconnect': true, - 'auto_register_muc_nickname': false, - 'websocket_url': this.element.dataset.websocketUrl || 'wss://jabber.happy-dev.fr/xmpp-websocket', - 'enable_smacks': true, - 'clear_messages_on_reconnection': false, - 'discover_connection_methods': false, - 'jid': jabberID.toLowerCase(), - 'i18n': this.element.dataset.i18n || 'fr', - 'loglevel': 'fatal', - 'message_archiving': 'always', - 'message_archiving_timeout': 60000, - 'muc_disable_slash_commands': true, - 'muc_hats': ['hats', 'vcard_roles', 'admin'], - 'role_affiliation_hat_conversions': { 'admin': 'Administrateur' }, - 'muc_nickname_from_jid': false, - 'muc_fetch_members': true, - 'muc_show_info_messages': [], - 'play_sounds': false, - 'root': this.element.shadowRoot, - 'show_client_info': false, - 'show_desktop_notifications': false, - 'persistent_store': 'none', - 'sounds_path': ComponentPath + '/dist/conversejs/', - 'show_send_button': false, - 'view_mode': 'fullscreen', - 'visible_toolbar_buttons': { - call: false, - spoiler: false, - emoji: true, - fileupload: true, // Not working in current Converse - toggle_occupants: false, - }, - 'whitelisted_plugins': [ - 'converse-rai', - 'sib-chat-navigation', - 'sib-connected', - 'sib-custom-hats', - 'sib-disconnected', - 'sib-mam-history', - 'sib-remove-notifications', - 'sib-subscribe-to-rai', - ], - }); - - converse_sib.loaded_deferred.resolve(); - }, 0); - }, + if (this.resource) { + if (await this.resource.jabberRoom) { + this.jid = await this.resource['jabberID']; + } else { + this.jid = await this.resource['chatProfile.jabberID']; + } + } else { + this.jid = jabberID; + } + + const idToken = await document.querySelector('sib-auth').getUserIdToken(); + + converse.initialize({ + 'assets_path': (/skypack/.test(ComponentPath) ? ComponentPath.replace('cdn.skypack.dev', 'unpkg.com') : ComponentPath) + '/dist/conversejs/', + 'authentication': this.element.dataset.authentication || 'login', + 'password': idToken, + 'allow_bookmarks': false, + 'allow_chat_pending_contacts': true, + 'allow_message_retraction': 'moderator', + 'allow_non_roster_messaging': true, + 'allow_dragresize': false, + 'allow_logout': false, + 'archived_messages_page_size': '30', + 'auto_list_rooms': true, + 'auto_login': this.element.dataset.autoLogin === 'true', + 'auto_join_on_invite': true, + 'auto_reconnect': true, + 'auto_register_muc_nickname': false, + 'websocket_url': this.element.dataset.websocketUrl || 'wss://jabber.happy-dev.fr/xmpp-websocket', + 'enable_smacks': true, + 'clear_messages_on_reconnection': false, + 'discover_connection_methods': false, + 'jid': jabberID.toLowerCase(), + 'i18n': this.element.dataset.i18n || 'fr', + 'loglevel': 'fatal', + 'message_archiving': 'always', + 'message_archiving_timeout': 60000, + 'muc_disable_slash_commands': true, + 'muc_hats': ['hats', 'vcard_roles', 'admin'], + 'role_affiliation_hat_conversions': { 'admin': 'Administrateur' }, + 'muc_nickname_from_jid': false, + 'muc_fetch_members': true, + 'muc_show_info_messages': [], + 'play_sounds': false, + 'root': this.element.shadowRoot, + 'show_client_info': false, + 'show_desktop_notifications': false, + 'persistent_store': 'none', + 'sounds_path': ComponentPath + '/dist/conversejs/', + 'show_send_button': false, + 'view_mode': 'fullscreen', + 'visible_toolbar_buttons': { + call: false, + spoiler: false, + emoji: true, + fileupload: true, // Not working in current Converse + toggle_occupants: false, + }, + 'whitelisted_plugins': [ + 'converse-rai', + 'sib-chat-navigation', + 'sib-connected', + 'sib-custom-hats', + 'sib-disconnected', + 'sib-mam-history', + 'sib-remove-notifications', + 'sib-subscribe-to-rai', + ], + }); + + converse_sib.loaded_deferred.resolve(); + }, 0); + }, }; Sib.register(SolidXMPPChat); diff --git a/src/utils.js b/src/utils.js index 0275089..01f067a 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,10 +1,10 @@ export class Deferred { - constructor() { - this.promise = new Promise(function(resolve, reject) { - this.resolve = resolve; - this.reject = reject; - }.bind(this)); - this.then = this.promise.then.bind(this.promise); - this.catch = this.promise.catch.bind(this.promise); - } + constructor() { + this.promise = new Promise(function(resolve, reject) { + this.resolve = resolve; + this.reject = reject; + }.bind(this)); + this.then = this.promise.then.bind(this.promise); + this.catch = this.promise.catch.bind(this.promise); + } } -- GitLab