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