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	static final String ATTRIBUTE_MEMBERS_ONLY = "members_only";
  64	static final String ATTRIBUTE_MODERATED = "moderated";
  65	static final String ATTRIBUTE_NON_ANONYMOUS = "non_anonymous";
  66	public static final String ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS = "formerly_private_non_anonymous";
  67	protected final ArrayList<Message> messages = new ArrayList<>();
  68	public AtomicBoolean messagesLoaded = new AtomicBoolean(true);
  69	protected Account account = null;
  70	private String draftMessage;
  71	private String name;
  72	private String contactUuid;
  73	private String accountUuid;
  74	private Jid contactJid;
  75	private int status;
  76	private long created;
  77	private int mode;
  78	private JSONObject attributes;
  79	private Jid nextCounterpart;
  80	private transient MucOptions mucOptions = null;
  81	private boolean messagesLeftOnServer = true;
  82	private ChatState mOutgoingChatState = Config.DEFAULT_CHATSTATE;
  83	private ChatState mIncomingChatState = Config.DEFAULT_CHATSTATE;
  84	private String mFirstMamReference = null;
  85	private Message correctingMessage;
  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	//TODO store uuid in attribute
 428	public boolean setCorrectingMessage(Message correctingMessage) {
 429		this.correctingMessage = correctingMessage;
 430		return correctingMessage == null && draftMessage != null;
 431	}
 432
 433	//TODO: dynamically find by uuid
 434	public Message getCorrectingMessage() {
 435		return this.correctingMessage;
 436	}
 437
 438	public boolean withSelf() {
 439		return getContact().isSelf();
 440	}
 441
 442	@Override
 443	public int compareTo(@NonNull Conversation another) {
 444		return Long.compare(another.getSortableTime(), getSortableTime());
 445	}
 446
 447	private long getSortableTime() {
 448		Draft draft = getDraft();
 449		long messageTime = getLatestMessage().getTimeSent();
 450		if (draft == null) {
 451			return messageTime;
 452		} else {
 453			return Math.max(messageTime, draft.getTimestamp());
 454		}
 455	}
 456
 457	public String getDraftMessage() {
 458		return draftMessage;
 459	}
 460
 461	public void setDraftMessage(String draftMessage) {
 462		this.draftMessage = draftMessage;
 463	}
 464
 465	public boolean isRead() {
 466		return (this.messages.size() == 0) || this.messages.get(this.messages.size() - 1).isRead();
 467	}
 468
 469	public List<Message> markRead(String upToUuid) {
 470		final List<Message> unread = new ArrayList<>();
 471		synchronized (this.messages) {
 472			for (Message message : this.messages) {
 473				if (!message.isRead()) {
 474					message.markRead();
 475					unread.add(message);
 476				}
 477				if (message.getUuid().equals(upToUuid)) {
 478					return unread;
 479				}
 480			}
 481		}
 482		return unread;
 483	}
 484
 485	public static Message getLatestMarkableMessage(final List<Message> messages, boolean isPrivateAndNonAnonymousMuc) {
 486			for (int i = messages.size() - 1; i >= 0; --i) {
 487				final Message message = messages.get(i);
 488				if (message.getStatus() <= Message.STATUS_RECEIVED
 489						&& (message.markable || isPrivateAndNonAnonymousMuc)
 490						&& message.getType() != Message.TYPE_PRIVATE) {
 491					return message;
 492				}
 493			}
 494		return null;
 495	}
 496
 497	public Message getLatestMessage() {
 498		synchronized (this.messages) {
 499			if (this.messages.size() == 0) {
 500				Message message = new Message(this, "", Message.ENCRYPTION_NONE);
 501				message.setType(Message.TYPE_STATUS);
 502				message.setTime(Math.max(getCreated(), getLastClearHistory().getTimestamp()));
 503				return message;
 504			} else {
 505				return this.messages.get(this.messages.size() - 1);
 506			}
 507		}
 508	}
 509
 510	public @NonNull CharSequence getName() {
 511		if (getMode() == MODE_MULTI) {
 512			final String roomName = getMucOptions().getName();
 513			final String subject = getMucOptions().getSubject();
 514			final Bookmark bookmark = getBookmark();
 515			final String bookmarkName = bookmark != null ? bookmark.getBookmarkName() : null;
 516			if (printableValue(roomName)) {
 517				return roomName;
 518			} else if (printableValue(subject)) {
 519				return subject;
 520			} else if (printableValue(bookmarkName, false)) {
 521				return bookmarkName;
 522			} else {
 523				final String generatedName = getMucOptions().createNameFromParticipants();
 524				if (printableValue(generatedName)) {
 525					return generatedName;
 526				} else {
 527					return contactJid.getLocal() != null ? contactJid.getLocal() : contactJid;
 528				}
 529			}
 530		} else if ((QuickConversationsService.isConversations() || !Config.QUICKSY_DOMAIN.equals(contactJid.getDomain())) && isWithStranger()) {
 531			return contactJid;
 532		} else {
 533			return this.getContact().getDisplayName();
 534		}
 535	}
 536
 537	public String getAccountUuid() {
 538		return this.accountUuid;
 539	}
 540
 541	public Account getAccount() {
 542		return this.account;
 543	}
 544
 545	public void setAccount(final Account account) {
 546		this.account = account;
 547	}
 548
 549	public Contact getContact() {
 550		return this.account.getRoster().getContact(this.contactJid);
 551	}
 552
 553	@Override
 554	public Jid getJid() {
 555		return this.contactJid;
 556	}
 557
 558	public int getStatus() {
 559		return this.status;
 560	}
 561
 562	public void setStatus(int status) {
 563		this.status = status;
 564	}
 565
 566	public long getCreated() {
 567		return this.created;
 568	}
 569
 570	public ContentValues getContentValues() {
 571		ContentValues values = new ContentValues();
 572		values.put(UUID, uuid);
 573		values.put(NAME, name);
 574		values.put(CONTACT, contactUuid);
 575		values.put(ACCOUNT, accountUuid);
 576		values.put(CONTACTJID, contactJid.toString());
 577		values.put(CREATED, created);
 578		values.put(STATUS, status);
 579		values.put(MODE, mode);
 580		values.put(ATTRIBUTES, attributes.toString());
 581		return values;
 582	}
 583
 584	public int getMode() {
 585		return this.mode;
 586	}
 587
 588	public void setMode(int mode) {
 589		this.mode = mode;
 590	}
 591
 592	/**
 593	 * short for is Private and Non-anonymous
 594	 */
 595	public boolean isSingleOrPrivateAndNonAnonymous() {
 596		return mode == MODE_SINGLE || isPrivateAndNonAnonymous();
 597	}
 598
 599	public boolean isPrivateAndNonAnonymous() {
 600		return getMucOptions().isPrivateAndNonAnonymous();
 601	}
 602
 603	public synchronized MucOptions getMucOptions() {
 604		if (this.mucOptions == null) {
 605			this.mucOptions = new MucOptions(this);
 606		}
 607		return this.mucOptions;
 608	}
 609
 610	public void resetMucOptions() {
 611		this.mucOptions = null;
 612	}
 613
 614	public void setContactJid(final Jid jid) {
 615		this.contactJid = jid;
 616	}
 617
 618	public Jid getNextCounterpart() {
 619		return this.nextCounterpart;
 620	}
 621
 622	public void setNextCounterpart(Jid jid) {
 623		this.nextCounterpart = jid;
 624	}
 625
 626	public int getNextEncryption() {
 627		if (!Config.supportOmemo() && !Config.supportOpenPgp()) {
 628			return Message.ENCRYPTION_NONE;
 629		}
 630		if (OmemoSetting.isAlways()) {
 631			return suitableForOmemoByDefault(this) ? Message.ENCRYPTION_AXOLOTL : Message.ENCRYPTION_NONE;
 632		}
 633		final int defaultEncryption;
 634		if (suitableForOmemoByDefault(this)) {
 635			defaultEncryption = OmemoSetting.getEncryption();
 636		} else {
 637			defaultEncryption = Message.ENCRYPTION_NONE;
 638		}
 639		int encryption = this.getIntAttribute(ATTRIBUTE_NEXT_ENCRYPTION, defaultEncryption);
 640		if (encryption == Message.ENCRYPTION_OTR || encryption < 0) {
 641			return defaultEncryption;
 642		} else {
 643			return encryption;
 644		}
 645	}
 646
 647	private static boolean suitableForOmemoByDefault(final Conversation conversation) {
 648		if (conversation.getJid().asBareJid().equals(Config.BUG_REPORTS)) {
 649			return false;
 650		}
 651		if (conversation.getContact().isOwnServer()) {
 652			return false;
 653		}
 654		final String contact = conversation.getJid().getDomain();
 655		final String account = conversation.getAccount().getServer();
 656		if (Config.OMEMO_EXCEPTIONS.CONTACT_DOMAINS.contains(contact) || Config.OMEMO_EXCEPTIONS.ACCOUNT_DOMAINS.contains(account)) {
 657			return false;
 658		}
 659		return conversation.isSingleOrPrivateAndNonAnonymous() || conversation.getBooleanAttribute(ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, false);
 660	}
 661
 662	public boolean setNextEncryption(int encryption) {
 663		return this.setAttribute(ATTRIBUTE_NEXT_ENCRYPTION, encryption);
 664	}
 665
 666	public String getNextMessage() {
 667		final String nextMessage = getAttribute(ATTRIBUTE_NEXT_MESSAGE);
 668		return nextMessage == null ? "" : nextMessage;
 669	}
 670
 671	public @Nullable
 672	Draft getDraft() {
 673		long timestamp = getLongAttribute(ATTRIBUTE_NEXT_MESSAGE_TIMESTAMP, 0);
 674		if (timestamp > getLatestMessage().getTimeSent()) {
 675			String message = getAttribute(ATTRIBUTE_NEXT_MESSAGE);
 676			if (!TextUtils.isEmpty(message) && timestamp != 0) {
 677				return new Draft(message, timestamp);
 678			}
 679		}
 680		return null;
 681	}
 682
 683	public boolean setNextMessage(final String input) {
 684		final String message = input == null || input.trim().isEmpty() ? null : input;
 685		boolean changed = !getNextMessage().equals(message);
 686		this.setAttribute(ATTRIBUTE_NEXT_MESSAGE, message);
 687		if (changed) {
 688			this.setAttribute(ATTRIBUTE_NEXT_MESSAGE_TIMESTAMP, message == null ? 0 : System.currentTimeMillis());
 689		}
 690		return changed;
 691	}
 692
 693	public Bookmark getBookmark() {
 694		return this.account.getBookmark(this.contactJid);
 695	}
 696
 697	public Message findDuplicateMessage(Message message) {
 698		synchronized (this.messages) {
 699			for (int i = this.messages.size() - 1; i >= 0; --i) {
 700				if (this.messages.get(i).similar(message)) {
 701					return this.messages.get(i);
 702				}
 703			}
 704		}
 705		return null;
 706	}
 707
 708	public boolean hasDuplicateMessage(Message message) {
 709		return findDuplicateMessage(message) != null;
 710	}
 711
 712	public Message findSentMessageWithBody(String body) {
 713		synchronized (this.messages) {
 714			for (int i = this.messages.size() - 1; i >= 0; --i) {
 715				Message message = this.messages.get(i);
 716				if (message.getStatus() == Message.STATUS_UNSEND || message.getStatus() == Message.STATUS_SEND) {
 717					String otherBody;
 718					if (message.hasFileOnRemoteHost()) {
 719						otherBody = message.getFileParams().url.toString();
 720					} else {
 721						otherBody = message.body;
 722					}
 723					if (otherBody != null && otherBody.equals(body)) {
 724						return message;
 725					}
 726				}
 727			}
 728			return null;
 729		}
 730	}
 731
 732	public boolean possibleDuplicate(final String serverMsgId, final String remoteMsgId) {
 733		if (serverMsgId == null || remoteMsgId == null) {
 734			return false;
 735		}
 736		synchronized (this.messages) {
 737			for(Message message : this.messages) {
 738				if (serverMsgId.equals(message.getServerMsgId()) || remoteMsgId.equals(message.getRemoteMsgId())) {
 739					return true;
 740				}
 741			}
 742		}
 743		return false;
 744	}
 745
 746	public MamReference getLastMessageTransmitted() {
 747		final MamReference lastClear = getLastClearHistory();
 748		MamReference lastReceived = new MamReference(0);
 749		synchronized (this.messages) {
 750			for (int i = this.messages.size() - 1; i >= 0; --i) {
 751				final Message message = this.messages.get(i);
 752				if (message.getType() == Message.TYPE_PRIVATE) {
 753					continue; //it's unsafe to use private messages as anchor. They could be coming from user archive
 754				}
 755				if (message.getStatus() == Message.STATUS_RECEIVED || message.isCarbon() || message.getServerMsgId() != null) {
 756					lastReceived = new MamReference(message.getTimeSent(), message.getServerMsgId());
 757					break;
 758				}
 759			}
 760		}
 761		return MamReference.max(lastClear, lastReceived);
 762	}
 763
 764	public void setMutedTill(long value) {
 765		this.setAttribute(ATTRIBUTE_MUTED_TILL, String.valueOf(value));
 766	}
 767
 768	public boolean isMuted() {
 769		return System.currentTimeMillis() < this.getLongAttribute(ATTRIBUTE_MUTED_TILL, 0);
 770	}
 771
 772	public boolean alwaysNotify() {
 773		return mode == MODE_SINGLE || getBooleanAttribute(ATTRIBUTE_ALWAYS_NOTIFY, Config.ALWAYS_NOTIFY_BY_DEFAULT || isPrivateAndNonAnonymous());
 774	}
 775
 776	public boolean setAttribute(String key, boolean value) {
 777		return setAttribute(key, String.valueOf(value));
 778	}
 779
 780	private boolean setAttribute(String key, long value) {
 781		return setAttribute(key, Long.toString(value));
 782	}
 783
 784	private boolean setAttribute(String key, int value) {
 785		return setAttribute(key, String.valueOf(value));
 786	}
 787
 788	public boolean setAttribute(String key, String value) {
 789		synchronized (this.attributes) {
 790			try {
 791				if (value == null) {
 792					if (this.attributes.has(key)) {
 793						this.attributes.remove(key);
 794						return true;
 795					} else {
 796						return false;
 797					}
 798				} else {
 799					final String prev = this.attributes.optString(key, null);
 800					this.attributes.put(key, value);
 801					return !value.equals(prev);
 802				}
 803			} catch (JSONException e) {
 804				throw new AssertionError(e);
 805			}
 806		}
 807	}
 808
 809	public boolean setAttribute(String key, List<Jid> jids) {
 810		JSONArray array = new JSONArray();
 811		for (Jid jid : jids) {
 812			array.put(jid.asBareJid().toString());
 813		}
 814		synchronized (this.attributes) {
 815			try {
 816				this.attributes.put(key, array);
 817				return true;
 818			} catch (JSONException e) {
 819				return false;
 820			}
 821		}
 822	}
 823
 824	public String getAttribute(String key) {
 825		synchronized (this.attributes) {
 826		    return this.attributes.optString(key, null);
 827		}
 828	}
 829
 830	private List<Jid> getJidListAttribute(String key) {
 831		ArrayList<Jid> list = new ArrayList<>();
 832		synchronized (this.attributes) {
 833			try {
 834				JSONArray array = this.attributes.getJSONArray(key);
 835				for (int i = 0; i < array.length(); ++i) {
 836					try {
 837						list.add(Jid.of(array.getString(i)));
 838					} catch (IllegalArgumentException e) {
 839						//ignored
 840					}
 841				}
 842			} catch (JSONException e) {
 843				//ignored
 844			}
 845		}
 846		return list;
 847	}
 848
 849	private int getIntAttribute(String key, int defaultValue) {
 850		String value = this.getAttribute(key);
 851		if (value == null) {
 852			return defaultValue;
 853		} else {
 854			try {
 855				return Integer.parseInt(value);
 856			} catch (NumberFormatException e) {
 857				return defaultValue;
 858			}
 859		}
 860	}
 861
 862	public long getLongAttribute(String key, long defaultValue) {
 863		String value = this.getAttribute(key);
 864		if (value == null) {
 865			return defaultValue;
 866		} else {
 867			try {
 868				return Long.parseLong(value);
 869			} catch (NumberFormatException e) {
 870				return defaultValue;
 871			}
 872		}
 873	}
 874
 875	public boolean getBooleanAttribute(String key, boolean defaultValue) {
 876		String value = this.getAttribute(key);
 877		if (value == null) {
 878			return defaultValue;
 879		} else {
 880			return Boolean.parseBoolean(value);
 881		}
 882	}
 883
 884	public void add(Message message) {
 885		synchronized (this.messages) {
 886			this.messages.add(message);
 887		}
 888	}
 889
 890	public void prepend(int offset, Message message) {
 891		synchronized (this.messages) {
 892			this.messages.add(Math.min(offset, this.messages.size()), message);
 893		}
 894	}
 895
 896	public void addAll(int index, List<Message> messages) {
 897		synchronized (this.messages) {
 898			this.messages.addAll(index, messages);
 899		}
 900		account.getPgpDecryptionService().decrypt(messages);
 901	}
 902
 903	public void expireOldMessages(long timestamp) {
 904		synchronized (this.messages) {
 905			for (ListIterator<Message> iterator = this.messages.listIterator(); iterator.hasNext(); ) {
 906				if (iterator.next().getTimeSent() < timestamp) {
 907					iterator.remove();
 908				}
 909			}
 910			untieMessages();
 911		}
 912	}
 913
 914	public void sort() {
 915		synchronized (this.messages) {
 916			Collections.sort(this.messages, (left, right) -> {
 917				if (left.getTimeSent() < right.getTimeSent()) {
 918					return -1;
 919				} else if (left.getTimeSent() > right.getTimeSent()) {
 920					return 1;
 921				} else {
 922					return 0;
 923				}
 924			});
 925			untieMessages();
 926		}
 927	}
 928
 929	private void untieMessages() {
 930		for (Message message : this.messages) {
 931			message.untie();
 932		}
 933	}
 934
 935	public int unreadCount() {
 936		synchronized (this.messages) {
 937			int count = 0;
 938			for (int i = this.messages.size() - 1; i >= 0; --i) {
 939				if (this.messages.get(i).isRead()) {
 940					return count;
 941				}
 942				++count;
 943			}
 944			return count;
 945		}
 946	}
 947
 948	public int receivedMessagesCount() {
 949		int count = 0;
 950		synchronized (this.messages) {
 951			for (Message message : messages) {
 952				if (message.getStatus() == Message.STATUS_RECEIVED) {
 953					++count;
 954				}
 955			}
 956		}
 957		return count;
 958	}
 959
 960	public int sentMessagesCount() {
 961		int count = 0;
 962		synchronized (this.messages) {
 963			for (Message message : messages) {
 964				if (message.getStatus() != Message.STATUS_RECEIVED) {
 965					++count;
 966				}
 967			}
 968		}
 969		return count;
 970	}
 971
 972	public boolean isWithStranger() {
 973		final Contact contact = getContact();
 974		return mode == MODE_SINGLE
 975				&& !contact.isOwnServer()
 976				&& !contact.showInContactList()
 977				&& !contact.isSelf()
 978				&& !Config.QUICKSY_DOMAIN.equals(contact.getJid().toEscapedString())
 979				&& sentMessagesCount() == 0;
 980	}
 981
 982	public int getReceivedMessagesCountSinceUuid(String uuid) {
 983		if (uuid == null) {
 984			return  0;
 985		}
 986		int count = 0;
 987		synchronized (this.messages) {
 988			for (int i = messages.size() - 1; i >= 0; i--) {
 989				final Message message = messages.get(i);
 990				if (uuid.equals(message.getUuid())) {
 991					return count;
 992				}
 993				if (message.getStatus() <= Message.STATUS_RECEIVED) {
 994					++count;
 995				}
 996			}
 997		}
 998		return 0;
 999	}
1000
1001	@Override
1002	public int getAvatarBackgroundColor() {
1003		return UIHelper.getColorForName(getName().toString());
1004	}
1005
1006	public interface OnMessageFound {
1007		void onMessageFound(final Message message);
1008	}
1009
1010	public static class Draft {
1011		private final String message;
1012		private final long timestamp;
1013
1014		private Draft(String message, long timestamp) {
1015			this.message = message;
1016			this.timestamp = timestamp;
1017		}
1018
1019		public long getTimestamp() {
1020			return timestamp;
1021		}
1022
1023		public String getMessage() {
1024			return message;
1025		}
1026	}
1027}