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 public boolean setCorrectingMessage(Message correctingMessage) {
428 this.correctingMessage = correctingMessage;
429 return correctingMessage == null && draftMessage != null;
430 }
431
432 public Message getCorrectingMessage() {
433 return this.correctingMessage;
434 }
435
436 public boolean withSelf() {
437 return getContact().isSelf();
438 }
439
440 @Override
441 public int compareTo(@NonNull Conversation another) {
442 return Long.compare(another.getSortableTime(), getSortableTime());
443 }
444
445 private long getSortableTime() {
446 Draft draft = getDraft();
447 long messageTime = getLatestMessage().getTimeSent();
448 if (draft == null) {
449 return messageTime;
450 } else {
451 return Math.max(messageTime, draft.getTimestamp());
452 }
453 }
454
455 public String getDraftMessage() {
456 return draftMessage;
457 }
458
459 public void setDraftMessage(String draftMessage) {
460 this.draftMessage = draftMessage;
461 }
462
463 public boolean isRead() {
464 return (this.messages.size() == 0) || this.messages.get(this.messages.size() - 1).isRead();
465 }
466
467 public List<Message> markRead(String upToUuid) {
468 final List<Message> unread = new ArrayList<>();
469 synchronized (this.messages) {
470 for (Message message : this.messages) {
471 if (!message.isRead()) {
472 message.markRead();
473 unread.add(message);
474 }
475 if (message.getUuid().equals(upToUuid)) {
476 return unread;
477 }
478 }
479 }
480 return unread;
481 }
482
483 public static Message getLatestMarkableMessage(final List<Message> messages, boolean isPrivateAndNonAnonymousMuc) {
484 for (int i = messages.size() - 1; i >= 0; --i) {
485 final Message message = messages.get(i);
486 if (message.getStatus() <= Message.STATUS_RECEIVED
487 && (message.markable || isPrivateAndNonAnonymousMuc)
488 && message.getType() != Message.TYPE_PRIVATE) {
489 return message;
490 }
491 }
492 return null;
493 }
494
495 public Message getLatestMessage() {
496 synchronized (this.messages) {
497 if (this.messages.size() == 0) {
498 Message message = new Message(this, "", Message.ENCRYPTION_NONE);
499 message.setType(Message.TYPE_STATUS);
500 message.setTime(Math.max(getCreated(), getLastClearHistory().getTimestamp()));
501 return message;
502 } else {
503 return this.messages.get(this.messages.size() - 1);
504 }
505 }
506 }
507
508 public @NonNull CharSequence getName() {
509 if (getMode() == MODE_MULTI) {
510 final String roomName = getMucOptions().getName();
511 final String subject = getMucOptions().getSubject();
512 final Bookmark bookmark = getBookmark();
513 final String bookmarkName = bookmark != null ? bookmark.getBookmarkName() : null;
514 if (printableValue(roomName)) {
515 return roomName;
516 } else if (printableValue(subject)) {
517 return subject;
518 } else if (printableValue(bookmarkName, false)) {
519 return bookmarkName;
520 } else {
521 final String generatedName = getMucOptions().createNameFromParticipants();
522 if (printableValue(generatedName)) {
523 return generatedName;
524 } else {
525 return contactJid.getLocal() != null ? contactJid.getLocal() : contactJid;
526 }
527 }
528 } else if ((QuickConversationsService.isConversations() || !Config.QUICKSY_DOMAIN.equals(contactJid.getDomain())) && isWithStranger()) {
529 return contactJid;
530 } else {
531 return this.getContact().getDisplayName();
532 }
533 }
534
535 public String getAccountUuid() {
536 return this.accountUuid;
537 }
538
539 public Account getAccount() {
540 return this.account;
541 }
542
543 public void setAccount(final Account account) {
544 this.account = account;
545 }
546
547 public Contact getContact() {
548 return this.account.getRoster().getContact(this.contactJid);
549 }
550
551 @Override
552 public Jid getJid() {
553 return this.contactJid;
554 }
555
556 public int getStatus() {
557 return this.status;
558 }
559
560 public void setStatus(int status) {
561 this.status = status;
562 }
563
564 public long getCreated() {
565 return this.created;
566 }
567
568 public ContentValues getContentValues() {
569 ContentValues values = new ContentValues();
570 values.put(UUID, uuid);
571 values.put(NAME, name);
572 values.put(CONTACT, contactUuid);
573 values.put(ACCOUNT, accountUuid);
574 values.put(CONTACTJID, contactJid.toString());
575 values.put(CREATED, created);
576 values.put(STATUS, status);
577 values.put(MODE, mode);
578 values.put(ATTRIBUTES, attributes.toString());
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.getType() == Message.TYPE_PRIVATE) {
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}