Message.java

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