utils.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. (function (root, factory) {
  2. define(['mock'], factory);
  3. }(this, function (mock) {
  4. const _ = converse.env._;
  5. const $msg = converse.env.$msg;
  6. const $pres = converse.env.$pres;
  7. const $iq = converse.env.$iq;
  8. const Strophe = converse.env.Strophe;
  9. const sizzle = converse.env.sizzle;
  10. const u = converse.env.utils;
  11. const utils = {};
  12. utils.waitUntilDiscoConfirmed = async function (_converse, entity_jid, identities, features=[], items=[], type='info') {
  13. const iq = await u.waitUntil(() => {
  14. return _.filter(
  15. _converse.connection.IQ_stanzas,
  16. (iq) => sizzle(`iq[to="${entity_jid}"] query[xmlns="http://jabber.org/protocol/disco#${type}"]`, iq).length
  17. ).pop();
  18. }, 300);
  19. const stanza = $iq({
  20. 'type': 'result',
  21. 'from': entity_jid,
  22. 'to': 'romeo@montague.lit/orchard',
  23. 'id': iq.getAttribute('id'),
  24. }).c('query', {'xmlns': 'http://jabber.org/protocol/disco#'+type});
  25. _.forEach(identities, function (identity) {
  26. stanza.c('identity', {'category': identity.category, 'type': identity.type}).up()
  27. });
  28. _.forEach(features, function (feature) {
  29. stanza.c('feature', {'var': feature}).up();
  30. });
  31. _.forEach(items, function (item) {
  32. stanza.c('item', {'jid': item}).up();
  33. });
  34. _converse.connection._dataRecv(utils.createRequest(stanza));
  35. }
  36. utils.createRequest = function (iq) {
  37. iq = typeof iq.tree == "function" ? iq.tree() : iq;
  38. var req = new Strophe.Request(iq, function() {});
  39. req.getResponse = function () {
  40. var env = new Strophe.Builder('env', {type: 'mock'}).tree();
  41. env.appendChild(iq);
  42. return env;
  43. };
  44. return req;
  45. };
  46. utils.closeAllChatBoxes = function (_converse) {
  47. return Promise.all(_converse.chatboxviews.map(view => view.close()));
  48. };
  49. utils.openControlBox = async function (_converse) {
  50. const model = await _converse.api.controlbox.open();
  51. await u.waitUntil(() => model.get('connected'));
  52. var toggle = document.querySelector(".toggle-controlbox");
  53. if (!u.isVisible(document.querySelector("#controlbox"))) {
  54. if (!u.isVisible(toggle)) {
  55. u.removeClass('hidden', toggle);
  56. }
  57. toggle.click();
  58. }
  59. return this;
  60. };
  61. utils.closeControlBox = function () {
  62. const controlbox = document.querySelector("#controlbox");
  63. if (u.isVisible(controlbox)) {
  64. const button = controlbox.querySelector(".close-chatbox-button");
  65. if (!_.isNull(button)) {
  66. button.click();
  67. }
  68. }
  69. return this;
  70. };
  71. utils.waitUntilBookmarksReturned = async function (_converse, bookmarks=[]) {
  72. await utils.waitUntilDiscoConfirmed(
  73. _converse, _converse.bare_jid,
  74. [{'category': 'pubsub', 'type': 'pep'}],
  75. ['http://jabber.org/protocol/pubsub#publish-options']
  76. );
  77. const IQ_stanzas = _converse.connection.IQ_stanzas;
  78. const sent_stanza = await u.waitUntil(
  79. () => IQ_stanzas.filter(s => sizzle('items[node="storage:bookmarks"]', s).length).pop()
  80. );
  81. const stanza = $iq({
  82. 'to': _converse.connection.jid,
  83. 'type':'result',
  84. 'id':sent_stanza.getAttribute('id')
  85. }).c('pubsub', {'xmlns': Strophe.NS.PUBSUB})
  86. .c('items', {'node': 'storage:bookmarks'})
  87. .c('item', {'id': 'current'})
  88. .c('storage', {'xmlns': 'storage:bookmarks'});
  89. bookmarks.forEach(bookmark => {
  90. stanza.c('conference', {
  91. 'name': bookmark.name,
  92. 'autojoin': bookmark.autojoin,
  93. 'jid': bookmark.jid
  94. }).c('nick').t(bookmark.nick).up().up()
  95. });
  96. _converse.connection._dataRecv(utils.createRequest(stanza));
  97. await _converse.api.waitUntil('bookmarksInitialized');
  98. };
  99. utils.openChatBoxes = function (converse, amount) {
  100. const views = [];
  101. for (let i=0; i<amount; i++) {
  102. const jid = mock.cur_names[i].replace(/ /g,'.').toLowerCase() + '@montague.lit';
  103. views.push(converse.roster.get(jid).trigger("open"));
  104. }
  105. return views;
  106. };
  107. utils.openChatBoxFor = async function (_converse, jid) {
  108. await _converse.api.waitUntil('rosterContactsFetched');
  109. _converse.roster.get(jid).trigger("open");
  110. return u.waitUntil(() => _converse.chatboxviews.get(jid), 1000);
  111. };
  112. utils.openChatRoomViaModal = async function (_converse, jid, nick='') {
  113. // Opens a new chatroom
  114. const model = await _converse.api.controlbox.open('controlbox');
  115. await u.waitUntil(() => model.get('connected'));
  116. await utils.openControlBox(_converse);
  117. const view = await _converse.chatboxviews.get('controlbox');
  118. const roomspanel = view.roomspanel;
  119. roomspanel.el.querySelector('.show-add-muc-modal').click();
  120. utils.closeControlBox(_converse);
  121. const modal = roomspanel.add_room_modal;
  122. await u.waitUntil(() => u.isVisible(modal.el), 1500)
  123. modal.el.querySelector('input[name="chatroom"]').value = jid;
  124. if (nick) {
  125. modal.el.querySelector('input[name="nickname"]').value = nick;
  126. }
  127. modal.el.querySelector('form input[type="submit"]').click();
  128. await u.waitUntil(() => _converse.chatboxviews.get(jid), 1000);
  129. return _converse.chatboxviews.get(jid);
  130. };
  131. utils.openChatRoom = function (_converse, room, server) {
  132. return _converse.api.rooms.open(`${room}@${server}`);
  133. };
  134. utils.getRoomFeatures = async function (_converse, muc_jid, features=[]) {
  135. const room = Strophe.getNodeFromJid(muc_jid);
  136. muc_jid = muc_jid.toLowerCase();
  137. const stanzas = _converse.connection.IQ_stanzas;
  138. const stanza = await u.waitUntil(() => stanzas.filter(
  139. iq => iq.querySelector(
  140. `iq[to="${muc_jid}"] query[xmlns="http://jabber.org/protocol/disco#info"]`
  141. )).pop()
  142. );
  143. const features_stanza = $iq({
  144. 'from': muc_jid,
  145. 'id': stanza.getAttribute('id'),
  146. 'to': 'romeo@montague.lit/desktop',
  147. 'type': 'result'
  148. }).c('query', { 'xmlns': 'http://jabber.org/protocol/disco#info'})
  149. .c('identity', {
  150. 'category': 'conference',
  151. 'name': room[0].toUpperCase() + room.slice(1),
  152. 'type': 'text'
  153. }).up();
  154. features = features.length ? features : mock.default_muc_features;
  155. features.forEach(f => features_stanza.c('feature', {'var': f}).up());
  156. features_stanza.c('x', { 'xmlns':'jabber:x:data', 'type':'result'})
  157. .c('field', {'var':'FORM_TYPE', 'type':'hidden'})
  158. .c('value').t('http://jabber.org/protocol/muc#roominfo').up().up()
  159. .c('field', {'type':'text-single', 'var':'muc#roominfo_description', 'label':'Description'})
  160. .c('value').t('This is the description').up().up()
  161. .c('field', {'type':'text-single', 'var':'muc#roominfo_occupants', 'label':'Number of occupants'})
  162. .c('value').t(0);
  163. _converse.connection._dataRecv(utils.createRequest(features_stanza));
  164. };
  165. utils.waitForReservedNick = async function (_converse, muc_jid, nick) {
  166. const stanzas = _converse.connection.IQ_stanzas;
  167. const selector = `iq[to="${muc_jid.toLowerCase()}"] query[node="x-roomuser-item"]`;
  168. const iq = await u.waitUntil(() => stanzas.filter(s => sizzle(selector, s).length).pop());
  169. // We remove the stanza, otherwise we might get stale stanzas returned in our filter above.
  170. stanzas.splice(stanzas.indexOf(iq), 1)
  171. // The XMPP server returns the reserved nick for this user.
  172. const IQ_id = iq.getAttribute('id');
  173. const stanza = $iq({
  174. 'type': 'result',
  175. 'id': IQ_id,
  176. 'from': muc_jid,
  177. 'to': _converse.connection.jid
  178. }).c('query', {'xmlns': 'http://jabber.org/protocol/disco#info', 'node': 'x-roomuser-item'});
  179. if (nick) {
  180. stanza.c('identity', {'category': 'conference', 'name': nick, 'type': 'text'});
  181. }
  182. _converse.connection._dataRecv(utils.createRequest(stanza));
  183. if (nick) {
  184. return u.waitUntil(() => nick);
  185. }
  186. };
  187. utils.returnMemberLists = async function (_converse, muc_jid, members=[], affiliations=['member', 'owner', 'admin']) {
  188. if (affiliations.length === 0) {
  189. return;
  190. }
  191. const stanzas = _converse.connection.IQ_stanzas;
  192. if (affiliations.includes('member')) {
  193. const member_IQ = await u.waitUntil(() => _.filter(
  194. stanzas,
  195. s => sizzle(`iq[to="${muc_jid}"] query[xmlns="${Strophe.NS.MUC_ADMIN}"] item[affiliation="member"]`, s).length
  196. ).pop());
  197. const member_list_stanza = $iq({
  198. 'from': 'coven@chat.shakespeare.lit',
  199. 'id': member_IQ.getAttribute('id'),
  200. 'to': 'romeo@montague.lit/orchard',
  201. 'type': 'result'
  202. }).c('query', {'xmlns': Strophe.NS.MUC_ADMIN});
  203. members.filter(m => m.affiliation === 'member').forEach(m => {
  204. member_list_stanza.c('item', {
  205. 'affiliation': m.affiliation,
  206. 'jid': m.jid,
  207. 'nick': m.nick
  208. });
  209. });
  210. _converse.connection._dataRecv(utils.createRequest(member_list_stanza));
  211. }
  212. if (affiliations.includes('admin')) {
  213. const admin_IQ = await u.waitUntil(() => _.filter(
  214. stanzas,
  215. s => sizzle(`iq[to="${muc_jid}"] query[xmlns="${Strophe.NS.MUC_ADMIN}"] item[affiliation="admin"]`, s).length
  216. ).pop());
  217. const admin_list_stanza = $iq({
  218. 'from': 'coven@chat.shakespeare.lit',
  219. 'id': admin_IQ.getAttribute('id'),
  220. 'to': 'romeo@montague.lit/orchard',
  221. 'type': 'result'
  222. }).c('query', {'xmlns': Strophe.NS.MUC_ADMIN});
  223. members.filter(m => m.affiliation === 'admin').forEach(m => {
  224. admin_list_stanza.c('item', {
  225. 'affiliation': m.affiliation,
  226. 'jid': m.jid,
  227. 'nick': m.nick
  228. });
  229. });
  230. _converse.connection._dataRecv(utils.createRequest(admin_list_stanza));
  231. }
  232. if (affiliations.includes('owner')) {
  233. const owner_IQ = await u.waitUntil(() => _.filter(
  234. stanzas,
  235. s => sizzle(`iq[to="${muc_jid}"] query[xmlns="${Strophe.NS.MUC_ADMIN}"] item[affiliation="owner"]`, s).length
  236. ).pop());
  237. const owner_list_stanza = $iq({
  238. 'from': 'coven@chat.shakespeare.lit',
  239. 'id': owner_IQ.getAttribute('id'),
  240. 'to': 'romeo@montague.lit/orchard',
  241. 'type': 'result'
  242. }).c('query', {'xmlns': Strophe.NS.MUC_ADMIN});
  243. members.filter(m => m.affiliation === 'owner').forEach(m => {
  244. owner_list_stanza.c('item', {
  245. 'affiliation': m.affiliation,
  246. 'jid': m.jid,
  247. 'nick': m.nick
  248. });
  249. });
  250. _converse.connection._dataRecv(utils.createRequest(owner_list_stanza));
  251. }
  252. return new Promise(resolve => _converse.api.listen.on('membersFetched', resolve));
  253. };
  254. utils.receiveOwnMUCPresence = async function (_converse, muc_jid, nick) {
  255. const sent_stanzas = _converse.connection.sent_stanzas;
  256. await u.waitUntil(() => sent_stanzas.filter(iq => sizzle('presence history', iq).length).pop());
  257. const presence = $pres({
  258. to: _converse.connection.jid,
  259. from: `${muc_jid}/${nick}`,
  260. id: u.getUniqueId()
  261. }).c('x').attrs({xmlns:'http://jabber.org/protocol/muc#user'})
  262. .c('item').attrs({
  263. affiliation: 'owner',
  264. jid: _converse.bare_jid,
  265. role: 'moderator'
  266. }).up()
  267. .c('status').attrs({code:'110'});
  268. _converse.connection._dataRecv(utils.createRequest(presence));
  269. };
  270. utils.openAndEnterChatRoom = async function (_converse, muc_jid, nick, features=[], members=[]) {
  271. muc_jid = muc_jid.toLowerCase();
  272. const room_creation_promise = _converse.api.rooms.open(muc_jid);
  273. await utils.getRoomFeatures(_converse, muc_jid, features);
  274. await utils.waitForReservedNick(_converse, muc_jid, nick);
  275. // The user has just entered the room (because join was called)
  276. // and receives their own presence from the server.
  277. // See example 24: https://xmpp.org/extensions/xep-0045.html#enter-pres
  278. await utils.receiveOwnMUCPresence(_converse, muc_jid, nick);
  279. await room_creation_promise;
  280. const view = _converse.chatboxviews.get(muc_jid);
  281. await u.waitUntil(() => (view.model.session.get('connection_status') === converse.ROOMSTATUS.ENTERED));
  282. const affs = _converse.muc_fetch_members;
  283. const all_affiliations = Array.isArray(affs) ? affs : (affs ? ['member', 'admin', 'owner'] : []);
  284. await utils.returnMemberLists(_converse, muc_jid, members, all_affiliations);
  285. await view.model.messages.fetched;
  286. };
  287. utils.clearChatBoxMessages = function (converse, jid) {
  288. const view = converse.chatboxviews.get(jid);
  289. view.el.querySelector('.chat-content').innerHTML = '';
  290. return view.model.messages.clearStore();
  291. };
  292. utils.createContact = async function (_converse, name, ask, requesting, subscription) {
  293. const jid = name.replace(/ /g,'.').toLowerCase() + '@montague.lit';
  294. if (_converse.roster.get(jid)) {
  295. return Promise.resolve();
  296. }
  297. const contact = await new Promise((success, error) => {
  298. _converse.roster.create({
  299. 'ask': ask,
  300. 'fullname': name,
  301. 'jid': jid,
  302. 'requesting': requesting,
  303. 'subscription': subscription
  304. }, {success, error});
  305. });
  306. return contact;
  307. };
  308. utils.createContacts = async function (_converse, type, length) {
  309. /* Create current (as opposed to requesting or pending) contacts
  310. * for the user's roster.
  311. *
  312. * These contacts are not grouped. See below.
  313. */
  314. await _converse.api.waitUntil('rosterContactsFetched');
  315. let names, subscription, requesting, ask;
  316. if (type === 'requesting') {
  317. names = mock.req_names;
  318. subscription = 'none';
  319. requesting = true;
  320. ask = null;
  321. } else if (type === 'pending') {
  322. names = mock.pend_names;
  323. subscription = 'none';
  324. requesting = false;
  325. ask = 'subscribe';
  326. } else if (type === 'current') {
  327. names = mock.cur_names;
  328. subscription = 'both';
  329. requesting = false;
  330. ask = null;
  331. } else if (type === 'all') {
  332. await this.createContacts(_converse, 'current');
  333. await this.createContacts(_converse, 'requesting')
  334. await this.createContacts(_converse, 'pending');
  335. return this;
  336. } else {
  337. throw Error("Need to specify the type of contact to create");
  338. }
  339. const promises = names.slice(0, length).map(n => this.createContact(_converse, n, ask, requesting, subscription));
  340. await Promise.all(promises);
  341. };
  342. utils.waitForRoster = async function (_converse, type='current', length=-1, include_nick=true, grouped=true) {
  343. const s = `iq[type="get"] query[xmlns="${Strophe.NS.ROSTER}"]`;
  344. const iq = await u.waitUntil(() => _converse.connection.IQ_stanzas.filter(iq => sizzle(s, iq).length).pop());
  345. const result = $iq({
  346. 'to': _converse.connection.jid,
  347. 'type': 'result',
  348. 'id': iq.getAttribute('id')
  349. }).c('query', {
  350. 'xmlns': 'jabber:iq:roster'
  351. });
  352. if (type === 'pending' || type === 'all') {
  353. const pend_names = (length > -1) ? mock.pend_names.slice(0, length) : mock.pend_names;
  354. pend_names.map(name =>
  355. result.c('item', {
  356. jid: name.replace(/ /g,'.').toLowerCase() + '@montague.lit',
  357. name: include_nick ? name : undefined,
  358. subscription: 'none',
  359. ask: 'subscribe'
  360. }).up()
  361. );
  362. }
  363. if (type === 'current' || type === 'all') {
  364. const cur_names = Object.keys(mock.current_contacts_map);
  365. const names = (length > -1) ? cur_names.slice(0, length) : cur_names;
  366. names.forEach(name => {
  367. result.c('item', {
  368. jid: name.replace(/ /g,'.').toLowerCase() + '@montague.lit',
  369. name: include_nick ? name : undefined,
  370. subscription: 'both',
  371. ask: null
  372. });
  373. if (grouped) {
  374. mock.current_contacts_map[name].forEach(g => result.c('group').t(g).up());
  375. }
  376. result.up();
  377. });
  378. }
  379. _converse.connection._dataRecv(utils.createRequest(result));
  380. await _converse.api.waitUntil('rosterContactsFetched');
  381. };
  382. utils.createChatMessage = function (_converse, sender_jid, message) {
  383. return $msg({
  384. from: sender_jid,
  385. to: _converse.connection.jid,
  386. type: 'chat',
  387. id: (new Date()).getTime()
  388. })
  389. .c('body').t(message).up()
  390. .c('active', {'xmlns': Strophe.NS.CHATSTATES}).tree();
  391. }
  392. utils.sendMessage = function (view, message) {
  393. const promise = new Promise(resolve => view.once('messageInserted', resolve));
  394. view.el.querySelector('.chat-textarea').value = message;
  395. view.onKeyDown({
  396. target: view.el.querySelector('textarea.chat-textarea'),
  397. preventDefault: _.noop,
  398. keyCode: 13
  399. });
  400. return promise;
  401. };
  402. return utils;
  403. }));