Commit 37f43989 authored by JC Brand's avatar JC Brand Committed by GitHub

Merge pull request #1269 from conversejs/async-await

Async await
parents c583678c ad27edb2
......@@ -9569,12 +9569,15 @@ body.reset {
max-height: 200px; }
#conversejs.converse-overlayed .emoji-picker {
height: 100px; }
#conversejs.converse-overlayed .chatbox form.sendXMPPMessage .chat-toolbar li .toolbar-menu {
#conversejs.converse-overlayed .chatbox .sendXMPPMessage .chat-toolbar li .toolbar-menu {
min-width: 235px; }
#conversejs.converse-overlayed .chatbox form.sendXMPPMessage .chat-toolbar li .toolbar-menu ul.emoji-toolbar {
#conversejs.converse-overlayed .chatbox .sendXMPPMessage .chat-toolbar li .toolbar-menu ul.emoji-toolbar {
width: 100%; }
#conversejs.converse-overlayed .chatbox form.sendXMPPMessage .chat-toolbar li .toolbar-menu ul.emoji-toolbar .emoji-category {
#conversejs.converse-overlayed .chatbox .sendXMPPMessage .chat-toolbar li .toolbar-menu ul.emoji-toolbar .emoji-category {
float: left; }
#conversejs.converse-overlayed .chatbox .sendXMPPMessage .chat-toolbar li.toggle-smiley .emoji-toolbar .emoji-category-picker ul {
flex-wrap: wrap;
justify-content: flex-start; }
@media (max-width: 767.98px) {
#conversejs.converse-overlayed > .row {
......
This diff is collapsed.
......@@ -527,7 +527,7 @@
height: $overlayed-emoji-picker-height;
}
.chatbox {
form.sendXMPPMessage {
.sendXMPPMessage {
.chat-toolbar {
li {
.toolbar-menu {
......@@ -541,6 +541,16 @@
}
}
}
&.toggle-smiley {
.emoji-toolbar {
.emoji-category-picker {
ul {
flex-wrap: wrap;
justify-content: flex-start;
}
}
}
}
}
}
}
......
This diff is collapsed.
This diff is collapsed.
......@@ -2329,35 +2329,34 @@
}));
it("can be minimized by clicking a DOM element with class 'toggle-chatbox-button'",
mock.initConverseWithPromises(
null, ['rosterGroupsFetched', 'chatBoxesFetched'], {},
function (done, _converse) {
mock.initConverseWithPromises(
null, ['rosterGroupsFetched', 'chatBoxesFetched'], {},
async function (done, _converse) {
test_utils.openChatRoom(_converse, 'lounge', 'localhost', 'dummy')
.then(() => {
const view = _converse.chatboxviews.get('lounge@localhost'),
trimmed_chatboxes = _converse.minimized_chats;
await test_utils.openChatRoom(_converse, 'lounge', 'localhost', 'dummy');
const view = _converse.chatboxviews.get('lounge@localhost'),
trimmed_chatboxes = _converse.minimized_chats;
spyOn(view, 'minimize').and.callThrough();
spyOn(view, 'maximize').and.callThrough();
spyOn(_converse, 'emit');
view.delegateEvents(); // We need to rebind all events otherwise our spy won't be called
view.el.querySelector('.toggle-chatbox-button').click();
expect(view.minimize).toHaveBeenCalled();
expect(_converse.emit).toHaveBeenCalledWith('chatBoxMinimized', jasmine.any(Object));
expect(u.isVisible(view.el)).toBeFalsy();
expect(view.model.get('minimized')).toBeTruthy();
expect(view.minimize).toHaveBeenCalled();
var trimmedview = trimmed_chatboxes.get(view.model.get('id'));
trimmedview.el.querySelector("a.restore-chat").click();
expect(view.maximize).toHaveBeenCalled();
expect(_converse.emit).toHaveBeenCalledWith('chatBoxMaximized', jasmine.any(Object));
expect(view.model.get('minimized')).toBeFalsy();
expect(_converse.emit.calls.count(), 3);
done();
spyOn(view, 'minimize').and.callThrough();
spyOn(view, 'maximize').and.callThrough();
spyOn(_converse, 'emit');
view.delegateEvents(); // We need to rebind all events otherwise our spy won't be called
view.el.querySelector('.toggle-chatbox-button').click();
expect(view.minimize).toHaveBeenCalled();
expect(_converse.emit).toHaveBeenCalledWith('chatBoxMinimized', jasmine.any(Object));
expect(u.isVisible(view.el)).toBeFalsy();
expect(view.model.get('minimized')).toBeTruthy();
expect(view.minimize).toHaveBeenCalled();
await test_utils.waitUntil(() => trimmed_chatboxes.get(view.model.get('id')));
const trimmedview = trimmed_chatboxes.get(view.model.get('id'));
trimmedview.el.querySelector("a.restore-chat").click();
expect(view.maximize).toHaveBeenCalled();
expect(_converse.emit).toHaveBeenCalledWith('chatBoxMaximized', jasmine.any(Object));
expect(view.model.get('minimized')).toBeFalsy();
expect(_converse.emit.calls.count(), 3);
done();
});
}));
it("can be closed again by clicking a DOM element with class 'close-chatbox-button'",
......
This diff is collapsed.
......@@ -159,47 +159,50 @@
it("is played when the current user is mentioned in a chat room",
mock.initConverseWithPromises(
null, ['rosterGroupsFetched'], {},
function (done, _converse) {
async function (done, _converse) {
test_utils.createContacts(_converse, 'current');
test_utils.openAndEnterChatRoom(_converse, 'lounge', 'localhost', 'dummy').then(function () {
_converse.play_sounds = true;
spyOn(_converse, 'playSoundNotification');
var view = _converse.chatboxviews.get('lounge@localhost');
if (!$(view.el).find('.chat-area').length) { view.renderChatArea(); }
var text = 'This message will play a sound because it mentions dummy';
var message = $msg({
from: 'lounge@localhost/otheruser',
id: '1',
to: 'dummy@localhost',
type: 'groupchat'
}).c('body').t(text);
view.model.onMessage(message.nodeTree);
expect(_converse.playSoundNotification).toHaveBeenCalled();
text = "This message won't play a sound";
message = $msg({
from: 'lounge@localhost/otheruser',
id: '2',
to: 'dummy@localhost',
type: 'groupchat'
}).c('body').t(text);
view.model.onMessage(message.nodeTree);
expect(_converse.playSoundNotification, 1);
_converse.play_sounds = false;
text = "This message won't play a sound because it is sent by dummy";
message = $msg({
from: 'lounge@localhost/dummy',
id: '3',
to: 'dummy@localhost',
type: 'groupchat'
}).c('body').t(text);
view.model.onMessage(message.nodeTree);
expect(_converse.playSoundNotification, 1);
_converse.play_sounds = false;
done();
});
await test_utils.openAndEnterChatRoom(_converse, 'lounge', 'localhost', 'dummy');
_converse.play_sounds = true;
spyOn(_converse, 'playSoundNotification');
const view = _converse.chatboxviews.get('lounge@localhost');
if (!view.el.querySelectorAll('.chat-area').length) {
view.renderChatArea();
}
let text = 'This message will play a sound because it mentions dummy';
let message = $msg({
from: 'lounge@localhost/otheruser',
id: '1',
to: 'dummy@localhost',
type: 'groupchat'
}).c('body').t(text);
view.model.onMessage(message.nodeTree);
await test_utils.waitUntil(() => _converse.playSoundNotification.calls.count());
expect(_converse.playSoundNotification).toHaveBeenCalled();
text = "This message won't play a sound";
message = $msg({
from: 'lounge@localhost/otheruser',
id: '2',
to: 'dummy@localhost',
type: 'groupchat'
}).c('body').t(text);
view.model.onMessage(message.nodeTree);
expect(_converse.playSoundNotification, 1);
_converse.play_sounds = false;
text = "This message won't play a sound because it is sent by dummy";
message = $msg({
from: 'lounge@localhost/dummy',
id: '3',
to: 'dummy@localhost',
type: 'groupchat'
}).c('body').t(text);
view.model.onMessage(message.nodeTree);
expect(_converse.playSoundNotification, 1);
_converse.play_sounds = false;
done();
}));
});
});
......
......@@ -10,28 +10,21 @@
const u = converse.env.utils;
const checkHeaderToggling = function (group) {
var $group = $(group);
const checkHeaderToggling = async function (group) {
var toggle = group.querySelector('a.group-toggle');
expect(u.isVisible($group[0])).toBeTruthy();
expect($group.find('ul.collapsed').length).toBe(0);
expect(u.isVisible(group)).toBeTruthy();
expect(group.querySelectorAll('ul.collapsed').length).toBe(0);
expect(u.hasClass('fa-caret-right', toggle.firstElementChild)).toBeFalsy();
expect(u.hasClass('fa-caret-down', toggle.firstElementChild)).toBeTruthy();
toggle.click();
return test_utils.waitUntil(function () {
return $group.find('ul.collapsed').length === 1;
}, 500).then(function () {
expect(u.hasClass('fa-caret-right', toggle.firstElementChild)).toBeTruthy();
expect(u.hasClass('fa-caret-down', toggle.firstElementChild)).toBeFalsy();
toggle.click();
return test_utils.waitUntil(function () {
return $group.find('li').length === $group.find('li:visible').length
}, 500);
}).then(function () {
expect(u.hasClass('fa-caret-right', toggle.firstElementChild)).toBeFalsy();
expect(u.hasClass('fa-caret-down', toggle.firstElementChild)).toBeTruthy();
});
await test_utils.waitUntil(() => group.querySelectorAll('ul.collapsed').length === 1);
expect(u.hasClass('fa-caret-right', toggle.firstElementChild)).toBeTruthy();
expect(u.hasClass('fa-caret-down', toggle.firstElementChild)).toBeFalsy();
toggle.click();
await test_utils.waitUntil(() => group.querySelectorAll('li').length === $(group).find('li:visible').length);
expect(u.hasClass('fa-caret-right', toggle.firstElementChild)).toBeFalsy();
expect(u.hasClass('fa-caret-down', toggle.firstElementChild)).toBeTruthy();
};
......@@ -501,7 +494,7 @@
it("remembers whether it is closed or opened",
mock.initConverseWithPromises(
null, ['rosterGroupsFetched'], {},
function (done, _converse) {
async function (done, _converse) {
_converse.roster_groups = true;
test_utils.openControlBox();
......@@ -524,20 +517,14 @@
});
}
});
var view = _converse.rosterview.get('colleagues');
var $toggle = $(view.el).find('a.group-toggle');
const view = _converse.rosterview.get('colleagues');
const toggle = view.el.querySelector('a.group-toggle');
expect(view.model.get('state')).toBe('opened');
$toggle[0].click();
return test_utils.waitUntil(function () {
return view.model.get('state') === 'closed';
}, 500).then(function () {
$toggle[0].click();
return test_utils.waitUntil(function () {
return view.model.get('state') === 'opened';
}, 500)
}).then(function () {
done();
});
toggle.click();
await test_utils.waitUntil(() => view.model.get('state') === 'closed');
toggle.click();
await test_utils.waitUntil(() => view.model.get('state') === 'opened');
done();
}));
});
......
......@@ -105,6 +105,7 @@
spyOn(view, 'onMessageSubmitted').and.callThrough();
spyOn(_converse.connection, 'send');
await test_utils.waitUntil(() => view.el.querySelector('.toggle-compose-spoiler'));
let spoiler_toggle = view.el.querySelector('.toggle-compose-spoiler');
spoiler_toggle.click();
......@@ -178,6 +179,8 @@
await test_utils.openChatBoxFor(_converse, contact_jid);
await test_utils.waitUntilDiscoConfirmed(_converse, contact_jid+'/phone', [], [Strophe.NS.SPOILER]);
const view = _converse.chatboxviews.get(contact_jid);
await test_utils.waitUntil(() => view.el.querySelector('.toggle-compose-spoiler'));
let spoiler_toggle = view.el.querySelector('.toggle-compose-spoiler');
spoiler_toggle.click();
......
......@@ -69,15 +69,14 @@ converse.plugins.add('converse-bookmarks', {
close_button.insertAdjacentHTML('afterend', bookmark_button);
},
renderHeading () {
async renderHeading () {
this.__super__.renderHeading.apply(this, arguments);
const { _converse } = this.__super__;
if (_converse.allow_bookmarks) {
_converse.checkBookmarksSupport().then((supported) => {
if (supported) {
this.renderBookmarkToggle();
}
}).catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
const supported = await _converse.checkBookmarksSupport();
if (supported) {
this.renderBookmarkToggle();
}
}
},
......@@ -518,32 +517,25 @@ converse.plugins.add('converse-bookmarks', {
}
});
_converse.checkBookmarksSupport = function () {
return new Promise((resolve, reject) => {
Promise.all([
_converse.api.disco.getIdentity('pubsub', 'pep', _converse.bare_jid),
_converse.api.disco.supports(Strophe.NS.PUBSUB+'#publish-options', _converse.bare_jid)
]).then((args) => {
resolve(args[0] && (args[1].length || _converse.allow_public_bookmarks));
}).catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
}).catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
_converse.checkBookmarksSupport = async function () {
const args = await Promise.all([
_converse.api.disco.getIdentity('pubsub', 'pep', _converse.bare_jid),
_converse.api.disco.supports(Strophe.NS.PUBSUB+'#publish-options', _converse.bare_jid)
]);
return args[0] && (args[1].length || _converse.allow_public_bookmarks);
}
const initBookmarks = function () {
const initBookmarks = async function () {
if (!_converse.allow_bookmarks) {
return;
}
_converse.checkBookmarksSupport().then((supported) => {
if (supported) {
_converse.bookmarks = new _converse.Bookmarks();
_converse.bookmarksview = new _converse.BookmarksView({'model': _converse.bookmarks});
_converse.bookmarks.fetchBookmarks()
.catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL))
.then(() => _converse.emit('bookmarksInitialized'));
} else {
_converse.emit('bookmarksInitialized');
}
});
const supported = await _converse.checkBookmarksSupport();
if (supported) {
_converse.bookmarks = new _converse.Bookmarks();
_converse.bookmarksview = new _converse.BookmarksView({'model': _converse.bookmarks});
await _converse.bookmarks.fetchBookmarks();
}
_converse.emit('bookmarksInitialized');
}
u.onMultipleEvents([
......
......@@ -10,6 +10,7 @@ import "converse-modal";
import * as twemoji from "twemoji";
import bootstrap from "bootstrap";
import converse from "@converse/headless/converse-core";
import tpl_alert from "templates/alert.html";
import tpl_chatbox from "templates/chatbox.html";
import tpl_chatbox_head from "templates/chatbox_head.html";
import tpl_chatbox_message_form from "templates/chatbox_message_form.html";
......@@ -229,13 +230,23 @@ converse.plugins.add('converse-chatview', {
}
},
refreshContact (ev) {
async refreshContact (ev) {
if (ev && ev.preventDefault) { ev.preventDefault(); }
const refresh_icon = this.el.querySelector('.fa-refresh');
u.addClass('fa-spin', refresh_icon);
_converse.api.vcard.update(this.model.contact.vcard, true)
.then(() => u.removeClass('fa-spin', refresh_icon))
.catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
try {
await _converse.api.vcard.update(this.model.contact.vcard, true);
} catch (e) {
_converse.log(e, Strophe.LogLevel.FATAL);
this.el.querySelector('.modal-body').insertAdjacentHTML(
'afterBegin',
tpl_alert({
'type': 'alert-danger',
'message': __('Sorry, something went wrong while trying to refresh')
})
);
}
u.removeClass('fa-spin', refresh_icon);
},
removeContact (ev) {
......@@ -387,17 +398,16 @@ converse.plugins.add('converse-chatview', {
this.model.sendFiles(evt.target.files);
},
addFileUploadButton (options) {
_converse.api.disco.supports(Strophe.NS.HTTPUPLOAD, _converse.domain).then((result) => {
if (result.length) {
this.el.querySelector('.chat-toolbar').insertAdjacentHTML(
'beforeend',
tpl_toolbar_fileupload({'tooltip_upload_file': __('Choose a file to send')}));
}
}).catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
async addFileUploadButton (options) {
const result = await _converse.api.disco.supports(Strophe.NS.HTTPUPLOAD, _converse.domain);
if (result.length) {
this.el.querySelector('.chat-toolbar').insertAdjacentHTML(
'beforeend',
tpl_toolbar_fileupload({'tooltip_upload_file': __('Choose a file to send')}));
}
},
addSpoilerButton (options) {
async addSpoilerButton (options) {
/* Asynchronously adds a button for writing spoiler
* messages, based on whether the contact's client supports
* it.
......@@ -410,18 +420,17 @@ converse.plugins.add('converse-chatview', {
if (_.isEmpty(resources)) {
return;
}
Promise.all(_.map(_.keys(resources), (resource) =>
_converse.api.disco.supports(Strophe.NS.SPOILER, `${contact_jid}/${resource}`)
)).then((results) => {
if (_.filter(results, 'length').length) {
const html = tpl_spoiler_button(this.model.toJSON());
if (_converse.visible_toolbar_buttons.emoji) {
this.el.querySelector('.toggle-smiley').insertAdjacentHTML('afterEnd', html);
} else {
this.el.querySelector('.chat-toolbar').insertAdjacentHTML('afterBegin', html);
}
const results = await Promise.all(_.map(_.keys(resources),
resource => _converse.api.disco.supports(Strophe.NS.SPOILER, `${contact_jid}/${resource}`)
));
if (_.filter(results, 'length').length) {
const html = tpl_spoiler_button(this.model.toJSON());
if (_converse.visible_toolbar_buttons.emoji) {
this.el.querySelector('.toggle-smiley').insertAdjacentHTML('afterEnd', html);
} else {
this.el.querySelector('.chat-toolbar').insertAdjacentHTML('afterBegin', html);
}
}).catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
}
},
insertHeading () {
......
......@@ -229,7 +229,7 @@ converse.plugins.add('converse-minimize', {
);
},
trimChats (newchat) {
async trimChats (newchat) {
/* This method is called when a newly created chat box will
* be shown.
*
......@@ -250,35 +250,34 @@ converse.plugins.add('converse-minimize', {
// fullscreen. In this case we don't trim.
return;
}
_converse.api.waitUntil('minimizedChatsInitialized').then(() => {
const minimized_el = _.get(_converse.minimized_chats, 'el'),
new_id = newchat ? newchat.model.get('id') : null;
if (minimized_el) {
const minimized_width = _.includes(this.model.pluck('minimized'), true) ?
u.getOuterWidth(minimized_el, true) : 0;
const boxes_width = _.reduce(
this.xget(new_id),
(memo, view) => memo + this.getChatBoxWidth(view),
newchat ? u.getOuterWidth(newchat.el, true) : 0
);
if ((minimized_width + boxes_width) > body_width) {
const oldest_chat = this.getOldestMaximizedChat([new_id]);
if (oldest_chat) {
// We hide the chat immediately, because waiting
// for the event to fire (and letting the
// ChatBoxView hide it then) causes race
// conditions.
const view = this.get(oldest_chat.get('id'));
if (view) {
view.hide();
}
oldest_chat.minimize();
await _converse.api.waitUntil('minimizedChatsInitialized');
const minimized_el = _.get(_converse.minimized_chats, 'el'),
new_id = newchat ? newchat.model.get('id') : null;
if (minimized_el) {
const minimized_width = _.includes(this.model.pluck('minimized'), true) ?
u.getOuterWidth(minimized_el, true) : 0;
const boxes_width = _.reduce(
this.xget(new_id),
(memo, view) => memo + this.getChatBoxWidth(view),
newchat ? u.getOuterWidth(newchat.el, true) : 0
);
if ((minimized_width + boxes_width) > body_width) {
const oldest_chat = this.getOldestMaximizedChat([new_id]);
if (oldest_chat) {
// We hide the chat immediately, because waiting
// for the event to fire (and letting the
// ChatBoxView hide it then) causes race
// conditions.
const view = this.get(oldest_chat.get('id'));
if (view) {
view.hide();
}
oldest_chat.minimize();
}
}
}).catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
}
},
getOldestMaximizedChat (exclude_ids) {
......
......@@ -258,7 +258,7 @@ converse.plugins.add('converse-muc-views', {
} else {
parent_el.insertAdjacentHTML('beforeend', tpl_spinner());
_converse.api.disco.info(ev.target.getAttribute('data-room-jid'), null)
.then((stanza) => insertRoomInfo(parent_el, stanza))
.then(stanza => insertRoomInfo(parent_el, stanza))
.catch(_.partial(_converse.log, _, Strophe.LogLevel.ERROR));
}
}
......@@ -1159,7 +1159,7 @@ converse.plugins.add('converse-muc-views', {
*/
this.showSpinner();
this.model.fetchRoomConfiguration()
.then(this.renderConfigurationForm.bind(this))
.then(iq => this.renderConfigurationForm(iq))
.catch(_.partial(_converse.log, _, Strophe.LogLevel.ERROR));
},
......
......@@ -106,17 +106,16 @@ converse.plugins.add("converse-oauth", {
}));
},
fetchOAuthProfileDataAndLogin () {
this.oauth_service.api('me').then((profile) => {
const response = this.oauth_service.getAuthResponse();
_converse.api.user.login({
'jid': `${profile.name}@${this.provider.get('host')}`,
'password': response.access_token
});
async fetchOAuthProfileDataAndLogin () {
const profile = await this.oauth_service.api('me');
const response = this.oauth_service.getAuthResponse();
_converse.api.user.login({
'jid': `${profile.name}@${this.provider.get('host')}`,
'password': response.access_token
});
},
oauthLogin (ev) {
async oauthLogin (ev) {
ev.preventDefault();
const id = ev.target.getAttribute('data-id');
this.provider = _converse.oauth_providers.get(id);
......@@ -128,10 +127,8 @@ converse.plugins.add("converse-oauth", {
'redirect_uri': '/redirect.html'
});
this.oauth_service.login().then(
() => this.fetchOAuthProfileDataAndLogin(),
(error) => _converse.log(error.error_message, Strophe.LogLevel.ERROR)
);
await this.oauth_service.login();
this.fetchOAuthProfileDataAndLogin();
}
});
}
......
......@@ -11,7 +11,6 @@ import "converse-modal";
import _FormData from "formdata-polyfill";
import bootstrap from "bootstrap";
import converse from "@converse/headless/converse-core";
import tpl_alert from "templates/alert.html";
import tpl_chat_status_modal from "templates/chat_status_modal.html";
import tpl_profile_modal from "templates/profile_modal.html";
import tpl_profile_view from "templates/profile_view.html";
......
......@@ -680,15 +680,14 @@ converse.plugins.add('converse-rosterview', {
this.filterOutContacts(this.getFilterMatches(q, type));
},
toggle (ev) {
async toggle (ev) {
if (ev && ev.preventDefault) { ev.preventDefault(); }
const icon_el = ev.target.querySelector('.fa');
if (_.includes(icon_el.classList, "fa-caret-down")) {
this.model.save({state: _converse.CLOSED});
this.collapse().then(() => {
icon_el.classList.remove("fa-caret-down");
icon_el.classList.add("fa-caret-right");
});
await this.collapse();
icon_el.classList.remove("fa-caret-down");
icon_el.classList.add("fa-caret-right");
} else {
icon_el.classList.remove("fa-caret-right");
icon_el.classList.add("fa-caret-down");
......
......@@ -144,27 +144,29 @@ converse.plugins.add('converse-chatboxes', {
return _converse.api.sendIQ(iq);
},
getRequestSlotURL () {
this.sendSlotRequestStanza().then((stanza) => {
const slot = stanza.querySelector('slot');
if (slot) {
this.save({
'get': slot.querySelector('get').getAttribute('url'),
'put': slot.querySelector('put').getAttribute('url'),
});
} else {
return this.save({
'type': 'error',
'message': __("Sorry, could not determine file upload URL.")
});
}
}).catch((e) => {
async getRequestSlotURL () {
let stanza;
try {
stanza = await this.sendSlotRequestStanza();
} catch (e) {
_converse.log(e, Strophe.LogLevel.ERROR);
return this.save({
'type': 'error',
'message': __("Sorry, could not determine upload URL.")
});
});
}
const slot = stanza.querySelector('slot');
if (slot) {
this.save({
'get': slot.querySelector('get').getAttribute('url'),
'put': slot.querySelector('put').getAttribute('url'),
});
} else {
return this.save({
'type': 'error',
'message': __("Sorry, could not determine file upload URL.")
});
}
},
uploadFile () {
......
......@@ -162,13 +162,14 @@ converse.plugins.add('converse-disco', {
});
},
queryForItems () {
async queryForItems () {
if (_.isEmpty(this.identities.where({'category': 'server'}))) {
// Don't fetch features and items if this is not a
// server or a conference component.
return;
}
_converse.api.disco.items(this.get('jid')).then(stanza => this.onDiscoItems(stanza));
const stanza = await _converse.api.disco.items(this.get('jid'));
this.onDiscoItems(stanza);
},
onInfo (stanza) {
......@@ -268,7 +269,7 @@ converse.plugins.add('converse-disco', {
_converse.emit('streamFeaturesAdded');
}
function initializeDisco () {
async function initializeDisco () {
addClientFeatures();
_converse.connection.addHandler(onDiscoInfoRequest, Strophe.NS.DISCO_INFO, 'iq', 'get', null, null);
......@@ -277,14 +278,13 @@ converse.plugins.add('converse-disco', {
b64_sha1(`converse.disco-entities-${_converse.bare_jid}`)
);
_converse.disco_entities.fetchEntities().then((collection) => {
if (collection.length === 0 || !collection.get(_converse.domain)) {
// If we don't have an entity for our own XMPP server,
// create one.
_converse.disco_entities.create({'jid': _converse.domain});
}
_converse.emit('discoInitialized');
}).catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
const collection = await _converse.disco_entities.fetchEntities();
if (collection.length === 0 || !collection.get(_converse.domain)) {
// If we don't have an entity for our own XMPP server,
// create one.
_converse.disco_entities.create({'jid': _converse.domain});
}
_converse.emit('discoInitialized');
}
_converse.api.listen.on('sessionInitialized', initStreamFeatures);
......@@ -513,18 +513,16 @@ converse.plugins.add('converse-disco', {
* @param {boolean} [create] Whether the entity should be created if it doesn't exist.
* @example _converse.api.disco.entities.get(jid);
*/
'get' (jid, create=false) {
return _converse.api.waitUntil('discoInitialized')
.then(() => {
if (_.isNil(jid)) {
return _converse.disco_entities;
}
const entity = _converse.disco_entities.get(jid);
if (entity || !create) {
return entity;
}
return _converse.disco_entities.create({'jid': jid});
});
async 'get' (jid, create=false) {
await _converse.api.waitUntil('discoInitialized');
if (_.isNil(jid)) {
return _converse.disco_entities;
}
const entity = _converse.disco_entities.get(jid);
if (entity || !create) {
return entity;
}
return _converse.disco_entities.create({'jid': jid});
}
},
......@@ -559,20 +557,19 @@ converse.plugins.add('converse-disco', {
* );
* });
*/
'supports' (feature, jid) {
async 'supports' (feature, jid) {
if (_.isNil(jid)) {
throw new TypeError('api.disco.supports: You need to provide an entity JID');
}
return _converse.api.waitUntil('discoInitialized')
.then(() => _converse.api.disco.entities.get(jid, true))
.then(entity => entity.waitUntilFeaturesDiscovered)
.then(entity => {
const promises = _.concat(
entity.items.map(item => item.hasFeature(feature)),
entity.hasFeature(feature)
);
return Promise.all(promises);
}).then(result => f.filter(f.isObject, result));
await _converse.api.waitUntil('discoInitialized');
let entity = await _converse.api.disco.entities.get(jid, true);
entity = await entity.waitUntilFeaturesDiscovered;
const promises = _.concat(
entity.items.map(item => item.hasFeature(feature)),
entity.hasFeature(feature)
);
const result = await Promise.all(promises);
return f.filter(f.isObject, result);
},
/**
......@@ -585,21 +582,18 @@ converse.plugins.add('converse-disco', {
* @example
* await _converse.api.disco.refreshFeatures('room@conference.example.org');
*/
'refreshFeatures' (jid) {
async 'refreshFeatures' (jid) {
if (_.isNil(jid)) {
throw new TypeError('api.disco.refreshFeatures: You need to provide an entity JID');
}
return _converse.api.waitUntil('discoInitialized')
.then(() => _converse.api.disco.entities.get(jid, true))
.then(entity => {
entity.features.reset();
entity.fields.reset();
entity.identities.reset();
entity.waitUntilFeaturesDiscovered = utils.getResolveablePromise()
entity.queryInfo();
return entity.waitUntilFeaturesDiscovered;
})
.catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
await _converse.api.waitUntil('discoInitialized');
const entity = await _converse.api.disco.entities.get(jid, true);
entity.features.reset();
entity.fields.reset();
entity.identities.reset();
entity.waitUntilFeaturesDiscovered = utils.getResolveablePromise()
entity.queryInfo();
return entity.waitUntilFeaturesDiscovered;
},
/**
......@@ -611,15 +605,14 @@ converse.plugins.add('converse-disco', {
* @example
* const features = await _converse.api.disco.getFeatures('room@conference.example.org');
*/
'getFeatures' (jid) {
async 'getFeatures' (jid) {
if (_.isNil(jid)) {
throw new TypeError('api.disco.getFeatures: You need to provide an entity JID');
}
return _converse.api.waitUntil('discoInitialized')
.then(() => _converse.api.disco.entities.get(jid, true))
.then(entity => entity.waitUntilFeaturesDiscovered)
.then(entity => entity.features)
.catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
await _converse.api.waitUntil('discoInitialized');
let entity = await _converse.api.disco.entities.get(jid, true);
entity = await entity.waitUntilFeaturesDiscovered;
return entity.features;
},
/**
......@@ -633,15 +626,14 @@ converse.plugins.add('converse-disco', {
* @example
* const fields = await _converse.api.disco.getFields('room@conference.example.org');
*/
'getFields' (jid) {
async 'getFields' (jid) {
if (_.isNil(jid)) {
throw new TypeError('api.disco.getFields: You need to provide an entity JID');
}
return _converse.api.waitUntil('discoInitialized')
.then(() => _converse.api.disco.entities.get(jid, true))
.then(entity => entity.waitUntilFeaturesDiscovered)
.then(entity => entity.fields)
.catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
await _converse.api.waitUntil('discoInitialized');
let entity = await _converse.api.disco.entities.get(jid, true);
entity = await entity.waitUntilFeaturesDiscovered;
return entity.fields;
},
/**
......@@ -675,8 +667,9 @@ converse.plugins.add('converse-disco', {
* }
* ).catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
*/
'getIdentity' (category, type, jid) {
return _converse.api.disco.entities.get(jid, true).then(e => e.getIdentity(category, type));
async 'getIdentity' (category, type, jid) {
const e = await _converse.api.disco.entities.get(jid, true);
return e.getIdentity(category, type);
}
}
});
......
......@@ -109,20 +109,18 @@ converse.plugins.add('converse-muc', {
_converse.api.promises.add(['roomsAutoJoined']);
function openRoom (jid) {
async function openRoom (jid) {
if (!u.isValidMUCJID(jid)) {
return _converse.log(
`Invalid JID "${jid}" provided in URL fragment`,
Strophe.LogLevel.WARN
);
}
const promises = [_converse.api.waitUntil('roomsAutoJoined')]
await _converse.api.waitUntil('roomsAutoJoined');
if (_converse.allow_bookmarks) {
promises.push( _converse.api.waitUntil('bookmarksInitialized'));
await _converse.api.waitUntil('bookmarksInitialized');
}
Promise.all(promises).then(() => {
_converse.api.rooms.open(jid);
});
_converse.api.rooms.open(jid);
}
_converse.router.route('converse/room?jid=:jid', openRoom);
......@@ -762,7 +760,7 @@ converse.plugins.add('converse-muc', {
}
},
checkForReservedNick () {
async checkForReservedNick () {
/* Use service-discovery to ask the XMPP server whether
* this user has a reserved nickname for this groupchat.
* If so, we'll use that, otherwise we render the nickname form.
......@@ -771,7 +769,7 @@ converse.plugins.add('converse-muc', {
* (Function) callback: Callback upon succesful IQ response
* (Function) errback: Callback upon error IQ response
*/
return _converse.api.sendIQ(
const iq = await _converse.api.sendIQ(
$iq({
'to': this.get('jid'),
'from': _converse.connection.jid,
......@@ -780,15 +778,14 @@ converse.plugins.add('converse-muc', {
'xmlns': Strophe.NS.DISCO_INFO,
'node': 'x-roomuser-item'
})
).then(iq => {
const identity_el = iq.querySelector('query[node="x-roomuser-item"] identity'),
nick = identity_el ? identity_el.getAttribute('name') : null;
this.save({
'reserved_nick': nick,
'nick': nick
}, {'silent': true});
return iq;
});
);
const identity_el = iq.querySelector('query[node="x-roomuser-item"] identity'),
nick = identity_el ? identity_el.getAttribute('name') : null;
this.save({
'reserved_nick': nick,
'nick': nick
}, {'silent': true});
return iq;
},
async registerNickname () {
......@@ -939,7 +936,7 @@ converse.plugins.add('converse-muc', {
}
},
onMessage (stanza) {
async onMessage (stanza) {
/* Handler for all MUC messages sent to this groupchat.
*
* Parameters:
......@@ -968,9 +965,8 @@ converse.plugins.add('converse-muc', {
const subject = _.propertyOf(subject_el)('textContent') || '';
u.safeSave(this, {'subject': {'author': sender, 'text': subject}});
}
this.createMessage(stanza, original_stanza)
.then(msg => this.incrementUnreadMsgCounter(msg))
.catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
const msg = await this.createMessage(stanza, original_stanza);
this.incrementUnreadMsgCounter(msg);
}
if (sender !== this.get('nick')) {
// We only emit an event if it's not our own message
......@@ -1141,37 +1137,35 @@ converse.plugins.add('converse-muc', {
}
},
fetchMembers () {
this.chatroom.getJidsWithAffiliations(['member', 'owner', 'admin'])
.then(new_members => {
const new_jids = new_members.map(m => m.jid).filter(m => !_.isUndefined(m)),
new_nicks = new_members.map(m => !m.jid && m.nick || undefined).filter(m => !_.isUndefined(m)),
removed_members = this.filter(m => {
return f.includes(m.get('affiliation'), ['admin', 'member', 'owner']) &&
!f.includes(m.get('nick'), new_nicks) &&
!f.includes(m.get('jid'), new_jids);
});
_.each(removed_members, (occupant) => {
if (occupant.get('jid') === _converse.bare_jid) { return; }
if (occupant.get('show') === 'offline') {
occupant.destroy();
}
});
_.each(new_members, (attrs) => {
let occupant;
if (attrs.jid) {
occupant = this.findOccupant({'jid': attrs.jid});
} else {
occupant = this.findOccupant({'nick': attrs.nick});
}
if (occupant) {
occupant.save(attrs);
} else {
this.create(attrs);
}
});
}).catch(_.partial(_converse.log, _, Strophe.LogLevel.ERROR));
async fetchMembers () {
const new_members = await this.chatroom.getJidsWithAffiliations(['member', 'owner', 'admin']);
const new_jids = new_members.map(m => m.jid).filter(m => !_.isUndefined(m)),
new_nicks = new_members.map(m => !m.jid && m.nick || undefined).filter(m => !_.isUndefined(m)),
removed_members = this.filter(m => {
return f.includes(m.get('affiliation'), ['admin', 'member', 'owner']) &&
!f.includes(m.get('nick'), new_nicks) &&
!f.includes(m.get('jid'), new_jids);
});
_.each(removed_members, (occupant) => {
if (occupant.get('jid') === _converse.bare_jid) { return; }
if (occupant.get('show') === 'offline') {
occupant.destroy();
}
});
_.each(new_members, (attrs) => {
let occupant;
if (attrs.jid) {
occupant = this.findOccupant({'jid': attrs.jid});
} else {
occupant = this.findOccupant({'nick': attrs.nick});
}
if (occupant) {
occupant.save(attrs);
} else {
this.create(attrs);
}
});
},
findOccupant (data) {
......
......@@ -333,14 +333,6 @@ u.replaceCurrentWord = function (input, new_value) {
input.selectionEnd = cursor - current_word.length + new_value.length + 1;
};
u.isVisible = function (el) {
if (u.hasClass('hidden', el)) {
return false;
}
// XXX: Taken from jQuery's "visible" implementation
return el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0;
};
u.triggerEvent = function (el, name, type="Event", bubbles=true, cancelable=true) {
const evt = document.createEvent(type);
evt.initEvent(name, bubbles, cancelable);
......
<div class="alert {{{o.type}}}" role="alert">{{{o.message}}}</div>
<div class="alert {{{o.type}}}" role="alert"><p>{{{o.message}}}</p></div>
......@@ -500,6 +500,15 @@ function afterAnimationEnds (el, callback) {
}
}
u.isVisible = function (el) {
if (u.hasClass('hidden', el)) {
return false;
}
// XXX: Taken from jQuery's "visible" implementation
return el.offsetWidth > 0 || el.offsetHeight > 0 || el.getClientRects().length > 0;
};
u.fadeIn = function (el, callback) {
if (_.isNil(el)) {
logger.warn("Undefined or null element passed into fadeIn");
......
......@@ -179,7 +179,6 @@ require.config(config);
var specs = [
"jasmine",
//"spec/transcripts",
//"spec/otr",
"spec/spoilers",
"spec/profiling",
"spec/utils",
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment