Skip to content

Commit

Permalink
Fix types
Browse files Browse the repository at this point in the history
  • Loading branch information
jcbrand committed Nov 18, 2023
1 parent e2c81c0 commit eb4c20b
Show file tree
Hide file tree
Showing 53 changed files with 667 additions and 459 deletions.
12 changes: 6 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/headless/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
},
"dependencies": {
"@converse/openpromise": "^0.0.1",
"@converse/skeletor": "conversejs/skeletor#0cc6669bb2e5852caa1ef29892ce3822eadbff9a",
"@converse/skeletor": "conversejs/skeletor#26e12674e71475406b000b597dafc92dc6ce7737",
"dayjs": "^1.11.8",
"dompurify": "^2.3.1",
"filesize": "^10.0.7",
Expand All @@ -41,7 +41,7 @@
"pluggable.js": "3.0.1",
"sizzle": "^2.3.5",
"sprintf-js": "^1.1.2",
"strophe.js": "strophe/strophejs#6b24a2a2121884b2d02aeb5756142f7dcaf05d9e",
"strophe.js": "strophe/strophejs#d683aba6f5f0cd7aaa7fcb82b8a37792a3d5143c",
"urijs": "^1.19.10"
},
"devDependencies": {}
Expand Down
1 change: 0 additions & 1 deletion src/headless/plugins/chat/message.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ class Message extends ModelWithContact {

/**
* Sets an auto-destruct timer for this message, if it's is_ephemeral.
* @private
* @method _converse.Message#setTimerForEphemeralMessage
*/
setTimerForEphemeralMessage () {
Expand Down
35 changes: 21 additions & 14 deletions src/headless/plugins/chat/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,20 @@ class ChatBox extends ModelWithContact {
defaults () {
return {
'bookmarked': false,
'chat_state': undefined,
'hidden': isUniView() && !api.settings.get('singleton'),
'message_type': 'chat',
'nickname': undefined,
'num_unread': 0,
'time_opened': this.get('time_opened') || (new Date()).getTime(),
'time_sent': (new Date(0)).toISOString(),
'type': PRIVATE_CHAT_TYPE,
'url': ''
}
}

constructor (attrs, options) {
super(attrs, options);
this.disable_mam = false;
}

async initialize () {
super.initialize();
this.initialized = getOpenPromise();
Expand All @@ -70,7 +72,8 @@ class ChatBox extends ModelWithContact {
this.initMessages();

if (this.get('type') === PRIVATE_CHAT_TYPE) {
this.presence = _converse.presences.get(jid) || _converse.presences.create({ jid });
const { presences } = _converse.state;
this.presence = presences.get(jid) || presences.create({ jid });
await this.setRosterContact(jid);
this.presence.on('change:show', item => this.onPresenceChanged(item));
}
Expand All @@ -89,7 +92,7 @@ class ChatBox extends ModelWithContact {
}

getMessagesCollection () {
return new _converse.Messages();
return new _converse.exports.Messages();
}

getMessagesCacheKey () {
Expand Down Expand Up @@ -514,11 +517,11 @@ class ChatBox extends ModelWithContact {
}

/**
* @private
* @method ChatBox#shouldShowErrorMessage
* @returns {boolean}
* @param {object} attrs
* @returns {Promise<boolean>}
*/
shouldShowErrorMessage (attrs) {
async shouldShowErrorMessage (attrs) {
const msg = this.getMessageReferencedByError(attrs);
if (!msg && attrs.chat_state) {
// If the error refers to a message not included in our store,
Expand All @@ -528,7 +531,7 @@ class ChatBox extends ModelWithContact {
return;
}
// Gets overridden in MUC
return true;
return Promise.resolve(true);
}

isSameUser (jid1, jid2) {
Expand Down Expand Up @@ -567,7 +570,6 @@ class ChatBox extends ModelWithContact {

/**
* Handles message retraction based on the passed in attributes.
* @private
* @method ChatBox#handleRetraction
* @param {object} attrs - Attributes representing a received
* message, as returned by {@link parseMessage}
Expand Down Expand Up @@ -609,7 +611,7 @@ class ChatBox extends ModelWithContact {
* @method ChatBox#getDuplicateMessage
* @param {object} attrs - Attributes representing a received
* message, as returned by {@link parseMessage}
* @returns {Promise<Message>}
* @returns {Message}
*/
getDuplicateMessage (attrs) {
const queries = [
Expand Down Expand Up @@ -849,7 +851,7 @@ class ChatBox extends ModelWithContact {
const body = text ? u.shortnamesToUnicode(text) : undefined;
attrs = Object.assign({}, attrs, {
'from': _converse.session.get('bare_jid'),
'fullname': _converse.xmppstatus.get('fullname'),
'fullname': _converse.state.xmppstatus.get('fullname'),
'id': origin_id,
'is_only_emojis': text ? u.isOnlyEmojis(text) : false,
'jid': this.get('jid'),
Expand Down Expand Up @@ -1056,9 +1058,12 @@ class ChatBox extends ModelWithContact {
});
}

/**
* @param {boolean} force
*/
maybeShow (force) {
if (isUniView()) {
const filter = c => !c.get('hidden') &&
const filter = (c) => !c.get('hidden') &&
c.get('jid') !== this.get('jid') &&
c.get('id') !== 'controlbox';
const other_chats = _converse.state.chatboxes.filter(filter);
Expand Down Expand Up @@ -1088,7 +1093,6 @@ class ChatBox extends ModelWithContact {
/**
* Given a newly received {@link Message} instance,
* update the unread counter if necessary.
* @private
* @method ChatBox#handleUnreadMessage
* @param {Message} message
*/
Expand All @@ -1111,6 +1115,9 @@ class ChatBox extends ModelWithContact {
}
}

/**
* @param {Message} message
*/
incrementUnreadMsgsCounter (message) {
const settings = {
'num_unread': this.get('num_unread') + 1
Expand Down
16 changes: 9 additions & 7 deletions src/headless/plugins/chat/parsers.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,19 @@ export async function parseMessage (stanza) {

let to_jid = stanza.getAttribute('to');
const to_resource = Strophe.getResourceFromJid(to_jid);
if (api.settings.get('filter_by_resource') && to_resource && to_resource !== _converse.resource) {
const resource = _converse.session.get('resource');
if (api.settings.get('filter_by_resource') && to_resource && to_resource !== resource) {
return new StanzaParseError(
`Ignoring incoming message intended for a different resource: ${to_jid}`,
stanza
);
}

const bare_jid = _converse.session.get('bare_jid');
const original_stanza = stanza;
let from_jid = stanza.getAttribute('from') || _converse.bare_jid;
let from_jid = stanza.getAttribute('from') || bare_jid;
if (isCarbon(stanza)) {
if (from_jid === _converse.bare_jid) {
if (from_jid === bare_jid) {
const selector = `[xmlns="${Strophe.NS.CARBONS}"] > forwarded[xmlns="${Strophe.NS.FORWARD}"] > message`;
stanza = sizzle(selector, stanza).pop();
to_jid = stanza.getAttribute('to');
Expand All @@ -69,7 +71,7 @@ export async function parseMessage (stanza) {

const is_archived = isArchived(stanza);
if (is_archived) {
if (from_jid === _converse.bare_jid) {
if (from_jid === bare_jid) {
const selector = `[xmlns="${Strophe.NS.MAM}"] > forwarded[xmlns="${Strophe.NS.FORWARD}"] > message`;
stanza = sizzle(selector, stanza).pop();
to_jid = stanza.getAttribute('to');
Expand All @@ -83,7 +85,7 @@ export async function parseMessage (stanza) {
}

const from_bare_jid = Strophe.getBareJidFromJid(from_jid);
const is_me = from_bare_jid === _converse.bare_jid;
const is_me = from_bare_jid === bare_jid;
if (is_me && to_jid === null) {
return new StanzaParseError(
`Don't know how to handle message stanza without 'to' attribute. ${stanza.outerHTML}`,
Expand Down Expand Up @@ -190,12 +192,12 @@ export async function parseMessage (stanza) {
getCorrectionAttributes(stanza, original_stanza),
getStanzaIDs(stanza, original_stanza),
getRetractionAttributes(stanza, original_stanza),
getEncryptionAttributes(stanza, _converse)
getEncryptionAttributes(stanza)
);

if (attrs.is_archived) {
const from = original_stanza.getAttribute('from');
if (from && from !== _converse.bare_jid) {
if (from && from !== bare_jid) {
return new StanzaParseError(`Invalid Stanza: Forged MAM message from ${from}`, stanza);
}
}
Expand Down
59 changes: 37 additions & 22 deletions src/headless/plugins/chat/utils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/**
* @typedef {import('./model.js').default} ChatBox
* @typedef {module:plugin-chat-parsers.MessageAttributes} MessageAttributes
* @typedef {import('strophe.js').Builder} Builder
*/
import sizzle from "sizzle";
import { Model } from '@converse/skeletor';
import _converse from '../../shared/_converse.js';
Expand All @@ -24,18 +29,23 @@ export function routeToChat (event) {

export async function onClearSession () {
if (shouldClearCache()) {
const { chatboxes } = _converse.state;
await Promise.all(
_converse.chatboxes.map(c => c.messages && c.messages.clearStore({ 'silent': true }))
chatboxes.map(/** @param {ChatBox} c */(c) => c.messages?.clearStore({ 'silent': true }))
);
const filter = o => o.get('type') !== CONTROLBOX_TYPE;
_converse.chatboxes.clearStore({ 'silent': true }, filter);
chatboxes.clearStore(
{ 'silent': true },
/** @param {Model} o */(o) => o.get('type') !== CONTROLBOX_TYPE);
}
}


/**
* Given a stanza, determine whether it's a new
* message, i.e. not a MAM archived one.
* @param {Element|Model|object} message
*/
export function isNewMessage (message) {
/* Given a stanza, determine whether it's a new
* message, i.e. not a MAM archived one.
*/
if (message instanceof Element) {
return !(
sizzle(`result[xmlns="${Strophe.NS.MAM}"]`, message).length &&
Expand All @@ -48,9 +58,13 @@ export function isNewMessage (message) {
}


/**
* @param {Element} stanza
*/
async function handleErrorMessage (stanza) {
const from_jid = Strophe.getBareJidFromJid(stanza.getAttribute('from'));
if (u.isSameBareJID(from_jid, _converse.bare_jid)) {
const bare_jid = _converse.session.get('bare_jid');
if (u.isSameBareJID(from_jid, bare_jid)) {
return;
}
const chatbox = await api.chatboxes.get(from_jid);
Expand All @@ -62,8 +76,8 @@ async function handleErrorMessage (stanza) {
export function autoJoinChats () {
// Automatically join private chats, based on the
// "auto_join_private_chats" configuration setting.
api.settings.get('auto_join_private_chats').forEach(jid => {
if (_converse.chatboxes.where({ 'jid': jid }).length) {
api.settings.get('auto_join_private_chats').forEach(/** @param {string} jid */(jid) => {
if (_converse.state.chatboxes.where({ 'jid': jid }).length) {
return;
}
if (typeof jid === 'string') {
Expand All @@ -85,7 +99,8 @@ export function autoJoinChats () {

export function registerMessageHandlers () {
api.connection.get().addHandler(
stanza => {
/** @param {Element} stanza */
(stanza) => {
if (
['groupchat', 'error'].includes(stanza.getAttribute('type')) ||
isHeadline(stanza) ||
Expand All @@ -94,14 +109,15 @@ export function registerMessageHandlers () {
) {
return true;
}
return _converse.handleMessageStanza(stanza) || true;
return _converse.exports.handleMessageStanza(stanza) || true;
},
null,
'message',
);

api.connection.get().addHandler(
stanza => handleErrorMessage(stanza) || true,
/** @param {Element} stanza */
(stanza) => handleErrorMessage(stanza) || true,

Check warning

Code scanning / CodeQL

Missing await Warning

Missing await. The call to 'handleErrorMessage' always returns a promise.

Check warning

Code scanning / CodeQL

Useless conditional Warning

This call to handleErrorMessage always evaluates to true.
null,
'message',
'error'
Expand All @@ -111,10 +127,10 @@ export function registerMessageHandlers () {

/**
* Handler method for all incoming single-user chat "message" stanzas.
* @param { MessageAttributes } attrs - The message attributes
* @param {Element|Builder} stanza
*/
export async function handleMessageStanza (stanza) {
stanza = stanza.tree?.() ?? stanza;
stanza = (stanza instanceof Element) ? stanza : stanza.tree();

if (isServerMessage(stanza)) {
// Prosody sends headline messages with type `chat`, so we need to filter them out here.
Expand All @@ -136,30 +152,29 @@ export async function handleMessageStanza (stanza) {
const chatbox = await api.chats.get(attrs.contact_jid, { 'nickname': attrs.nick }, has_body);
await chatbox?.queueMessage(attrs);
/**
* @typedef { Object } MessageData
* @typedef {Object} MessageData
* An object containing the original message stanza, as well as the
* parsed attributes.
* @property { Element } stanza
* @property { MessageAttributes } stanza
* @property { ChatBox } chatbox
* @property {Element} stanza
* @property {MessageAttributes} stanza
* @property {ChatBox} chatbox
*/
const data = { stanza, attrs, chatbox };
/**
* Triggered when a message stanza is been received and processed.
* @event _converse#message
* @type { object }
* @property { module:converse-chat~MessageData } data
* @type {MessageData} data
*/
api.trigger('message', data);
}

/**
* Ask the XMPP server to enable Message Carbons
* See [XEP-0280](https://xmpp.org/extensions/xep-0280.html#enabling)
* @param { Boolean } reconnecting
*/
export async function enableCarbons () {
const domain = Strophe.getDomainFromJid(_converse.bare_jid);
const bare_jid = _converse.session.get('bare_jid');
const domain = Strophe.getDomainFromJid(bare_jid);
const supported = await api.disco.supports(Strophe.NS.CARBONS, domain);

if (!supported) {
Expand Down
Loading

0 comments on commit eb4c20b

Please sign in to comment.