Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Message.ts « src - github.com/jsxc/jsxc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e3ab0d7d5173acea3a717451ce89204d2bb0614a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
import Storage from './Storage';
import Attachment from './Attachment';
import JID from './JID';
import * as CONST from './CONST';
import Emoticons from './Emoticons';
import IIdentifiable from './Identifiable.interface';
import Client from './Client';
import Utils from './util/Utils';
import { IMessage, DIRECTION, IMessagePayload, MessageMark } from './Message.interface';
import { ContactType } from './Contact.interface';
import PersistentMap from './util/PersistentMap';
import UUID from './util/UUID';
import Pipe from '@util/Pipe';
import { IJID } from './JID.interface';

const ATREGEX = new RegExp('(xmpp:)?(' + CONST.REGEX.JID.source + ')(\\?[^\\s]+\\b)?', 'i');

export default class Message implements IIdentifiable, IMessage {
   public static exists(uid: string) {
      let data = PersistentMap.getData(Client.getStorage(), uid);

      return !!(data && data.attrId);
   }

   private static formattingPipe = new Pipe();

   private static formatText(text: string, direction: DIRECTION, peer: IJID, senderName: string): Promise<string> {
      return Message.formattingPipe.run(text, direction, peer, senderName).then(args => args[0]);
   }

   public static addFormatter(
      formatter: (
         text: string,
         direction: DIRECTION,
         peer?: IJID,
         senderName?: string
      ) => Promise<[string, DIRECTION, IJID, string]> | string,
      priority?: number
   ) {
      Message.formattingPipe.addProcessor((text: string, direction: DIRECTION, peer: IJID, senderName: string) => {
         let returnValue = formatter(text, direction, peer, senderName);

         if (typeof returnValue === 'string') {
            return Promise.resolve([returnValue, direction, peer, senderName]);
         }

         return returnValue;
      }, priority);
   }

   private uid: string;

   private data: PersistentMap;

   private attachment: Attachment;

   private replacedBy: IMessage;

   private original: IMessage;

   public static readonly DIRECTION = DIRECTION;

   public static readonly MSGTYPE = ContactType;

   private storage: Storage;

   constructor(uid: string);
   constructor(data: IMessagePayload);
   constructor(arg0) {
      this.storage = Client.getStorage();
      let data;

      if (typeof arg0 === 'string' && arg0.length > 0 && arguments.length === 1) {
         this.uid = arg0;
      } else if (typeof arg0 === 'object' && arg0 !== null) {
         data = arg0;

         this.uid = data.uid || UUID.v4();
         data.attrId = data.attrId || this.uid;

         delete data.uid;
      }

      this.data = new PersistentMap(this.storage, this.uid);

      if (data) {
         if (data.peer) {
            data.peer = data.peer.full;
         }

         if (data.sender?.jid) {
            data.sender.jid = data.sender.jid?.toString();
         }

         if (data.attachment instanceof Attachment) {
            this.attachment = data.attachment;
            data.attachment = data.attachment.getUid();
         }

         this.data.set(
            $.extend(
               {
                  unread: true,
                  mark: MessageMark.pending,
                  encrypted: null,
                  forwarded: false,
                  stamp: new Date().getTime(),
                  type: ContactType.CHAT,
                  encryptedHtmlMessage: null,
                  encryptedPlaintextMessage: null,
               },
               data
            )
         );
      } else if (!this.data.get('attrId')) {
         throw new Error(`Could not load message ${this.uid}`);
      }
   }

   public registerHook(property: string, func: (newValue: any, oldValue: any) => void) {
      this.data.registerHook(property, func);
   }

   public getId() {
      // eslint-disable-next-line no-console
      console.trace('Deprecated Message.getId called');
      return this.getUid();
   }

   public getUid(): string {
      return this.uid;
   }

   public getAttrId(): string {
      return this.data.get('attrId');
   }

   public delete() {
      let attachment = this.getAttachment();

      if (attachment) {
         attachment.delete();
      }

      this.data.delete();

      this.attachment = undefined;
      this.data = undefined;
      this.uid = undefined;
   }

   public getNextId(): string {
      return this.data.get('next');
   }

   public setNext(message: IMessage | string | undefined): void {
      let nextId = typeof message === 'string' || typeof message === 'undefined' ? message : message.getUid();

      if (this.getNextId() === this.uid) {
         // eslint-disable-next-line no-console
         console.trace('Loop detected ' + this.uid);
      } else {
         this.data.set('next', nextId);
      }
   }

   public getCssId(): string {
      return this.uid.replace(/:/g, '-');
   }

   public getDOM(): JQuery<HTMLElement> {
      return $('#' + this.getCssId());
   }

   public getStamp(): Date {
      return new Date(this.data.get('stamp'));
   }

   public getDirection(): DIRECTION {
      return this.data.get('direction');
   }

   public getDirectionString(): string {
      return DIRECTION[this.getDirection()].toLowerCase();
   }

   public isSystem(): boolean {
      return this.getDirection() === DIRECTION.SYS;
   }

   public isIncoming(): boolean {
      return this.getDirection() === DIRECTION.IN || this.getDirection() === DIRECTION.PROBABLY_IN;
   }

   public isOutgoing(): boolean {
      return this.getDirection() === DIRECTION.OUT || this.getDirection() === DIRECTION.PROBABLY_OUT;
   }

   public getAttachment(): Attachment {
      if (!this.attachment && this.data.get('attachment')) {
         this.attachment = new Attachment(this.data.get('attachment'));
      }

      return this.attachment;
   }

   public setAttachment(attachment: Attachment) {
      this.attachment = attachment;

      this.data.set('attachment', attachment.getUid());
   }

   public getPeer(): JID {
      return new JID(this.data.get('peer'));
   }

   public getType(): ContactType {
      return this.data.get('type');
   }

   public getTypeString(): string {
      return ContactType[this.getType()].toLowerCase();
   }

   public getHtmlMessage(): string {
      return this.data.get('htmlMessage');
   }

   public setHtmlMessage(htmlMessage: string) {
      this.data.set('htmlMessage', htmlMessage);
   }

   public getEncryptedHtmlMessage(): string {
      return this.data.get('encryptedHtmlMessage');
   }

   public getPlaintextMessage(): string {
      return this.data.get('plaintextMessage');
   }

   public getEncryptedPlaintextMessage(): string {
      return this.data.get('encryptedPlaintextMessage');
   }

   public getSender(): { name: string; jid?: JID } {
      let sender = this.data.get('sender');

      return {
         name: sender?.name,
         jid: sender?.jid ? new JID(sender.jid) : undefined,
      };
   }

   public getMark(): MessageMark {
      return this.data.get('mark');
   }

   public aborted() {
      let currentMark = this.data.get('mark', MessageMark.pending);

      if (currentMark === MessageMark.pending) {
         this.data.set('mark', MessageMark.aborted);
      }
   }

   public isAborted(): boolean {
      return this.data.get('mark', MessageMark.aborted) === MessageMark.aborted;
   }

   public transferred() {
      let currentMark = this.data.get('mark', MessageMark.pending);

      this.data.set('mark', Math.max(currentMark, MessageMark.transferred));
   }

   public isTransferred(): boolean {
      return this.data.get('mark', MessageMark.pending) >= MessageMark.transferred;
   }

   public received() {
      let currentMark = this.data.get('mark', MessageMark.pending);

      this.data.set('mark', Math.max(currentMark, MessageMark.received));
   }

   public isReceived(): boolean {
      //this.data.get('received') is deprecated since 4.0.x
      return this.data.get('mark', MessageMark.pending) >= MessageMark.received || !!this.data.get('received');
   }

   public displayed() {
      let currentMark = this.data.get('mark', MessageMark.pending);

      this.data.set('mark', Math.max(currentMark, MessageMark.displayed));
   }

   public isDisplayed(): boolean {
      return this.data.get('mark', MessageMark.pending) >= MessageMark.displayed;
   }

   public acknowledged() {
      this.data.set('mark', MessageMark.acknowledged);
   }

   public isAcknowledged(): boolean {
      return this.data.get('mark', MessageMark.pending) >= MessageMark.acknowledged;
   }

   public isForwarded(): boolean {
      return !!this.data.get('forwarded');
   }

   public isEncrypted(): boolean {
      return !!this.data.get('encrypted');
   }

   public hasAttachment(): boolean {
      return !!this.data.get('attachment');
   }

   public isUnread(): boolean {
      return !!this.data.get('unread');
   }

   public read() {
      this.data.set('unread', false);
   }

   public setDirection(direction: DIRECTION) {
      this.data.set('direction', direction);
   }

   public setPlaintextMessage(plaintextMessage: string) {
      this.data.set('plaintextMessage', plaintextMessage);
   }

   public setEncryptedPlaintextMessage(encryptedPlaintextMessage: string) {
      this.data.set('encryptedPlaintextMessage', encryptedPlaintextMessage);
   }

   public setEncrypted(encrypted: boolean = false) {
      this.data.set('encrypted', encrypted);
   }

   public async getProcessedBody(): Promise<string> {
      let body = this.getPlaintextMessage();

      body = Utils.escapeHTML(body);
      body = await Message.formatText(body, this.getDirection(), this.getPeer(), this.getSender().name);

      return `<p dir="auto">${body}</p>`;
   }

   public getPlaintextEmoticonMessage(emotions: 'unicode' | 'image' = 'image'): string {
      let body = this.getPlaintextMessage();

      body = Utils.escapeHTML(body);
      body = emotions === 'unicode' ? Emoticons.toUnicode(body) : Emoticons.toImage(body);

      return body;
   }

   public setErrorMessage(error: string) {
      return this.data.set('errorMessage', error);
   }

   public getErrorMessage(): string {
      return this.data.get('errorMessage');
   }

   public updateProgress(transferred: number, size: number) {
      this.data.set('progress', transferred / size);
   }

   public getLastVersion(): IMessage {
      let replacedBy = this.getReplacedBy();

      while (replacedBy && replacedBy.getReplacedBy()) {
         replacedBy = replacedBy.getReplacedBy();
      }

      return replacedBy || this;
   }

   public getReplacedBy(): IMessage {
      if (this.replacedBy) {
         return this.replacedBy;
      }

      const replacedByUid = this.data.get('replacedBy');

      this.replacedBy = replacedByUid ? new Message(replacedByUid) : undefined;

      return this.replacedBy;
   }

   public setReplacedBy(message: IMessage): void {
      this.data.set('replacedBy', message.getUid());
   }

   public getOriginal(): IMessage {
      if (this.original) {
         return this.original;
      }

      const originalUid = this.data.get('original');

      this.original = originalUid ? new Message(originalUid) : undefined;

      return this.original;
   }

   public setOriginal(message: IMessage): void {
      this.data.set('original', message.getUid());
   }

   public isReplacement(): boolean {
      return !!this.data.get('original');
   }
}

function convertUrlToLink(text: string) {
   return text.replace(CONST.REGEX.URL, function (url) {
      let href = url.match(/^https?:\/\//i) ? url : 'http://' + url;

      return '<a href="' + href + '" target="_blank" rel="noopener noreferrer">' + url + '</a>';
   });
}

function convertEmailToLink(text: string) {
   return text.replace(ATREGEX, function (str, protocol, jid, action) {
      if (protocol === 'xmpp:') {
         if (typeof action === 'string') {
            jid += action;
         }

         return '<a href="xmpp:' + jid + '">xmpp:' + jid + '</a>';
      }

      return '<a href="mailto:' + jid + '" target="_blank">' + jid + '</a>';
   });
}

function convertGeoToLink(text: string) {
   return text.replace(CONST.REGEX.GEOURI, url => {
      return `<a href="${url}" target="_blank" rel="noopener noreferrer">${url}</a>`;
   });
}

function markQuotation(text: string) {
   return text
      .split(/(?:\n|\r\n|\r)/)
      .map(line => {
         return line.indexOf('&gt;') === 0
            ? '<span class="jsxc-quote">' + line.replace(/^&gt; ?/, '') + '</span>'
            : line;
      })
      .join('\n');
}

function replaceLineBreaks(text: string) {
   return text.replace(/(\r\n|\r|\n){2}/g, '</p><p dir="auto">').replace(/(\r\n|\r|\n)/g, '<br/>');
}

Message.addFormatter(convertUrlToLink);
Message.addFormatter(convertEmailToLink);
Message.addFormatter(convertGeoToLink);
Message.addFormatter(Emoticons.toImage.bind(Emoticons));
Message.addFormatter(markQuotation);
Message.addFormatter(replaceLineBreaks);