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