1package eu.siacs.conversations.entities;
2
3import android.content.ContentValues;
4import android.database.Cursor;
5import android.graphics.drawable.Drawable;
6import android.graphics.Color;
7import android.os.Build;
8import android.text.Html;
9import android.text.SpannableStringBuilder;
10import android.text.Spanned;
11import android.text.style.ImageSpan;
12import android.text.style.ClickableSpan;
13import android.util.Base64;
14import android.util.Log;
15import android.util.Pair;
16import android.view.View;
17
18import com.cheogram.android.BobTransfer;
19import com.cheogram.android.GetThumbnailForCid;
20import com.cheogram.android.InlineImageSpan;
21import com.cheogram.android.SpannedToXHTML;
22
23import com.google.common.io.ByteSource;
24import com.google.common.base.Strings;
25import com.google.common.collect.ImmutableSet;
26import com.google.common.primitives.Longs;
27
28import org.json.JSONException;
29
30import java.lang.ref.WeakReference;
31import java.io.IOException;
32import java.net.URI;
33import java.net.URISyntaxException;
34import java.time.Duration;
35import java.security.NoSuchAlgorithmException;
36import java.util.ArrayList;
37import java.util.Arrays;
38import java.util.HashSet;
39import java.util.Iterator;
40import java.util.List;
41import java.util.Set;
42import java.util.stream.Collectors;
43import java.util.concurrent.CopyOnWriteArraySet;
44
45import io.ipfs.cid.Cid;
46
47import eu.siacs.conversations.Config;
48import eu.siacs.conversations.crypto.axolotl.AxolotlService;
49import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
50import eu.siacs.conversations.http.URL;
51import eu.siacs.conversations.services.AvatarService;
52import eu.siacs.conversations.ui.util.MyLinkify;
53import eu.siacs.conversations.ui.util.PresenceSelector;
54import eu.siacs.conversations.ui.util.QuoteHelper;
55import eu.siacs.conversations.utils.CryptoHelper;
56import eu.siacs.conversations.utils.Emoticons;
57import eu.siacs.conversations.utils.GeoHelper;
58import eu.siacs.conversations.utils.MessageUtils;
59import eu.siacs.conversations.utils.MimeUtils;
60import eu.siacs.conversations.utils.StringUtils;
61import eu.siacs.conversations.utils.UIHelper;
62import eu.siacs.conversations.xmpp.Jid;
63import eu.siacs.conversations.xml.Element;
64import eu.siacs.conversations.xml.Namespace;
65import eu.siacs.conversations.xml.Tag;
66import eu.siacs.conversations.xml.XmlReader;
67
68public class Message extends AbstractEntity implements AvatarService.Avatarable {
69
70 public static final String TABLENAME = "messages";
71
72 public static final int STATUS_RECEIVED = 0;
73 public static final int STATUS_UNSEND = 1;
74 public static final int STATUS_SEND = 2;
75 public static final int STATUS_SEND_FAILED = 3;
76 public static final int STATUS_WAITING = 5;
77 public static final int STATUS_OFFERED = 6;
78 public static final int STATUS_SEND_RECEIVED = 7;
79 public static final int STATUS_SEND_DISPLAYED = 8;
80
81 public static final int ENCRYPTION_NONE = 0;
82 public static final int ENCRYPTION_PGP = 1;
83 public static final int ENCRYPTION_OTR = 2;
84 public static final int ENCRYPTION_DECRYPTED = 3;
85 public static final int ENCRYPTION_DECRYPTION_FAILED = 4;
86 public static final int ENCRYPTION_AXOLOTL = 5;
87 public static final int ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE = 6;
88 public static final int ENCRYPTION_AXOLOTL_FAILED = 7;
89
90 public static final int TYPE_TEXT = 0;
91 public static final int TYPE_IMAGE = 1;
92 public static final int TYPE_FILE = 2;
93 public static final int TYPE_STATUS = 3;
94 public static final int TYPE_PRIVATE = 4;
95 public static final int TYPE_PRIVATE_FILE = 5;
96 public static final int TYPE_RTP_SESSION = 6;
97
98 public static final String CONVERSATION = "conversationUuid";
99 public static final String COUNTERPART = "counterpart";
100 public static final String TRUE_COUNTERPART = "trueCounterpart";
101 public static final String BODY = "body";
102 public static final String BODY_LANGUAGE = "bodyLanguage";
103 public static final String TIME_SENT = "timeSent";
104 public static final String ENCRYPTION = "encryption";
105 public static final String STATUS = "status";
106 public static final String TYPE = "type";
107 public static final String CARBON = "carbon";
108 public static final String OOB = "oob";
109 public static final String EDITED = "edited";
110 public static final String REMOTE_MSG_ID = "remoteMsgId";
111 public static final String SERVER_MSG_ID = "serverMsgId";
112 public static final String RELATIVE_FILE_PATH = "relativeFilePath";
113 public static final String FINGERPRINT = "axolotl_fingerprint";
114 public static final String READ = "read";
115 public static final String ERROR_MESSAGE = "errorMsg";
116 public static final String READ_BY_MARKERS = "readByMarkers";
117 public static final String MARKABLE = "markable";
118 public static final String DELETED = "deleted";
119 public static final String ME_COMMAND = "/me ";
120
121 public static final String ERROR_MESSAGE_CANCELLED = "eu.siacs.conversations.cancelled";
122
123
124 public boolean markable = false;
125 protected String conversationUuid;
126 protected Jid counterpart;
127 protected Jid trueCounterpart;
128 protected String body;
129 protected String subject;
130 protected String encryptedBody;
131 protected long timeSent;
132 protected long timeReceived;
133 protected int encryption;
134 protected int status;
135 protected int type;
136 protected boolean deleted = false;
137 protected boolean carbon = false;
138 private boolean oob = false;
139 protected List<Element> payloads = new ArrayList<>();
140 protected List<Edit> edits = new ArrayList<>();
141 protected String relativeFilePath;
142 protected boolean read = true;
143 protected String remoteMsgId = null;
144 private String bodyLanguage = null;
145 protected String serverMsgId = null;
146 private final Conversational conversation;
147 protected Transferable transferable = null;
148 private Message mNextMessage = null;
149 private Message mPreviousMessage = null;
150 private String axolotlFingerprint = null;
151 private String errorMessage = null;
152 private Set<ReadByMarker> readByMarkers = new CopyOnWriteArraySet<>();
153
154 private Boolean isGeoUri = null;
155 private Boolean isEmojisOnly = null;
156 private Boolean treatAsDownloadable = null;
157 private FileParams fileParams = null;
158 private List<MucOptions.User> counterparts;
159 private WeakReference<MucOptions.User> user;
160
161 protected Message(Conversational conversation) {
162 this.conversation = conversation;
163 }
164
165 public Message(Conversational conversation, String body, int encryption) {
166 this(conversation, body, encryption, STATUS_UNSEND);
167 }
168
169 public Message(Conversational conversation, String body, int encryption, int status) {
170 this(conversation, java.util.UUID.randomUUID().toString(),
171 conversation.getUuid(),
172 conversation.getJid() == null ? null : conversation.getJid().asBareJid(),
173 null,
174 body,
175 System.currentTimeMillis(),
176 encryption,
177 status,
178 TYPE_TEXT,
179 false,
180 null,
181 null,
182 null,
183 null,
184 true,
185 null,
186 false,
187 null,
188 null,
189 false,
190 false,
191 null,
192 System.currentTimeMillis(),
193 null,
194 null,
195 null);
196 }
197
198 public Message(Conversation conversation, int status, int type, final String remoteMsgId) {
199 this(conversation, java.util.UUID.randomUUID().toString(),
200 conversation.getUuid(),
201 conversation.getJid() == null ? null : conversation.getJid().asBareJid(),
202 null,
203 null,
204 System.currentTimeMillis(),
205 Message.ENCRYPTION_NONE,
206 status,
207 type,
208 false,
209 remoteMsgId,
210 null,
211 null,
212 null,
213 true,
214 null,
215 false,
216 null,
217 null,
218 false,
219 false,
220 null,
221 System.currentTimeMillis(),
222 null,
223 null,
224 null);
225 }
226
227 protected Message(final Conversational conversation, final String uuid, final String conversationUUid, final Jid counterpart,
228 final Jid trueCounterpart, final String body, final long timeSent,
229 final int encryption, final int status, final int type, final boolean carbon,
230 final String remoteMsgId, final String relativeFilePath,
231 final String serverMsgId, final String fingerprint, final boolean read,
232 final String edited, final boolean oob, final String errorMessage, final Set<ReadByMarker> readByMarkers,
233 final boolean markable, final boolean deleted, final String bodyLanguage, final long timeReceived, final String subject, final String fileParams, final List<Element> payloads) {
234 this.conversation = conversation;
235 this.uuid = uuid;
236 this.conversationUuid = conversationUUid;
237 this.counterpart = counterpart;
238 this.trueCounterpart = trueCounterpart;
239 this.body = body == null ? "" : body;
240 this.timeSent = timeSent;
241 this.encryption = encryption;
242 this.status = status;
243 this.type = type;
244 this.carbon = carbon;
245 this.remoteMsgId = remoteMsgId;
246 this.relativeFilePath = relativeFilePath;
247 this.serverMsgId = serverMsgId;
248 this.axolotlFingerprint = fingerprint;
249 this.read = read;
250 this.edits = Edit.fromJson(edited);
251 this.oob = oob;
252 this.errorMessage = errorMessage;
253 this.readByMarkers = readByMarkers == null ? new CopyOnWriteArraySet<>() : readByMarkers;
254 this.markable = markable;
255 this.deleted = deleted;
256 this.bodyLanguage = bodyLanguage;
257 this.timeReceived = timeReceived;
258 this.subject = subject;
259 if (payloads != null) this.payloads = payloads;
260 if (fileParams != null && getSims().isEmpty()) this.fileParams = new FileParams(fileParams);
261 }
262
263 public static Message fromCursor(Cursor cursor, Conversation conversation) throws IOException {
264 String payloadsStr = cursor.getString(cursor.getColumnIndex("payloads"));
265 List<Element> payloads = new ArrayList<>();
266 if (payloadsStr != null) {
267 final XmlReader xmlReader = new XmlReader();
268 xmlReader.setInputStream(ByteSource.wrap(payloadsStr.getBytes()).openStream());
269 Tag tag;
270 while ((tag = xmlReader.readTag()) != null) {
271 payloads.add(xmlReader.readElement(tag));
272 }
273 }
274
275 return new Message(conversation,
276 cursor.getString(cursor.getColumnIndex(UUID)),
277 cursor.getString(cursor.getColumnIndex(CONVERSATION)),
278 fromString(cursor.getString(cursor.getColumnIndex(COUNTERPART))),
279 fromString(cursor.getString(cursor.getColumnIndex(TRUE_COUNTERPART))),
280 cursor.getString(cursor.getColumnIndex(BODY)),
281 cursor.getLong(cursor.getColumnIndex(TIME_SENT)),
282 cursor.getInt(cursor.getColumnIndex(ENCRYPTION)),
283 cursor.getInt(cursor.getColumnIndex(STATUS)),
284 cursor.getInt(cursor.getColumnIndex(TYPE)),
285 cursor.getInt(cursor.getColumnIndex(CARBON)) > 0,
286 cursor.getString(cursor.getColumnIndex(REMOTE_MSG_ID)),
287 cursor.getString(cursor.getColumnIndex(RELATIVE_FILE_PATH)),
288 cursor.getString(cursor.getColumnIndex(SERVER_MSG_ID)),
289 cursor.getString(cursor.getColumnIndex(FINGERPRINT)),
290 cursor.getInt(cursor.getColumnIndex(READ)) > 0,
291 cursor.getString(cursor.getColumnIndex(EDITED)),
292 cursor.getInt(cursor.getColumnIndex(OOB)) > 0,
293 cursor.getString(cursor.getColumnIndex(ERROR_MESSAGE)),
294 ReadByMarker.fromJsonString(cursor.getString(cursor.getColumnIndex(READ_BY_MARKERS))),
295 cursor.getInt(cursor.getColumnIndex(MARKABLE)) > 0,
296 cursor.getInt(cursor.getColumnIndex(DELETED)) > 0,
297 cursor.getString(cursor.getColumnIndex(BODY_LANGUAGE)),
298 cursor.getLong(cursor.getColumnIndex(cursor.isNull(cursor.getColumnIndex("timeReceived")) ? TIME_SENT : "timeReceived")),
299 cursor.getString(cursor.getColumnIndex("subject")),
300 cursor.getString(cursor.getColumnIndex("fileParams")),
301 payloads
302 );
303 }
304
305 private static Jid fromString(String value) {
306 try {
307 if (value != null) {
308 return Jid.of(value);
309 }
310 } catch (IllegalArgumentException e) {
311 return null;
312 }
313 return null;
314 }
315
316 public static Message createStatusMessage(Conversation conversation, String body) {
317 final Message message = new Message(conversation);
318 message.setType(Message.TYPE_STATUS);
319 message.setStatus(Message.STATUS_RECEIVED);
320 message.body = body;
321 return message;
322 }
323
324 public static Message createLoadMoreMessage(Conversation conversation) {
325 final Message message = new Message(conversation);
326 message.setType(Message.TYPE_STATUS);
327 message.body = "LOAD_MORE";
328 return message;
329 }
330
331 public ContentValues getCheogramContentValues() {
332 ContentValues values = new ContentValues();
333 values.put(UUID, uuid);
334 values.put("subject", subject);
335 values.put("fileParams", fileParams == null ? null : fileParams.toString());
336 if (fileParams != null && !fileParams.isEmpty()) {
337 List<Element> sims = getSims();
338 if (sims.isEmpty()) {
339 addPayload(fileParams.toSims());
340 } else {
341 sims.get(0).replaceChildren(fileParams.toSims().getChildren());
342 }
343 }
344 values.put("payloads", payloads.size() < 1 ? null : payloads.stream().map(Object::toString).collect(Collectors.joining()));
345 return values;
346 }
347
348 @Override
349 public ContentValues getContentValues() {
350 ContentValues values = new ContentValues();
351 values.put(UUID, uuid);
352 values.put(CONVERSATION, conversationUuid);
353 if (counterpart == null) {
354 values.putNull(COUNTERPART);
355 } else {
356 values.put(COUNTERPART, counterpart.toString());
357 }
358 if (trueCounterpart == null) {
359 values.putNull(TRUE_COUNTERPART);
360 } else {
361 values.put(TRUE_COUNTERPART, trueCounterpart.toString());
362 }
363 values.put(BODY, body.length() > Config.MAX_STORAGE_MESSAGE_CHARS ? body.substring(0, Config.MAX_STORAGE_MESSAGE_CHARS) : body);
364 values.put(TIME_SENT, timeSent);
365 values.put(ENCRYPTION, encryption);
366 values.put(STATUS, status);
367 values.put(TYPE, type);
368 values.put(CARBON, carbon ? 1 : 0);
369 values.put(REMOTE_MSG_ID, remoteMsgId);
370 values.put(RELATIVE_FILE_PATH, relativeFilePath);
371 values.put(SERVER_MSG_ID, serverMsgId);
372 values.put(FINGERPRINT, axolotlFingerprint);
373 values.put(READ, read ? 1 : 0);
374 try {
375 values.put(EDITED, Edit.toJson(edits));
376 } catch (JSONException e) {
377 Log.e(Config.LOGTAG, "error persisting json for edits", e);
378 }
379 values.put(OOB, oob ? 1 : 0);
380 values.put(ERROR_MESSAGE, errorMessage);
381 values.put(READ_BY_MARKERS, ReadByMarker.toJson(readByMarkers).toString());
382 values.put(MARKABLE, markable ? 1 : 0);
383 values.put(DELETED, deleted ? 1 : 0);
384 values.put(BODY_LANGUAGE, bodyLanguage);
385 return values;
386 }
387
388 public String replyId() {
389 if (conversation.getMode() == Conversation.MODE_MULTI) return getServerMsgId();
390 final String remote = getRemoteMsgId();
391 if (remote == null && getStatus() > STATUS_RECEIVED) return getUuid();
392 return remote;
393 }
394
395 public Message reply() {
396 Message m = new Message(conversation, QuoteHelper.quote(MessageUtils.prepareQuote(this)) + "\n", ENCRYPTION_NONE);
397 m.setThread(getThread());
398 final String replyId = replyId();
399 if (replyId == null) return m;
400
401 m.addPayload(
402 new Element("reply", "urn:xmpp:reply:0")
403 .setAttribute("to", getCounterpart())
404 .setAttribute("id", replyId())
405 );
406 final Element fallback = new Element("fallback", "urn:xmpp:fallback:0").setAttribute("for", "urn:xmpp:reply:0");
407 fallback.addChild("body", "urn:xmpp:fallback:0")
408 .setAttribute("start", "0")
409 .setAttribute("end", "" + m.body.codePointCount(0, m.body.length()));
410 m.addPayload(fallback);
411 return m;
412 }
413
414 public Message react(String emoji) {
415 Set<String> emojis = new HashSet<>();
416 if (conversation instanceof Conversation) emojis = ((Conversation) conversation).findReactionsTo(replyId(), null);
417 emojis.add(emoji);
418 final Message m = reply();
419 m.appendBody(emoji);
420 final Element fallback = new Element("fallback", "urn:xmpp:fallback:0").setAttribute("for", "urn:xmpp:reactions:0");
421 fallback.addChild("body", "urn:xmpp:fallback:0");
422 m.addPayload(fallback);
423 final Element reactions = new Element("reactions", "urn:xmpp:reactions:0").setAttribute("id", replyId());
424 for (String oneEmoji : emojis) {
425 reactions.addChild("reaction", "urn:xmpp:reactions:0").setContent(oneEmoji);
426 }
427 m.addPayload(reactions);
428 return m;
429 }
430
431 public void setReactions(Element reactions) {
432 if (this.payloads != null) {
433 this.payloads.remove(getReactions());
434 }
435 addPayload(reactions);
436 }
437
438 public Element getReactions() {
439 if (this.payloads == null) return null;
440
441 for (Element el : this.payloads) {
442 if (el.getName().equals("reactions") && el.getNamespace().equals("urn:xmpp:reactions:0")) {
443 return el;
444 }
445 }
446
447 return null;
448 }
449
450 public Element getReply() {
451 if (this.payloads == null) return null;
452
453 for (Element el : this.payloads) {
454 if (el.getName().equals("reply") && el.getNamespace().equals("urn:xmpp:reply:0")) {
455 return el;
456 }
457 }
458
459 return null;
460 }
461
462 public boolean isAttention() {
463 if (this.payloads == null) return false;
464
465 for (Element el : this.payloads) {
466 if (el.getName().equals("attention") && el.getNamespace().equals("urn:xmpp:attention:0")) {
467 return true;
468 }
469 }
470
471 return false;
472 }
473
474 public String getConversationUuid() {
475 return conversationUuid;
476 }
477
478 public Conversational getConversation() {
479 return this.conversation;
480 }
481
482 public Jid getCounterpart() {
483 return counterpart;
484 }
485
486 public void setCounterpart(final Jid counterpart) {
487 this.counterpart = counterpart;
488 }
489
490 public Contact getContact() {
491 if (this.conversation.getMode() == Conversation.MODE_SINGLE) {
492 if (this.trueCounterpart != null) {
493 return this.conversation.getAccount().getRoster()
494 .getContact(this.trueCounterpart);
495 }
496
497 return this.conversation.getContact();
498 } else {
499 if (this.trueCounterpart == null) {
500 return null;
501 } else {
502 return this.conversation.getAccount().getRoster()
503 .getContactFromContactList(this.trueCounterpart);
504 }
505 }
506 }
507
508 public String getQuoteableBody() {
509 return this.body;
510 }
511
512 public String getBody() {
513 StringBuilder body = new StringBuilder(this.body);
514
515 List<Element> fallbacks = getFallbacks("http://jabber.org/protocol/address", Namespace.OOB);
516 List<Pair<Integer, Integer>> spans = new ArrayList<>();
517 for (Element fallback : fallbacks) {
518 for (Element span : fallback.getChildren()) {
519 if (!span.getName().equals("body") && !span.getNamespace().equals("urn:xmpp:fallback:0")) continue;
520 if (span.getAttribute("start") == null || span.getAttribute("end") == null) return "";
521 spans.add(new Pair(parseInt(span.getAttribute("start")), parseInt(span.getAttribute("end"))));
522 }
523 }
524 // Do them in reverse order so that span deletions don't affect the indexes of other spans
525 spans.sort((x, y) -> y.first.compareTo(x.first));
526 try {
527 for (Pair<Integer, Integer> span : spans) {
528 body.delete(body.offsetByCodePoints(0, span.first.intValue()), body.offsetByCodePoints(0, span.second.intValue()));
529 }
530 } catch (final IndexOutOfBoundsException e) { spans.clear(); }
531
532 if (spans.isEmpty() && getOob() != null) {
533 return body.toString().replace(getOob().toString(), "");
534 } else if (spans.isEmpty() && isGeoUri()) {
535 return "";
536 } else {
537 return body.toString();
538 }
539 }
540
541 public synchronized void clearFallbacks(String... includeFor) {
542 this.payloads.removeAll(getFallbacks(includeFor));
543 }
544
545 public synchronized Element getOrMakeHtml() {
546 Element html = getHtml();
547 if (html != null) return html;
548 html = new Element("html", "http://jabber.org/protocol/xhtml-im");
549 Element body = html.addChild("body", "http://www.w3.org/1999/xhtml");
550 SpannedToXHTML.append(body, new SpannableStringBuilder(getBody()));
551 addPayload(html);
552 return body;
553 }
554
555 public synchronized void setBody(Spanned span) {
556 setBody(span.toString());
557 final Element body = getOrMakeHtml();
558 body.clearChildren();
559 SpannedToXHTML.append(body, span);
560 if (body.getContent().equals(span.toString())) {
561 this.payloads.remove(getHtml(true));
562 }
563 }
564
565 public synchronized void setHtml(Element html) {
566 final Element oldHtml = getHtml(true);
567 if (oldHtml != null) this.payloads.remove(oldHtml);
568 if (html != null) addPayload(html);
569 }
570
571 public synchronized void setBody(String body) {
572 this.body = body;
573 this.isGeoUri = null;
574 this.isEmojisOnly = null;
575 this.treatAsDownloadable = null;
576 }
577
578 public synchronized void appendBody(Spanned append) {
579 final Element body = getOrMakeHtml();
580 SpannedToXHTML.append(body, append);
581 if (body.getContent().equals(this.body + append.toString())) {
582 this.payloads.remove(getHtml());
583 }
584 appendBody(append.toString());
585 }
586
587 public synchronized void appendBody(String append) {
588 this.body += append;
589 this.isGeoUri = null;
590 this.isEmojisOnly = null;
591 this.treatAsDownloadable = null;
592 }
593
594 public String getSubject() {
595 return subject;
596 }
597
598 public synchronized void setSubject(String subject) {
599 this.subject = subject;
600 }
601
602 public Element getThread() {
603 if (this.payloads == null) return null;
604
605 for (Element el : this.payloads) {
606 if (el.getName().equals("thread") && el.getNamespace().equals("jabber:client")) {
607 return el;
608 }
609 }
610
611 return null;
612 }
613
614 public void setThread(Element thread) {
615 payloads.removeIf(el -> el.getName().equals("thread") && el.getNamespace().equals("jabber:client"));
616 addPayload(thread);
617 }
618
619 public void setMucUser(MucOptions.User user) {
620 this.user = new WeakReference<>(user);
621 }
622
623 public boolean sameMucUser(Message otherMessage) {
624 final MucOptions.User thisUser = this.user == null ? null : this.user.get();
625 final MucOptions.User otherUser = otherMessage.user == null ? null : otherMessage.user.get();
626 return thisUser != null && thisUser == otherUser;
627 }
628
629 public String getErrorMessage() {
630 return errorMessage;
631 }
632
633 public boolean setErrorMessage(String message) {
634 boolean changed = (message != null && !message.equals(errorMessage))
635 || (message == null && errorMessage != null);
636 this.errorMessage = message;
637 return changed;
638 }
639
640 public long getTimeReceived() {
641 return timeReceived;
642 }
643
644 public long getTimeSent() {
645 return timeSent;
646 }
647
648 public int getEncryption() {
649 return encryption;
650 }
651
652 public void setEncryption(int encryption) {
653 this.encryption = encryption;
654 }
655
656 public int getStatus() {
657 return status;
658 }
659
660 public void setStatus(int status) {
661 this.status = status;
662 }
663
664 public String getRelativeFilePath() {
665 return this.relativeFilePath;
666 }
667
668 public void setRelativeFilePath(String path) {
669 this.relativeFilePath = path;
670 }
671
672 public String getRemoteMsgId() {
673 return this.remoteMsgId;
674 }
675
676 public void setRemoteMsgId(String id) {
677 this.remoteMsgId = id;
678 }
679
680 public String getServerMsgId() {
681 return this.serverMsgId;
682 }
683
684 public void setServerMsgId(String id) {
685 this.serverMsgId = id;
686 }
687
688 public boolean isRead() {
689 return this.read;
690 }
691
692 public boolean isDeleted() {
693 return this.deleted;
694 }
695
696 public Element getModerated() {
697 if (this.payloads == null) return null;
698
699 for (Element el : this.payloads) {
700 if (el.getName().equals("moderated") && el.getNamespace().equals("urn:xmpp:message-moderate:0")) {
701 return el;
702 }
703 }
704
705 return null;
706 }
707
708 public void setDeleted(boolean deleted) {
709 this.deleted = deleted;
710 }
711
712 public void markRead() {
713 this.read = true;
714 }
715
716 public void markUnread() {
717 this.read = false;
718 }
719
720 public void setTime(long time) {
721 this.timeSent = time;
722 }
723
724 public void setTimeReceived(long time) {
725 this.timeReceived = time;
726 }
727
728 public String getEncryptedBody() {
729 return this.encryptedBody;
730 }
731
732 public void setEncryptedBody(String body) {
733 this.encryptedBody = body;
734 }
735
736 public int getType() {
737 return this.type;
738 }
739
740 public void setType(int type) {
741 this.type = type;
742 }
743
744 public boolean isCarbon() {
745 return carbon;
746 }
747
748 public void setCarbon(boolean carbon) {
749 this.carbon = carbon;
750 }
751
752 public void putEdited(String edited, String serverMsgId) {
753 final Edit edit = new Edit(edited, serverMsgId);
754 if (this.edits.size() < 128 && !this.edits.contains(edit)) {
755 this.edits.add(edit);
756 }
757 }
758
759 boolean remoteMsgIdMatchInEdit(String id) {
760 for (Edit edit : this.edits) {
761 if (id.equals(edit.getEditedId())) {
762 return true;
763 }
764 }
765 return false;
766 }
767
768 public String getBodyLanguage() {
769 return this.bodyLanguage;
770 }
771
772 public void setBodyLanguage(String language) {
773 this.bodyLanguage = language;
774 }
775
776 public boolean edited() {
777 return this.edits.size() > 0;
778 }
779
780 public void setTrueCounterpart(Jid trueCounterpart) {
781 this.trueCounterpart = trueCounterpart;
782 }
783
784 public Jid getTrueCounterpart() {
785 return this.trueCounterpart;
786 }
787
788 public Transferable getTransferable() {
789 return this.transferable;
790 }
791
792 public synchronized void setTransferable(Transferable transferable) {
793 this.transferable = transferable;
794 }
795
796 public boolean addReadByMarker(ReadByMarker readByMarker) {
797 if (readByMarker.getRealJid() != null) {
798 if (readByMarker.getRealJid().asBareJid().equals(trueCounterpart)) {
799 return false;
800 }
801 } else if (readByMarker.getFullJid() != null) {
802 if (readByMarker.getFullJid().equals(counterpart)) {
803 return false;
804 }
805 }
806 if (this.readByMarkers.add(readByMarker)) {
807 if (readByMarker.getRealJid() != null && readByMarker.getFullJid() != null) {
808 Iterator<ReadByMarker> iterator = this.readByMarkers.iterator();
809 while (iterator.hasNext()) {
810 ReadByMarker marker = iterator.next();
811 if (marker.getRealJid() == null && readByMarker.getFullJid().equals(marker.getFullJid())) {
812 iterator.remove();
813 }
814 }
815 }
816 return true;
817 } else {
818 return false;
819 }
820 }
821
822 public Set<ReadByMarker> getReadByMarkers() {
823 return ImmutableSet.copyOf(this.readByMarkers);
824 }
825
826 boolean similar(Message message) {
827 if (!isPrivateMessage() && this.serverMsgId != null && message.getServerMsgId() != null) {
828 return this.serverMsgId.equals(message.getServerMsgId()) || Edit.wasPreviouslyEditedServerMsgId(edits, message.getServerMsgId());
829 } else if (Edit.wasPreviouslyEditedServerMsgId(edits, message.getServerMsgId())) {
830 return true;
831 } else if (this.body == null || this.counterpart == null) {
832 return false;
833 } else {
834 String body, otherBody;
835 if (this.hasFileOnRemoteHost() && (this.body == null || "".equals(this.body))) {
836 body = getFileParams().url;
837 otherBody = message.body == null ? null : message.body.trim();
838 } else {
839 body = this.body;
840 otherBody = message.body;
841 }
842 final boolean matchingCounterpart = this.counterpart.equals(message.getCounterpart());
843 if (message.getRemoteMsgId() != null) {
844 final boolean hasUuid = CryptoHelper.UUID_PATTERN.matcher(message.getRemoteMsgId()).matches();
845 if (hasUuid && matchingCounterpart && Edit.wasPreviouslyEditedRemoteMsgId(edits, message.getRemoteMsgId())) {
846 return true;
847 }
848 return (message.getRemoteMsgId().equals(this.remoteMsgId) || message.getRemoteMsgId().equals(this.uuid))
849 && matchingCounterpart
850 && (body.equals(otherBody) || (message.getEncryption() == Message.ENCRYPTION_PGP && hasUuid));
851 } else {
852 return this.remoteMsgId == null
853 && matchingCounterpart
854 && body.equals(otherBody)
855 && Math.abs(this.getTimeSent() - message.getTimeSent()) < Config.MESSAGE_MERGE_WINDOW * 1000;
856 }
857 }
858 }
859
860 public Message next() {
861 if (this.conversation instanceof Conversation) {
862 final Conversation conversation = (Conversation) this.conversation;
863 synchronized (conversation.messages) {
864 if (this.mNextMessage == null) {
865 int index = conversation.messages.indexOf(this);
866 if (index < 0 || index >= conversation.messages.size() - 1) {
867 this.mNextMessage = null;
868 } else {
869 this.mNextMessage = conversation.messages.get(index + 1);
870 }
871 }
872 return this.mNextMessage;
873 }
874 } else {
875 throw new AssertionError("Calling next should be disabled for stubs");
876 }
877 }
878
879 public Message prev() {
880 if (this.conversation instanceof Conversation) {
881 final Conversation conversation = (Conversation) this.conversation;
882 synchronized (conversation.messages) {
883 if (this.mPreviousMessage == null) {
884 int index = conversation.messages.indexOf(this);
885 if (index <= 0 || index > conversation.messages.size()) {
886 this.mPreviousMessage = null;
887 } else {
888 this.mPreviousMessage = conversation.messages.get(index - 1);
889 }
890 }
891 }
892 return this.mPreviousMessage;
893 } else {
894 throw new AssertionError("Calling prev should be disabled for stubs");
895 }
896 }
897
898 public boolean isLastCorrectableMessage() {
899 Message next = next();
900 while (next != null) {
901 if (next.isEditable()) {
902 return false;
903 }
904 next = next.next();
905 }
906 return isEditable();
907 }
908
909 public boolean isEditable() {
910 return status != STATUS_RECEIVED && !isCarbon() && type != Message.TYPE_RTP_SESSION;
911 }
912
913 public boolean mergeable(final Message message) {
914 return message != null &&
915 (message.getType() == Message.TYPE_TEXT &&
916 this.getTransferable() == null &&
917 message.getTransferable() == null &&
918 message.getEncryption() != Message.ENCRYPTION_PGP &&
919 message.getEncryption() != Message.ENCRYPTION_DECRYPTION_FAILED &&
920 this.getType() == message.getType() &&
921 this.getSubject() != null &&
922 isStatusMergeable(this.getStatus(), message.getStatus()) &&
923 isEncryptionMergeable(this.getEncryption(),message.getEncryption()) &&
924 this.getCounterpart() != null &&
925 this.getCounterpart().equals(message.getCounterpart()) &&
926 this.edited() == message.edited() &&
927 (message.getTimeSent() - this.getTimeSent()) <= (Config.MESSAGE_MERGE_WINDOW * 1000) &&
928 this.getBody().length() + message.getBody().length() <= Config.MAX_DISPLAY_MESSAGE_CHARS &&
929 !message.isGeoUri() &&
930 !this.isGeoUri() &&
931 !message.isOOb() &&
932 !this.isOOb() &&
933 !message.treatAsDownloadable() &&
934 !this.treatAsDownloadable() &&
935 !message.hasMeCommand() &&
936 !this.hasMeCommand() &&
937 !this.bodyIsOnlyEmojis() &&
938 !message.bodyIsOnlyEmojis() &&
939 ((this.axolotlFingerprint == null && message.axolotlFingerprint == null) || this.axolotlFingerprint.equals(message.getFingerprint())) &&
940 UIHelper.sameDay(message.getTimeSent(), this.getTimeSent()) &&
941 this.getReadByMarkers().equals(message.getReadByMarkers()) &&
942 !this.conversation.getJid().asBareJid().equals(Config.BUG_REPORTS)
943 );
944 }
945
946 private static boolean isStatusMergeable(int a, int b) {
947 return a == b || (
948 (a == Message.STATUS_SEND_RECEIVED && b == Message.STATUS_UNSEND)
949 || (a == Message.STATUS_SEND_RECEIVED && b == Message.STATUS_SEND)
950 || (a == Message.STATUS_SEND_RECEIVED && b == Message.STATUS_WAITING)
951 || (a == Message.STATUS_SEND && b == Message.STATUS_UNSEND)
952 || (a == Message.STATUS_SEND && b == Message.STATUS_WAITING)
953 );
954 }
955
956 private static boolean isEncryptionMergeable(final int a, final int b) {
957 return a == b
958 && Arrays.asList(ENCRYPTION_NONE, ENCRYPTION_DECRYPTED, ENCRYPTION_AXOLOTL)
959 .contains(a);
960 }
961
962 public void setCounterparts(List<MucOptions.User> counterparts) {
963 this.counterparts = counterparts;
964 }
965
966 public List<MucOptions.User> getCounterparts() {
967 return this.counterparts;
968 }
969
970 @Override
971 public int getAvatarBackgroundColor() {
972 if (type == Message.TYPE_STATUS && getCounterparts() != null && getCounterparts().size() > 1) {
973 return Color.TRANSPARENT;
974 } else {
975 return UIHelper.getColorForName(UIHelper.getMessageDisplayName(this));
976 }
977 }
978
979 @Override
980 public String getAvatarName() {
981 return UIHelper.getMessageDisplayName(this);
982 }
983
984 public boolean isOOb() {
985 return oob || getFileParams().url != null;
986 }
987
988 public static class MergeSeparator {
989 }
990
991 public SpannableStringBuilder getSpannableBody(GetThumbnailForCid thumbnailer, Drawable fallbackImg) {
992 final Element html = getHtml();
993 if (html == null || Build.VERSION.SDK_INT < 24) {
994 return new SpannableStringBuilder(MessageUtils.filterLtrRtl(getBody()).trim());
995 } else {
996 SpannableStringBuilder spannable = new SpannableStringBuilder(Html.fromHtml(
997 MessageUtils.filterLtrRtl(html.toString()).trim(),
998 Html.FROM_HTML_MODE_COMPACT,
999 (source) -> {
1000 try {
1001 if (thumbnailer == null || source == null) return fallbackImg;
1002 Cid cid = BobTransfer.cid(new URI(source));
1003 if (cid == null) return fallbackImg;
1004 Drawable thumbnail = thumbnailer.getThumbnail(cid);
1005 if (thumbnail == null) return fallbackImg;
1006 return thumbnail;
1007 } catch (final URISyntaxException e) {
1008 return fallbackImg;
1009 }
1010 },
1011 (opening, tag, output, xmlReader) -> {}
1012 ));
1013
1014 // Make images clickable and long-clickable with BetterLinkMovementMethod
1015 ImageSpan[] imageSpans = spannable.getSpans(0, spannable.length(), ImageSpan.class);
1016 for (ImageSpan span : imageSpans) {
1017 final int start = spannable.getSpanStart(span);
1018 final int end = spannable.getSpanEnd(span);
1019
1020 ClickableSpan click_span = new ClickableSpan() {
1021 @Override
1022 public void onClick(View widget) { }
1023 };
1024
1025 spannable.removeSpan(span);
1026 spannable.setSpan(new InlineImageSpan(span.getDrawable(), span.getSource()), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1027 spannable.setSpan(click_span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
1028 }
1029
1030 // https://stackoverflow.com/a/10187511/8611
1031 int i = spannable.length();
1032 while(--i >= 0 && Character.isWhitespace(spannable.charAt(i))) { }
1033 return (SpannableStringBuilder) spannable.subSequence(0, i+1);
1034 }
1035 }
1036
1037 public SpannableStringBuilder getMergedBody() {
1038 return getMergedBody(null, null);
1039 }
1040
1041 public SpannableStringBuilder getMergedBody(GetThumbnailForCid thumbnailer, Drawable fallbackImg) {
1042 SpannableStringBuilder body = getSpannableBody(thumbnailer, fallbackImg);
1043 Message current = this;
1044 while (current.mergeable(current.next())) {
1045 current = current.next();
1046 if (current == null) {
1047 break;
1048 }
1049 body.append("\n\n");
1050 body.setSpan(new MergeSeparator(), body.length() - 2, body.length(),
1051 SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
1052 body.append(current.getSpannableBody(thumbnailer, fallbackImg));
1053 }
1054 return body;
1055 }
1056
1057 public boolean hasMeCommand() {
1058 return this.body.trim().startsWith(ME_COMMAND);
1059 }
1060
1061 public int getMergedStatus() {
1062 int status = this.status;
1063 Message current = this;
1064 while (current.mergeable(current.next())) {
1065 current = current.next();
1066 if (current == null) {
1067 break;
1068 }
1069 status = current.status;
1070 }
1071 return status;
1072 }
1073
1074 public long getMergedTimeSent() {
1075 long time = this.timeSent;
1076 Message current = this;
1077 while (current.mergeable(current.next())) {
1078 current = current.next();
1079 if (current == null) {
1080 break;
1081 }
1082 time = current.timeSent;
1083 }
1084 return time;
1085 }
1086
1087 public boolean wasMergedIntoPrevious() {
1088 Message prev = this.prev();
1089 return prev != null && prev.mergeable(this);
1090 }
1091
1092 public boolean trusted() {
1093 Contact contact = this.getContact();
1094 return status > STATUS_RECEIVED || (contact != null && (contact.showInContactList() || contact.isSelf()));
1095 }
1096
1097 public boolean fixCounterpart() {
1098 final Presences presences = conversation.getContact().getPresences();
1099 if (counterpart != null && presences.has(Strings.nullToEmpty(counterpart.getResource()))) {
1100 return true;
1101 } else if (presences.size() >= 1) {
1102 counterpart = PresenceSelector.getNextCounterpart(getContact(), presences.toResourceArray()[0]);
1103 return true;
1104 } else {
1105 counterpart = null;
1106 return false;
1107 }
1108 }
1109
1110 public void setUuid(String uuid) {
1111 this.uuid = uuid;
1112 }
1113
1114 public String getEditedId() {
1115 if (edits.size() > 0) {
1116 return edits.get(edits.size() - 1).getEditedId();
1117 } else {
1118 throw new IllegalStateException("Attempting to store unedited message");
1119 }
1120 }
1121
1122 public String getEditedIdWireFormat() {
1123 if (edits.size() > 0) {
1124 return edits.get(Config.USE_LMC_VERSION_1_1 ? 0 : edits.size() - 1).getEditedId();
1125 } else {
1126 throw new IllegalStateException("Attempting to store unedited message");
1127 }
1128 }
1129
1130 public List<URI> getLinks() {
1131 SpannableStringBuilder text = new SpannableStringBuilder(
1132 getBody().replaceAll("^>.*", "") // Remove quotes
1133 );
1134 return MyLinkify.extractLinks(text).stream().map((url) -> {
1135 try {
1136 return new URI(url);
1137 } catch (final URISyntaxException e) {
1138 return null;
1139 }
1140 }).filter(x -> x != null).collect(Collectors.toList());
1141 }
1142
1143 public URI getOob() {
1144 final String url = getFileParams().url;
1145 try {
1146 return url == null ? null : new URI(url);
1147 } catch (final URISyntaxException e) {
1148 return null;
1149 }
1150 }
1151
1152 public void clearPayloads() {
1153 this.payloads.clear();
1154 }
1155
1156 public void addPayload(Element el) {
1157 if (el == null) return;
1158
1159 this.payloads.add(el);
1160 }
1161
1162 public List<Element> getPayloads() {
1163 return new ArrayList<>(this.payloads);
1164 }
1165
1166 public List<Element> getFallbacks(String... includeFor) {
1167 List<Element> fallbacks = new ArrayList<>();
1168
1169 if (this.payloads == null) return fallbacks;
1170
1171 for (Element el : this.payloads) {
1172 if (el.getName().equals("fallback") && el.getNamespace().equals("urn:xmpp:fallback:0")) {
1173 final String fallbackFor = el.getAttribute("for");
1174 if (fallbackFor == null) continue;
1175 for (String includeOne : includeFor) {
1176 if (fallbackFor.equals(includeOne)) {
1177 fallbacks.add(el);
1178 break;
1179 }
1180 }
1181 }
1182 }
1183
1184 return fallbacks;
1185 }
1186
1187 public Element getHtml() {
1188 return getHtml(false);
1189 }
1190
1191 public Element getHtml(boolean root) {
1192 if (this.payloads == null) return null;
1193
1194 for (Element el : this.payloads) {
1195 if (el.getName().equals("html") && el.getNamespace().equals("http://jabber.org/protocol/xhtml-im")) {
1196 return root ? el : el.getChildren().get(0);
1197 }
1198 }
1199
1200 return null;
1201 }
1202
1203 public List<Element> getCommands() {
1204 if (this.payloads == null) return null;
1205
1206 for (Element el : this.payloads) {
1207 if (el.getName().equals("query") && el.getNamespace().equals("http://jabber.org/protocol/disco#items") && el.getAttribute("node").equals("http://jabber.org/protocol/commands")) {
1208 return el.getChildren();
1209 }
1210 }
1211
1212 return null;
1213 }
1214
1215 public String getMimeType() {
1216 String extension;
1217 if (relativeFilePath != null) {
1218 extension = MimeUtils.extractRelevantExtension(relativeFilePath);
1219 } else {
1220 final String url = URL.tryParse(getOob() == null ? body.split("\n")[0] : getOob().toString());
1221 if (url == null) {
1222 return null;
1223 }
1224 extension = MimeUtils.extractRelevantExtension(url);
1225 }
1226 return MimeUtils.guessMimeTypeFromExtension(extension);
1227 }
1228
1229 public synchronized boolean treatAsDownloadable() {
1230 if (treatAsDownloadable == null) {
1231 treatAsDownloadable = MessageUtils.treatAsDownloadable(this.body, isOOb());
1232 }
1233 return treatAsDownloadable;
1234 }
1235
1236 public synchronized boolean hasCustomEmoji() {
1237 if (getHtml() != null) {
1238 SpannableStringBuilder spannable = getSpannableBody(null, null);
1239 ImageSpan[] imageSpans = spannable.getSpans(0, spannable.length(), ImageSpan.class);
1240 return imageSpans.length > 0;
1241 }
1242
1243 return false;
1244 }
1245
1246 public synchronized boolean bodyIsOnlyEmojis() {
1247 if (isEmojisOnly == null) {
1248 isEmojisOnly = Emoticons.isOnlyEmoji(getBody().replaceAll("\\s", ""));
1249 if (isEmojisOnly) return true;
1250
1251 if (getHtml() != null) {
1252 SpannableStringBuilder spannable = getSpannableBody(null, null);
1253 ImageSpan[] imageSpans = spannable.getSpans(0, spannable.length(), ImageSpan.class);
1254 for (ImageSpan span : imageSpans) {
1255 final int start = spannable.getSpanStart(span);
1256 final int end = spannable.getSpanEnd(span);
1257 spannable.delete(start, end);
1258 }
1259 final String after = spannable.toString().replaceAll("\\s", "");
1260 isEmojisOnly = after.length() == 0 || Emoticons.isOnlyEmoji(after);
1261 }
1262 }
1263 return isEmojisOnly;
1264 }
1265
1266 public synchronized boolean isGeoUri() {
1267 if (isGeoUri == null) {
1268 isGeoUri = GeoHelper.GEO_URI.matcher(body).matches();
1269 }
1270 return isGeoUri;
1271 }
1272
1273 protected List<Element> getSims() {
1274 return payloads.stream().filter(el ->
1275 el.getName().equals("reference") && el.getNamespace().equals("urn:xmpp:reference:0") &&
1276 el.findChild("media-sharing", "urn:xmpp:sims:1") != null
1277 ).collect(Collectors.toList());
1278 }
1279
1280 public synchronized void resetFileParams() {
1281 this.fileParams = null;
1282 }
1283
1284 public synchronized void setFileParams(FileParams fileParams) {
1285 if (fileParams != null && this.fileParams != null && this.fileParams.sims != null && fileParams.sims == null) {
1286 fileParams.sims = this.fileParams.sims;
1287 }
1288 this.fileParams = fileParams;
1289 if (fileParams != null && getSims().isEmpty()) {
1290 addPayload(fileParams.toSims());
1291 }
1292 }
1293
1294 public synchronized FileParams getFileParams() {
1295 if (fileParams == null) {
1296 List<Element> sims = getSims();
1297 fileParams = sims.isEmpty() ? new FileParams(oob ? this.body : "") : new FileParams(sims.get(0));
1298 if (this.transferable != null) {
1299 fileParams.size = this.transferable.getFileSize();
1300 }
1301 }
1302
1303 return fileParams;
1304 }
1305
1306 private static int parseInt(String value) {
1307 try {
1308 return Integer.parseInt(value);
1309 } catch (NumberFormatException e) {
1310 return 0;
1311 }
1312 }
1313
1314 public void untie() {
1315 this.mNextMessage = null;
1316 this.mPreviousMessage = null;
1317 }
1318
1319 public boolean isPrivateMessage() {
1320 return type == TYPE_PRIVATE || type == TYPE_PRIVATE_FILE;
1321 }
1322
1323 public boolean isFileOrImage() {
1324 return type == TYPE_FILE || type == TYPE_IMAGE || type == TYPE_PRIVATE_FILE;
1325 }
1326
1327
1328 public boolean isTypeText() {
1329 return type == TYPE_TEXT || type == TYPE_PRIVATE;
1330 }
1331
1332 public boolean hasFileOnRemoteHost() {
1333 return isFileOrImage() && getFileParams().url != null;
1334 }
1335
1336 public boolean needsUploading() {
1337 return isFileOrImage() && getFileParams().url == null;
1338 }
1339
1340 public static class FileParams {
1341 public String url;
1342 public Long size = null;
1343 public int width = 0;
1344 public int height = 0;
1345 public int runtime = 0;
1346 public Element sims = null;
1347
1348 public FileParams() { }
1349
1350 public FileParams(Element el) {
1351 if (el.getName().equals("x") && el.getNamespace().equals(Namespace.OOB)) {
1352 this.url = el.findChildContent("url", Namespace.OOB);
1353 }
1354 if (el.getName().equals("reference") && el.getNamespace().equals("urn:xmpp:reference:0")) {
1355 sims = el;
1356 final String refUri = el.getAttribute("uri");
1357 if (refUri != null) url = refUri;
1358 final Element mediaSharing = el.findChild("media-sharing", "urn:xmpp:sims:1");
1359 if (mediaSharing != null) {
1360 Element file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:5");
1361 if (file == null) file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:4");
1362 if (file == null) file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:3");
1363 if (file != null) {
1364 try {
1365 String sizeS = file.findChildContent("size", file.getNamespace());
1366 if (sizeS != null) size = new Long(sizeS);
1367 String widthS = file.findChildContent("width", "https://schema.org/");
1368 if (widthS != null) width = parseInt(widthS);
1369 String heightS = file.findChildContent("height", "https://schema.org/");
1370 if (heightS != null) height = parseInt(heightS);
1371 String durationS = file.findChildContent("duration", "https://schema.org/");
1372 if (durationS != null) runtime = (int)(Duration.parse(durationS).toMillis() / 1000L);
1373 } catch (final NumberFormatException e) {
1374 Log.w(Config.LOGTAG, "Trouble parsing as number: " + e);
1375 }
1376 }
1377
1378 final Element sources = mediaSharing.findChild("sources", "urn:xmpp:sims:1");
1379 if (sources != null) {
1380 final Element ref = sources.findChild("reference", "urn:xmpp:reference:0");
1381 if (ref != null) url = ref.getAttribute("uri");
1382 }
1383 }
1384 }
1385 }
1386
1387 public FileParams(String ser) {
1388 final String[] parts = ser == null ? new String[0] : ser.split("\\|");
1389 switch (parts.length) {
1390 case 1:
1391 try {
1392 this.size = Long.parseLong(parts[0]);
1393 } catch (final NumberFormatException e) {
1394 this.url = URL.tryParse(parts[0]);
1395 }
1396 break;
1397 case 5:
1398 this.runtime = parseInt(parts[4]);
1399 case 4:
1400 this.width = parseInt(parts[2]);
1401 this.height = parseInt(parts[3]);
1402 case 2:
1403 this.url = URL.tryParse(parts[0]);
1404 this.size = Longs.tryParse(parts[1]);
1405 break;
1406 case 3:
1407 this.size = Longs.tryParse(parts[0]);
1408 this.width = parseInt(parts[1]);
1409 this.height = parseInt(parts[2]);
1410 break;
1411 }
1412 }
1413
1414 public boolean isEmpty() {
1415 return StringUtils.nullOnEmpty(toString()) == null && StringUtils.nullOnEmpty(toSims().getContent()) == null;
1416 }
1417
1418 public long getSize() {
1419 return size == null ? 0 : size;
1420 }
1421
1422 public String getName() {
1423 Element file = getFileElement();
1424 if (file == null) return null;
1425
1426 return file.findChildContent("name", file.getNamespace());
1427 }
1428
1429 public void setName(final String name) {
1430 if (sims == null) toSims();
1431 Element file = getFileElement();
1432
1433 for (Element child : file.getChildren()) {
1434 if (child.getName().equals("name") && child.getNamespace().equals(file.getNamespace())) {
1435 file.removeChild(child);
1436 }
1437 }
1438
1439 if (name != null) {
1440 file.addChild("name", file.getNamespace()).setContent(name);
1441 }
1442 }
1443
1444 public String getMediaType() {
1445 Element file = getFileElement();
1446 if (file == null) return null;
1447
1448 return file.findChildContent("media-type", file.getNamespace());
1449 }
1450
1451 public void setMediaType(final String mime) {
1452 if (sims == null) toSims();
1453 Element file = getFileElement();
1454
1455 for (Element child : file.getChildren()) {
1456 if (child.getName().equals("media-type") && child.getNamespace().equals(file.getNamespace())) {
1457 file.removeChild(child);
1458 }
1459 }
1460
1461 if (mime != null) {
1462 file.addChild("media-type", file.getNamespace()).setContent(mime);
1463 }
1464 }
1465
1466 public Element toSims() {
1467 if (sims == null) sims = new Element("reference", "urn:xmpp:reference:0");
1468 sims.setAttribute("type", "data");
1469 Element mediaSharing = sims.findChild("media-sharing", "urn:xmpp:sims:1");
1470 if (mediaSharing == null) mediaSharing = sims.addChild("media-sharing", "urn:xmpp:sims:1");
1471
1472 Element file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:5");
1473 if (file == null) file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:4");
1474 if (file == null) file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:3");
1475 if (file == null) file = mediaSharing.addChild("file", "urn:xmpp:jingle:apps:file-transfer:5");
1476
1477 file.removeChild(file.findChild("size", file.getNamespace()));
1478 if (size != null) file.addChild("size", file.getNamespace()).setContent(size.toString());
1479
1480 file.removeChild(file.findChild("width", "https://schema.org/"));
1481 if (width > 0) file.addChild("width", "https://schema.org/").setContent(String.valueOf(width));
1482
1483 file.removeChild(file.findChild("height", "https://schema.org/"));
1484 if (height > 0) file.addChild("height", "https://schema.org/").setContent(String.valueOf(height));
1485
1486 file.removeChild(file.findChild("duration", "https://schema.org/"));
1487 if (runtime > 0) file.addChild("duration", "https://schema.org/").setContent("PT" + runtime + "S");
1488
1489 if (url != null) {
1490 Element sources = mediaSharing.findChild("sources", mediaSharing.getNamespace());
1491 if (sources == null) sources = mediaSharing.addChild("sources", mediaSharing.getNamespace());
1492
1493 Element source = sources.findChild("reference", "urn:xmpp:reference:0");
1494 if (source == null) source = sources.addChild("reference", "urn:xmpp:reference:0");
1495 source.setAttribute("type", "data");
1496 source.setAttribute("uri", url);
1497 }
1498
1499 return sims;
1500 }
1501
1502 protected Element getFileElement() {
1503 Element file = null;
1504 if (sims == null) return file;
1505
1506 Element mediaSharing = sims.findChild("media-sharing", "urn:xmpp:sims:1");
1507 if (mediaSharing == null) return file;
1508 file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:5");
1509 if (file == null) file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:4");
1510 if (file == null) file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:3");
1511 return file;
1512 }
1513
1514 public void setCids(Iterable<Cid> cids) throws NoSuchAlgorithmException {
1515 if (sims == null) toSims();
1516 Element file = getFileElement();
1517
1518 for (Element child : file.getChildren()) {
1519 if (child.getName().equals("hash") && child.getNamespace().equals("urn:xmpp:hashes:2")) {
1520 file.removeChild(child);
1521 }
1522 }
1523
1524 for (Cid cid : cids) {
1525 file.addChild("hash", "urn:xmpp:hashes:2")
1526 .setAttribute("algo", CryptoHelper.multihashAlgo(cid.getType()))
1527 .setContent(Base64.encodeToString(cid.getHash(), Base64.NO_WRAP));
1528 }
1529 }
1530
1531 public List<Cid> getCids() {
1532 List<Cid> cids = new ArrayList<>();
1533 Element file = getFileElement();
1534 if (file == null) return cids;
1535
1536 for (Element child : file.getChildren()) {
1537 if (child.getName().equals("hash") && child.getNamespace().equals("urn:xmpp:hashes:2")) {
1538 try {
1539 cids.add(CryptoHelper.cid(Base64.decode(child.getContent(), Base64.DEFAULT), child.getAttribute("algo")));
1540 } catch (final NoSuchAlgorithmException | IllegalStateException e) { }
1541 }
1542 }
1543
1544 cids.sort((x, y) -> y.getType().compareTo(x.getType()));
1545
1546 return cids;
1547 }
1548
1549 public void addThumbnail(int width, int height, String mimeType, String uri) {
1550 for (Element thumb : getThumbnails()) {
1551 if (uri.equals(thumb.getAttribute("uri"))) return;
1552 }
1553
1554 if (sims == null) toSims();
1555 Element file = getFileElement();
1556 file.addChild(
1557 new Element("thumbnail", "urn:xmpp:thumbs:1")
1558 .setAttribute("width", Integer.toString(width))
1559 .setAttribute("height", Integer.toString(height))
1560 .setAttribute("type", mimeType)
1561 .setAttribute("uri", uri)
1562 );
1563 }
1564
1565 public List<Element> getThumbnails() {
1566 List<Element> thumbs = new ArrayList<>();
1567 Element file = getFileElement();
1568 if (file == null) return thumbs;
1569
1570 for (Element child : file.getChildren()) {
1571 if (child.getName().equals("thumbnail") && child.getNamespace().equals("urn:xmpp:thumbs:1")) {
1572 thumbs.add(child);
1573 }
1574 }
1575
1576 return thumbs;
1577 }
1578
1579 public String toString() {
1580 final StringBuilder builder = new StringBuilder();
1581 if (url != null) builder.append(url);
1582 if (size != null) builder.append('|').append(size.toString());
1583 if (width > 0 || height > 0 || runtime > 0) builder.append('|').append(width);
1584 if (height > 0 || runtime > 0) builder.append('|').append(height);
1585 if (runtime > 0) builder.append('|').append(runtime);
1586 return builder.toString();
1587 }
1588
1589 public boolean equals(Object o) {
1590 if (!(o instanceof FileParams)) return false;
1591 if (url == null) return false;
1592
1593 return url.equals(((FileParams) o).url);
1594 }
1595
1596 public int hashCode() {
1597 return url == null ? super.hashCode() : url.hashCode();
1598 }
1599 }
1600
1601 public void setFingerprint(String fingerprint) {
1602 this.axolotlFingerprint = fingerprint;
1603 }
1604
1605 public String getFingerprint() {
1606 return axolotlFingerprint;
1607 }
1608
1609 public boolean isTrusted() {
1610 final AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
1611 final FingerprintStatus s = axolotlService != null ? axolotlService.getFingerprintTrust(axolotlFingerprint) : null;
1612 return s != null && s.isTrusted();
1613 }
1614
1615 private int getPreviousEncryption() {
1616 for (Message iterator = this.prev(); iterator != null; iterator = iterator.prev()) {
1617 if (iterator.isCarbon() || iterator.getStatus() == STATUS_RECEIVED) {
1618 continue;
1619 }
1620 return iterator.getEncryption();
1621 }
1622 return ENCRYPTION_NONE;
1623 }
1624
1625 private int getNextEncryption() {
1626 if (this.conversation instanceof Conversation) {
1627 Conversation conversation = (Conversation) this.conversation;
1628 for (Message iterator = this.next(); iterator != null; iterator = iterator.next()) {
1629 if (iterator.isCarbon() || iterator.getStatus() == STATUS_RECEIVED) {
1630 continue;
1631 }
1632 return iterator.getEncryption();
1633 }
1634 return conversation.getNextEncryption();
1635 } else {
1636 throw new AssertionError("This should never be called since isInValidSession should be disabled for stubs");
1637 }
1638 }
1639
1640 public boolean isValidInSession() {
1641 int pastEncryption = getCleanedEncryption(this.getPreviousEncryption());
1642 int futureEncryption = getCleanedEncryption(this.getNextEncryption());
1643
1644 boolean inUnencryptedSession = pastEncryption == ENCRYPTION_NONE
1645 || futureEncryption == ENCRYPTION_NONE
1646 || pastEncryption != futureEncryption;
1647
1648 return inUnencryptedSession || getCleanedEncryption(this.getEncryption()) == pastEncryption;
1649 }
1650
1651 private static int getCleanedEncryption(int encryption) {
1652 if (encryption == ENCRYPTION_DECRYPTED || encryption == ENCRYPTION_DECRYPTION_FAILED) {
1653 return ENCRYPTION_PGP;
1654 }
1655 if (encryption == ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE || encryption == ENCRYPTION_AXOLOTL_FAILED) {
1656 return ENCRYPTION_AXOLOTL;
1657 }
1658 return encryption;
1659 }
1660
1661 public static boolean configurePrivateMessage(final Message message) {
1662 return configurePrivateMessage(message, false);
1663 }
1664
1665 public static boolean configurePrivateFileMessage(final Message message) {
1666 return configurePrivateMessage(message, true);
1667 }
1668
1669 private static boolean configurePrivateMessage(final Message message, final boolean isFile) {
1670 final Conversation conversation;
1671 if (message.conversation instanceof Conversation) {
1672 conversation = (Conversation) message.conversation;
1673 } else {
1674 return false;
1675 }
1676 if (conversation.getMode() == Conversation.MODE_MULTI) {
1677 final Jid nextCounterpart = conversation.getNextCounterpart();
1678 return configurePrivateMessage(conversation, message, nextCounterpart, isFile);
1679 }
1680 return false;
1681 }
1682
1683 public static boolean configurePrivateMessage(final Message message, final Jid counterpart) {
1684 final Conversation conversation;
1685 if (message.conversation instanceof Conversation) {
1686 conversation = (Conversation) message.conversation;
1687 } else {
1688 return false;
1689 }
1690 return configurePrivateMessage(conversation, message, counterpart, false);
1691 }
1692
1693 private static boolean configurePrivateMessage(final Conversation conversation, final Message message, final Jid counterpart, final boolean isFile) {
1694 if (counterpart == null) {
1695 return false;
1696 }
1697 message.setCounterpart(counterpart);
1698 message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(counterpart));
1699 message.setType(isFile ? Message.TYPE_PRIVATE_FILE : Message.TYPE_PRIVATE);
1700 return true;
1701 }
1702}