converse-chatboxes.js 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  1. // Converse.js
  2. // https://conversejs.org
  3. //
  4. // Copyright (c) 2012-2019, the Converse.js developers
  5. // Licensed under the Mozilla Public License (MPLv2)
  6. import "./utils/emoji";
  7. import "./utils/form";
  8. import converse from "./converse-core";
  9. import filesize from "filesize";
  10. const { $msg, Backbone, Promise, Strophe, b64_sha1, moment, sizzle, utils, _ } = converse.env;
  11. const u = converse.env.utils;
  12. Strophe.addNamespace('MESSAGE_CORRECT', 'urn:xmpp:message-correct:0');
  13. Strophe.addNamespace('RECEIPTS', 'urn:xmpp:receipts');
  14. Strophe.addNamespace('REFERENCE', 'urn:xmpp:reference:0');
  15. Strophe.addNamespace('MARKERS', 'urn:xmpp:chat-markers:0');
  16. converse.plugins.add('converse-chatboxes', {
  17. dependencies: ["converse-roster", "converse-vcard"],
  18. initialize () {
  19. /* The initialize function gets called as soon as the plugin is
  20. * loaded by converse.js's plugin machinery.
  21. */
  22. const { _converse } = this,
  23. { __ } = _converse;
  24. // Configuration values for this plugin
  25. // ====================================
  26. // Refer to docs/source/configuration.rst for explanations of these
  27. // configuration settings.
  28. _converse.api.settings.update({
  29. 'auto_join_private_chats': [],
  30. 'filter_by_resource': false,
  31. 'send_chat_state_notifications': true
  32. });
  33. _converse.api.promises.add([
  34. 'chatBoxesFetched',
  35. 'chatBoxesInitialized',
  36. 'privateChatsAutoJoined'
  37. ]);
  38. function openChat (jid) {
  39. if (!utils.isValidJID(jid)) {
  40. return _converse.log(
  41. `Invalid JID "${jid}" provided in URL fragment`,
  42. Strophe.LogLevel.WARN
  43. );
  44. }
  45. _converse.api.chats.open(jid);
  46. }
  47. _converse.router.route('converse/chat?jid=:jid', openChat);
  48. _converse.Message = Backbone.Model.extend({
  49. defaults () {
  50. return {
  51. 'msgid': _converse.connection.getUniqueId(),
  52. 'time': moment().format()
  53. };
  54. },
  55. initialize () {
  56. this.setVCard();
  57. if (this.get('file')) {
  58. this.on('change:put', this.uploadFile, this);
  59. }
  60. if (this.isOnlyChatStateNotification()) {
  61. window.setTimeout(this.destroy.bind(this), 20000);
  62. }
  63. },
  64. getVCardForChatroomOccupant () {
  65. const chatbox = this.collection.chatbox,
  66. nick = Strophe.getResourceFromJid(this.get('from'));
  67. if (chatbox.get('nick') === nick) {
  68. return _converse.xmppstatus.vcard;
  69. } else {
  70. let vcard;
  71. if (this.get('vcard_jid')) {
  72. vcard = _converse.vcards.findWhere({'jid': this.get('vcard_jid')});
  73. }
  74. if (!vcard) {
  75. let jid;
  76. const occupant = chatbox.occupants.findWhere({'nick': nick});
  77. if (occupant && occupant.get('jid')) {
  78. jid = occupant.get('jid');
  79. this.save({'vcard_jid': jid}, {'silent': true});
  80. } else {
  81. jid = this.get('from');
  82. }
  83. vcard = _converse.vcards.findWhere({'jid': jid}) || _converse.vcards.create({'jid': jid});
  84. }
  85. return vcard;
  86. }
  87. },
  88. setVCard () {
  89. if (this.get('type') === 'error') {
  90. return;
  91. } else if (this.get('type') === 'groupchat') {
  92. this.vcard = this.getVCardForChatroomOccupant();
  93. } else {
  94. const jid = this.get('from');
  95. this.vcard = _converse.vcards.findWhere({'jid': jid}) || _converse.vcards.create({'jid': jid});
  96. }
  97. },
  98. isOnlyChatStateNotification () {
  99. return u.isOnlyChatStateNotification(this);
  100. },
  101. getDisplayName () {
  102. if (this.get('type') === 'groupchat') {
  103. return this.get('nick');
  104. } else {
  105. return this.vcard.get('fullname') || this.get('from');
  106. }
  107. },
  108. sendSlotRequestStanza () {
  109. /* Send out an IQ stanza to request a file upload slot.
  110. *
  111. * https://xmpp.org/extensions/xep-0363.html#request
  112. */
  113. if (_.isNil(this.file)) {
  114. return Promise.reject(new Error("file is undefined"));
  115. }
  116. const iq = converse.env.$iq({
  117. 'from': _converse.jid,
  118. 'to': this.get('slot_request_url'),
  119. 'type': 'get'
  120. }).c('request', {
  121. 'xmlns': Strophe.NS.HTTPUPLOAD,
  122. 'filename': this.file.name,
  123. 'size': this.file.size,
  124. 'content-type': this.file.type
  125. })
  126. return _converse.api.sendIQ(iq);
  127. },
  128. async getRequestSlotURL () {
  129. let stanza;
  130. try {
  131. stanza = await this.sendSlotRequestStanza();
  132. } catch (e) {
  133. _converse.log(e, Strophe.LogLevel.ERROR);
  134. return this.save({
  135. 'type': 'error',
  136. 'message': __("Sorry, could not determine upload URL.")
  137. });
  138. }
  139. const slot = stanza.querySelector('slot');
  140. if (slot) {
  141. this.save({
  142. 'get': slot.querySelector('get').getAttribute('url'),
  143. 'put': slot.querySelector('put').getAttribute('url'),
  144. });
  145. } else {
  146. return this.save({
  147. 'type': 'error',
  148. 'message': __("Sorry, could not determine file upload URL.")
  149. });
  150. }
  151. },
  152. uploadFile () {
  153. const xhr = new XMLHttpRequest();
  154. xhr.onreadystatechange = () => {
  155. if (xhr.readyState === XMLHttpRequest.DONE) {
  156. _converse.log("Status: " + xhr.status, Strophe.LogLevel.INFO);
  157. if (xhr.status === 200 || xhr.status === 201) {
  158. this.save({
  159. 'upload': _converse.SUCCESS,
  160. 'oob_url': this.get('get'),
  161. 'message': this.get('get')
  162. });
  163. } else {
  164. xhr.onerror();
  165. }
  166. }
  167. };
  168. xhr.upload.addEventListener("progress", (evt) => {
  169. if (evt.lengthComputable) {
  170. this.set('progress', evt.loaded / evt.total);
  171. }
  172. }, false);
  173. xhr.onerror = () => {
  174. let message;
  175. if (xhr.responseText) {
  176. message = __('Sorry, could not succesfully upload your file. Your server’s response: "%1$s"', xhr.responseText)
  177. } else {
  178. message = __('Sorry, could not succesfully upload your file.');
  179. }
  180. this.save({
  181. 'type': 'error',
  182. 'upload': _converse.FAILURE,
  183. 'message': message
  184. });
  185. };
  186. xhr.open('PUT', this.get('put'), true);
  187. xhr.setRequestHeader("Content-type", this.file.type);
  188. xhr.send(this.file);
  189. }
  190. });
  191. _converse.Messages = Backbone.Collection.extend({
  192. model: _converse.Message,
  193. comparator: 'time'
  194. });
  195. /**
  196. * The "_converse.ChatBox" namespace
  197. *
  198. * @namespace _converse.ChatBox
  199. * @memberOf _converse
  200. */
  201. _converse.ChatBox = Backbone.Model.extend({
  202. defaults () {
  203. return {
  204. 'bookmarked': false,
  205. 'chat_state': undefined,
  206. 'hidden': _.includes(['mobile', 'fullscreen'], _converse.view_mode),
  207. 'message_type': 'chat',
  208. 'nickname': undefined,
  209. 'num_unread': 0,
  210. 'type': _converse.PRIVATE_CHAT_TYPE,
  211. 'url': ''
  212. }
  213. },
  214. initialize () {
  215. const jid = this.get('jid');
  216. if (!jid) {
  217. // XXX: The `validate` method will prevent this model
  218. // from being persisted if there's no jid, but that gets
  219. // called after model instantiation, so we have to deal
  220. // with invalid models here also.
  221. //
  222. // This happens when the controlbox is in browser storage,
  223. // but we're in embedded mode.
  224. return;
  225. }
  226. this.vcard = _converse.vcards.findWhere({'jid': jid}) || _converse.vcards.create({'jid': jid});
  227. // XXX: this creates a dependency on converse-roster, which we
  228. // probably shouldn't have here, so we should probably move
  229. // ChatBox out of converse-chatboxes
  230. this.presence = _converse.presences.findWhere({'jid': jid}) || _converse.presences.create({'jid': jid});
  231. this.messages = new _converse.Messages();
  232. const storage = _converse.config.get('storage');
  233. this.messages.browserStorage = new Backbone.BrowserStorage[storage](
  234. b64_sha1(`converse.messages${jid}${_converse.bare_jid}`));
  235. this.messages.chatbox = this;
  236. this.messages.on('change:upload', (message) => {
  237. if (message.get('upload') === _converse.SUCCESS) {
  238. _converse.api.send(this.createMessageStanza(message));
  239. }
  240. });
  241. this.on('change:chat_state', this.sendChatState, this);
  242. // Models get saved immediately after creation, so no need to
  243. // call `save` here.
  244. this.set({
  245. // The chat_state will be set to ACTIVE once the chat box is opened
  246. // and we listen for change:chat_state, so shouldn't set it to ACTIVE here.
  247. 'box_id' : b64_sha1(this.get('jid')),
  248. 'time_opened': this.get('time_opened') || moment().valueOf(),
  249. 'user_id' : Strophe.getNodeFromJid(this.get('jid')),
  250. 'nickname':_.get(_converse.api.contacts.get(this.get('jid')), 'attributes.nickname')
  251. });
  252. },
  253. validate (attrs, options) {
  254. const { _converse } = this.__super__;
  255. if (!attrs.jid) {
  256. return 'Ignored ChatBox without JID';
  257. }
  258. },
  259. getDisplayName () {
  260. return this.vcard.get('fullname') || this.get('jid');
  261. },
  262. getUpdatedMessageAttributes (message, stanza) {
  263. // Overridden in converse-muc and converse-mam
  264. return {};
  265. },
  266. updateMessage (message, stanza) {
  267. // Overridden in converse-muc and converse-mam
  268. const attrs = this.getUpdatedMessageAttributes(message, stanza);
  269. if (attrs) {
  270. message.save(attrs, {'patch': true});
  271. }
  272. },
  273. handleMessageCorrection (stanza) {
  274. const replace = sizzle(`replace[xmlns="${Strophe.NS.MESSAGE_CORRECT}"]`, stanza).pop();
  275. if (replace) {
  276. const msgid = replace && replace.getAttribute('id') || stanza.getAttribute('id'),
  277. message = msgid && this.messages.findWhere({msgid});
  278. if (!message) {
  279. // XXX: Looks like we received a correction for a
  280. // non-existing message, probably due to MAM.
  281. // Not clear what can be done about this... we'll
  282. // just create it as a separate message for now.
  283. return false;
  284. }
  285. const older_versions = message.get('older_versions') || [];
  286. older_versions.push(message.get('message'));
  287. message.save({
  288. 'message': _converse.chatboxes.getMessageBody(stanza),
  289. 'references': this.getReferencesFromStanza(stanza),
  290. 'older_versions': older_versions,
  291. 'edited': moment().format()
  292. });
  293. return true;
  294. }
  295. return false;
  296. },
  297. getDuplicateMessage (stanza) {
  298. return this.findDuplicateFromOriginID(stanza) || this.findDuplicateFromStanzaID(stanza);
  299. },
  300. findDuplicateFromOriginID (stanza) {
  301. const origin_id = sizzle(`origin-id[xmlns="${Strophe.NS.SID}"]`, stanza).pop();
  302. if (!origin_id) {
  303. return null;
  304. }
  305. return this.messages.findWhere({
  306. 'origin_id': origin_id.getAttribute('id'),
  307. 'sender': 'me'
  308. });
  309. },
  310. async findDuplicateFromStanzaID(stanza) {
  311. const stanza_id = sizzle(`stanza-id[xmlns="${Strophe.NS.SID}"]`, stanza).pop();
  312. if (!stanza_id) {
  313. return false;
  314. }
  315. const by_jid = stanza_id.getAttribute('by');
  316. const result = await _converse.api.disco.supports(Strophe.NS.SID, by_jid);
  317. if (!result.length) {
  318. return false;
  319. }
  320. const query = {};
  321. query[`stanza_id ${by_jid}`] = stanza_id.getAttribute('id');
  322. return this.messages.findWhere(query);
  323. },
  324. sendMarker(to_jid, id, type) {
  325. const stanza = $msg({
  326. 'from': _converse.connection.jid,
  327. 'id': _converse.connection.getUniqueId(),
  328. 'to': to_jid,
  329. 'type': 'chat',
  330. }).c(type, {'xmlns': Strophe.NS.MARKERS, 'id': id});
  331. _converse.api.send(stanza);
  332. },
  333. handleChatMarker (stanza, from_jid, is_carbon, is_roster_contact, is_mam) {
  334. const to_bare_jid = Strophe.getBareJidFromJid(stanza.getAttribute('to'));
  335. if (to_bare_jid !== _converse.bare_jid) {
  336. return false;
  337. }
  338. const markers = sizzle(`[xmlns="${Strophe.NS.MARKERS}"]`, stanza);
  339. if (markers.length === 0) {
  340. return false;
  341. } else if (markers.length > 1) {
  342. _converse.log(
  343. 'handleChatMarker: Ignoring incoming stanza with multiple message markers',
  344. Strophe.LogLevel.ERROR
  345. );
  346. _converse.log(stanza, Strophe.LogLevel.ERROR);
  347. return false;
  348. } else {
  349. const marker = markers.pop();
  350. if (marker.nodeName === 'markable') {
  351. if (is_roster_contact && !is_carbon && !is_mam) {
  352. this.sendMarker(from_jid, stanza.getAttribute('id'), 'received');
  353. }
  354. return false;
  355. } else {
  356. const msgid = marker && marker.getAttribute('id'),
  357. message = msgid && this.messages.findWhere({msgid}),
  358. field_name = `marker_${marker.nodeName}`;
  359. if (message && !message.get(field_name)) {
  360. message.save({field_name: moment().format()});
  361. }
  362. return true;
  363. }
  364. }
  365. },
  366. sendReceiptStanza (to_jid, id) {
  367. const receipt_stanza = $msg({
  368. 'from': _converse.connection.jid,
  369. 'id': _converse.connection.getUniqueId(),
  370. 'to': to_jid,
  371. 'type': 'chat',
  372. }).c('received', {'xmlns': Strophe.NS.RECEIPTS, 'id': id}).up()
  373. .c('store', {'xmlns': Strophe.NS.HINTS}).up();
  374. _converse.api.send(receipt_stanza);
  375. },
  376. handleReceipt (stanza, from_jid, is_carbon, is_me, is_mam) {
  377. const requests_receipt = !_.isUndefined(sizzle(`request[xmlns="${Strophe.NS.RECEIPTS}"]`, stanza).pop());
  378. if (requests_receipt && !is_carbon && !is_me) {
  379. this.sendReceiptStanza(from_jid, stanza.getAttribute('id'));
  380. }
  381. const to_bare_jid = Strophe.getBareJidFromJid(stanza.getAttribute('to'));
  382. if (to_bare_jid === _converse.bare_jid) {
  383. const receipt = sizzle(`received[xmlns="${Strophe.NS.RECEIPTS}"]`, stanza).pop();
  384. if (receipt) {
  385. const msgid = receipt && receipt.getAttribute('id'),
  386. message = msgid && this.messages.findWhere({msgid});
  387. if (message && !message.get('received')) {
  388. message.save({'received': moment().format()});
  389. }
  390. return true;
  391. }
  392. }
  393. return false;
  394. },
  395. createMessageStanza (message) {
  396. /* Given a _converse.Message Backbone.Model, return the XML
  397. * stanza that represents it.
  398. *
  399. * Parameters:
  400. * (Object) message - The Backbone.Model representing the message
  401. */
  402. const stanza = $msg({
  403. 'from': _converse.connection.jid,
  404. 'to': this.get('jid'),
  405. 'type': this.get('message_type'),
  406. 'id': message.get('edited') && _converse.connection.getUniqueId() || message.get('msgid'),
  407. }).c('body').t(message.get('message')).up()
  408. .c(_converse.ACTIVE, {'xmlns': Strophe.NS.CHATSTATES}).root();
  409. if (message.get('type') === 'chat') {
  410. stanza.c('request', {'xmlns': Strophe.NS.RECEIPTS}).root();
  411. }
  412. if (message.get('is_spoiler')) {
  413. if (message.get('spoiler_hint')) {
  414. stanza.c('spoiler', {'xmlns': Strophe.NS.SPOILER}, message.get('spoiler_hint')).root();
  415. } else {
  416. stanza.c('spoiler', {'xmlns': Strophe.NS.SPOILER}).root();
  417. }
  418. }
  419. (message.get('references') || []).forEach(reference => {
  420. const attrs = {
  421. 'xmlns': Strophe.NS.REFERENCE,
  422. 'begin': reference.begin,
  423. 'end': reference.end,
  424. 'type': reference.type,
  425. }
  426. if (reference.uri) {
  427. attrs.uri = reference.uri;
  428. }
  429. stanza.c('reference', attrs).root();
  430. });
  431. if (message.get('oob_url')) {
  432. stanza.c('x', {'xmlns': Strophe.NS.OUTOFBAND}).c('url').t(message.get('oob_url')).root();
  433. }
  434. if (message.get('edited')) {
  435. stanza.c('replace', {
  436. 'xmlns': Strophe.NS.MESSAGE_CORRECT,
  437. 'id': message.get('msgid')
  438. }).root();
  439. }
  440. if (message.get('origin_id')) {
  441. stanza.c('origin-id', {'xmlns': Strophe.NS.SID, 'id': message.get('origin_id')}).root();
  442. }
  443. return stanza;
  444. },
  445. getOutgoingMessageAttributes (text, spoiler_hint) {
  446. const is_spoiler = this.get('composing_spoiler'),
  447. origin_id = _converse.connection.getUniqueId();
  448. return _.extend(this.toJSON(), {
  449. 'msgid': origin_id,
  450. 'origin_id': origin_id,
  451. 'fullname': _converse.xmppstatus.get('fullname'),
  452. 'from': _converse.bare_jid,
  453. 'sender': 'me',
  454. 'time': moment().format(),
  455. 'message': text ? u.httpToGeoUri(u.shortnameToUnicode(text), _converse) : undefined,
  456. 'is_spoiler': is_spoiler,
  457. 'spoiler_hint': is_spoiler ? spoiler_hint : undefined,
  458. 'type': this.get('message_type')
  459. });
  460. },
  461. /**
  462. * Responsible for sending off a text message inside an ongoing
  463. * chat conversation.
  464. *
  465. * @method _converse.ChatBox#sendMessage
  466. * @memberOf _converse.ChatBox
  467. *
  468. * @param {String} text - The chat message text
  469. * @param {String} spoiler_hint - An optional hint, if the message being sent is a spoiler
  470. *
  471. * @example
  472. * const chat = _converse.api.chats.get('buddy1@example.com');
  473. * chat.sendMessage('hello world');
  474. */
  475. sendMessage (text, spoiler_hint) {
  476. const attrs = this.getOutgoingMessageAttributes(text, spoiler_hint);
  477. let message = this.messages.findWhere('correcting')
  478. if (message) {
  479. const older_versions = message.get('older_versions') || [];
  480. older_versions.push(message.get('message'));
  481. message.save({
  482. 'correcting': false,
  483. 'edited': moment().format(),
  484. 'message': attrs.message,
  485. 'older_versions': older_versions,
  486. 'references': attrs.references
  487. });
  488. } else {
  489. message = this.messages.create(attrs);
  490. }
  491. _converse.api.send(this.createMessageStanza(message));
  492. return true;
  493. },
  494. sendChatState () {
  495. /* Sends a message with the status of the user in this chat session
  496. * as taken from the 'chat_state' attribute of the chat box.
  497. * See XEP-0085 Chat State Notifications.
  498. */
  499. if (_converse.send_chat_state_notifications && this.get('chat_state')) {
  500. _converse.api.send(
  501. $msg({
  502. 'id': _converse.connection.getUniqueId(),
  503. 'to': this.get('jid'),
  504. 'type': 'chat'
  505. }).c(this.get('chat_state'), {'xmlns': Strophe.NS.CHATSTATES}).up()
  506. .c('no-store', {'xmlns': Strophe.NS.HINTS}).up()
  507. .c('no-permanent-store', {'xmlns': Strophe.NS.HINTS})
  508. );
  509. }
  510. },
  511. async sendFiles (files) {
  512. const result = await _converse.api.disco.supports(Strophe.NS.HTTPUPLOAD, _converse.domain),
  513. item = result.pop();
  514. if (!item) {
  515. this.messages.create({
  516. 'message': __("Sorry, looks like file upload is not supported by your server."),
  517. 'type': 'error'
  518. });
  519. return;
  520. }
  521. const data = item.dataforms.where({'FORM_TYPE': {'value': Strophe.NS.HTTPUPLOAD, 'type': "hidden"}}).pop(),
  522. max_file_size = window.parseInt(_.get(data, 'attributes.max-file-size.value')),
  523. slot_request_url = _.get(item, 'id');
  524. if (!slot_request_url) {
  525. this.messages.create({
  526. 'message': __("Sorry, looks like file upload is not supported by your server."),
  527. 'type': 'error'
  528. });
  529. return;
  530. }
  531. _.each(files, (file) => {
  532. if (!window.isNaN(max_file_size) && window.parseInt(file.size) > max_file_size) {
  533. return this.messages.create({
  534. 'message': __('The size of your file, %1$s, exceeds the maximum allowed by your server, which is %2$s.',
  535. file.name, filesize(max_file_size)),
  536. 'type': 'error'
  537. });
  538. } else {
  539. const message = this.messages.create(
  540. _.extend(
  541. this.getOutgoingMessageAttributes(), {
  542. 'file': true,
  543. 'progress': 0,
  544. 'slot_request_url': slot_request_url
  545. }), {'silent': true}
  546. );
  547. message.file = file;
  548. this.messages.trigger('add', message);
  549. message.getRequestSlotURL();
  550. }
  551. });
  552. },
  553. getReferencesFromStanza (stanza) {
  554. const text = _.propertyOf(stanza.querySelector('body'))('textContent');
  555. return sizzle(`reference[xmlns="${Strophe.NS.REFERENCE}"]`, stanza).map(ref => {
  556. const begin = ref.getAttribute('begin'),
  557. end = ref.getAttribute('end');
  558. return {
  559. 'begin': begin,
  560. 'end': end,
  561. 'type': ref.getAttribute('type'),
  562. 'value': text.slice(begin, end),
  563. 'uri': ref.getAttribute('uri')
  564. };
  565. });
  566. },
  567. getStanzaIDs (stanza) {
  568. /* Extract the XEP-0359 stanza IDs from the passed in stanza
  569. * and return a map containing them.
  570. *
  571. * Parameters:
  572. * (XMLElement) stanza - The message stanza
  573. */
  574. const attrs = {};
  575. const stanza_ids = sizzle(`stanza-id[xmlns="${Strophe.NS.SID}"]`, stanza);
  576. if (stanza_ids.length) {
  577. stanza_ids.forEach(s => (attrs[`stanza_id ${s.getAttribute('by')}`] = s.getAttribute('id')));
  578. }
  579. const result = sizzle(`message > result[xmlns="${Strophe.NS.MAM}"]`, stanza).pop();
  580. if (result) {
  581. const by_jid = stanza.getAttribute('from');
  582. attrs[`stanza_id ${by_jid}`] = result.getAttribute('id');
  583. }
  584. const origin_id = sizzle(`origin-id[xmlns="${Strophe.NS.SID}"]`, stanza).pop();
  585. if (origin_id) {
  586. attrs['origin_id'] = origin_id.getAttribute('id');
  587. }
  588. return attrs;
  589. },
  590. isArchived (original_stanza) {
  591. return !_.isNil(sizzle(`result[xmlns="${Strophe.NS.MAM}"]`, original_stanza).pop());
  592. },
  593. getMessageAttributesFromStanza (stanza, original_stanza) {
  594. /* Parses a passed in message stanza and returns an object
  595. * of attributes.
  596. *
  597. * Parameters:
  598. * (XMLElement) stanza - The message stanza
  599. * (XMLElement) delay - The <delay> node from the
  600. * stanza, if there was one.
  601. * (XMLElement) original_stanza - The original stanza,
  602. * that contains the message stanza, if it was
  603. * contained, otherwise it's the message stanza itself.
  604. */
  605. const spoiler = sizzle(`spoiler[xmlns="${Strophe.NS.SPOILER}"]`, original_stanza).pop(),
  606. delay = sizzle(`delay[xmlns="${Strophe.NS.DELAY}"]`, original_stanza).pop(),
  607. text = _converse.chatboxes.getMessageBody(stanza) || undefined,
  608. chat_state = stanza.getElementsByTagName(_converse.COMPOSING).length && _converse.COMPOSING ||
  609. stanza.getElementsByTagName(_converse.PAUSED).length && _converse.PAUSED ||
  610. stanza.getElementsByTagName(_converse.INACTIVE).length && _converse.INACTIVE ||
  611. stanza.getElementsByTagName(_converse.ACTIVE).length && _converse.ACTIVE ||
  612. stanza.getElementsByTagName(_converse.GONE).length && _converse.GONE;
  613. const attrs = _.extend({
  614. 'chat_state': chat_state,
  615. 'is_archived': this.isArchived(original_stanza),
  616. 'is_delayed': !_.isNil(delay),
  617. 'is_spoiler': !_.isNil(spoiler),
  618. 'is_single_emoji': text ? u.isSingleEmoji(text) : false,
  619. 'message': text,
  620. 'msgid': stanza.getAttribute('id'),
  621. 'references': this.getReferencesFromStanza(stanza),
  622. 'subject': _.propertyOf(stanza.querySelector('subject'))('textContent'),
  623. 'thread': _.propertyOf(stanza.querySelector('thread'))('textContent'),
  624. 'time': delay ? delay.getAttribute('stamp') : moment().format(),
  625. 'type': stanza.getAttribute('type')
  626. }, this.getStanzaIDs(original_stanza));
  627. if (attrs.type === 'groupchat') {
  628. attrs.from = stanza.getAttribute('from');
  629. attrs.nick = Strophe.unescapeNode(Strophe.getResourceFromJid(attrs.from));
  630. attrs.sender = attrs.nick === this.get('nick') ? 'me': 'them';
  631. } else {
  632. attrs.from = Strophe.getBareJidFromJid(stanza.getAttribute('from'));
  633. if (attrs.from === _converse.bare_jid) {
  634. attrs.sender = 'me';
  635. attrs.fullname = _converse.xmppstatus.get('fullname');
  636. } else {
  637. attrs.sender = 'them';
  638. attrs.fullname = this.get('fullname') || this.get('fullname')
  639. }
  640. }
  641. _.each(sizzle(`x[xmlns="${Strophe.NS.OUTOFBAND}"]`, stanza), (xform) => {
  642. attrs['oob_url'] = xform.querySelector('url').textContent;
  643. attrs['oob_desc'] = xform.querySelector('url').textContent;
  644. });
  645. if (spoiler) {
  646. attrs.spoiler_hint = spoiler.textContent.length > 0 ? spoiler.textContent : '';
  647. }
  648. // We prefer to use one of the XEP-0359 unique and stable stanza IDs as the Model id, to avoid duplicates.
  649. attrs['id'] = attrs['origin_id'] || attrs[`stanza_id ${attrs.from}`] || _converse.connection.getUniqueId();
  650. return attrs;
  651. },
  652. isHidden () {
  653. /* Returns a boolean to indicate whether a newly received
  654. * message will be visible to the user or not.
  655. */
  656. return this.get('hidden') ||
  657. this.get('minimized') ||
  658. this.isScrolledUp() ||
  659. _converse.windowState === 'hidden';
  660. },
  661. incrementUnreadMsgCounter (message) {
  662. /* Given a newly received message, update the unread counter if
  663. * necessary.
  664. */
  665. if (!message) { return; }
  666. if (_.isNil(message.get('message'))) { return; }
  667. if (utils.isNewMessage(message) && this.isHidden()) {
  668. this.save({'num_unread': this.get('num_unread') + 1});
  669. _converse.incrementMsgCounter();
  670. }
  671. },
  672. clearUnreadMsgCounter () {
  673. u.safeSave(this, {'num_unread': 0});
  674. },
  675. isScrolledUp () {
  676. return this.get('scrolled', true);
  677. }
  678. });
  679. _converse.ChatBoxes = Backbone.Collection.extend({
  680. comparator: 'time_opened',
  681. model (attrs, options) {
  682. return new _converse.ChatBox(attrs, options);
  683. },
  684. registerMessageHandler () {
  685. _converse.connection.addHandler(stanza => {
  686. this.onMessage(stanza);
  687. return true;
  688. }, null, 'message', 'chat');
  689. _converse.connection.addHandler(stanza => {
  690. // Message receipts are usually without the `type` attribute. See #1353
  691. if (!_.isNull(stanza.getAttribute('type'))) {
  692. // TODO: currently Strophe has no way to register a handler
  693. // for stanzas without a `type` attribute.
  694. // We could update it to accept null to mean no attribute,
  695. // but that would be a backward-incompatible chnge
  696. return true; // Gets handled above.
  697. }
  698. this.onMessage(stanza);
  699. return true;
  700. }, Strophe.NS.RECEIPTS, 'message');
  701. _converse.connection.addHandler(stanza => {
  702. this.onErrorMessage(stanza);
  703. return true;
  704. }, null, 'message', 'error');
  705. },
  706. chatBoxMayBeShown (chatbox) {
  707. return true;
  708. },
  709. onChatBoxesFetched (collection) {
  710. /* Show chat boxes upon receiving them from sessionStorage */
  711. collection.each(chatbox => {
  712. if (this.chatBoxMayBeShown(chatbox)) {
  713. chatbox.trigger('show');
  714. }
  715. });
  716. _converse.emit('chatBoxesFetched');
  717. },
  718. onConnected () {
  719. this.browserStorage = new Backbone.BrowserStorage.session(
  720. `converse.chatboxes-${_converse.bare_jid}`);
  721. this.registerMessageHandler();
  722. this.fetch({
  723. 'add': true,
  724. 'success': this.onChatBoxesFetched.bind(this)
  725. });
  726. },
  727. async onErrorMessage (message) {
  728. /* Handler method for all incoming error message stanzas
  729. */
  730. const from_jid = Strophe.getBareJidFromJid(message.getAttribute('from'));
  731. if (utils.isSameBareJID(from_jid, _converse.bare_jid)) {
  732. return true;
  733. }
  734. const chatbox = this.getChatBox(from_jid);
  735. if (!chatbox) {
  736. return true;
  737. }
  738. const id = message.getAttribute('id');
  739. if (id) {
  740. const msgs = chatbox.messages.where({'msgid': id});
  741. if (!msgs.length || msgs.filter(m => m.get('type') === 'error').length) {
  742. // If the error refers to a message not included in our store.
  743. // We assume that this was a CSI message (which we don't store).
  744. // See https://github.com/conversejs/converse.js/issues/1317
  745. //
  746. // We also ignore duplicate error messages.
  747. return;
  748. }
  749. } else {
  750. // An error message without id likely means that we
  751. // sent a message without id (which shouldn't happen).
  752. _converse.log('Received an error message without id attribute!', Strophe.LogLevel.ERROR);
  753. _converse.log(message, Strophe.LogLevel.ERROR);
  754. }
  755. const attrs = await chatbox.getMessageAttributesFromStanza(message, message);
  756. chatbox.messages.create(attrs);
  757. },
  758. getMessageBody (stanza) {
  759. /* Given a message stanza, return the text contained in its body.
  760. */
  761. const type = stanza.getAttribute('type');
  762. if (type === 'error') {
  763. const error = stanza.querySelector('error');
  764. return _.propertyOf(error.querySelector('text'))('textContent') ||
  765. __('Sorry, an error occurred:') + ' ' + error.innerHTML;
  766. } else {
  767. return _.propertyOf(stanza.querySelector('body'))('textContent');
  768. }
  769. },
  770. async onMessage (stanza) {
  771. /* Handler method for all incoming single-user chat "message"
  772. * stanzas.
  773. *
  774. * Parameters:
  775. * (XMLElement) stanza - The incoming message stanza
  776. */
  777. let to_jid = stanza.getAttribute('to');
  778. const to_resource = Strophe.getResourceFromJid(to_jid);
  779. if (_converse.filter_by_resource && (to_resource && to_resource !== _converse.resource)) {
  780. _converse.log(
  781. `onMessage: Ignoring incoming message intended for a different resource: ${to_jid}`,
  782. Strophe.LogLevel.INFO
  783. );
  784. return true;
  785. } else if (utils.isHeadlineMessage(_converse, stanza)) {
  786. // XXX: Ideally we wouldn't have to check for headline
  787. // messages, but Prosody sends headline messages with the
  788. // wrong type ('chat'), so we need to filter them out here.
  789. _converse.log(
  790. `onMessage: Ignoring incoming headline message from JID: ${stanza.getAttribute('from')}`,
  791. Strophe.LogLevel.INFO
  792. );
  793. return true;
  794. }
  795. let from_jid = stanza.getAttribute('from'),
  796. is_carbon = false,
  797. is_mam = false;
  798. const forwarded = stanza.querySelector('forwarded'),
  799. original_stanza = stanza;
  800. if (!_.isNull(forwarded)) {
  801. const forwarded_message = forwarded.querySelector('message'),
  802. forwarded_from = forwarded_message.getAttribute('from');
  803. is_carbon = !_.isNull(stanza.querySelector(`received[xmlns="${Strophe.NS.CARBONS}"]`));
  804. is_mam = sizzle(`message > result[xmlns="${Strophe.NS.MAM}"]`, stanza).length > 0;
  805. if (is_carbon && Strophe.getBareJidFromJid(forwarded_from) !== from_jid) {
  806. // Prevent message forging via carbons
  807. // https://xmpp.org/extensions/xep-0280.html#security
  808. return true;
  809. }
  810. stanza = forwarded_message;
  811. from_jid = stanza.getAttribute('from');
  812. to_jid = stanza.getAttribute('to');
  813. }
  814. const from_bare_jid = Strophe.getBareJidFromJid(from_jid),
  815. from_resource = Strophe.getResourceFromJid(from_jid),
  816. is_me = from_bare_jid === _converse.bare_jid;
  817. let contact_jid,
  818. is_roster_contact = false;
  819. if (is_me) {
  820. // I am the sender, so this must be a forwarded message...
  821. if (_.isNull(to_jid)) {
  822. return _converse.log(
  823. `Don't know how to handle message stanza without 'to' attribute. ${stanza.outerHTML}`,
  824. Strophe.LogLevel.ERROR
  825. );
  826. }
  827. contact_jid = Strophe.getBareJidFromJid(to_jid);
  828. } else {
  829. contact_jid = from_bare_jid;
  830. await _converse.api.waitUntil('rosterContactsFetched');
  831. is_roster_contact = !_.isUndefined(_converse.roster.get(contact_jid));
  832. if (!is_roster_contact && !_converse.allow_non_roster_messaging) {
  833. return;
  834. }
  835. }
  836. // Get chat box, but only create when the message has something to show to the user
  837. const has_body = sizzle(`body, encrypted[xmlns="${Strophe.NS.OMEMO}"]`, stanza).length > 0,
  838. roster_nick = _.get(_converse.api.contacts.get(contact_jid), 'attributes.nickname'),
  839. chatbox = this.getChatBox(contact_jid, {'nickname': roster_nick}, has_body);
  840. if (chatbox) {
  841. const message = await chatbox.getDuplicateMessage(stanza);
  842. if (message) {
  843. chatbox.updateMessage(message, original_stanza);
  844. }
  845. if (!message &&
  846. !chatbox.handleMessageCorrection(stanza) &&
  847. !chatbox.handleReceipt (stanza, from_jid, is_carbon, is_me, is_mam) &&
  848. !chatbox.handleChatMarker(stanza, from_jid, is_carbon, is_roster_contact, is_mam)) {
  849. const attrs = await chatbox.getMessageAttributesFromStanza(stanza, original_stanza);
  850. if (attrs['chat_state'] || !u.isEmptyMessage(attrs)) {
  851. const msg = chatbox.messages.create(attrs);
  852. chatbox.incrementUnreadMsgCounter(msg);
  853. }
  854. }
  855. }
  856. _converse.emit('message', {'stanza': original_stanza, 'chatbox': chatbox});
  857. },
  858. getChatBox (jid, attrs={}, create) {
  859. /* Returns a chat box or optionally return a newly
  860. * created one if one doesn't exist.
  861. *
  862. * Parameters:
  863. * (String) jid - The JID of the user whose chat box we want
  864. * (Boolean) create - Should a new chat box be created if none exists?
  865. * (Object) attrs - Optional chat box atributes.
  866. */
  867. if (_.isObject(jid)) {
  868. create = attrs;
  869. attrs = jid;
  870. jid = attrs.jid;
  871. }
  872. jid = Strophe.getBareJidFromJid(jid.toLowerCase());
  873. let chatbox = this.get(Strophe.getBareJidFromJid(jid));
  874. if (!chatbox && create) {
  875. _.extend(attrs, {'jid': jid, 'id': jid});
  876. chatbox = this.create(attrs, {
  877. 'error' (model, response) {
  878. _converse.log(response.responseText);
  879. }
  880. });
  881. }
  882. return chatbox;
  883. }
  884. });
  885. function autoJoinChats () {
  886. /* Automatically join private chats, based on the
  887. * "auto_join_private_chats" configuration setting.
  888. */
  889. _.each(_converse.auto_join_private_chats, function (jid) {
  890. if (_converse.chatboxes.where({'jid': jid}).length) {
  891. return;
  892. }
  893. if (_.isString(jid)) {
  894. _converse.api.chats.open(jid);
  895. } else {
  896. _converse.log(
  897. 'Invalid jid criteria specified for "auto_join_private_chats"',
  898. Strophe.LogLevel.ERROR);
  899. }
  900. });
  901. _converse.emit('privateChatsAutoJoined');
  902. }
  903. /************************ BEGIN Event Handlers ************************/
  904. _converse.on('chatBoxesFetched', autoJoinChats);
  905. _converse.on('addClientFeatures', () => {
  906. _converse.api.disco.own.features.add(Strophe.NS.MESSAGE_CORRECT);
  907. _converse.api.disco.own.features.add(Strophe.NS.HTTPUPLOAD);
  908. _converse.api.disco.own.features.add(Strophe.NS.OUTOFBAND);
  909. });
  910. _converse.api.listen.on('pluginsInitialized', () => {
  911. _converse.chatboxes = new _converse.ChatBoxes();
  912. _converse.emit('chatBoxesInitialized');
  913. });
  914. _converse.api.listen.on('presencesInitialized', () => _converse.chatboxes.onConnected());
  915. /************************ END Event Handlers ************************/
  916. /************************ BEGIN API ************************/
  917. _.extend(_converse.api, {
  918. /**
  919. * The "chats" namespace (used for one-on-one chats)
  920. *
  921. * @namespace _converse.api.chats
  922. * @memberOf _converse.api
  923. */
  924. 'chats': {
  925. /**
  926. * @method _converse.api.chats.create
  927. * @param {string|string[]} jid|jids An jid or array of jids
  928. * @param {object} attrs An object containing configuration attributes.
  929. */
  930. 'create' (jids, attrs) {
  931. if (_.isUndefined(jids)) {
  932. _converse.log(
  933. "chats.create: You need to provide at least one JID",
  934. Strophe.LogLevel.ERROR
  935. );
  936. return null;
  937. }
  938. if (_.isString(jids)) {
  939. if (attrs && !_.get(attrs, 'fullname')) {
  940. attrs.fullname = _.get(_converse.api.contacts.get(jids), 'attributes.fullname');
  941. }
  942. const chatbox = _converse.chatboxes.getChatBox(jids, attrs, true);
  943. if (_.isNil(chatbox)) {
  944. _converse.log("Could not open chatbox for JID: "+jids, Strophe.LogLevel.ERROR);
  945. return;
  946. }
  947. return chatbox;
  948. }
  949. return _.map(jids, (jid) => {
  950. attrs.fullname = _.get(_converse.api.contacts.get(jid), 'attributes.fullname');
  951. return _converse.chatboxes.getChatBox(jid, attrs, true).trigger('show');
  952. });
  953. },
  954. /**
  955. * Opens a new one-on-one chat.
  956. *
  957. * @method _converse.api.chats.open
  958. * @param {String|string[]} name - e.g. 'buddy@example.com' or ['buddy1@example.com', 'buddy2@example.com']
  959. * @returns {Promise} Promise which resolves with the Backbone.Model representing the chat.
  960. *
  961. * @example
  962. * // To open a single chat, provide the JID of the contact you're chatting with in that chat:
  963. * converse.plugins.add('myplugin', {
  964. * initialize: function() {
  965. * var _converse = this._converse;
  966. * // Note, buddy@example.org must be in your contacts roster!
  967. * _converse.api.chats.open('buddy@example.com').then((chat) => {
  968. * // Now you can do something with the chat model
  969. * });
  970. * }
  971. * });
  972. *
  973. * @example
  974. * // To open an array of chats, provide an array of JIDs:
  975. * converse.plugins.add('myplugin', {
  976. * initialize: function () {
  977. * var _converse = this._converse;
  978. * // Note, these users must first be in your contacts roster!
  979. * _converse.api.chats.open(['buddy1@example.com', 'buddy2@example.com']).then((chats) => {
  980. * // Now you can do something with the chat models
  981. * });
  982. * }
  983. * });
  984. *
  985. */
  986. 'open' (jids, attrs) {
  987. return new Promise((resolve, reject) => {
  988. Promise.all([
  989. _converse.api.waitUntil('rosterContactsFetched'),
  990. _converse.api.waitUntil('chatBoxesFetched')
  991. ]).then(() => {
  992. if (_.isUndefined(jids)) {
  993. const err_msg = "chats.open: You need to provide at least one JID";
  994. _converse.log(err_msg, Strophe.LogLevel.ERROR);
  995. reject(new Error(err_msg));
  996. } else if (_.isString(jids)) {
  997. resolve(_converse.api.chats.create(jids, attrs).trigger('show'));
  998. } else {
  999. resolve(_.map(jids, (jid) => _converse.api.chats.create(jid, attrs).trigger('show')));
  1000. }
  1001. }).catch(_.partial(_converse.log, _, Strophe.LogLevel.FATAL));
  1002. });
  1003. },
  1004. /**
  1005. * Returns a chat model. The chat should already be open.
  1006. *
  1007. * @method _converse.api.chats.get
  1008. * @param {String|string[]} name - e.g. 'buddy@example.com' or ['buddy1@example.com', 'buddy2@example.com']
  1009. * @returns {_converse.ChatBox}
  1010. *
  1011. * @example
  1012. * // To return a single chat, provide the JID of the contact you're chatting with in that chat:
  1013. * const model = _converse.api.chats.get('buddy@example.com');
  1014. *
  1015. * @example
  1016. * // To return an array of chats, provide an array of JIDs:
  1017. * const models = _converse.api.chats.get(['buddy1@example.com', 'buddy2@example.com']);
  1018. *
  1019. * @example
  1020. * // To return all open chats, call the method without any parameters::
  1021. * const models = _converse.api.chats.get();
  1022. *
  1023. */
  1024. 'get' (jids) {
  1025. if (_.isUndefined(jids)) {
  1026. const result = [];
  1027. _converse.chatboxes.each(function (chatbox) {
  1028. // FIXME: Leaky abstraction from MUC. We need to add a
  1029. // base type for chat boxes, and check for that.
  1030. if (chatbox.get('type') !== _converse.CHATROOMS_TYPE) {
  1031. result.push(chatbox);
  1032. }
  1033. });
  1034. return result;
  1035. } else if (_.isString(jids)) {
  1036. return _converse.chatboxes.getChatBox(jids);
  1037. }
  1038. return _.map(jids, _.partial(_converse.chatboxes.getChatBox.bind(_converse.chatboxes), _, {}, true));
  1039. }
  1040. }
  1041. });
  1042. /************************ END API ************************/
  1043. }
  1044. });