mock.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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', 'Lady Capulet', 'Servant'
  74. ];
  75. mock.cur_names = [
  76. 'Mercutio', 'Juliet Capulet', 'Lady Montague', 'Lord Montague', 'Friar Laurence',
  77. 'Tybalt', 'Lady Capulet', 'Benviolo', 'Balthasar',
  78. 'Peter', 'Abram', 'Sampson', 'Gregory', 'Potpan', 'Friar John'
  79. ];
  80. mock.num_contacts = mock.req_names.length + mock.pend_names.length + mock.cur_names.length;
  81. mock.groups = {
  82. 'colleagues': 3,
  83. 'friends & acquaintences': 3,
  84. 'Family': 4,
  85. 'ænemies': 3,
  86. 'Ungrouped': 2
  87. };
  88. mock.chatroom_names = [
  89. 'Dyon van de Wege',
  90. 'Thomas Kalb',
  91. 'Dirk Theissen',
  92. 'Felix Hofmann',
  93. 'Ka Lek',
  94. 'Anne Ebersbacher'
  95. ];
  96. // TODO: need to also test other roles and affiliations
  97. mock.chatroom_roles = {
  98. 'Anne Ebersbacher': { affiliation: "owner", role: "moderator" },
  99. 'Dirk Theissen': { affiliation: "admin", role: "moderator" },
  100. 'Dyon van de Wege': { affiliation: "member", role: "occupant" },
  101. 'Felix Hofmann': { affiliation: "member", role: "occupant" },
  102. 'Ka Lek': { affiliation: "member", role: "occupant" },
  103. 'Thomas Kalb': { affiliation: "member", role: "occupant" }
  104. };
  105. mock.event = {
  106. 'preventDefault': function () {}
  107. };
  108. const OriginalConnection = Strophe.Connection;
  109. function MockConnection (service, options) {
  110. OriginalConnection.call(this, service, options);
  111. Strophe.Bosh.prototype._processRequest = function () {}; // Don't attempt to send out stanzas
  112. const sendIQ = this.sendIQ;
  113. this.IQ_stanzas = [];
  114. this.IQ_ids = [];
  115. this.sendIQ = function (iq, callback, errback) {
  116. if (!_.isElement(iq)) {
  117. iq = iq.nodeTree;
  118. }
  119. this.IQ_stanzas.push(iq);
  120. const id = sendIQ.bind(this)(iq, callback, errback);
  121. this.IQ_ids.push(id);
  122. return id;
  123. }
  124. const send = this.send;
  125. this.sent_stanzas = [];
  126. this.send = function (stanza) {
  127. if (_.isElement(stanza)) {
  128. this.sent_stanzas.push(stanza);
  129. } else {
  130. this.sent_stanzas.push(stanza.nodeTree);
  131. }
  132. return send.apply(this, arguments);
  133. }
  134. this.features = Strophe.xmlHtmlNode(
  135. '<stream:features xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">'+
  136. '<ver xmlns="urn:xmpp:features:rosterver"/>'+
  137. '<csi xmlns="urn:xmpp:csi:0"/>'+
  138. '<this xmlns="http://jabber.org/protocol/caps" ver="UwBpfJpEt3IoLYfWma/o/p3FFRo=" hash="sha-1" node="http://prosody.im"/>'+
  139. '<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">'+
  140. '<required/>'+
  141. '</bind>'+
  142. `<sm xmlns='urn:xmpp:sm:3'/>`+
  143. '<session xmlns="urn:ietf:params:xml:ns:xmpp-session">'+
  144. '<optional/>'+
  145. '</session>'+
  146. '</stream:features>').firstChild;
  147. this._proto._connect = () => {
  148. this.connected = true;
  149. this.mock = true;
  150. this.jid = 'romeo@montague.lit/orchard';
  151. this._changeConnectStatus(Strophe.Status.BINDREQUIRED);
  152. };
  153. this.bind = () => {
  154. this.authenticated = true;
  155. this.authenticated = true;
  156. this._changeConnectStatus(Strophe.Status.CONNECTED);
  157. };
  158. this._proto._disconnect = () => this._onDisconnectTimeout();
  159. this._proto._onDisconnectTimeout = _.noop;
  160. }
  161. MockConnection.prototype = Object.create(OriginalConnection.prototype);
  162. Strophe.Connection = MockConnection;
  163. async function initConverse (settings) {
  164. window.localStorage.clear();
  165. window.sessionStorage.clear();
  166. const _converse = await converse.initialize(Object.assign({
  167. 'animate': false,
  168. 'auto_subscribe': false,
  169. 'bosh_service_url': 'montague.lit/http-bind',
  170. 'debug': false,
  171. 'i18n': 'en',
  172. 'no_trimming': true,
  173. 'play_sounds': false,
  174. 'use_emojione': false,
  175. 'view_mode': mock.view_mode,
  176. }, settings || {}));
  177. _converse.ChatBoxViews.prototype.trimChat = function () {};
  178. _converse.api.vcard.get = function (model, force) {
  179. return new Promise(resolve => {
  180. let jid;
  181. if (_.isString(model)) {
  182. jid = model;
  183. } else if (!model.get('vcard_updated') || force) {
  184. jid = model.get('jid') || model.get('muc_jid');
  185. }
  186. let fullname;
  187. if (!jid || jid == 'romeo@montague.lit') {
  188. jid = 'romeo@montague.lit';
  189. fullname = 'Romeo Montague' ;
  190. } else {
  191. const name = jid.split('@')[0].replace(/\./g, ' ').split(' ');
  192. const last = name.length-1;
  193. name[0] = name[0].charAt(0).toUpperCase()+name[0].slice(1);
  194. name[last] = name[last].charAt(0).toUpperCase()+name[last].slice(1);
  195. fullname = name.join(' ');
  196. }
  197. const vcard = $iq().c('vCard').c('FN').t(fullname).nodeTree;
  198. const result = {
  199. 'vcard': vcard,
  200. 'fullname': _.get(vcard.querySelector('FN'), 'textContent'),
  201. 'image': _.get(vcard.querySelector('PHOTO BINVAL'), 'textContent'),
  202. 'image_type': _.get(vcard.querySelector('PHOTO TYPE'), 'textContent'),
  203. 'url': _.get(vcard.querySelector('URL'), 'textContent'),
  204. 'vcard_updated': dayjs().format(),
  205. 'vcard_error': undefined
  206. };
  207. resolve(result);
  208. }).catch(e => _converse.log(e, Strophe.LogLevel.FATAL));
  209. };
  210. if (_.get(settings, 'auto_login') !== false) {
  211. _converse.api.user.login('romeo@montague.lit/orchard', 'secret');
  212. await _converse.api.waitUntil('afterResourceBinding');
  213. }
  214. window.converse_disable_effects = true;
  215. return _converse;
  216. }
  217. mock.initConverse = function (promise_names=[], settings=null, func) {
  218. if (_.isFunction(promise_names)) {
  219. func = promise_names;
  220. promise_names = []
  221. settings = null;
  222. }
  223. return async done => {
  224. const _converse = await initConverse(settings);
  225. async function _done () {
  226. if (_converse.api.connection.connected()) {
  227. await _converse.api.user.logout();
  228. }
  229. const el = document.querySelector('#conversejs');
  230. if (el) {
  231. el.parentElement.removeChild(el);
  232. }
  233. document.title = "Converse Tests";
  234. done();
  235. }
  236. await Promise.all((promise_names || []).map(_converse.api.waitUntil));
  237. try {
  238. await func(_done, _converse);
  239. } catch(e) {
  240. console.error(e);
  241. fail(e);
  242. _done();
  243. }
  244. }
  245. };
  246. return mock;
  247. }));