message.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import ModelWithContact from './model-with-contact.js';
  2. import dayjs from 'dayjs';
  3. import log from '../../log.js';
  4. import { _converse, api, converse } from '../../core.js';
  5. import { getOpenPromise } from '@converse/openpromise';
  6. const { Strophe, sizzle, u } = converse.env;
  7. /**
  8. * Mixin which turns a `ModelWithContact` model into a non-MUC message. These can be either `chat` messages or `headline` messages.
  9. * @mixin
  10. * @namespace _converse.Message
  11. * @memberOf _converse
  12. * @example const msg = new _converse.Message({'message': 'hello world!'});
  13. */
  14. const MessageMixin = {
  15. defaults () {
  16. return {
  17. 'msgid': u.getUniqueId(),
  18. 'time': new Date().toISOString(),
  19. 'is_ephemeral': false
  20. };
  21. },
  22. async initialize () {
  23. if (!this.checkValidity()) {
  24. return;
  25. }
  26. this.initialized = getOpenPromise();
  27. if (this.get('type') === 'chat') {
  28. ModelWithContact.prototype.initialize.apply(this, arguments);
  29. this.setRosterContact(Strophe.getBareJidFromJid(this.get('from')));
  30. }
  31. if (this.get('file')) {
  32. this.on('change:put', this.uploadFile, this);
  33. }
  34. this.setTimerForEphemeralMessage();
  35. /**
  36. * Triggered once a {@link _converse.Message} has been created and initialized.
  37. * @event _converse#messageInitialized
  38. * @type { _converse.Message}
  39. * @example _converse.api.listen.on('messageInitialized', model => { ... });
  40. */
  41. await api.trigger('messageInitialized', this, { 'Synchronous': true });
  42. this.initialized.resolve();
  43. },
  44. /**
  45. * Sets an auto-destruct timer for this message, if it's is_ephemeral.
  46. * @private
  47. * @method _converse.Message#setTimerForEphemeralMessage
  48. * @returns { Boolean } - Indicates whether the message is
  49. * ephemeral or not, and therefore whether the timer was set or not.
  50. */
  51. setTimerForEphemeralMessage () {
  52. const setTimer = () => {
  53. this.ephemeral_timer = window.setTimeout(this.safeDestroy.bind(this), 10000);
  54. };
  55. if (this.isEphemeral()) {
  56. setTimer();
  57. return true;
  58. } else {
  59. this.on('change:is_ephemeral', () =>
  60. this.isEphemeral() ? setTimer() : clearTimeout(this.ephemeral_timer)
  61. );
  62. return false;
  63. }
  64. },
  65. checkValidity () {
  66. if (Object.keys(this.attributes).length === 3) {
  67. // XXX: This is an empty message with only the 3 default values.
  68. // This seems to happen when saving a newly created message
  69. // fails for some reason.
  70. // TODO: This is likely fixable by setting `wait` when
  71. // creating messages. See the wait-for-messages branch.
  72. this.validationError = 'Empty message';
  73. this.safeDestroy();
  74. return false;
  75. }
  76. return true;
  77. },
  78. /**
  79. * Determines whether this messsage may be retracted by the current user.
  80. * @private
  81. * @method _converse.Messages#mayBeRetracted
  82. * @returns { Boolean }
  83. */
  84. mayBeRetracted () {
  85. const is_own_message = this.get('sender') === 'me';
  86. const not_canceled = this.get('error_type') !== 'cancel';
  87. return is_own_message && not_canceled && ['all', 'own'].includes(api.settings.get('allow_message_retraction'));
  88. },
  89. safeDestroy () {
  90. try {
  91. this.destroy();
  92. } catch (e) {
  93. log.error(e);
  94. }
  95. },
  96. /**
  97. * Returns a boolean indicating whether this message is ephemeral,
  98. * meaning it will get automatically removed after ten seconds.
  99. * @returns { boolean }
  100. */
  101. isEphemeral () {
  102. return this.get('is_ephemeral');
  103. },
  104. /**
  105. * Returns a boolean indicating whether this message is a XEP-0245 /me command.
  106. * @returns { boolean }
  107. */
  108. isMeCommand () {
  109. const text = this.getMessageText();
  110. if (!text) {
  111. return false;
  112. }
  113. return text.startsWith('/me ');
  114. },
  115. /**
  116. * Returns a boolean indicating whether this message is considered a followup
  117. * message from the previous one. Followup messages are shown grouped together
  118. * under one author heading.
  119. * A message is considered a followup of it's predecessor when it's a chat
  120. * message from the same author, within 10 minutes.
  121. * @returns { boolean }
  122. */
  123. isFollowup () {
  124. const messages = this.collection.models;
  125. const idx = messages.indexOf(this);
  126. const prev_model = idx ? messages[idx-1] : null;
  127. if (prev_model === null) {
  128. return false;
  129. }
  130. const date = dayjs(this.get('time'));
  131. return this.get('from') === prev_model.get('from') &&
  132. !this.isMeCommand() &&
  133. !prev_model.isMeCommand() &&
  134. this.get('type') !== 'info' &&
  135. prev_model.get('type') !== 'info' &&
  136. date.isBefore(dayjs(prev_model.get('time')).add(10, 'minutes')) &&
  137. !!this.get('is_encrypted') === !!prev_model.get('is_encrypted');
  138. },
  139. getDisplayName () {
  140. if (this.contact) {
  141. return this.contact.getDisplayName();
  142. } else if (this.vcard) {
  143. return this.vcard.getDisplayName();
  144. } else {
  145. return this.get('from');
  146. }
  147. },
  148. getMessageText () {
  149. const { __ } = _converse;
  150. if (this.get('is_encrypted')) {
  151. return this.get('plaintext') || this.get('body') || __('Undecryptable OMEMO message');
  152. }
  153. return this.get('message');
  154. },
  155. /**
  156. * Send out an IQ stanza to request a file upload slot.
  157. * https://xmpp.org/extensions/xep-0363.html#request
  158. * @private
  159. * @method _converse.Message#sendSlotRequestStanza
  160. */
  161. sendSlotRequestStanza () {
  162. if (!this.file) {
  163. return Promise.reject(new Error('file is undefined'));
  164. }
  165. const iq = converse.env
  166. .$iq({
  167. 'from': _converse.jid,
  168. 'to': this.get('slot_request_url'),
  169. 'type': 'get'
  170. })
  171. .c('request', {
  172. 'xmlns': Strophe.NS.HTTPUPLOAD,
  173. 'filename': this.file.name,
  174. 'size': this.file.size,
  175. 'content-type': this.file.type
  176. });
  177. return api.sendIQ(iq);
  178. },
  179. getUploadRequestMetadata (stanza) {
  180. const headers = sizzle(`slot[xmlns="${Strophe.NS.HTTPUPLOAD}"] put header`, stanza);
  181. // https://xmpp.org/extensions/xep-0363.html#request
  182. // TODO: Can't set the Cookie header in JavaScipt, instead cookies need
  183. // to be manually set via document.cookie, so we're leaving it out here.
  184. return {
  185. 'headers': headers
  186. .map(h => ({ 'name': h.getAttribute('name'), 'value': h.textContent }))
  187. .filter(h => ['Authorization', 'Expires'].includes(h.name))
  188. }
  189. },
  190. async getRequestSlotURL () {
  191. const { __ } = _converse;
  192. let stanza;
  193. try {
  194. stanza = await this.sendSlotRequestStanza();
  195. } catch (e) {
  196. log.error(e);
  197. return this.save({
  198. 'type': 'error',
  199. 'message': __('Sorry, could not determine upload URL.'),
  200. 'is_ephemeral': true
  201. });
  202. }
  203. const slot = sizzle(`slot[xmlns="${Strophe.NS.HTTPUPLOAD}"]`, stanza).pop();
  204. if (slot) {
  205. this.upload_metadata = this.getUploadRequestMetadata(stanza);
  206. this.save({
  207. 'get': slot.querySelector('get').getAttribute('url'),
  208. 'put': slot.querySelector('put').getAttribute('url')
  209. });
  210. } else {
  211. return this.save({
  212. 'type': 'error',
  213. 'message': __('Sorry, could not determine file upload URL.'),
  214. 'is_ephemeral': true
  215. });
  216. }
  217. },
  218. uploadFile () {
  219. const xhr = new XMLHttpRequest();
  220. xhr.onreadystatechange = async () => {
  221. if (xhr.readyState === XMLHttpRequest.DONE) {
  222. log.info('Status: ' + xhr.status);
  223. if (xhr.status === 200 || xhr.status === 201) {
  224. let attrs = {
  225. 'upload': _converse.SUCCESS,
  226. 'oob_url': this.get('get'),
  227. 'message': this.get('get'),
  228. 'body': this.get('get'),
  229. };
  230. /**
  231. * *Hook* which allows plugins to change the attributes
  232. * saved on the message once a file has been uploaded.
  233. * @event _converse#afterFileUploaded
  234. */
  235. attrs = await api.hook('afterFileUploaded', this, attrs);
  236. this.save(attrs);
  237. } else {
  238. xhr.onerror();
  239. }
  240. }
  241. };
  242. xhr.upload.addEventListener(
  243. 'progress',
  244. evt => {
  245. if (evt.lengthComputable) {
  246. this.set('progress', evt.loaded / evt.total);
  247. }
  248. },
  249. false
  250. );
  251. xhr.onerror = () => {
  252. const { __ } = _converse;
  253. let message;
  254. if (xhr.responseText) {
  255. message = __(
  256. 'Sorry, could not succesfully upload your file. Your server’s response: "%1$s"',
  257. xhr.responseText
  258. );
  259. } else {
  260. message = __('Sorry, could not succesfully upload your file.');
  261. }
  262. this.save({
  263. 'type': 'error',
  264. 'upload': _converse.FAILURE,
  265. 'message': message,
  266. 'is_ephemeral': true
  267. });
  268. };
  269. xhr.open('PUT', this.get('put'), true);
  270. xhr.setRequestHeader('Content-type', this.file.type);
  271. this.upload_metadata.headers?.forEach(h => xhr.setRequestHeader(h.name, h.value));
  272. xhr.send(this.file);
  273. }
  274. };
  275. export default MessageMixin;