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 if (SpannedToXHTML.isPlainText(span)) {
558 this.payloads.remove(getHtml(true));
559 } else {
560 final Element body = getOrMakeHtml();
561 body.clearChildren();
562 SpannedToXHTML.append(body, span);
563 }
564 }
565
566 public synchronized void setHtml(Element html) {
567 final Element oldHtml = getHtml(true);
568 if (oldHtml != null) this.payloads.remove(oldHtml);
569 if (html != null) addPayload(html);
570 }
571
572 public synchronized void setBody(String body) {
573 this.body = body;
574 this.isGeoUri = null;
575 this.isEmojisOnly = null;
576 this.treatAsDownloadable = null;
577 }
578
579 public synchronized void appendBody(Spanned append) {
580 if (!SpannedToXHTML.isPlainText(append) || getHtml() != null) {
581 final Element body = getOrMakeHtml();
582 SpannedToXHTML.append(body, append);
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 false; // Merrgine messages messes up reply, so disable for now
915 }
916
917 private static boolean isStatusMergeable(int a, int b) {
918 return a == b || (
919 (a == Message.STATUS_SEND_RECEIVED && b == Message.STATUS_UNSEND)
920 || (a == Message.STATUS_SEND_RECEIVED && b == Message.STATUS_SEND)
921 || (a == Message.STATUS_SEND_RECEIVED && b == Message.STATUS_WAITING)
922 || (a == Message.STATUS_SEND && b == Message.STATUS_UNSEND)
923 || (a == Message.STATUS_SEND && b == Message.STATUS_WAITING)
924 );
925 }
926
927 private static boolean isEncryptionMergeable(final int a, final int b) {
928 return a == b
929 && Arrays.asList(ENCRYPTION_NONE, ENCRYPTION_DECRYPTED, ENCRYPTION_AXOLOTL)
930 .contains(a);
931 }
932
933 public void setCounterparts(List<MucOptions.User> counterparts) {
934 this.counterparts = counterparts;
935 }
936
937 public List<MucOptions.User> getCounterparts() {
938 return this.counterparts;
939 }
940
941 @Override
942 public int getAvatarBackgroundColor() {
943 if (type == Message.TYPE_STATUS && getCounterparts() != null && getCounterparts().size() > 1) {
944 return Color.TRANSPARENT;
945 } else {
946 return UIHelper.getColorForName(UIHelper.getMessageDisplayName(this));
947 }
948 }
949
950 @Override
951 public String getAvatarName() {
952 return UIHelper.getMessageDisplayName(this);
953 }
954
955 public boolean isOOb() {
956 return oob || getFileParams().url != null;
957 }
958
959 public static class MergeSeparator {
960 }
961
962 public SpannableStringBuilder getSpannableBody(GetThumbnailForCid thumbnailer, Drawable fallbackImg) {
963 final Element html = getHtml();
964 if (html == null || Build.VERSION.SDK_INT < 24) {
965 return new SpannableStringBuilder(MessageUtils.filterLtrRtl(getBody()).trim());
966 } else {
967 SpannableStringBuilder spannable = new SpannableStringBuilder(Html.fromHtml(
968 MessageUtils.filterLtrRtl(html.toString()).trim(),
969 Html.FROM_HTML_MODE_COMPACT,
970 (source) -> {
971 try {
972 if (thumbnailer == null || source == null) return fallbackImg;
973 Cid cid = BobTransfer.cid(new URI(source));
974 if (cid == null) return fallbackImg;
975 Drawable thumbnail = thumbnailer.getThumbnail(cid);
976 if (thumbnail == null) return fallbackImg;
977 return thumbnail;
978 } catch (final URISyntaxException e) {
979 return fallbackImg;
980 }
981 },
982 (opening, tag, output, xmlReader) -> {}
983 ));
984
985 // Make images clickable and long-clickable with BetterLinkMovementMethod
986 ImageSpan[] imageSpans = spannable.getSpans(0, spannable.length(), ImageSpan.class);
987 for (ImageSpan span : imageSpans) {
988 final int start = spannable.getSpanStart(span);
989 final int end = spannable.getSpanEnd(span);
990
991 ClickableSpan click_span = new ClickableSpan() {
992 @Override
993 public void onClick(View widget) { }
994 };
995
996 spannable.removeSpan(span);
997 spannable.setSpan(new InlineImageSpan(span.getDrawable(), span.getSource()), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
998 spannable.setSpan(click_span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
999 }
1000
1001 // https://stackoverflow.com/a/10187511/8611
1002 int i = spannable.length();
1003 while(--i >= 0 && Character.isWhitespace(spannable.charAt(i))) { }
1004 return (SpannableStringBuilder) spannable.subSequence(0, i+1);
1005 }
1006 }
1007
1008 public SpannableStringBuilder getMergedBody() {
1009 return getMergedBody(null, null);
1010 }
1011
1012 public SpannableStringBuilder getMergedBody(GetThumbnailForCid thumbnailer, Drawable fallbackImg) {
1013 SpannableStringBuilder body = getSpannableBody(thumbnailer, fallbackImg);
1014 Message current = this;
1015 while (current.mergeable(current.next())) {
1016 current = current.next();
1017 if (current == null || current.getModerated() != null) {
1018 break;
1019 }
1020 body.append("\n\n");
1021 body.setSpan(new MergeSeparator(), body.length() - 2, body.length(),
1022 SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
1023 body.append(current.getSpannableBody(thumbnailer, fallbackImg));
1024 }
1025 return body;
1026 }
1027
1028 public boolean hasMeCommand() {
1029 return this.body.trim().startsWith(ME_COMMAND);
1030 }
1031
1032 public int getMergedStatus() {
1033 int status = this.status;
1034 Message current = this;
1035 while (current.mergeable(current.next())) {
1036 current = current.next();
1037 if (current == null) {
1038 break;
1039 }
1040 status = current.status;
1041 }
1042 return status;
1043 }
1044
1045 public long getMergedTimeSent() {
1046 long time = this.timeSent;
1047 Message current = this;
1048 while (current.mergeable(current.next())) {
1049 current = current.next();
1050 if (current == null) {
1051 break;
1052 }
1053 time = current.timeSent;
1054 }
1055 return time;
1056 }
1057
1058 public boolean wasMergedIntoPrevious() {
1059 Message prev = this.prev();
1060 if (prev != null && getModerated() != null && prev.getModerated() != null) return true;
1061 return prev != null && prev.mergeable(this);
1062 }
1063
1064 public boolean trusted() {
1065 Contact contact = this.getContact();
1066 return status > STATUS_RECEIVED || (contact != null && (contact.showInContactList() || contact.isSelf()));
1067 }
1068
1069 public boolean fixCounterpart() {
1070 final Presences presences = conversation.getContact().getPresences();
1071 if (counterpart != null && presences.has(Strings.nullToEmpty(counterpart.getResource()))) {
1072 return true;
1073 } else if (presences.size() >= 1) {
1074 counterpart = PresenceSelector.getNextCounterpart(getContact(), presences.toResourceArray()[0]);
1075 return true;
1076 } else {
1077 counterpart = null;
1078 return false;
1079 }
1080 }
1081
1082 public void setUuid(String uuid) {
1083 this.uuid = uuid;
1084 }
1085
1086 public String getEditedId() {
1087 if (edits.size() > 0) {
1088 return edits.get(edits.size() - 1).getEditedId();
1089 } else {
1090 throw new IllegalStateException("Attempting to store unedited message");
1091 }
1092 }
1093
1094 public String getEditedIdWireFormat() {
1095 if (edits.size() > 0) {
1096 return edits.get(Config.USE_LMC_VERSION_1_1 ? 0 : edits.size() - 1).getEditedId();
1097 } else {
1098 throw new IllegalStateException("Attempting to store unedited message");
1099 }
1100 }
1101
1102 public List<URI> getLinks() {
1103 SpannableStringBuilder text = new SpannableStringBuilder(
1104 getBody().replaceAll("^>.*", "") // Remove quotes
1105 );
1106 return MyLinkify.extractLinks(text).stream().map((url) -> {
1107 try {
1108 return new URI(url);
1109 } catch (final URISyntaxException e) {
1110 return null;
1111 }
1112 }).filter(x -> x != null).collect(Collectors.toList());
1113 }
1114
1115 public URI getOob() {
1116 final String url = getFileParams().url;
1117 try {
1118 return url == null ? null : new URI(url);
1119 } catch (final URISyntaxException e) {
1120 return null;
1121 }
1122 }
1123
1124 public void clearPayloads() {
1125 this.payloads.clear();
1126 }
1127
1128 public void addPayload(Element el) {
1129 if (el == null) return;
1130
1131 this.payloads.add(el);
1132 }
1133
1134 public List<Element> getPayloads() {
1135 return new ArrayList<>(this.payloads);
1136 }
1137
1138 public List<Element> getFallbacks(String... includeFor) {
1139 List<Element> fallbacks = new ArrayList<>();
1140
1141 if (this.payloads == null) return fallbacks;
1142
1143 for (Element el : this.payloads) {
1144 if (el.getName().equals("fallback") && el.getNamespace().equals("urn:xmpp:fallback:0")) {
1145 final String fallbackFor = el.getAttribute("for");
1146 if (fallbackFor == null) continue;
1147 for (String includeOne : includeFor) {
1148 if (fallbackFor.equals(includeOne)) {
1149 fallbacks.add(el);
1150 break;
1151 }
1152 }
1153 }
1154 }
1155
1156 return fallbacks;
1157 }
1158
1159 public Element getHtml() {
1160 return getHtml(false);
1161 }
1162
1163 public Element getHtml(boolean root) {
1164 if (this.payloads == null) return null;
1165
1166 for (Element el : this.payloads) {
1167 if (el.getName().equals("html") && el.getNamespace().equals("http://jabber.org/protocol/xhtml-im")) {
1168 return root ? el : el.getChildren().get(0);
1169 }
1170 }
1171
1172 return null;
1173 }
1174
1175 public List<Element> getCommands() {
1176 if (this.payloads == null) return null;
1177
1178 for (Element el : this.payloads) {
1179 if (el.getName().equals("query") && el.getNamespace().equals("http://jabber.org/protocol/disco#items") && el.getAttribute("node").equals("http://jabber.org/protocol/commands")) {
1180 return el.getChildren();
1181 }
1182 }
1183
1184 return null;
1185 }
1186
1187 public String getMimeType() {
1188 String extension;
1189 if (relativeFilePath != null) {
1190 extension = MimeUtils.extractRelevantExtension(relativeFilePath);
1191 } else {
1192 final String url = URL.tryParse(getOob() == null ? body.split("\n")[0] : getOob().toString());
1193 if (url == null) {
1194 return null;
1195 }
1196 extension = MimeUtils.extractRelevantExtension(url);
1197 }
1198 return MimeUtils.guessMimeTypeFromExtension(extension);
1199 }
1200
1201 public synchronized boolean treatAsDownloadable() {
1202 if (treatAsDownloadable == null) {
1203 treatAsDownloadable = MessageUtils.treatAsDownloadable(this.body, isOOb());
1204 }
1205 return treatAsDownloadable;
1206 }
1207
1208 public synchronized boolean hasCustomEmoji() {
1209 if (getHtml() != null) {
1210 SpannableStringBuilder spannable = getSpannableBody(null, null);
1211 ImageSpan[] imageSpans = spannable.getSpans(0, spannable.length(), ImageSpan.class);
1212 return imageSpans.length > 0;
1213 }
1214
1215 return false;
1216 }
1217
1218 public synchronized boolean bodyIsOnlyEmojis() {
1219 if (isEmojisOnly == null) {
1220 isEmojisOnly = Emoticons.isOnlyEmoji(getBody().replaceAll("\\s", ""));
1221 if (isEmojisOnly) return true;
1222
1223 if (getHtml() != null) {
1224 SpannableStringBuilder spannable = getSpannableBody(null, null);
1225 ImageSpan[] imageSpans = spannable.getSpans(0, spannable.length(), ImageSpan.class);
1226 for (ImageSpan span : imageSpans) {
1227 final int start = spannable.getSpanStart(span);
1228 final int end = spannable.getSpanEnd(span);
1229 spannable.delete(start, end);
1230 }
1231 final String after = spannable.toString().replaceAll("\\s", "");
1232 isEmojisOnly = after.length() == 0 || Emoticons.isOnlyEmoji(after);
1233 }
1234 }
1235 return isEmojisOnly;
1236 }
1237
1238 public synchronized boolean isGeoUri() {
1239 if (isGeoUri == null) {
1240 isGeoUri = GeoHelper.GEO_URI.matcher(body).matches();
1241 }
1242 return isGeoUri;
1243 }
1244
1245 protected List<Element> getSims() {
1246 return payloads.stream().filter(el ->
1247 el.getName().equals("reference") && el.getNamespace().equals("urn:xmpp:reference:0") &&
1248 el.findChild("media-sharing", "urn:xmpp:sims:1") != null
1249 ).collect(Collectors.toList());
1250 }
1251
1252 public synchronized void resetFileParams() {
1253 this.fileParams = null;
1254 }
1255
1256 public synchronized void setFileParams(FileParams fileParams) {
1257 if (fileParams != null && this.fileParams != null && this.fileParams.sims != null && fileParams.sims == null) {
1258 fileParams.sims = this.fileParams.sims;
1259 }
1260 this.fileParams = fileParams;
1261 if (fileParams != null && getSims().isEmpty()) {
1262 addPayload(fileParams.toSims());
1263 }
1264 }
1265
1266 public synchronized FileParams getFileParams() {
1267 if (fileParams == null) {
1268 List<Element> sims = getSims();
1269 fileParams = sims.isEmpty() ? new FileParams(oob ? this.body : "") : new FileParams(sims.get(0));
1270 if (this.transferable != null) {
1271 fileParams.size = this.transferable.getFileSize();
1272 }
1273 }
1274
1275 return fileParams;
1276 }
1277
1278 private static int parseInt(String value) {
1279 try {
1280 return Integer.parseInt(value);
1281 } catch (NumberFormatException e) {
1282 return 0;
1283 }
1284 }
1285
1286 public void untie() {
1287 this.mNextMessage = null;
1288 this.mPreviousMessage = null;
1289 }
1290
1291 public boolean isPrivateMessage() {
1292 return type == TYPE_PRIVATE || type == TYPE_PRIVATE_FILE;
1293 }
1294
1295 public boolean isFileOrImage() {
1296 return type == TYPE_FILE || type == TYPE_IMAGE || type == TYPE_PRIVATE_FILE;
1297 }
1298
1299
1300 public boolean isTypeText() {
1301 return type == TYPE_TEXT || type == TYPE_PRIVATE;
1302 }
1303
1304 public boolean hasFileOnRemoteHost() {
1305 return isFileOrImage() && getFileParams().url != null;
1306 }
1307
1308 public boolean needsUploading() {
1309 return isFileOrImage() && getFileParams().url == null;
1310 }
1311
1312 public static class FileParams {
1313 public String url;
1314 public Long size = null;
1315 public int width = 0;
1316 public int height = 0;
1317 public int runtime = 0;
1318 public Element sims = null;
1319
1320 public FileParams() { }
1321
1322 public FileParams(Element el) {
1323 if (el.getName().equals("x") && el.getNamespace().equals(Namespace.OOB)) {
1324 this.url = el.findChildContent("url", Namespace.OOB);
1325 }
1326 if (el.getName().equals("reference") && el.getNamespace().equals("urn:xmpp:reference:0")) {
1327 sims = el;
1328 final String refUri = el.getAttribute("uri");
1329 if (refUri != null) url = refUri;
1330 final Element mediaSharing = el.findChild("media-sharing", "urn:xmpp:sims:1");
1331 if (mediaSharing != null) {
1332 Element file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:5");
1333 if (file == null) file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:4");
1334 if (file == null) file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:3");
1335 if (file != null) {
1336 try {
1337 String sizeS = file.findChildContent("size", file.getNamespace());
1338 if (sizeS != null) size = new Long(sizeS);
1339 String widthS = file.findChildContent("width", "https://schema.org/");
1340 if (widthS != null) width = parseInt(widthS);
1341 String heightS = file.findChildContent("height", "https://schema.org/");
1342 if (heightS != null) height = parseInt(heightS);
1343 String durationS = file.findChildContent("duration", "https://schema.org/");
1344 if (durationS != null) runtime = (int)(Duration.parse(durationS).toMillis() / 1000L);
1345 } catch (final NumberFormatException e) {
1346 Log.w(Config.LOGTAG, "Trouble parsing as number: " + e);
1347 }
1348 }
1349
1350 final Element sources = mediaSharing.findChild("sources", "urn:xmpp:sims:1");
1351 if (sources != null) {
1352 final Element ref = sources.findChild("reference", "urn:xmpp:reference:0");
1353 if (ref != null) url = ref.getAttribute("uri");
1354 }
1355 }
1356 }
1357 }
1358
1359 public FileParams(String ser) {
1360 final String[] parts = ser == null ? new String[0] : ser.split("\\|");
1361 switch (parts.length) {
1362 case 1:
1363 try {
1364 this.size = Long.parseLong(parts[0]);
1365 } catch (final NumberFormatException e) {
1366 this.url = URL.tryParse(parts[0]);
1367 }
1368 break;
1369 case 5:
1370 this.runtime = parseInt(parts[4]);
1371 case 4:
1372 this.width = parseInt(parts[2]);
1373 this.height = parseInt(parts[3]);
1374 case 2:
1375 this.url = URL.tryParse(parts[0]);
1376 this.size = Longs.tryParse(parts[1]);
1377 break;
1378 case 3:
1379 this.size = Longs.tryParse(parts[0]);
1380 this.width = parseInt(parts[1]);
1381 this.height = parseInt(parts[2]);
1382 break;
1383 }
1384 }
1385
1386 public boolean isEmpty() {
1387 return StringUtils.nullOnEmpty(toString()) == null && StringUtils.nullOnEmpty(toSims().getContent()) == null;
1388 }
1389
1390 public long getSize() {
1391 return size == null ? 0 : size;
1392 }
1393
1394 public String getName() {
1395 Element file = getFileElement();
1396 if (file == null) return null;
1397
1398 return file.findChildContent("name", file.getNamespace());
1399 }
1400
1401 public void setName(final String name) {
1402 if (sims == null) toSims();
1403 Element file = getFileElement();
1404
1405 for (Element child : file.getChildren()) {
1406 if (child.getName().equals("name") && child.getNamespace().equals(file.getNamespace())) {
1407 file.removeChild(child);
1408 }
1409 }
1410
1411 if (name != null) {
1412 file.addChild("name", file.getNamespace()).setContent(name);
1413 }
1414 }
1415
1416 public String getMediaType() {
1417 Element file = getFileElement();
1418 if (file == null) return null;
1419
1420 return file.findChildContent("media-type", file.getNamespace());
1421 }
1422
1423 public void setMediaType(final String mime) {
1424 if (sims == null) toSims();
1425 Element file = getFileElement();
1426
1427 for (Element child : file.getChildren()) {
1428 if (child.getName().equals("media-type") && child.getNamespace().equals(file.getNamespace())) {
1429 file.removeChild(child);
1430 }
1431 }
1432
1433 if (mime != null) {
1434 file.addChild("media-type", file.getNamespace()).setContent(mime);
1435 }
1436 }
1437
1438 public Element toSims() {
1439 if (sims == null) sims = new Element("reference", "urn:xmpp:reference:0");
1440 sims.setAttribute("type", "data");
1441 Element mediaSharing = sims.findChild("media-sharing", "urn:xmpp:sims:1");
1442 if (mediaSharing == null) mediaSharing = sims.addChild("media-sharing", "urn:xmpp:sims:1");
1443
1444 Element file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:5");
1445 if (file == null) file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:4");
1446 if (file == null) file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:3");
1447 if (file == null) file = mediaSharing.addChild("file", "urn:xmpp:jingle:apps:file-transfer:5");
1448
1449 file.removeChild(file.findChild("size", file.getNamespace()));
1450 if (size != null) file.addChild("size", file.getNamespace()).setContent(size.toString());
1451
1452 file.removeChild(file.findChild("width", "https://schema.org/"));
1453 if (width > 0) file.addChild("width", "https://schema.org/").setContent(String.valueOf(width));
1454
1455 file.removeChild(file.findChild("height", "https://schema.org/"));
1456 if (height > 0) file.addChild("height", "https://schema.org/").setContent(String.valueOf(height));
1457
1458 file.removeChild(file.findChild("duration", "https://schema.org/"));
1459 if (runtime > 0) file.addChild("duration", "https://schema.org/").setContent("PT" + runtime + "S");
1460
1461 if (url != null) {
1462 Element sources = mediaSharing.findChild("sources", mediaSharing.getNamespace());
1463 if (sources == null) sources = mediaSharing.addChild("sources", mediaSharing.getNamespace());
1464
1465 Element source = sources.findChild("reference", "urn:xmpp:reference:0");
1466 if (source == null) source = sources.addChild("reference", "urn:xmpp:reference:0");
1467 source.setAttribute("type", "data");
1468 source.setAttribute("uri", url);
1469 }
1470
1471 return sims;
1472 }
1473
1474 protected Element getFileElement() {
1475 Element file = null;
1476 if (sims == null) return file;
1477
1478 Element mediaSharing = sims.findChild("media-sharing", "urn:xmpp:sims:1");
1479 if (mediaSharing == null) return file;
1480 file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:5");
1481 if (file == null) file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:4");
1482 if (file == null) file = mediaSharing.findChild("file", "urn:xmpp:jingle:apps:file-transfer:3");
1483 return file;
1484 }
1485
1486 public void setCids(Iterable<Cid> cids) throws NoSuchAlgorithmException {
1487 if (sims == null) toSims();
1488 Element file = getFileElement();
1489
1490 for (Element child : file.getChildren()) {
1491 if (child.getName().equals("hash") && child.getNamespace().equals("urn:xmpp:hashes:2")) {
1492 file.removeChild(child);
1493 }
1494 }
1495
1496 for (Cid cid : cids) {
1497 file.addChild("hash", "urn:xmpp:hashes:2")
1498 .setAttribute("algo", CryptoHelper.multihashAlgo(cid.getType()))
1499 .setContent(Base64.encodeToString(cid.getHash(), Base64.NO_WRAP));
1500 }
1501 }
1502
1503 public List<Cid> getCids() {
1504 List<Cid> cids = new ArrayList<>();
1505 Element file = getFileElement();
1506 if (file == null) return cids;
1507
1508 for (Element child : file.getChildren()) {
1509 if (child.getName().equals("hash") && child.getNamespace().equals("urn:xmpp:hashes:2")) {
1510 try {
1511 cids.add(CryptoHelper.cid(Base64.decode(child.getContent(), Base64.DEFAULT), child.getAttribute("algo")));
1512 } catch (final NoSuchAlgorithmException | IllegalStateException e) { }
1513 }
1514 }
1515
1516 cids.sort((x, y) -> y.getType().compareTo(x.getType()));
1517
1518 return cids;
1519 }
1520
1521 public void addThumbnail(int width, int height, String mimeType, String uri) {
1522 for (Element thumb : getThumbnails()) {
1523 if (uri.equals(thumb.getAttribute("uri"))) return;
1524 }
1525
1526 if (sims == null) toSims();
1527 Element file = getFileElement();
1528 file.addChild(
1529 new Element("thumbnail", "urn:xmpp:thumbs:1")
1530 .setAttribute("width", Integer.toString(width))
1531 .setAttribute("height", Integer.toString(height))
1532 .setAttribute("type", mimeType)
1533 .setAttribute("uri", uri)
1534 );
1535 }
1536
1537 public List<Element> getThumbnails() {
1538 List<Element> thumbs = new ArrayList<>();
1539 Element file = getFileElement();
1540 if (file == null) return thumbs;
1541
1542 for (Element child : file.getChildren()) {
1543 if (child.getName().equals("thumbnail") && child.getNamespace().equals("urn:xmpp:thumbs:1")) {
1544 thumbs.add(child);
1545 }
1546 }
1547
1548 return thumbs;
1549 }
1550
1551 public String toString() {
1552 final StringBuilder builder = new StringBuilder();
1553 if (url != null) builder.append(url);
1554 if (size != null) builder.append('|').append(size.toString());
1555 if (width > 0 || height > 0 || runtime > 0) builder.append('|').append(width);
1556 if (height > 0 || runtime > 0) builder.append('|').append(height);
1557 if (runtime > 0) builder.append('|').append(runtime);
1558 return builder.toString();
1559 }
1560
1561 public boolean equals(Object o) {
1562 if (!(o instanceof FileParams)) return false;
1563 if (url == null) return false;
1564
1565 return url.equals(((FileParams) o).url);
1566 }
1567
1568 public int hashCode() {
1569 return url == null ? super.hashCode() : url.hashCode();
1570 }
1571 }
1572
1573 public void setFingerprint(String fingerprint) {
1574 this.axolotlFingerprint = fingerprint;
1575 }
1576
1577 public String getFingerprint() {
1578 return axolotlFingerprint;
1579 }
1580
1581 public boolean isTrusted() {
1582 final AxolotlService axolotlService = conversation.getAccount().getAxolotlService();
1583 final FingerprintStatus s = axolotlService != null ? axolotlService.getFingerprintTrust(axolotlFingerprint) : null;
1584 return s != null && s.isTrusted();
1585 }
1586
1587 private int getPreviousEncryption() {
1588 for (Message iterator = this.prev(); iterator != null; iterator = iterator.prev()) {
1589 if (iterator.isCarbon() || iterator.getStatus() == STATUS_RECEIVED) {
1590 continue;
1591 }
1592 return iterator.getEncryption();
1593 }
1594 return ENCRYPTION_NONE;
1595 }
1596
1597 private int getNextEncryption() {
1598 if (this.conversation instanceof Conversation) {
1599 Conversation conversation = (Conversation) this.conversation;
1600 for (Message iterator = this.next(); iterator != null; iterator = iterator.next()) {
1601 if (iterator.isCarbon() || iterator.getStatus() == STATUS_RECEIVED) {
1602 continue;
1603 }
1604 return iterator.getEncryption();
1605 }
1606 return conversation.getNextEncryption();
1607 } else {
1608 throw new AssertionError("This should never be called since isInValidSession should be disabled for stubs");
1609 }
1610 }
1611
1612 public boolean isValidInSession() {
1613 int pastEncryption = getCleanedEncryption(this.getPreviousEncryption());
1614 int futureEncryption = getCleanedEncryption(this.getNextEncryption());
1615
1616 boolean inUnencryptedSession = pastEncryption == ENCRYPTION_NONE
1617 || futureEncryption == ENCRYPTION_NONE
1618 || pastEncryption != futureEncryption;
1619
1620 return inUnencryptedSession || getCleanedEncryption(this.getEncryption()) == pastEncryption;
1621 }
1622
1623 private static int getCleanedEncryption(int encryption) {
1624 if (encryption == ENCRYPTION_DECRYPTED || encryption == ENCRYPTION_DECRYPTION_FAILED) {
1625 return ENCRYPTION_PGP;
1626 }
1627 if (encryption == ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE || encryption == ENCRYPTION_AXOLOTL_FAILED) {
1628 return ENCRYPTION_AXOLOTL;
1629 }
1630 return encryption;
1631 }
1632
1633 public static boolean configurePrivateMessage(final Message message) {
1634 return configurePrivateMessage(message, false);
1635 }
1636
1637 public static boolean configurePrivateFileMessage(final Message message) {
1638 return configurePrivateMessage(message, true);
1639 }
1640
1641 private static boolean configurePrivateMessage(final Message message, final boolean isFile) {
1642 final Conversation conversation;
1643 if (message.conversation instanceof Conversation) {
1644 conversation = (Conversation) message.conversation;
1645 } else {
1646 return false;
1647 }
1648 if (conversation.getMode() == Conversation.MODE_MULTI) {
1649 final Jid nextCounterpart = conversation.getNextCounterpart();
1650 return configurePrivateMessage(conversation, message, nextCounterpart, isFile);
1651 }
1652 return false;
1653 }
1654
1655 public static boolean configurePrivateMessage(final Message message, final Jid counterpart) {
1656 final Conversation conversation;
1657 if (message.conversation instanceof Conversation) {
1658 conversation = (Conversation) message.conversation;
1659 } else {
1660 return false;
1661 }
1662 return configurePrivateMessage(conversation, message, counterpart, false);
1663 }
1664
1665 private static boolean configurePrivateMessage(final Conversation conversation, final Message message, final Jid counterpart, final boolean isFile) {
1666 if (counterpart == null) {
1667 return false;
1668 }
1669 message.setCounterpart(counterpart);
1670 message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(counterpart));
1671 message.setType(isFile ? Message.TYPE_PRIVATE_FILE : Message.TYPE_PRIVATE);
1672 return true;
1673 }
1674}