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 com.google.common.collect.ComparisonChain;
10import com.google.common.collect.Lists;
11
12import org.json.JSONArray;
13import org.json.JSONException;
14import org.json.JSONObject;
15
16import java.util.ArrayList;
17import java.util.Collections;
18import java.util.Iterator;
19import java.util.List;
20import java.util.ListIterator;
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.persistance.DatabaseBackend;
27import eu.siacs.conversations.services.AvatarService;
28import eu.siacs.conversations.services.QuickConversationsService;
29import eu.siacs.conversations.utils.JidHelper;
30import eu.siacs.conversations.utils.UIHelper;
31import eu.siacs.conversations.xmpp.chatstate.ChatState;
32import eu.siacs.conversations.xmpp.mam.MamReference;
33import eu.siacs.conversations.xmpp.Jid;
34
35import static eu.siacs.conversations.entities.Bookmark.printableValue;
36
37
38public class Conversation extends AbstractEntity implements Blockable, Comparable<Conversation>, Conversational, AvatarService.Avatarable {
39 public static final String TABLENAME = "conversations";
40
41 public static final int STATUS_AVAILABLE = 0;
42 public static final int STATUS_ARCHIVED = 1;
43
44 public static final String NAME = "name";
45 public static final String ACCOUNT = "accountUuid";
46 public static final String CONTACT = "contactUuid";
47 public static final String CONTACTJID = "contactJid";
48 public static final String STATUS = "status";
49 public static final String CREATED = "created";
50 public static final String MODE = "mode";
51 public static final String ATTRIBUTES = "attributes";
52
53 public static final String ATTRIBUTE_MUTED_TILL = "muted_till";
54 public static final String ATTRIBUTE_ALWAYS_NOTIFY = "always_notify";
55 public static final String ATTRIBUTE_LAST_CLEAR_HISTORY = "last_clear_history";
56 public static final String ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS = "formerly_private_non_anonymous";
57 public static final String ATTRIBUTE_PINNED_ON_TOP = "pinned_on_top";
58 static final String ATTRIBUTE_MUC_PASSWORD = "muc_password";
59 static final String ATTRIBUTE_MEMBERS_ONLY = "members_only";
60 static final String ATTRIBUTE_MODERATED = "moderated";
61 static final String ATTRIBUTE_NON_ANONYMOUS = "non_anonymous";
62 private static final String ATTRIBUTE_NEXT_MESSAGE = "next_message";
63 private static final String ATTRIBUTE_NEXT_MESSAGE_TIMESTAMP = "next_message_timestamp";
64 private static final String ATTRIBUTE_CRYPTO_TARGETS = "crypto_targets";
65 private static final String ATTRIBUTE_NEXT_ENCRYPTION = "next_encryption";
66 private static final String ATTRIBUTE_CORRECTING_MESSAGE = "correcting_message";
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_CHAT_STATE;
83 private ChatState mIncomingChatState = Config.DEFAULT_CHAT_STATE;
84 private String mFirstMamReference = null;
85
86 public Conversation(final String name, final Account account, final Jid contactJid,
87 final int mode) {
88 this(java.util.UUID.randomUUID().toString(), name, null, account
89 .getUuid(), contactJid, System.currentTimeMillis(),
90 STATUS_AVAILABLE, mode, "");
91 this.account = account;
92 }
93
94 public Conversation(final String uuid, final String name, final String contactUuid,
95 final String accountUuid, final Jid contactJid, final long created, final int status,
96 final int mode, final String attributes) {
97 this.uuid = uuid;
98 this.name = name;
99 this.contactUuid = contactUuid;
100 this.accountUuid = accountUuid;
101 this.contactJid = contactJid;
102 this.created = created;
103 this.status = status;
104 this.mode = mode;
105 try {
106 this.attributes = new JSONObject(attributes == null ? "" : attributes);
107 } catch (JSONException e) {
108 this.attributes = new JSONObject();
109 }
110 }
111
112 public static Conversation fromCursor(Cursor cursor) {
113 return new Conversation(cursor.getString(cursor.getColumnIndex(UUID)),
114 cursor.getString(cursor.getColumnIndex(NAME)),
115 cursor.getString(cursor.getColumnIndex(CONTACT)),
116 cursor.getString(cursor.getColumnIndex(ACCOUNT)),
117 JidHelper.parseOrFallbackToInvalid(cursor.getString(cursor.getColumnIndex(CONTACTJID))),
118 cursor.getLong(cursor.getColumnIndex(CREATED)),
119 cursor.getInt(cursor.getColumnIndex(STATUS)),
120 cursor.getInt(cursor.getColumnIndex(MODE)),
121 cursor.getString(cursor.getColumnIndex(ATTRIBUTES)));
122 }
123
124 public static Message getLatestMarkableMessage(final List<Message> messages, boolean isPrivateAndNonAnonymousMuc) {
125 for (int i = messages.size() - 1; i >= 0; --i) {
126 final Message message = messages.get(i);
127 if (message.getStatus() <= Message.STATUS_RECEIVED
128 && (message.markable || isPrivateAndNonAnonymousMuc)
129 && !message.isPrivateMessage()) {
130 return message;
131 }
132 }
133 return null;
134 }
135
136 private static boolean suitableForOmemoByDefault(final Conversation conversation) {
137 if (conversation.getJid().asBareJid().equals(Config.BUG_REPORTS)) {
138 return false;
139 }
140 if (conversation.getContact().isOwnServer()) {
141 return false;
142 }
143 final String contact = conversation.getJid().getDomain().toEscapedString();
144 final String account = conversation.getAccount().getServer();
145 if (Config.OMEMO_EXCEPTIONS.CONTACT_DOMAINS.contains(contact) || Config.OMEMO_EXCEPTIONS.ACCOUNT_DOMAINS.contains(account)) {
146 return false;
147 }
148 return conversation.isSingleOrPrivateAndNonAnonymous() || conversation.getBooleanAttribute(ATTRIBUTE_FORMERLY_PRIVATE_NON_ANONYMOUS, false);
149 }
150
151 public boolean hasMessagesLeftOnServer() {
152 return messagesLeftOnServer;
153 }
154
155 public void setHasMessagesLeftOnServer(boolean value) {
156 this.messagesLeftOnServer = value;
157 }
158
159 public Message getFirstUnreadMessage() {
160 Message first = null;
161 synchronized (this.messages) {
162 for (int i = messages.size() - 1; i >= 0; --i) {
163 if (messages.get(i).isRead()) {
164 return first;
165 } else {
166 first = messages.get(i);
167 }
168 }
169 }
170 return first;
171 }
172
173 public String findMostRecentRemoteDisplayableId() {
174 final boolean multi = mode == Conversation.MODE_MULTI;
175 synchronized (this.messages) {
176 for(final Message message : Lists.reverse(this.messages)) {
177 if (message.getStatus() == Message.STATUS_RECEIVED) {
178 final String serverMsgId = message.getServerMsgId();
179 if (serverMsgId != null && multi) {
180 return serverMsgId;
181 }
182 return message.getRemoteMsgId();
183 }
184 }
185 }
186 return null;
187 }
188
189 public Message findUnsentMessageWithUuid(String uuid) {
190 synchronized (this.messages) {
191 for (final Message message : this.messages) {
192 final int s = message.getStatus();
193 if ((s == Message.STATUS_UNSEND || s == Message.STATUS_WAITING) && message.getUuid().equals(uuid)) {
194 return message;
195 }
196 }
197 }
198 return null;
199 }
200
201 public void findWaitingMessages(OnMessageFound onMessageFound) {
202 final ArrayList<Message> results = new ArrayList<>();
203 synchronized (this.messages) {
204 for (Message message : this.messages) {
205 if (message.getStatus() == Message.STATUS_WAITING) {
206 results.add(message);
207 }
208 }
209 }
210 for (Message result : results) {
211 onMessageFound.onMessageFound(result);
212 }
213 }
214
215 public void findUnreadMessages(OnMessageFound onMessageFound) {
216 final ArrayList<Message> results = new ArrayList<>();
217 synchronized (this.messages) {
218 for (final Message message : this.messages) {
219 if (message.isRead() || message.getType() == Message.TYPE_RTP_SESSION) {
220 continue;
221 }
222 results.add(message);
223 }
224 }
225 for (final Message result : results) {
226 onMessageFound.onMessageFound(result);
227 }
228 }
229
230 public Message findMessageWithFileAndUuid(final String uuid) {
231 synchronized (this.messages) {
232 for (final Message message : this.messages) {
233 if (message.getUuid().equals(uuid)
234 && message.getEncryption() != Message.ENCRYPTION_PGP
235 && (message.isFileOrImage() || message.treatAsDownloadable())) {
236 return message;
237 }
238 }
239 }
240 return null;
241 }
242
243 public boolean markAsDeleted(final List<String> uuids) {
244 boolean deleted = false;
245 final PgpDecryptionService pgpDecryptionService = account.getPgpDecryptionService();
246 synchronized (this.messages) {
247 for (Message message : this.messages) {
248 if (uuids.contains(message.getUuid())) {
249 message.setDeleted(true);
250 deleted = true;
251 if (message.getEncryption() == Message.ENCRYPTION_PGP && pgpDecryptionService != null) {
252 pgpDecryptionService.discard(message);
253 }
254 }
255 }
256 }
257 return deleted;
258 }
259
260 public boolean markAsChanged(final List<DatabaseBackend.FilePathInfo> files) {
261 boolean changed = false;
262 final PgpDecryptionService pgpDecryptionService = account.getPgpDecryptionService();
263 synchronized (this.messages) {
264 for (Message message : this.messages) {
265 for (final DatabaseBackend.FilePathInfo file : files)
266 if (file.uuid.toString().equals(message.getUuid())) {
267 message.setDeleted(file.deleted);
268 changed = true;
269 if (file.deleted && message.getEncryption() == Message.ENCRYPTION_PGP && pgpDecryptionService != null) {
270 pgpDecryptionService.discard(message);
271 }
272 }
273 }
274 }
275 return changed;
276 }
277
278 public void clearMessages() {
279 synchronized (this.messages) {
280 this.messages.clear();
281 }
282 }
283
284 public boolean setIncomingChatState(ChatState state) {
285 if (this.mIncomingChatState == state) {
286 return false;
287 }
288 this.mIncomingChatState = state;
289 return true;
290 }
291
292 public ChatState getIncomingChatState() {
293 return this.mIncomingChatState;
294 }
295
296 public boolean setOutgoingChatState(ChatState state) {
297 if (mode == MODE_SINGLE && !getContact().isSelf() || (isPrivateAndNonAnonymous() && getNextCounterpart() == null)) {
298 if (this.mOutgoingChatState != state) {
299 this.mOutgoingChatState = state;
300 return true;
301 }
302 }
303 return false;
304 }
305
306 public ChatState getOutgoingChatState() {
307 return this.mOutgoingChatState;
308 }
309
310 public void trim() {
311 synchronized (this.messages) {
312 final int size = messages.size();
313 final int maxsize = Config.PAGE_SIZE * Config.MAX_NUM_PAGES;
314 if (size > maxsize) {
315 List<Message> discards = this.messages.subList(0, size - maxsize);
316 final PgpDecryptionService pgpDecryptionService = account.getPgpDecryptionService();
317 if (pgpDecryptionService != null) {
318 pgpDecryptionService.discard(discards);
319 }
320 discards.clear();
321 untieMessages();
322 }
323 }
324 }
325
326 public void findUnsentTextMessages(OnMessageFound onMessageFound) {
327 final ArrayList<Message> results = new ArrayList<>();
328 synchronized (this.messages) {
329 for (Message message : this.messages) {
330 if ((message.getType() == Message.TYPE_TEXT || message.hasFileOnRemoteHost()) && message.getStatus() == Message.STATUS_UNSEND) {
331 results.add(message);
332 }
333 }
334 }
335 for (Message result : results) {
336 onMessageFound.onMessageFound(result);
337 }
338 }
339
340 public Message findSentMessageWithUuidOrRemoteId(String id) {
341 synchronized (this.messages) {
342 for (Message message : this.messages) {
343 if (id.equals(message.getUuid())
344 || (message.getStatus() >= Message.STATUS_SEND
345 && id.equals(message.getRemoteMsgId()))) {
346 return message;
347 }
348 }
349 }
350 return null;
351 }
352
353 public Message findMessageWithRemoteIdAndCounterpart(String id, Jid counterpart, boolean received, boolean carbon) {
354 synchronized (this.messages) {
355 for (int i = this.messages.size() - 1; i >= 0; --i) {
356 final Message message = messages.get(i);
357 final Jid mcp = message.getCounterpart();
358 if (mcp == null) {
359 continue;
360 }
361 if (mcp.equals(counterpart) && ((message.getStatus() == Message.STATUS_RECEIVED) == received)
362 && (carbon == message.isCarbon() || received)) {
363 final boolean idMatch = id.equals(message.getRemoteMsgId()) || message.remoteMsgIdMatchInEdit(id);
364 if (idMatch && !message.isFileOrImage() && !message.treatAsDownloadable()) {
365 return message;
366 } else {
367 return null;
368 }
369 }
370 }
371 }
372 return null;
373 }
374
375 public Message findSentMessageWithUuid(String id) {
376 synchronized (this.messages) {
377 for (Message message : this.messages) {
378 if (id.equals(message.getUuid())) {
379 return message;
380 }
381 }
382 }
383 return null;
384 }
385
386 public Message findMessageWithRemoteId(String id, Jid counterpart) {
387 synchronized (this.messages) {
388 for (Message message : this.messages) {
389 if (counterpart.equals(message.getCounterpart())
390 && (id.equals(message.getRemoteMsgId()) || id.equals(message.getUuid()))) {
391 return message;
392 }
393 }
394 }
395 return null;
396 }
397
398 public Message findMessageWithServerMsgId(String id) {
399 synchronized (this.messages) {
400 for (Message message : this.messages) {
401 if (id != null && id.equals(message.getServerMsgId())) {
402 return message;
403 }
404 }
405 }
406 return null;
407 }
408
409 public boolean hasMessageWithCounterpart(Jid counterpart) {
410 synchronized (this.messages) {
411 for (Message message : this.messages) {
412 if (counterpart.equals(message.getCounterpart())) {
413 return true;
414 }
415 }
416 }
417 return false;
418 }
419
420 public void populateWithMessages(final List<Message> messages) {
421 synchronized (this.messages) {
422 messages.clear();
423 messages.addAll(this.messages);
424 }
425 for (Iterator<Message> iterator = messages.iterator(); iterator.hasNext(); ) {
426 if (iterator.next().wasMergedIntoPrevious()) {
427 iterator.remove();
428 }
429 }
430 }
431
432 @Override
433 public boolean isBlocked() {
434 return getContact().isBlocked();
435 }
436
437 @Override
438 public boolean isDomainBlocked() {
439 return getContact().isDomainBlocked();
440 }
441
442 @Override
443 public Jid getBlockedJid() {
444 return getContact().getBlockedJid();
445 }
446
447 public int countMessages() {
448 synchronized (this.messages) {
449 return this.messages.size();
450 }
451 }
452
453 public String getFirstMamReference() {
454 return this.mFirstMamReference;
455 }
456
457 public void setFirstMamReference(String reference) {
458 this.mFirstMamReference = reference;
459 }
460
461 public void setLastClearHistory(long time, String reference) {
462 if (reference != null) {
463 setAttribute(ATTRIBUTE_LAST_CLEAR_HISTORY, String.valueOf(time) + ":" + reference);
464 } else {
465 setAttribute(ATTRIBUTE_LAST_CLEAR_HISTORY, time);
466 }
467 }
468
469 public MamReference getLastClearHistory() {
470 return MamReference.fromAttribute(getAttribute(ATTRIBUTE_LAST_CLEAR_HISTORY));
471 }
472
473 public List<Jid> getAcceptedCryptoTargets() {
474 if (mode == MODE_SINGLE) {
475 return Collections.singletonList(getJid().asBareJid());
476 } else {
477 return getJidListAttribute(ATTRIBUTE_CRYPTO_TARGETS);
478 }
479 }
480
481 public void setAcceptedCryptoTargets(List<Jid> acceptedTargets) {
482 setAttribute(ATTRIBUTE_CRYPTO_TARGETS, acceptedTargets);
483 }
484
485 public boolean setCorrectingMessage(Message correctingMessage) {
486 setAttribute(ATTRIBUTE_CORRECTING_MESSAGE, correctingMessage == null ? null : correctingMessage.getUuid());
487 return correctingMessage == null && draftMessage != null;
488 }
489
490 public Message getCorrectingMessage() {
491 final String uuid = getAttribute(ATTRIBUTE_CORRECTING_MESSAGE);
492 return uuid == null ? null : findSentMessageWithUuid(uuid);
493 }
494
495 public boolean withSelf() {
496 return getContact().isSelf();
497 }
498
499 @Override
500 public int compareTo(@NonNull Conversation another) {
501 return ComparisonChain.start()
502 .compareFalseFirst(another.getBooleanAttribute(ATTRIBUTE_PINNED_ON_TOP, false), getBooleanAttribute(ATTRIBUTE_PINNED_ON_TOP,false))
503 .compare(another.getSortableTime(), getSortableTime())
504 .result();
505 }
506
507 private long getSortableTime() {
508 Draft draft = getDraft();
509 long messageTime = getLatestMessage().getTimeSent();
510 if (draft == null) {
511 return messageTime;
512 } else {
513 return Math.max(messageTime, draft.getTimestamp());
514 }
515 }
516
517 public String getDraftMessage() {
518 return draftMessage;
519 }
520
521 public void setDraftMessage(String draftMessage) {
522 this.draftMessage = draftMessage;
523 }
524
525 public boolean isRead() {
526 return (this.messages.size() == 0) || this.messages.get(this.messages.size() - 1).isRead();
527 }
528
529 public List<Message> markRead(String upToUuid) {
530 final List<Message> unread = new ArrayList<>();
531 synchronized (this.messages) {
532 for (Message message : this.messages) {
533 if (!message.isRead()) {
534 message.markRead();
535 unread.add(message);
536 }
537 if (message.getUuid().equals(upToUuid)) {
538 return unread;
539 }
540 }
541 }
542 return unread;
543 }
544
545 public Message getLatestMessage() {
546 synchronized (this.messages) {
547 if (this.messages.size() == 0) {
548 Message message = new Message(this, "", Message.ENCRYPTION_NONE);
549 message.setType(Message.TYPE_STATUS);
550 message.setTime(Math.max(getCreated(), getLastClearHistory().getTimestamp()));
551 return message;
552 } else {
553 return this.messages.get(this.messages.size() - 1);
554 }
555 }
556 }
557
558 public @NonNull
559 CharSequence getName() {
560 if (getMode() == MODE_MULTI) {
561 final String roomName = getMucOptions().getName();
562 final String subject = getMucOptions().getSubject();
563 final Bookmark bookmark = getBookmark();
564 final String bookmarkName = bookmark != null ? bookmark.getBookmarkName() : null;
565 if (printableValue(roomName)) {
566 return roomName;
567 } else if (printableValue(subject)) {
568 return subject;
569 } else if (printableValue(bookmarkName, false)) {
570 return bookmarkName;
571 } else {
572 final String generatedName = getMucOptions().createNameFromParticipants();
573 if (printableValue(generatedName)) {
574 return generatedName;
575 } else {
576 return contactJid.getLocal() != null ? contactJid.getLocal() : contactJid;
577 }
578 }
579 } else if ((QuickConversationsService.isConversations() || !Config.QUICKSY_DOMAIN.equals(contactJid.getDomain())) && isWithStranger()) {
580 return contactJid;
581 } else {
582 return this.getContact().getDisplayName();
583 }
584 }
585
586 public String getAccountUuid() {
587 return this.accountUuid;
588 }
589
590 public Account getAccount() {
591 return this.account;
592 }
593
594 public void setAccount(final Account account) {
595 this.account = account;
596 }
597
598 public Contact getContact() {
599 return this.account.getRoster().getContact(this.contactJid);
600 }
601
602 @Override
603 public Jid getJid() {
604 return this.contactJid;
605 }
606
607 public int getStatus() {
608 return this.status;
609 }
610
611 public void setStatus(int status) {
612 this.status = status;
613 }
614
615 public long getCreated() {
616 return this.created;
617 }
618
619 public ContentValues getContentValues() {
620 ContentValues values = new ContentValues();
621 values.put(UUID, uuid);
622 values.put(NAME, name);
623 values.put(CONTACT, contactUuid);
624 values.put(ACCOUNT, accountUuid);
625 values.put(CONTACTJID, contactJid.toString());
626 values.put(CREATED, created);
627 values.put(STATUS, status);
628 values.put(MODE, mode);
629 synchronized (this.attributes) {
630 values.put(ATTRIBUTES, attributes.toString());
631 }
632 return values;
633 }
634
635 public int getMode() {
636 return this.mode;
637 }
638
639 public void setMode(int mode) {
640 this.mode = mode;
641 }
642
643 /**
644 * short for is Private and Non-anonymous
645 */
646 public boolean isSingleOrPrivateAndNonAnonymous() {
647 return mode == MODE_SINGLE || isPrivateAndNonAnonymous();
648 }
649
650 public boolean isPrivateAndNonAnonymous() {
651 return getMucOptions().isPrivateAndNonAnonymous();
652 }
653
654 public synchronized MucOptions getMucOptions() {
655 if (this.mucOptions == null) {
656 this.mucOptions = new MucOptions(this);
657 }
658 return this.mucOptions;
659 }
660
661 public void resetMucOptions() {
662 this.mucOptions = null;
663 }
664
665 public void setContactJid(final Jid jid) {
666 this.contactJid = jid;
667 }
668
669 public Jid getNextCounterpart() {
670 return this.nextCounterpart;
671 }
672
673 public void setNextCounterpart(Jid jid) {
674 this.nextCounterpart = jid;
675 }
676
677 public int getNextEncryption() {
678 if (!Config.supportOmemo() && !Config.supportOpenPgp()) {
679 return Message.ENCRYPTION_NONE;
680 }
681 if (OmemoSetting.isAlways()) {
682 return suitableForOmemoByDefault(this) ? Message.ENCRYPTION_AXOLOTL : Message.ENCRYPTION_NONE;
683 }
684 final int defaultEncryption;
685 if (suitableForOmemoByDefault(this)) {
686 defaultEncryption = OmemoSetting.getEncryption();
687 } else {
688 defaultEncryption = Message.ENCRYPTION_NONE;
689 }
690 int encryption = this.getIntAttribute(ATTRIBUTE_NEXT_ENCRYPTION, defaultEncryption);
691 if (encryption == Message.ENCRYPTION_OTR || encryption < 0) {
692 return defaultEncryption;
693 } else {
694 return encryption;
695 }
696 }
697
698 public boolean setNextEncryption(int encryption) {
699 return this.setAttribute(ATTRIBUTE_NEXT_ENCRYPTION, encryption);
700 }
701
702 public String getNextMessage() {
703 final String nextMessage = getAttribute(ATTRIBUTE_NEXT_MESSAGE);
704 return nextMessage == null ? "" : nextMessage;
705 }
706
707 public @Nullable
708 Draft getDraft() {
709 long timestamp = getLongAttribute(ATTRIBUTE_NEXT_MESSAGE_TIMESTAMP, 0);
710 if (timestamp > getLatestMessage().getTimeSent()) {
711 String message = getAttribute(ATTRIBUTE_NEXT_MESSAGE);
712 if (!TextUtils.isEmpty(message) && timestamp != 0) {
713 return new Draft(message, timestamp);
714 }
715 }
716 return null;
717 }
718
719 public boolean setNextMessage(final String input) {
720 final String message = input == null || input.trim().isEmpty() ? null : input;
721 boolean changed = !getNextMessage().equals(message);
722 this.setAttribute(ATTRIBUTE_NEXT_MESSAGE, message);
723 if (changed) {
724 this.setAttribute(ATTRIBUTE_NEXT_MESSAGE_TIMESTAMP, message == null ? 0 : System.currentTimeMillis());
725 }
726 return changed;
727 }
728
729 public Bookmark getBookmark() {
730 return this.account.getBookmark(this.contactJid);
731 }
732
733 public Message findDuplicateMessage(Message message) {
734 synchronized (this.messages) {
735 for (int i = this.messages.size() - 1; i >= 0; --i) {
736 if (this.messages.get(i).similar(message)) {
737 return this.messages.get(i);
738 }
739 }
740 }
741 return null;
742 }
743
744 public boolean hasDuplicateMessage(Message message) {
745 return findDuplicateMessage(message) != null;
746 }
747
748 public Message findSentMessageWithBody(String body) {
749 synchronized (this.messages) {
750 for (int i = this.messages.size() - 1; i >= 0; --i) {
751 Message message = this.messages.get(i);
752 if (message.getStatus() == Message.STATUS_UNSEND || message.getStatus() == Message.STATUS_SEND) {
753 String otherBody;
754 if (message.hasFileOnRemoteHost()) {
755 otherBody = message.getFileParams().url.toString();
756 } else {
757 otherBody = message.body;
758 }
759 if (otherBody != null && otherBody.equals(body)) {
760 return message;
761 }
762 }
763 }
764 return null;
765 }
766 }
767
768 public Message findRtpSession(final String sessionId, final int s) {
769 synchronized (this.messages) {
770 for (int i = this.messages.size() - 1; i >= 0; --i) {
771 final Message message = this.messages.get(i);
772 if ((message.getStatus() == s) && (message.getType() == Message.TYPE_RTP_SESSION) && sessionId.equals(message.getRemoteMsgId())) {
773 return message;
774 }
775 }
776 }
777 return null;
778 }
779
780 public boolean possibleDuplicate(final String serverMsgId, final String remoteMsgId) {
781 if (serverMsgId == null || remoteMsgId == null) {
782 return false;
783 }
784 synchronized (this.messages) {
785 for (Message message : this.messages) {
786 if (serverMsgId.equals(message.getServerMsgId()) || remoteMsgId.equals(message.getRemoteMsgId())) {
787 return true;
788 }
789 }
790 }
791 return false;
792 }
793
794 public MamReference getLastMessageTransmitted() {
795 final MamReference lastClear = getLastClearHistory();
796 MamReference lastReceived = new MamReference(0);
797 synchronized (this.messages) {
798 for (int i = this.messages.size() - 1; i >= 0; --i) {
799 final Message message = this.messages.get(i);
800 if (message.isPrivateMessage()) {
801 continue; //it's unsafe to use private messages as anchor. They could be coming from user archive
802 }
803 if (message.getStatus() == Message.STATUS_RECEIVED || message.isCarbon() || message.getServerMsgId() != null) {
804 lastReceived = new MamReference(message.getTimeSent(), message.getServerMsgId());
805 break;
806 }
807 }
808 }
809 return MamReference.max(lastClear, lastReceived);
810 }
811
812 public void setMutedTill(long value) {
813 this.setAttribute(ATTRIBUTE_MUTED_TILL, String.valueOf(value));
814 }
815
816 public boolean isMuted() {
817 return System.currentTimeMillis() < this.getLongAttribute(ATTRIBUTE_MUTED_TILL, 0);
818 }
819
820 public boolean alwaysNotify() {
821 return mode == MODE_SINGLE || getBooleanAttribute(ATTRIBUTE_ALWAYS_NOTIFY, Config.ALWAYS_NOTIFY_BY_DEFAULT || isPrivateAndNonAnonymous());
822 }
823
824 public boolean setAttribute(String key, boolean value) {
825 return setAttribute(key, String.valueOf(value));
826 }
827
828 private boolean setAttribute(String key, long value) {
829 return setAttribute(key, Long.toString(value));
830 }
831
832 private boolean setAttribute(String key, int value) {
833 return setAttribute(key, String.valueOf(value));
834 }
835
836 public boolean setAttribute(String key, String value) {
837 synchronized (this.attributes) {
838 try {
839 if (value == null) {
840 if (this.attributes.has(key)) {
841 this.attributes.remove(key);
842 return true;
843 } else {
844 return false;
845 }
846 } else {
847 final String prev = this.attributes.optString(key, null);
848 this.attributes.put(key, value);
849 return !value.equals(prev);
850 }
851 } catch (JSONException e) {
852 throw new AssertionError(e);
853 }
854 }
855 }
856
857 public boolean setAttribute(String key, List<Jid> jids) {
858 JSONArray array = new JSONArray();
859 for (Jid jid : jids) {
860 array.put(jid.asBareJid().toString());
861 }
862 synchronized (this.attributes) {
863 try {
864 this.attributes.put(key, array);
865 return true;
866 } catch (JSONException e) {
867 return false;
868 }
869 }
870 }
871
872 public String getAttribute(String key) {
873 synchronized (this.attributes) {
874 return this.attributes.optString(key, null);
875 }
876 }
877
878 private List<Jid> getJidListAttribute(String key) {
879 ArrayList<Jid> list = new ArrayList<>();
880 synchronized (this.attributes) {
881 try {
882 JSONArray array = this.attributes.getJSONArray(key);
883 for (int i = 0; i < array.length(); ++i) {
884 try {
885 list.add(Jid.of(array.getString(i)));
886 } catch (IllegalArgumentException e) {
887 //ignored
888 }
889 }
890 } catch (JSONException e) {
891 //ignored
892 }
893 }
894 return list;
895 }
896
897 private int getIntAttribute(String key, int defaultValue) {
898 String value = this.getAttribute(key);
899 if (value == null) {
900 return defaultValue;
901 } else {
902 try {
903 return Integer.parseInt(value);
904 } catch (NumberFormatException e) {
905 return defaultValue;
906 }
907 }
908 }
909
910 public long getLongAttribute(String key, long defaultValue) {
911 String value = this.getAttribute(key);
912 if (value == null) {
913 return defaultValue;
914 } else {
915 try {
916 return Long.parseLong(value);
917 } catch (NumberFormatException e) {
918 return defaultValue;
919 }
920 }
921 }
922
923 public boolean getBooleanAttribute(String key, boolean defaultValue) {
924 String value = this.getAttribute(key);
925 if (value == null) {
926 return defaultValue;
927 } else {
928 return Boolean.parseBoolean(value);
929 }
930 }
931
932 public void add(Message message) {
933 synchronized (this.messages) {
934 this.messages.add(message);
935 }
936 }
937
938 public void prepend(int offset, Message message) {
939 synchronized (this.messages) {
940 this.messages.add(Math.min(offset, this.messages.size()), message);
941 }
942 }
943
944 public void addAll(int index, List<Message> messages) {
945 synchronized (this.messages) {
946 this.messages.addAll(index, messages);
947 }
948 account.getPgpDecryptionService().decrypt(messages);
949 }
950
951 public void expireOldMessages(long timestamp) {
952 synchronized (this.messages) {
953 for (ListIterator<Message> iterator = this.messages.listIterator(); iterator.hasNext(); ) {
954 if (iterator.next().getTimeSent() < timestamp) {
955 iterator.remove();
956 }
957 }
958 untieMessages();
959 }
960 }
961
962 public void sort() {
963 synchronized (this.messages) {
964 Collections.sort(this.messages, (left, right) -> {
965 if (left.getTimeSent() < right.getTimeSent()) {
966 return -1;
967 } else if (left.getTimeSent() > right.getTimeSent()) {
968 return 1;
969 } else {
970 return 0;
971 }
972 });
973 untieMessages();
974 }
975 }
976
977 private void untieMessages() {
978 for (Message message : this.messages) {
979 message.untie();
980 }
981 }
982
983 public int unreadCount() {
984 synchronized (this.messages) {
985 int count = 0;
986 for (int i = this.messages.size() - 1; i >= 0; --i) {
987 if (this.messages.get(i).isRead()) {
988 return count;
989 }
990 ++count;
991 }
992 return count;
993 }
994 }
995
996 public int receivedMessagesCount() {
997 int count = 0;
998 synchronized (this.messages) {
999 for (Message message : messages) {
1000 if (message.getStatus() == Message.STATUS_RECEIVED) {
1001 ++count;
1002 }
1003 }
1004 }
1005 return count;
1006 }
1007
1008 public int sentMessagesCount() {
1009 int count = 0;
1010 synchronized (this.messages) {
1011 for (Message message : messages) {
1012 if (message.getStatus() != Message.STATUS_RECEIVED) {
1013 ++count;
1014 }
1015 }
1016 }
1017 return count;
1018 }
1019
1020 public boolean isWithStranger() {
1021 final Contact contact = getContact();
1022 return mode == MODE_SINGLE
1023 && !contact.isOwnServer()
1024 && !contact.showInContactList()
1025 && !contact.isSelf()
1026 && !JidHelper.isQuicksyDomain(contact.getJid())
1027 && sentMessagesCount() == 0;
1028 }
1029
1030 public int getReceivedMessagesCountSinceUuid(String uuid) {
1031 if (uuid == null) {
1032 return 0;
1033 }
1034 int count = 0;
1035 synchronized (this.messages) {
1036 for (int i = messages.size() - 1; i >= 0; i--) {
1037 final Message message = messages.get(i);
1038 if (uuid.equals(message.getUuid())) {
1039 return count;
1040 }
1041 if (message.getStatus() <= Message.STATUS_RECEIVED) {
1042 ++count;
1043 }
1044 }
1045 }
1046 return 0;
1047 }
1048
1049 @Override
1050 public int getAvatarBackgroundColor() {
1051 return UIHelper.getColorForName(getName().toString());
1052 }
1053
1054 public interface OnMessageFound {
1055 void onMessageFound(final Message message);
1056 }
1057
1058 public static class Draft {
1059 private final String message;
1060 private final long timestamp;
1061
1062 private Draft(String message, long timestamp) {
1063 this.message = message;
1064 this.timestamp = timestamp;
1065 }
1066
1067 public long getTimestamp() {
1068 return timestamp;
1069 }
1070
1071 public String getMessage() {
1072 return message;
1073 }
1074 }
1075}