2
0

mock.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. (function (root, factory) {
  2. define("mock", [], factory);
  3. }(this, function () {
  4. converse.load();
  5. const _ = converse.env._;
  6. const Promise = converse.env.Promise;
  7. const Strophe = converse.env.Strophe;
  8. const dayjs = converse.env.dayjs;
  9. const $iq = converse.env.$iq;
  10. window.libsignal = {
  11. 'SignalProtocolAddress': function (name, device_id) {
  12. this.name = name;
  13. this.deviceId = device_id;
  14. },
  15. 'SessionCipher': function (storage, remote_address) {
  16. this.remoteAddress = remote_address;
  17. this.storage = storage;
  18. this.encrypt = () => Promise.resolve({
  19. 'type': 1,
  20. 'body': 'c1ph3R73X7',
  21. 'registrationId': '1337'
  22. });
  23. this.decryptPreKeyWhisperMessage = (key_and_tag) => {
  24. return Promise.resolve(key_and_tag);
  25. };
  26. this.decryptWhisperMessage = (key_and_tag) => {
  27. return Promise.resolve(key_and_tag);
  28. }
  29. },
  30. 'SessionBuilder': function (storage, remote_address) { // eslint-disable-line no-unused-vars
  31. this.processPreKey = function () {
  32. return Promise.resolve();
  33. }
  34. },
  35. 'KeyHelper': {
  36. 'generateIdentityKeyPair': function () {
  37. return Promise.resolve({
  38. 'pubKey': new TextEncoder('utf-8').encode('1234'),
  39. 'privKey': new TextEncoder('utf-8').encode('4321')
  40. });
  41. },
  42. 'generateRegistrationId': function () {
  43. return '123456789';
  44. },
  45. 'generatePreKey': function (keyid) {
  46. return Promise.resolve({
  47. 'keyId': keyid,
  48. 'keyPair': {
  49. 'pubKey': new TextEncoder('utf-8').encode('1234'),
  50. 'privKey': new TextEncoder('utf-8').encode('4321')
  51. }
  52. });
  53. },
  54. 'generateSignedPreKey': function (identity_keypair, keyid) {
  55. return Promise.resolve({
  56. 'signature': new TextEncoder('utf-8').encode('11112222333344445555'),
  57. 'keyId': keyid,
  58. 'keyPair': {
  59. 'pubKey': new TextEncoder('utf-8').encode('1234'),
  60. 'privKey': new TextEncoder('utf-8').encode('4321')
  61. }
  62. });
  63. }
  64. }
  65. };
  66. const mock = {};
  67. mock.view_mode = 'overlayed';
  68. // Names from http://www.fakenamegenerator.com/
  69. mock.req_names = [
  70. 'Escalus, prince of Verona', 'The Nurse', 'Paris'
  71. ];
  72. mock.pend_names = [
  73. 'Lord Capulet', 'Guard', 'Servant'
  74. ];
  75. mock.current_contacts_map = {
  76. 'Mercutio': ['Colleagues', 'friends & acquaintences'],
  77. 'Juliet Capulet': ['friends & acquaintences'],
  78. 'Lady Montague': ['Colleagues', 'Family'],
  79. 'Lord Montague': ['Family'],
  80. 'Friar Laurence': ['friends & acquaintences'],
  81. 'Tybalt': ['friends & acquaintences'],
  82. 'Lady Capulet': ['ænemies'],
  83. 'Benviolo': ['friends & acquaintences'],
  84. 'Balthasar': ['Colleagues'],
  85. 'Peter': ['Colleagues'],
  86. 'Abram': ['Colleagues'],
  87. 'Sampson': ['Colleagues'],
  88. 'Gregory': ['friends & acquaintences'],
  89. 'Potpan': [],
  90. 'Friar John': []
  91. };
  92. const map = mock.current_contacts_map;
  93. const groups_map = {};
  94. Object.keys(map).forEach(k => {
  95. const groups = map[k].length ? map[k] : ["Ungrouped"];
  96. Object.values(groups).forEach(g => {
  97. groups_map[g] = groups_map[g] ? [...groups_map[g], k] : [k]
  98. });
  99. });
  100. mock.groups_map = groups_map;
  101. mock.cur_names = Object.keys(mock.current_contacts_map);
  102. mock.num_contacts = mock.req_names.length + mock.pend_names.length + mock.cur_names.length;
  103. mock.groups = {
  104. 'colleagues': 3,
  105. 'friends & acquaintences': 3,
  106. 'Family': 4,
  107. 'ænemies': 3,
  108. 'Ungrouped': 2
  109. };
  110. mock.chatroom_names = [
  111. 'Dyon van de Wege',
  112. 'Thomas Kalb',
  113. 'Dirk Theissen',
  114. 'Felix Hofmann',
  115. 'Ka Lek',
  116. 'Anne Ebersbacher'
  117. ];
  118. // TODO: need to also test other roles and affiliations
  119. mock.chatroom_roles = {
  120. 'Anne Ebersbacher': { affiliation: "owner", role: "moderator" },
  121. 'Dirk Theissen': { affiliation: "admin", role: "moderator" },
  122. 'Dyon van de Wege': { affiliation: "member", role: "occupant" },
  123. 'Felix Hofmann': { affiliation: "member", role: "occupant" },
  124. 'Ka Lek': { affiliation: "member", role: "occupant" },
  125. 'Thomas Kalb': { affiliation: "member", role: "occupant" }
  126. };
  127. mock.event = {
  128. 'preventDefault': function () {}
  129. };
  130. const OriginalConnection = Strophe.Connection;
  131. function MockConnection (service, options) {
  132. OriginalConnection.call(this, service, options);
  133. Strophe.Bosh.prototype._processRequest = function () {}; // Don't attempt to send out stanzas
  134. const sendIQ = this.sendIQ;
  135. this.IQ_stanzas = [];
  136. this.IQ_ids = [];
  137. this.sendIQ = function (iq, callback, errback) {
  138. if (!_.isElement(iq)) {
  139. iq = iq.nodeTree;
  140. }
  141. this.IQ_stanzas.push(iq);
  142. const id = sendIQ.bind(this)(iq, callback, errback);
  143. this.IQ_ids.push(id);
  144. return id;
  145. }
  146. const send = this.send;
  147. this.sent_stanzas = [];
  148. this.send = function (stanza) {
  149. if (_.isElement(stanza)) {
  150. this.sent_stanzas.push(stanza);
  151. } else {
  152. this.sent_stanzas.push(stanza.nodeTree);
  153. }
  154. return send.apply(this, arguments);
  155. }
  156. this.features = Strophe.xmlHtmlNode(
  157. '<stream:features xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">'+
  158. '<ver xmlns="urn:xmpp:features:rosterver"/>'+
  159. '<csi xmlns="urn:xmpp:csi:0"/>'+
  160. '<this xmlns="http://jabber.org/protocol/caps" ver="UwBpfJpEt3IoLYfWma/o/p3FFRo=" hash="sha-1" node="http://prosody.im"/>'+
  161. '<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">'+
  162. '<required/>'+
  163. '</bind>'+
  164. `<sm xmlns='urn:xmpp:sm:3'/>`+
  165. '<session xmlns="urn:ietf:params:xml:ns:xmpp-session">'+
  166. '<optional/>'+
  167. '</session>'+
  168. '</stream:features>').firstChild;
  169. this._proto._connect = () => {
  170. this.connected = true;
  171. this.mock = true;
  172. this.jid = 'romeo@montague.lit/orchard';
  173. this._changeConnectStatus(Strophe.Status.BINDREQUIRED);
  174. };
  175. this.bind = () => {
  176. this.authenticated = true;
  177. this.authenticated = true;
  178. this._changeConnectStatus(Strophe.Status.CONNECTED);
  179. };
  180. this._proto._disconnect = () => this._onDisconnectTimeout();
  181. this._proto._onDisconnectTimeout = _.noop;
  182. }
  183. MockConnection.prototype = Object.create(OriginalConnection.prototype);
  184. Strophe.Connection = MockConnection;
  185. async function initConverse (settings) {
  186. window.localStorage.clear();
  187. window.sessionStorage.clear();
  188. const _converse = await converse.initialize(Object.assign({
  189. 'animate': false,
  190. 'auto_subscribe': false,
  191. 'bosh_service_url': 'montague.lit/http-bind',
  192. 'debug': false,
  193. 'i18n': 'en',
  194. 'no_trimming': true,
  195. 'play_sounds': false,
  196. 'use_emojione': false,
  197. 'view_mode': mock.view_mode
  198. }, settings || {}));
  199. _converse.ChatBoxViews.prototype.trimChat = function () {};
  200. _converse.api.vcard.get = function (model, force) {
  201. let jid;
  202. if (_.isString(model)) {
  203. jid = model;
  204. } else if (!model.get('vcard_updated') || force) {
  205. jid = model.get('jid') || model.get('muc_jid');
  206. }
  207. let fullname;
  208. if (!jid || jid == 'romeo@montague.lit') {
  209. jid = 'romeo@montague.lit';
  210. fullname = 'Romeo Montague' ;
  211. } else {
  212. const name = jid.split('@')[0].replace(/\./g, ' ').split(' ');
  213. const last = name.length-1;
  214. name[0] = name[0].charAt(0).toUpperCase()+name[0].slice(1);
  215. name[last] = name[last].charAt(0).toUpperCase()+name[last].slice(1);
  216. fullname = name.join(' ');
  217. }
  218. const vcard = $iq().c('vCard').c('FN').t(fullname).nodeTree;
  219. return {
  220. 'vcard': vcard,
  221. 'fullname': _.get(vcard.querySelector('FN'), 'textContent'),
  222. 'image': _.get(vcard.querySelector('PHOTO BINVAL'), 'textContent'),
  223. 'image_type': _.get(vcard.querySelector('PHOTO TYPE'), 'textContent'),
  224. 'url': _.get(vcard.querySelector('URL'), 'textContent'),
  225. 'vcard_updated': dayjs().format(),
  226. 'vcard_error': undefined
  227. };
  228. };
  229. if (_.get(settings, 'auto_login') !== false) {
  230. _converse.api.user.login('romeo@montague.lit/orchard', 'secret');
  231. await _converse.api.waitUntil('afterResourceBinding');
  232. }
  233. window.converse_disable_effects = true;
  234. return _converse;
  235. }
  236. mock.initConverse = function (promise_names=[], settings=null, func) {
  237. if (_.isFunction(promise_names)) {
  238. func = promise_names;
  239. promise_names = []
  240. settings = null;
  241. }
  242. return async done => {
  243. const _converse = await initConverse(settings);
  244. async function _done () {
  245. if (_converse.api.connection.connected()) {
  246. await _converse.api.user.logout();
  247. }
  248. const el = document.querySelector('#conversejs');
  249. if (el) {
  250. el.parentElement.removeChild(el);
  251. }
  252. document.title = "Converse Tests";
  253. done();
  254. }
  255. await Promise.all((promise_names || []).map(_converse.api.waitUntil));
  256. try {
  257. await func(_done, _converse);
  258. } catch(e) {
  259. console.error(e);
  260. fail(e);
  261. _done();
  262. }
  263. }
  264. };
  265. return mock;
  266. }));