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 values.put(ATTRIBUTES, attributes.toString());
580 return values;
581 }
582
583 public int getMode() {
584 return this.mode;
585 }
586
587 public void setMode(int mode) {
588 this.mode = mode;
589 }
590
591 /**
592 * short for is Private and Non-anonymous
593 */
594 public boolean isSingleOrPrivateAndNonAnonymous() {
595 return mode == MODE_SINGLE || isPrivateAndNonAnonymous();
596 }
597
598 public boolean isPrivateAndNonAnonymous() {
599 return getMucOptions().isPrivateAndNonAnonymous();
600 }
601
602 public synchronized MucOptions getMucOptions() {
603 if (this.mucOptions == null) {
604 this.mucOptions = new MucOptions(this);
605 }
606 return this.mucOptions;
607 }
608
609 public void resetMucOptions() {
610 this.mucOptions = null;
611 }
612
613 public void setContactJid(final Jid jid) {
614 this.contactJid = jid;
615 }
616
617 public Jid getNextCounterpart() {
618 return this.nextCounterpart;
619 }
620
621 public void setNextCounterpart(Jid jid) {
622 this.nextCounterpart = jid;
623 }
624
625 public int getNextEncryption() {
626 if (!Config.supportOmemo() && !Config.supportOpenPgp()) {
627 return Message.ENCRYPTION_NONE;
628 }
629 if (OmemoSetting.isAlways()) {
630 return suitableForOmemoByDefault(this) ? Message.ENCRYPTION_AXOLOTL : Message.ENCRYPTION_NONE;
631 }
632 final int defaultEncryption;
633 if (suitableForOmemoByDefault(this)) {
634 defaultEncryption = OmemoSetting.getEncryption();
635 } else {
636 defaultEncryption = Message.ENCRYPTION_NONE;
637 }
638 int encryption = this.getIntAttribute(ATTRIBUTE_NEXT_ENCRYPTION, defaultEncryption);
639 if (encryption == Message.ENCRYPTION_OTR || encryption < 0) {
640 return defaultEncryption;
641 } else {
642 return encryption;
643 }
644 }
645
646 private static boolean suitableForOmemoByDefault(final Conversation conversation) {
647 if (conversation.getJid().asBareJid().equals(Config.BUG_REPORTS)) {
648 return false;
649 }
650 if (conversation.getContact().isOwnServer()) {
651 return false;
652 }
653 final String contact = conversation.getJid().getDomain();
654 final String account = conversation.getAccount().getServer();
655 if (Config.OMEMO_EXCEPTIONS.CONTACT_DOMAINS.contains(contact) || Config.OMEMO_EXCEPTIONS.ACCOUNT_DOMAINS.contains(account)) {
656 return false;
657 }
658 return conversation.isSingleOrPrivateAndNonAnonymous() || conversation.getBooleanAttribute(ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, false);
659 }
660
661 public boolean setNextEncryption(int encryption) {
662 return this.setAttribute(ATTRIBUTE_NEXT_ENCRYPTION, encryption);
663 }
664
665 public String getNextMessage() {
666 final String nextMessage = getAttribute(ATTRIBUTE_NEXT_MESSAGE);
667 return nextMessage == null ? "" : nextMessage;
668 }
669
670 public @Nullable
671 Draft getDraft() {
672 long timestamp = getLongAttribute(ATTRIBUTE_NEXT_MESSAGE_TIMESTAMP, 0);
673 if (timestamp > getLatestMessage().getTimeSent()) {
674 String message = getAttribute(ATTRIBUTE_NEXT_MESSAGE);
675 if (!TextUtils.isEmpty(message) && timestamp != 0) {
676 return new Draft(message, timestamp);
677 }
678 }
679 return null;
680 }
681
682 public boolean setNextMessage(final String input) {
683 final String message = input == null || input.trim().isEmpty() ? null : input;
684 boolean changed = !getNextMessage().equals(message);
685 this.setAttribute(ATTRIBUTE_NEXT_MESSAGE, message);
686 if (changed) {
687 this.setAttribute(ATTRIBUTE_NEXT_MESSAGE_TIMESTAMP, message == null ? 0 : System.currentTimeMillis());
688 }
689 return changed;
690 }
691
692 public Bookmark getBookmark() {
693 return this.account.getBookmark(this.contactJid);
694 }
695
696 public Message findDuplicateMessage(Message message) {
697 synchronized (this.messages) {
698 for (int i = this.messages.size() - 1; i >= 0; --i) {
699 if (this.messages.get(i).similar(message)) {
700 return this.messages.get(i);
701 }
702 }
703 }
704 return null;
705 }
706
707 public boolean hasDuplicateMessage(Message message) {
708 return findDuplicateMessage(message) != null;
709 }
710
711 public Message findSentMessageWithBody(String body) {
712 synchronized (this.messages) {
713 for (int i = this.messages.size() - 1; i >= 0; --i) {
714 Message message = this.messages.get(i);
715 if (message.getStatus() == Message.STATUS_UNSEND || message.getStatus() == Message.STATUS_SEND) {
716 String otherBody;
717 if (message.hasFileOnRemoteHost()) {
718 otherBody = message.getFileParams().url.toString();
719 } else {
720 otherBody = message.body;
721 }
722 if (otherBody != null && otherBody.equals(body)) {
723 return message;
724 }
725 }
726 }
727 return null;
728 }
729 }
730
731 public boolean possibleDuplicate(final String serverMsgId, final String remoteMsgId) {
732 if (serverMsgId == null || remoteMsgId == null) {
733 return false;
734 }
735 synchronized (this.messages) {
736 for(Message message : this.messages) {
737 if (serverMsgId.equals(message.getServerMsgId()) || remoteMsgId.equals(message.getRemoteMsgId())) {
738 return true;
739 }
740 }
741 }
742 return false;
743 }
744
745 public MamReference getLastMessageTransmitted() {
746 final MamReference lastClear = getLastClearHistory();
747 MamReference lastReceived = new MamReference(0);
748 synchronized (this.messages) {
749 for (int i = this.messages.size() - 1; i >= 0; --i) {
750 final Message message = this.messages.get(i);
751 if (message.isPrivateMessage()) {
752 continue; //it's unsafe to use private messages as anchor. They could be coming from user archive
753 }
754 if (message.getStatus() == Message.STATUS_RECEIVED || message.isCarbon() || message.getServerMsgId() != null) {
755 lastReceived = new MamReference(message.getTimeSent(), message.getServerMsgId());
756 break;
757 }
758 }
759 }
760 return MamReference.max(lastClear, lastReceived);
761 }
762
763 public void setMutedTill(long value) {
764 this.setAttribute(ATTRIBUTE_MUTED_TILL, String.valueOf(value));
765 }
766
767 public boolean isMuted() {
768 return System.currentTimeMillis() < this.getLongAttribute(ATTRIBUTE_MUTED_TILL, 0);
769 }
770
771 public boolean alwaysNotify() {
772 return mode == MODE_SINGLE || getBooleanAttribute(ATTRIBUTE_ALWAYS_NOTIFY, Config.ALWAYS_NOTIFY_BY_DEFAULT || isPrivateAndNonAnonymous());
773 }
774
775 public boolean setAttribute(String key, boolean value) {
776 return setAttribute(key, String.valueOf(value));
777 }
778
779 private boolean setAttribute(String key, long value) {
780 return setAttribute(key, Long.toString(value));
781 }
782
783 private boolean setAttribute(String key, int value) {
784 return setAttribute(key, String.valueOf(value));
785 }
786
787 public boolean setAttribute(String key, String value) {
788 synchronized (this.attributes) {
789 try {
790 if (value == null) {
791 if (this.attributes.has(key)) {
792 this.attributes.remove(key);
793 return true;
794 } else {
795 return false;
796 }
797 } else {
798 final String prev = this.attributes.optString(key, null);
799 this.attributes.put(key, value);
800 return !value.equals(prev);
801 }
802 } catch (JSONException e) {
803 throw new AssertionError(e);
804 }
805 }
806 }
807
808 public boolean setAttribute(String key, List<Jid> jids) {
809 JSONArray array = new JSONArray();
810 for (Jid jid : jids) {
811 array.put(jid.asBareJid().toString());
812 }
813 synchronized (this.attributes) {
814 try {
815 this.attributes.put(key, array);
816 return true;
817 } catch (JSONException e) {
818 return false;
819 }
820 }
821 }
822
823 public String getAttribute(String key) {
824 synchronized (this.attributes) {
825 return this.attributes.optString(key, null);
826 }
827 }
828
829 private List<Jid> getJidListAttribute(String key) {
830 ArrayList<Jid> list = new ArrayList<>();
831 synchronized (this.attributes) {
832 try {
833 JSONArray array = this.attributes.getJSONArray(key);
834 for (int i = 0; i < array.length(); ++i) {
835 try {
836 list.add(Jid.of(array.getString(i)));
837 } catch (IllegalArgumentException e) {
838 //ignored
839 }
840 }
841 } catch (JSONException e) {
842 //ignored
843 }
844 }
845 return list;
846 }
847
848 private int getIntAttribute(String key, int defaultValue) {
849 String value = this.getAttribute(key);
850 if (value == null) {
851 return defaultValue;
852 } else {
853 try {
854 return Integer.parseInt(value);
855 } catch (NumberFormatException e) {
856 return defaultValue;
857 }
858 }
859 }
860
861 public long getLongAttribute(String key, long defaultValue) {
862 String value = this.getAttribute(key);
863 if (value == null) {
864 return defaultValue;
865 } else {
866 try {
867 return Long.parseLong(value);
868 } catch (NumberFormatException e) {
869 return defaultValue;
870 }
871 }
872 }
873
874 public boolean getBooleanAttribute(String key, boolean defaultValue) {
875 String value = this.getAttribute(key);
876 if (value == null) {
877 return defaultValue;
878 } else {
879 return Boolean.parseBoolean(value);
880 }
881 }
882
883 public void add(Message message) {
884 synchronized (this.messages) {
885 this.messages.add(message);
886 }
887 }
888
889 public void prepend(int offset, Message message) {
890 synchronized (this.messages) {
891 this.messages.add(Math.min(offset, this.messages.size()), message);
892 }
893 }
894
895 public void addAll(int index, List<Message> messages) {
896 synchronized (this.messages) {
897 this.messages.addAll(index, messages);
898 }
899 account.getPgpDecryptionService().decrypt(messages);
900 }
901
902 public void expireOldMessages(long timestamp) {
903 synchronized (this.messages) {
904 for (ListIterator<Message> iterator = this.messages.listIterator(); iterator.hasNext(); ) {
905 if (iterator.next().getTimeSent() < timestamp) {
906 iterator.remove();
907 }
908 }
909 untieMessages();
910 }
911 }
912
913 public void sort() {
914 synchronized (this.messages) {
915 Collections.sort(this.messages, (left, right) -> {
916 if (left.getTimeSent() < right.getTimeSent()) {
917 return -1;
918 } else if (left.getTimeSent() > right.getTimeSent()) {
919 return 1;
920 } else {
921 return 0;
922 }
923 });
924 untieMessages();
925 }
926 }
927
928 private void untieMessages() {
929 for (Message message : this.messages) {
930 message.untie();
931 }
932 }
933
934 public int unreadCount() {
935 synchronized (this.messages) {
936 int count = 0;
937 for (int i = this.messages.size() - 1; i >= 0; --i) {
938 if (this.messages.get(i).isRead()) {
939 return count;
940 }
941 ++count;
942 }
943 return count;
944 }
945 }
946
947 public int receivedMessagesCount() {
948 int count = 0;
949 synchronized (this.messages) {
950 for (Message message : messages) {
951 if (message.getStatus() == Message.STATUS_RECEIVED) {
952 ++count;
953 }
954 }
955 }
956 return count;
957 }
958
959 public int sentMessagesCount() {
960 int count = 0;
961 synchronized (this.messages) {
962 for (Message message : messages) {
963 if (message.getStatus() != Message.STATUS_RECEIVED) {
964 ++count;
965 }
966 }
967 }
968 return count;
969 }
970
971 public boolean isWithStranger() {
972 final Contact contact = getContact();
973 return mode == MODE_SINGLE
974 && !contact.isOwnServer()
975 && !contact.showInContactList()
976 && !contact.isSelf()
977 && !Config.QUICKSY_DOMAIN.equals(contact.getJid().toEscapedString())
978 && sentMessagesCount() == 0;
979 }
980
981 public int getReceivedMessagesCountSinceUuid(String uuid) {
982 if (uuid == null) {
983 return 0;
984 }
985 int count = 0;
986 synchronized (this.messages) {
987 for (int i = messages.size() - 1; i >= 0; i--) {
988 final Message message = messages.get(i);
989 if (uuid.equals(message.getUuid())) {
990 return count;
991 }
992 if (message.getStatus() <= Message.STATUS_RECEIVED) {
993 ++count;
994 }
995 }
996 }
997 return 0;
998 }
999
1000 @Override
1001 public int getAvatarBackgroundColor() {
1002 return UIHelper.getColorForName(getName().toString());
1003 }
1004
1005 public interface OnMessageFound {
1006 void onMessageFound(final Message message);
1007 }
1008
1009 public static class Draft {
1010 private final String message;
1011 private final long timestamp;
1012
1013 private Draft(String message, long timestamp) {
1014 this.message = message;
1015 this.timestamp = timestamp;
1016 }
1017
1018 public long getTimestamp() {
1019 return timestamp;
1020 }
1021
1022 public String getMessage() {
1023 return message;
1024 }
1025 }
1026}