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