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