Conversation.java

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