Conversation.java

   1package eu.siacs.conversations.entities;
   2
   3import android.content.ContentValues;
   4import android.database.Cursor;
   5import android.support.annotation.NonNull;
   6import android.support.annotation.Nullable;
   7import android.text.TextUtils;
   8
   9import org.json.JSONArray;
  10import org.json.JSONException;
  11import org.json.JSONObject;
  12
  13import java.util.ArrayList;
  14import java.util.Collections;
  15import java.util.Iterator;
  16import java.util.List;
  17import java.util.ListIterator;
  18import java.util.concurrent.atomic.AtomicBoolean;
  19
  20import eu.siacs.conversations.Config;
  21import eu.siacs.conversations.crypto.OmemoSetting;
  22import eu.siacs.conversations.crypto.PgpDecryptionService;
  23import eu.siacs.conversations.persistance.DatabaseBackend;
  24import eu.siacs.conversations.services.AvatarService;
  25import eu.siacs.conversations.services.QuickConversationsService;
  26import eu.siacs.conversations.utils.JidHelper;
  27import eu.siacs.conversations.utils.UIHelper;
  28import eu.siacs.conversations.xmpp.chatstate.ChatState;
  29import eu.siacs.conversations.xmpp.mam.MamReference;
  30import rocks.xmpp.addr.Jid;
  31
  32import static eu.siacs.conversations.entities.Bookmark.printableValue;
  33
  34
  35public class Conversation extends AbstractEntity implements Blockable, Comparable<Conversation>, Conversational, AvatarService.Avatarable {
  36    public static final String TABLENAME = "conversations";
  37
  38    public static final int STATUS_AVAILABLE = 0;
  39    public static final int STATUS_ARCHIVED = 1;
  40
  41    public static final String NAME = "name";
  42    public static final String ACCOUNT = "accountUuid";
  43    public static final String CONTACT = "contactUuid";
  44    public static final String CONTACTJID = "contactJid";
  45    public static final String STATUS = "status";
  46    public static final String CREATED = "created";
  47    public static final String MODE = "mode";
  48    public static final String ATTRIBUTES = "attributes";
  49
  50    public static final String ATTRIBUTE_MUTED_TILL = "muted_till";
  51    public static final String ATTRIBUTE_ALWAYS_NOTIFY = "always_notify";
  52    public static final String ATTRIBUTE_PUSH_NODE = "push_node";
  53    public static final String ATTRIBUTE_LAST_CLEAR_HISTORY = "last_clear_history";
  54    public static final String ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS = "formerly_private_non_anonymous";
  55    static final String ATTRIBUTE_MUC_PASSWORD = "muc_password";
  56    static final String ATTRIBUTE_MEMBERS_ONLY = "members_only";
  57    static final String ATTRIBUTE_MODERATED = "moderated";
  58    static final String ATTRIBUTE_NON_ANONYMOUS = "non_anonymous";
  59    private static final String ATTRIBUTE_NEXT_MESSAGE = "next_message";
  60    private static final String ATTRIBUTE_NEXT_MESSAGE_TIMESTAMP = "next_message_timestamp";
  61    private static final String ATTRIBUTE_CRYPTO_TARGETS = "crypto_targets";
  62    private static final String ATTRIBUTE_NEXT_ENCRYPTION = "next_encryption";
  63    private static final String ATTRIBUTE_CORRECTING_MESSAGE = "correcting_message";
  64    protected final ArrayList<Message> messages = new ArrayList<>();
  65    public AtomicBoolean messagesLoaded = new AtomicBoolean(true);
  66    protected Account account = null;
  67    private String draftMessage;
  68    private String name;
  69    private String contactUuid;
  70    private String accountUuid;
  71    private Jid contactJid;
  72    private int status;
  73    private long created;
  74    private int mode;
  75    private JSONObject attributes;
  76    private Jid nextCounterpart;
  77    private transient MucOptions mucOptions = null;
  78    private boolean messagesLeftOnServer = true;
  79    private ChatState mOutgoingChatState = Config.DEFAULT_CHAT_STATE;
  80    private ChatState mIncomingChatState = Config.DEFAULT_CHAT_STATE;
  81    private String mFirstMamReference = null;
  82
  83    public Conversation(final String name, final Account account, final Jid contactJid,
  84                        final int mode) {
  85        this(java.util.UUID.randomUUID().toString(), name, null, account
  86                        .getUuid(), contactJid, System.currentTimeMillis(),
  87                STATUS_AVAILABLE, mode, "");
  88        this.account = account;
  89    }
  90
  91    public Conversation(final String uuid, final String name, final String contactUuid,
  92                        final String accountUuid, final Jid contactJid, final long created, final int status,
  93                        final int mode, final String attributes) {
  94        this.uuid = uuid;
  95        this.name = name;
  96        this.contactUuid = contactUuid;
  97        this.accountUuid = accountUuid;
  98        this.contactJid = contactJid;
  99        this.created = created;
 100        this.status = status;
 101        this.mode = mode;
 102        try {
 103            this.attributes = new JSONObject(attributes == null ? "" : attributes);
 104        } catch (JSONException e) {
 105            this.attributes = new JSONObject();
 106        }
 107    }
 108
 109    public static Conversation fromCursor(Cursor cursor) {
 110        return new Conversation(cursor.getString(cursor.getColumnIndex(UUID)),
 111                cursor.getString(cursor.getColumnIndex(NAME)),
 112                cursor.getString(cursor.getColumnIndex(CONTACT)),
 113                cursor.getString(cursor.getColumnIndex(ACCOUNT)),
 114                JidHelper.parseOrFallbackToInvalid(cursor.getString(cursor.getColumnIndex(CONTACTJID))),
 115                cursor.getLong(cursor.getColumnIndex(CREATED)),
 116                cursor.getInt(cursor.getColumnIndex(STATUS)),
 117                cursor.getInt(cursor.getColumnIndex(MODE)),
 118                cursor.getString(cursor.getColumnIndex(ATTRIBUTES)));
 119    }
 120
 121    public static Message getLatestMarkableMessage(final List<Message> messages, boolean isPrivateAndNonAnonymousMuc) {
 122        for (int i = messages.size() - 1; i >= 0; --i) {
 123            final Message message = messages.get(i);
 124            if (message.getStatus() <= Message.STATUS_RECEIVED
 125                    && (message.markable || isPrivateAndNonAnonymousMuc)
 126                    && !message.isPrivateMessage()) {
 127                return message;
 128            }
 129        }
 130        return null;
 131    }
 132
 133    private static boolean suitableForOmemoByDefault(final Conversation conversation) {
 134        if (conversation.getJid().asBareJid().equals(Config.BUG_REPORTS)) {
 135            return false;
 136        }
 137        if (conversation.getContact().isOwnServer()) {
 138            return false;
 139        }
 140        final String contact = conversation.getJid().getDomain();
 141        final String account = conversation.getAccount().getServer();
 142        if (Config.OMEMO_EXCEPTIONS.CONTACT_DOMAINS.contains(contact) || Config.OMEMO_EXCEPTIONS.ACCOUNT_DOMAINS.contains(account)) {
 143            return false;
 144        }
 145        return conversation.isSingleOrPrivateAndNonAnonymous() || conversation.getBooleanAttribute(ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, false);
 146    }
 147
 148    public boolean hasMessagesLeftOnServer() {
 149        return messagesLeftOnServer;
 150    }
 151
 152    public void setHasMessagesLeftOnServer(boolean value) {
 153        this.messagesLeftOnServer = value;
 154    }
 155
 156    public Message getFirstUnreadMessage() {
 157        Message first = null;
 158        synchronized (this.messages) {
 159            for (int i = messages.size() - 1; i >= 0; --i) {
 160                if (messages.get(i).isRead()) {
 161                    return first;
 162                } else {
 163                    first = messages.get(i);
 164                }
 165            }
 166        }
 167        return first;
 168    }
 169
 170    public Message findUnsentMessageWithUuid(String uuid) {
 171        synchronized (this.messages) {
 172            for (final Message message : this.messages) {
 173                final int s = message.getStatus();
 174                if ((s == Message.STATUS_UNSEND || s == Message.STATUS_WAITING) && message.getUuid().equals(uuid)) {
 175                    return message;
 176                }
 177            }
 178        }
 179        return null;
 180    }
 181
 182    public void findWaitingMessages(OnMessageFound onMessageFound) {
 183        final ArrayList<Message> results = new ArrayList<>();
 184        synchronized (this.messages) {
 185            for (Message message : this.messages) {
 186                if (message.getStatus() == Message.STATUS_WAITING) {
 187                    results.add(message);
 188                }
 189            }
 190        }
 191        for (Message result : results) {
 192            onMessageFound.onMessageFound(result);
 193        }
 194    }
 195
 196    public void findUnreadMessages(OnMessageFound onMessageFound) {
 197        final ArrayList<Message> results = new ArrayList<>();
 198        synchronized (this.messages) {
 199            for (Message message : this.messages) {
 200                if (!message.isRead()) {
 201                    results.add(message);
 202                }
 203            }
 204        }
 205        for (Message result : results) {
 206            onMessageFound.onMessageFound(result);
 207        }
 208    }
 209
 210    public Message findMessageWithFileAndUuid(final String uuid) {
 211        synchronized (this.messages) {
 212            for (final Message message : this.messages) {
 213                if (message.getUuid().equals(uuid)
 214                        && message.getEncryption() != Message.ENCRYPTION_PGP
 215                        && (message.isFileOrImage() || message.treatAsDownloadable())) {
 216                    return message;
 217                }
 218            }
 219        }
 220        return null;
 221    }
 222
 223    public boolean markAsDeleted(final List<String> uuids) {
 224        boolean deleted = false;
 225        final PgpDecryptionService pgpDecryptionService = account.getPgpDecryptionService();
 226        synchronized (this.messages) {
 227            for (Message message : this.messages) {
 228                if (uuids.contains(message.getUuid())) {
 229                    message.setDeleted(true);
 230                    deleted = true;
 231                    if (message.getEncryption() == Message.ENCRYPTION_PGP && pgpDecryptionService != null) {
 232                        pgpDecryptionService.discard(message);
 233                    }
 234                }
 235            }
 236        }
 237        return deleted;
 238    }
 239
 240    public boolean markAsChanged(final List<DatabaseBackend.FilePathInfo> files) {
 241        boolean changed = false;
 242        final PgpDecryptionService pgpDecryptionService = account.getPgpDecryptionService();
 243        synchronized (this.messages) {
 244            for (Message message : this.messages) {
 245                for (final DatabaseBackend.FilePathInfo file : files)
 246                    if (file.uuid.toString().equals(message.getUuid())) {
 247                        message.setDeleted(file.deleted);
 248                        changed = true;
 249                        if (file.deleted && message.getEncryption() == Message.ENCRYPTION_PGP && pgpDecryptionService != null) {
 250                            pgpDecryptionService.discard(message);
 251                        }
 252                    }
 253            }
 254        }
 255        return changed;
 256    }
 257
 258    public void clearMessages() {
 259        synchronized (this.messages) {
 260            this.messages.clear();
 261        }
 262    }
 263
 264    public boolean setIncomingChatState(ChatState state) {
 265        if (this.mIncomingChatState == state) {
 266            return false;
 267        }
 268        this.mIncomingChatState = state;
 269        return true;
 270    }
 271
 272    public ChatState getIncomingChatState() {
 273        return this.mIncomingChatState;
 274    }
 275
 276    public boolean setOutgoingChatState(ChatState state) {
 277        if (mode == MODE_SINGLE && !getContact().isSelf() || (isPrivateAndNonAnonymous() && getNextCounterpart() == null)) {
 278            if (this.mOutgoingChatState != state) {
 279                this.mOutgoingChatState = state;
 280                return true;
 281            }
 282        }
 283        return false;
 284    }
 285
 286    public ChatState getOutgoingChatState() {
 287        return this.mOutgoingChatState;
 288    }
 289
 290    public void trim() {
 291        synchronized (this.messages) {
 292            final int size = messages.size();
 293            final int maxsize = Config.PAGE_SIZE * Config.MAX_NUM_PAGES;
 294            if (size > maxsize) {
 295                List<Message> discards = this.messages.subList(0, size - maxsize);
 296                final PgpDecryptionService pgpDecryptionService = account.getPgpDecryptionService();
 297                if (pgpDecryptionService != null) {
 298                    pgpDecryptionService.discard(discards);
 299                }
 300                discards.clear();
 301                untieMessages();
 302            }
 303        }
 304    }
 305
 306    public void findUnsentTextMessages(OnMessageFound onMessageFound) {
 307        final ArrayList<Message> results = new ArrayList<>();
 308        synchronized (this.messages) {
 309            for (Message message : this.messages) {
 310                if ((message.getType() == Message.TYPE_TEXT || message.hasFileOnRemoteHost()) && message.getStatus() == Message.STATUS_UNSEND) {
 311                    results.add(message);
 312                }
 313            }
 314        }
 315        for (Message result : results) {
 316            onMessageFound.onMessageFound(result);
 317        }
 318    }
 319
 320    public Message findSentMessageWithUuidOrRemoteId(String id) {
 321        synchronized (this.messages) {
 322            for (Message message : this.messages) {
 323                if (id.equals(message.getUuid())
 324                        || (message.getStatus() >= Message.STATUS_SEND
 325                        && id.equals(message.getRemoteMsgId()))) {
 326                    return message;
 327                }
 328            }
 329        }
 330        return null;
 331    }
 332
 333    public Message findMessageWithRemoteIdAndCounterpart(String id, Jid counterpart, boolean received, boolean carbon) {
 334        synchronized (this.messages) {
 335            for (int i = this.messages.size() - 1; i >= 0; --i) {
 336                final Message message = messages.get(i);
 337                final Jid mcp = message.getCounterpart();
 338                if (mcp == null) {
 339                    continue;
 340                }
 341                if (mcp.equals(counterpart) && ((message.getStatus() == Message.STATUS_RECEIVED) == received)
 342                        && (carbon == message.isCarbon() || received)) {
 343                    final boolean idMatch = id.equals(message.getRemoteMsgId()) || message.remoteMsgIdMatchInEdit(id);
 344                    if (idMatch && !message.isFileOrImage() && !message.treatAsDownloadable()) {
 345                        return message;
 346                    } else {
 347                        return null;
 348                    }
 349                }
 350            }
 351        }
 352        return null;
 353    }
 354
 355    public Message findSentMessageWithUuid(String id) {
 356        synchronized (this.messages) {
 357            for (Message message : this.messages) {
 358                if (id.equals(message.getUuid())) {
 359                    return message;
 360                }
 361            }
 362        }
 363        return null;
 364    }
 365
 366    public Message findMessageWithRemoteId(String id, Jid counterpart) {
 367        synchronized (this.messages) {
 368            for (Message message : this.messages) {
 369                if (counterpart.equals(message.getCounterpart())
 370                        && (id.equals(message.getRemoteMsgId()) || id.equals(message.getUuid()))) {
 371                    return message;
 372                }
 373            }
 374        }
 375        return null;
 376    }
 377
 378    public Message findMessageWithServerMsgId(String id) {
 379        synchronized (this.messages) {
 380            for (Message message : this.messages) {
 381                if (id != null && id.equals(message.getServerMsgId())) {
 382                    return message;
 383                }
 384            }
 385        }
 386        return null;
 387    }
 388
 389    public boolean hasMessageWithCounterpart(Jid counterpart) {
 390        synchronized (this.messages) {
 391            for (Message message : this.messages) {
 392                if (counterpart.equals(message.getCounterpart())) {
 393                    return true;
 394                }
 395            }
 396        }
 397        return false;
 398    }
 399
 400    public void populateWithMessages(final List<Message> messages) {
 401        synchronized (this.messages) {
 402            messages.clear();
 403            messages.addAll(this.messages);
 404        }
 405        for (Iterator<Message> iterator = messages.iterator(); iterator.hasNext(); ) {
 406            if (iterator.next().wasMergedIntoPrevious()) {
 407                iterator.remove();
 408            }
 409        }
 410    }
 411
 412    @Override
 413    public boolean isBlocked() {
 414        return getContact().isBlocked();
 415    }
 416
 417    @Override
 418    public boolean isDomainBlocked() {
 419        return getContact().isDomainBlocked();
 420    }
 421
 422    @Override
 423    public Jid getBlockedJid() {
 424        return getContact().getBlockedJid();
 425    }
 426
 427    public int countMessages() {
 428        synchronized (this.messages) {
 429            return this.messages.size();
 430        }
 431    }
 432
 433    public String getFirstMamReference() {
 434        return this.mFirstMamReference;
 435    }
 436
 437    public void setFirstMamReference(String reference) {
 438        this.mFirstMamReference = reference;
 439    }
 440
 441    public void setLastClearHistory(long time, String reference) {
 442        if (reference != null) {
 443            setAttribute(ATTRIBUTE_LAST_CLEAR_HISTORY, String.valueOf(time) + ":" + reference);
 444        } else {
 445            setAttribute(ATTRIBUTE_LAST_CLEAR_HISTORY, time);
 446        }
 447    }
 448
 449    public MamReference getLastClearHistory() {
 450        return MamReference.fromAttribute(getAttribute(ATTRIBUTE_LAST_CLEAR_HISTORY));
 451    }
 452
 453    public List<Jid> getAcceptedCryptoTargets() {
 454        if (mode == MODE_SINGLE) {
 455            return Collections.singletonList(getJid().asBareJid());
 456        } else {
 457            return getJidListAttribute(ATTRIBUTE_CRYPTO_TARGETS);
 458        }
 459    }
 460
 461    public void setAcceptedCryptoTargets(List<Jid> acceptedTargets) {
 462        setAttribute(ATTRIBUTE_CRYPTO_TARGETS, acceptedTargets);
 463    }
 464
 465    public boolean setCorrectingMessage(Message correctingMessage) {
 466        setAttribute(ATTRIBUTE_CORRECTING_MESSAGE, correctingMessage == null ? null : correctingMessage.getUuid());
 467        return correctingMessage == null && draftMessage != null;
 468    }
 469
 470    public Message getCorrectingMessage() {
 471        final String uuid = getAttribute(ATTRIBUTE_CORRECTING_MESSAGE);
 472        return uuid == null ? null : findSentMessageWithUuid(uuid);
 473    }
 474
 475    public boolean withSelf() {
 476        return getContact().isSelf();
 477    }
 478
 479    @Override
 480    public int compareTo(@NonNull Conversation another) {
 481        return Long.compare(another.getSortableTime(), getSortableTime());
 482    }
 483
 484    private long getSortableTime() {
 485        Draft draft = getDraft();
 486        long messageTime = getLatestMessage().getTimeSent();
 487        if (draft == null) {
 488            return messageTime;
 489        } else {
 490            return Math.max(messageTime, draft.getTimestamp());
 491        }
 492    }
 493
 494    public String getDraftMessage() {
 495        return draftMessage;
 496    }
 497
 498    public void setDraftMessage(String draftMessage) {
 499        this.draftMessage = draftMessage;
 500    }
 501
 502    public boolean isRead() {
 503        return (this.messages.size() == 0) || this.messages.get(this.messages.size() - 1).isRead();
 504    }
 505
 506    public List<Message> markRead(String upToUuid) {
 507        final List<Message> unread = new ArrayList<>();
 508        synchronized (this.messages) {
 509            for (Message message : this.messages) {
 510                if (!message.isRead()) {
 511                    message.markRead();
 512                    unread.add(message);
 513                }
 514                if (message.getUuid().equals(upToUuid)) {
 515                    return unread;
 516                }
 517            }
 518        }
 519        return unread;
 520    }
 521
 522    public Message getLatestMessage() {
 523        synchronized (this.messages) {
 524            if (this.messages.size() == 0) {
 525                Message message = new Message(this, "", Message.ENCRYPTION_NONE);
 526                message.setType(Message.TYPE_STATUS);
 527                message.setTime(Math.max(getCreated(), getLastClearHistory().getTimestamp()));
 528                return message;
 529            } else {
 530                return this.messages.get(this.messages.size() - 1);
 531            }
 532        }
 533    }
 534
 535    public @NonNull
 536    CharSequence getName() {
 537        if (getMode() == MODE_MULTI) {
 538            final String roomName = getMucOptions().getName();
 539            final String subject = getMucOptions().getSubject();
 540            final Bookmark bookmark = getBookmark();
 541            final String bookmarkName = bookmark != null ? bookmark.getBookmarkName() : null;
 542            if (printableValue(roomName)) {
 543                return roomName;
 544            } else if (printableValue(subject)) {
 545                return subject;
 546            } else if (printableValue(bookmarkName, false)) {
 547                return bookmarkName;
 548            } else {
 549                final String generatedName = getMucOptions().createNameFromParticipants();
 550                if (printableValue(generatedName)) {
 551                    return generatedName;
 552                } else {
 553                    return contactJid.getLocal() != null ? contactJid.getLocal() : contactJid;
 554                }
 555            }
 556        } else if ((QuickConversationsService.isConversations() || !Config.QUICKSY_DOMAIN.equals(contactJid.getDomain())) && isWithStranger()) {
 557            return contactJid;
 558        } else {
 559            return this.getContact().getDisplayName();
 560        }
 561    }
 562
 563    public String getAccountUuid() {
 564        return this.accountUuid;
 565    }
 566
 567    public Account getAccount() {
 568        return this.account;
 569    }
 570
 571    public void setAccount(final Account account) {
 572        this.account = account;
 573    }
 574
 575    public Contact getContact() {
 576        return this.account.getRoster().getContact(this.contactJid);
 577    }
 578
 579    @Override
 580    public Jid getJid() {
 581        return this.contactJid;
 582    }
 583
 584    public int getStatus() {
 585        return this.status;
 586    }
 587
 588    public void setStatus(int status) {
 589        this.status = status;
 590    }
 591
 592    public long getCreated() {
 593        return this.created;
 594    }
 595
 596    public ContentValues getContentValues() {
 597        ContentValues values = new ContentValues();
 598        values.put(UUID, uuid);
 599        values.put(NAME, name);
 600        values.put(CONTACT, contactUuid);
 601        values.put(ACCOUNT, accountUuid);
 602        values.put(CONTACTJID, contactJid.toString());
 603        values.put(CREATED, created);
 604        values.put(STATUS, status);
 605        values.put(MODE, mode);
 606        synchronized (this.attributes) {
 607            values.put(ATTRIBUTES, attributes.toString());
 608        }
 609        return values;
 610    }
 611
 612    public int getMode() {
 613        return this.mode;
 614    }
 615
 616    public void setMode(int mode) {
 617        this.mode = mode;
 618    }
 619
 620    /**
 621     * short for is Private and Non-anonymous
 622     */
 623    public boolean isSingleOrPrivateAndNonAnonymous() {
 624        return mode == MODE_SINGLE || isPrivateAndNonAnonymous();
 625    }
 626
 627    public boolean isPrivateAndNonAnonymous() {
 628        return getMucOptions().isPrivateAndNonAnonymous();
 629    }
 630
 631    public synchronized MucOptions getMucOptions() {
 632        if (this.mucOptions == null) {
 633            this.mucOptions = new MucOptions(this);
 634        }
 635        return this.mucOptions;
 636    }
 637
 638    public void resetMucOptions() {
 639        this.mucOptions = null;
 640    }
 641
 642    public void setContactJid(final Jid jid) {
 643        this.contactJid = jid;
 644    }
 645
 646    public Jid getNextCounterpart() {
 647        return this.nextCounterpart;
 648    }
 649
 650    public void setNextCounterpart(Jid jid) {
 651        this.nextCounterpart = jid;
 652    }
 653
 654    public int getNextEncryption() {
 655        if (!Config.supportOmemo() && !Config.supportOpenPgp()) {
 656            return Message.ENCRYPTION_NONE;
 657        }
 658        if (OmemoSetting.isAlways()) {
 659            return suitableForOmemoByDefault(this) ? Message.ENCRYPTION_AXOLOTL : Message.ENCRYPTION_NONE;
 660        }
 661        final int defaultEncryption;
 662        if (suitableForOmemoByDefault(this)) {
 663            defaultEncryption = OmemoSetting.getEncryption();
 664        } else {
 665            defaultEncryption = Message.ENCRYPTION_NONE;
 666        }
 667        int encryption = this.getIntAttribute(ATTRIBUTE_NEXT_ENCRYPTION, defaultEncryption);
 668        if (encryption == Message.ENCRYPTION_OTR || encryption < 0) {
 669            return defaultEncryption;
 670        } else {
 671            return encryption;
 672        }
 673    }
 674
 675    public boolean setNextEncryption(int encryption) {
 676        return this.setAttribute(ATTRIBUTE_NEXT_ENCRYPTION, encryption);
 677    }
 678
 679    public String getNextMessage() {
 680        final String nextMessage = getAttribute(ATTRIBUTE_NEXT_MESSAGE);
 681        return nextMessage == null ? "" : nextMessage;
 682    }
 683
 684    public @Nullable
 685    Draft getDraft() {
 686        long timestamp = getLongAttribute(ATTRIBUTE_NEXT_MESSAGE_TIMESTAMP, 0);
 687        if (timestamp > getLatestMessage().getTimeSent()) {
 688            String message = getAttribute(ATTRIBUTE_NEXT_MESSAGE);
 689            if (!TextUtils.isEmpty(message) && timestamp != 0) {
 690                return new Draft(message, timestamp);
 691            }
 692        }
 693        return null;
 694    }
 695
 696    public boolean setNextMessage(final String input) {
 697        final String message = input == null || input.trim().isEmpty() ? null : input;
 698        boolean changed = !getNextMessage().equals(message);
 699        this.setAttribute(ATTRIBUTE_NEXT_MESSAGE, message);
 700        if (changed) {
 701            this.setAttribute(ATTRIBUTE_NEXT_MESSAGE_TIMESTAMP, message == null ? 0 : System.currentTimeMillis());
 702        }
 703        return changed;
 704    }
 705
 706    public Bookmark getBookmark() {
 707        return this.account.getBookmark(this.contactJid);
 708    }
 709
 710    public Message findDuplicateMessage(Message message) {
 711        synchronized (this.messages) {
 712            for (int i = this.messages.size() - 1; i >= 0; --i) {
 713                if (this.messages.get(i).similar(message)) {
 714                    return this.messages.get(i);
 715                }
 716            }
 717        }
 718        return null;
 719    }
 720
 721    public boolean hasDuplicateMessage(Message message) {
 722        return findDuplicateMessage(message) != null;
 723    }
 724
 725    public Message findSentMessageWithBody(String body) {
 726        synchronized (this.messages) {
 727            for (int i = this.messages.size() - 1; i >= 0; --i) {
 728                Message message = this.messages.get(i);
 729                if (message.getStatus() == Message.STATUS_UNSEND || message.getStatus() == Message.STATUS_SEND) {
 730                    String otherBody;
 731                    if (message.hasFileOnRemoteHost()) {
 732                        otherBody = message.getFileParams().url.toString();
 733                    } else {
 734                        otherBody = message.body;
 735                    }
 736                    if (otherBody != null && otherBody.equals(body)) {
 737                        return message;
 738                    }
 739                }
 740            }
 741            return null;
 742        }
 743    }
 744
 745    public Message findRtpSession(final String sessionId, final int s) {
 746        synchronized (this.messages) {
 747            for (int i = this.messages.size() - 1; i >= 0; --i) {
 748                final Message message = this.messages.get(i);
 749                if ((message.getStatus() == s) && (message.getType() == Message.TYPE_RTP_SESSION) && sessionId.equals(message.getRemoteMsgId())) {
 750                    return message;
 751                }
 752            }
 753        }
 754        return null;
 755    }
 756
 757    public boolean possibleDuplicate(final String serverMsgId, final String remoteMsgId) {
 758        if (serverMsgId == null || remoteMsgId == null) {
 759            return false;
 760        }
 761        synchronized (this.messages) {
 762            for (Message message : this.messages) {
 763                if (serverMsgId.equals(message.getServerMsgId()) || remoteMsgId.equals(message.getRemoteMsgId())) {
 764                    return true;
 765                }
 766            }
 767        }
 768        return false;
 769    }
 770
 771    public MamReference getLastMessageTransmitted() {
 772        final MamReference lastClear = getLastClearHistory();
 773        MamReference lastReceived = new MamReference(0);
 774        synchronized (this.messages) {
 775            for (int i = this.messages.size() - 1; i >= 0; --i) {
 776                final Message message = this.messages.get(i);
 777                if (message.isPrivateMessage()) {
 778                    continue; //it's unsafe to use private messages as anchor. They could be coming from user archive
 779                }
 780                if (message.getStatus() == Message.STATUS_RECEIVED || message.isCarbon() || message.getServerMsgId() != null) {
 781                    lastReceived = new MamReference(message.getTimeSent(), message.getServerMsgId());
 782                    break;
 783                }
 784            }
 785        }
 786        return MamReference.max(lastClear, lastReceived);
 787    }
 788
 789    public void setMutedTill(long value) {
 790        this.setAttribute(ATTRIBUTE_MUTED_TILL, String.valueOf(value));
 791    }
 792
 793    public boolean isMuted() {
 794        return System.currentTimeMillis() < this.getLongAttribute(ATTRIBUTE_MUTED_TILL, 0);
 795    }
 796
 797    public boolean alwaysNotify() {
 798        return mode == MODE_SINGLE || getBooleanAttribute(ATTRIBUTE_ALWAYS_NOTIFY, Config.ALWAYS_NOTIFY_BY_DEFAULT || isPrivateAndNonAnonymous());
 799    }
 800
 801    public boolean setAttribute(String key, boolean value) {
 802        return setAttribute(key, String.valueOf(value));
 803    }
 804
 805    private boolean setAttribute(String key, long value) {
 806        return setAttribute(key, Long.toString(value));
 807    }
 808
 809    private boolean setAttribute(String key, int value) {
 810        return setAttribute(key, String.valueOf(value));
 811    }
 812
 813    public boolean setAttribute(String key, String value) {
 814        synchronized (this.attributes) {
 815            try {
 816                if (value == null) {
 817                    if (this.attributes.has(key)) {
 818                        this.attributes.remove(key);
 819                        return true;
 820                    } else {
 821                        return false;
 822                    }
 823                } else {
 824                    final String prev = this.attributes.optString(key, null);
 825                    this.attributes.put(key, value);
 826                    return !value.equals(prev);
 827                }
 828            } catch (JSONException e) {
 829                throw new AssertionError(e);
 830            }
 831        }
 832    }
 833
 834    public boolean setAttribute(String key, List<Jid> jids) {
 835        JSONArray array = new JSONArray();
 836        for (Jid jid : jids) {
 837            array.put(jid.asBareJid().toString());
 838        }
 839        synchronized (this.attributes) {
 840            try {
 841                this.attributes.put(key, array);
 842                return true;
 843            } catch (JSONException e) {
 844                return false;
 845            }
 846        }
 847    }
 848
 849    public String getAttribute(String key) {
 850        synchronized (this.attributes) {
 851            return this.attributes.optString(key, null);
 852        }
 853    }
 854
 855    private List<Jid> getJidListAttribute(String key) {
 856        ArrayList<Jid> list = new ArrayList<>();
 857        synchronized (this.attributes) {
 858            try {
 859                JSONArray array = this.attributes.getJSONArray(key);
 860                for (int i = 0; i < array.length(); ++i) {
 861                    try {
 862                        list.add(Jid.of(array.getString(i)));
 863                    } catch (IllegalArgumentException e) {
 864                        //ignored
 865                    }
 866                }
 867            } catch (JSONException e) {
 868                //ignored
 869            }
 870        }
 871        return list;
 872    }
 873
 874    private int getIntAttribute(String key, int defaultValue) {
 875        String value = this.getAttribute(key);
 876        if (value == null) {
 877            return defaultValue;
 878        } else {
 879            try {
 880                return Integer.parseInt(value);
 881            } catch (NumberFormatException e) {
 882                return defaultValue;
 883            }
 884        }
 885    }
 886
 887    public long getLongAttribute(String key, long defaultValue) {
 888        String value = this.getAttribute(key);
 889        if (value == null) {
 890            return defaultValue;
 891        } else {
 892            try {
 893                return Long.parseLong(value);
 894            } catch (NumberFormatException e) {
 895                return defaultValue;
 896            }
 897        }
 898    }
 899
 900    public boolean getBooleanAttribute(String key, boolean defaultValue) {
 901        String value = this.getAttribute(key);
 902        if (value == null) {
 903            return defaultValue;
 904        } else {
 905            return Boolean.parseBoolean(value);
 906        }
 907    }
 908
 909    public void add(Message message) {
 910        synchronized (this.messages) {
 911            this.messages.add(message);
 912        }
 913    }
 914
 915    public void prepend(int offset, Message message) {
 916        synchronized (this.messages) {
 917            this.messages.add(Math.min(offset, this.messages.size()), message);
 918        }
 919    }
 920
 921    public void addAll(int index, List<Message> messages) {
 922        synchronized (this.messages) {
 923            this.messages.addAll(index, messages);
 924        }
 925        account.getPgpDecryptionService().decrypt(messages);
 926    }
 927
 928    public void expireOldMessages(long timestamp) {
 929        synchronized (this.messages) {
 930            for (ListIterator<Message> iterator = this.messages.listIterator(); iterator.hasNext(); ) {
 931                if (iterator.next().getTimeSent() < timestamp) {
 932                    iterator.remove();
 933                }
 934            }
 935            untieMessages();
 936        }
 937    }
 938
 939    public void sort() {
 940        synchronized (this.messages) {
 941            Collections.sort(this.messages, (left, right) -> {
 942                if (left.getTimeSent() < right.getTimeSent()) {
 943                    return -1;
 944                } else if (left.getTimeSent() > right.getTimeSent()) {
 945                    return 1;
 946                } else {
 947                    return 0;
 948                }
 949            });
 950            untieMessages();
 951        }
 952    }
 953
 954    private void untieMessages() {
 955        for (Message message : this.messages) {
 956            message.untie();
 957        }
 958    }
 959
 960    public int unreadCount() {
 961        synchronized (this.messages) {
 962            int count = 0;
 963            for (int i = this.messages.size() - 1; i >= 0; --i) {
 964                if (this.messages.get(i).isRead()) {
 965                    return count;
 966                }
 967                ++count;
 968            }
 969            return count;
 970        }
 971    }
 972
 973    public int receivedMessagesCount() {
 974        int count = 0;
 975        synchronized (this.messages) {
 976            for (Message message : messages) {
 977                if (message.getStatus() == Message.STATUS_RECEIVED) {
 978                    ++count;
 979                }
 980            }
 981        }
 982        return count;
 983    }
 984
 985    public int sentMessagesCount() {
 986        int count = 0;
 987        synchronized (this.messages) {
 988            for (Message message : messages) {
 989                if (message.getStatus() != Message.STATUS_RECEIVED) {
 990                    ++count;
 991                }
 992            }
 993        }
 994        return count;
 995    }
 996
 997    public boolean isWithStranger() {
 998        final Contact contact = getContact();
 999        return mode == MODE_SINGLE
1000                && !contact.isOwnServer()
1001                && !contact.showInContactList()
1002                && !contact.isSelf()
1003                && !Config.QUICKSY_DOMAIN.equals(contact.getJid().toEscapedString())
1004                && sentMessagesCount() == 0;
1005    }
1006
1007    public int getReceivedMessagesCountSinceUuid(String uuid) {
1008        if (uuid == null) {
1009            return 0;
1010        }
1011        int count = 0;
1012        synchronized (this.messages) {
1013            for (int i = messages.size() - 1; i >= 0; i--) {
1014                final Message message = messages.get(i);
1015                if (uuid.equals(message.getUuid())) {
1016                    return count;
1017                }
1018                if (message.getStatus() <= Message.STATUS_RECEIVED) {
1019                    ++count;
1020                }
1021            }
1022        }
1023        return 0;
1024    }
1025
1026    @Override
1027    public int getAvatarBackgroundColor() {
1028        return UIHelper.getColorForName(getName().toString());
1029    }
1030
1031    public interface OnMessageFound {
1032        void onMessageFound(final Message message);
1033    }
1034
1035    public static class Draft {
1036        private final String message;
1037        private final long timestamp;
1038
1039        private Draft(String message, long timestamp) {
1040            this.message = message;
1041            this.timestamp = timestamp;
1042        }
1043
1044        public long getTimestamp() {
1045            return timestamp;
1046        }
1047
1048        public String getMessage() {
1049            return message;
1050        }
1051    }
1052}