1package eu.siacs.conversations.parser;
2
3import android.util.Log;
4import android.util.Pair;
5
6import com.google.common.collect.ImmutableSet;
7
8import java.text.SimpleDateFormat;
9import java.util.ArrayList;
10import java.util.Arrays;
11import java.util.Collections;
12import java.util.Date;
13import java.util.List;
14import java.util.Locale;
15import java.util.Map;
16import java.util.Set;
17import java.util.UUID;
18
19import eu.siacs.conversations.AppSettings;
20import eu.siacs.conversations.Config;
21import eu.siacs.conversations.R;
22import eu.siacs.conversations.crypto.axolotl.AxolotlService;
23import eu.siacs.conversations.crypto.axolotl.BrokenSessionException;
24import eu.siacs.conversations.crypto.axolotl.NotEncryptedForThisDeviceException;
25import eu.siacs.conversations.crypto.axolotl.OutdatedSenderException;
26import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
27import eu.siacs.conversations.entities.Account;
28import eu.siacs.conversations.entities.Bookmark;
29import eu.siacs.conversations.entities.Contact;
30import eu.siacs.conversations.entities.Conversation;
31import eu.siacs.conversations.entities.Conversational;
32import eu.siacs.conversations.entities.Message;
33import eu.siacs.conversations.entities.MucOptions;
34import eu.siacs.conversations.entities.ReadByMarker;
35import eu.siacs.conversations.entities.ReceiptRequest;
36import eu.siacs.conversations.entities.RtpSessionStatus;
37import eu.siacs.conversations.http.HttpConnectionManager;
38import eu.siacs.conversations.services.MessageArchiveService;
39import eu.siacs.conversations.services.QuickConversationsService;
40import eu.siacs.conversations.services.XmppConnectionService;
41import eu.siacs.conversations.utils.CryptoHelper;
42import eu.siacs.conversations.xml.Element;
43import eu.siacs.conversations.xml.LocalizedContent;
44import eu.siacs.conversations.xml.Namespace;
45import eu.siacs.conversations.xmpp.InvalidJid;
46import eu.siacs.conversations.xmpp.Jid;
47import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
48import eu.siacs.conversations.xmpp.chatstate.ChatState;
49import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
50import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
51import eu.siacs.conversations.xmpp.pep.Avatar;
52import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
53
54public class MessageParser extends AbstractParser implements OnMessagePacketReceived {
55
56 private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
57
58 private static final List<String> JINGLE_MESSAGE_ELEMENT_NAMES =
59 Arrays.asList("accept", "propose", "proceed", "reject", "retract", "ringing", "finish");
60
61 public MessageParser(XmppConnectionService service) {
62 super(service);
63 }
64
65 private static String extractStanzaId(Element packet, boolean isTypeGroupChat, Conversation conversation) {
66 final Jid by;
67 final boolean safeToExtract;
68 if (isTypeGroupChat) {
69 by = conversation.getJid().asBareJid();
70 safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
71 } else {
72 Account account = conversation.getAccount();
73 by = account.getJid().asBareJid();
74 safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
75 }
76 return safeToExtract ? extractStanzaId(packet, by) : null;
77 }
78
79 private static String extractStanzaId(Account account, Element packet) {
80 final boolean safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
81 return safeToExtract ? extractStanzaId(packet, account.getJid().asBareJid()) : null;
82 }
83
84 private static String extractStanzaId(Element packet, Jid by) {
85 for (Element child : packet.getChildren()) {
86 if (child.getName().equals("stanza-id")
87 && Namespace.STANZA_IDS.equals(child.getNamespace())
88 && by.equals(InvalidJid.getNullForInvalid(child.getAttributeAsJid("by")))) {
89 return child.getAttribute("id");
90 }
91 }
92 return null;
93 }
94
95 private static Jid getTrueCounterpart(Element mucUserElement, Jid fallback) {
96 final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
97 Jid result = item == null ? null : InvalidJid.getNullForInvalid(item.getAttributeAsJid("jid"));
98 return result != null ? result : fallback;
99 }
100
101 private boolean extractChatState(Conversation c, final boolean isTypeGroupChat, final MessagePacket packet) {
102 ChatState state = ChatState.parse(packet);
103 if (state != null && c != null) {
104 final Account account = c.getAccount();
105 final Jid from = packet.getFrom();
106 if (from.asBareJid().equals(account.getJid().asBareJid())) {
107 c.setOutgoingChatState(state);
108 if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
109 if (c.getContact().isSelf()) {
110 return false;
111 }
112 mXmppConnectionService.markRead(c);
113 activateGracePeriod(account);
114 }
115 return false;
116 } else {
117 if (isTypeGroupChat) {
118 MucOptions.User user = c.getMucOptions().findUserByFullJid(from);
119 if (user != null) {
120 return user.setChatState(state);
121 } else {
122 return false;
123 }
124 } else {
125 return c.setIncomingChatState(state);
126 }
127 }
128 }
129 return false;
130 }
131
132 private Message parseAxolotlChat(Element axolotlMessage, Jid from, Conversation conversation, int status, final boolean checkedForDuplicates, boolean postpone) {
133 final AxolotlService service = conversation.getAccount().getAxolotlService();
134 final XmppAxolotlMessage xmppAxolotlMessage;
135 try {
136 xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.asBareJid());
137 } catch (Exception e) {
138 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": invalid omemo message received " + e.getMessage());
139 return null;
140 }
141 if (xmppAxolotlMessage.hasPayload()) {
142 final XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage;
143 try {
144 plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage, postpone);
145 } catch (BrokenSessionException e) {
146 if (checkedForDuplicates) {
147 if (service.trustedOrPreviouslyResponded(from.asBareJid())) {
148 service.reportBrokenSessionException(e, postpone);
149 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
150 } else {
151 Log.d(Config.LOGTAG, "ignoring broken session exception because contact was not trusted");
152 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
153 }
154 } else {
155 Log.d(Config.LOGTAG, "ignoring broken session exception because checkForDuplicates failed");
156 return null;
157 }
158 } catch (NotEncryptedForThisDeviceException e) {
159 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE, status);
160 } catch (OutdatedSenderException e) {
161 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
162 }
163 if (plaintextMessage != null) {
164 Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
165 finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
166 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount()) + " Received Message with session fingerprint: " + plaintextMessage.getFingerprint());
167 return finishedMessage;
168 }
169 } else {
170 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": received OMEMO key transport message");
171 service.processReceivingKeyTransportMessage(xmppAxolotlMessage, postpone);
172 }
173 return null;
174 }
175
176 private Invite extractInvite(final Element message) {
177 final Element mucUser = message.findChild("x", Namespace.MUC_USER);
178 if (mucUser != null) {
179 final Element invite = mucUser.findChild("invite");
180 if (invite != null) {
181 final String password = mucUser.findChildContent("password");
182 final Jid from = InvalidJid.getNullForInvalid(invite.getAttributeAsJid("from"));
183 final Jid to = InvalidJid.getNullForInvalid(invite.getAttributeAsJid("to"));
184 if (to != null && from == null) {
185 Log.d(Config.LOGTAG,"do not parse outgoing mediated invite "+message);
186 return null;
187 }
188 final Jid room = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
189 if (room == null) {
190 return null;
191 }
192 return new Invite(room, password, false, from);
193 }
194 }
195 final Element conference = message.findChild("x", "jabber:x:conference");
196 if (conference != null) {
197 Jid from = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
198 Jid room = InvalidJid.getNullForInvalid(conference.getAttributeAsJid("jid"));
199 if (room == null) {
200 return null;
201 }
202 return new Invite(room, conference.getAttribute("password"), true, from);
203 }
204 return null;
205 }
206
207 private void parseEvent(final Element event, final Jid from, final Account account) {
208 final Element items = event.findChild("items");
209 final String node = items == null ? null : items.getAttribute("node");
210 if ("urn:xmpp:avatar:metadata".equals(node)) {
211 Avatar avatar = Avatar.parseMetadata(items);
212 if (avatar != null) {
213 avatar.owner = from.asBareJid();
214 if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
215 if (account.getJid().asBareJid().equals(from)) {
216 if (account.setAvatar(avatar.getFilename())) {
217 mXmppConnectionService.databaseBackend.updateAccount(account);
218 mXmppConnectionService.notifyAccountAvatarHasChanged(account);
219 }
220 mXmppConnectionService.getAvatarService().clear(account);
221 mXmppConnectionService.updateConversationUi();
222 mXmppConnectionService.updateAccountUi();
223 } else {
224 final Contact contact = account.getRoster().getContact(from);
225 contact.setAvatar(avatar);
226 mXmppConnectionService.syncRoster(account);
227 mXmppConnectionService.getAvatarService().clear(contact);
228 mXmppConnectionService.updateConversationUi();
229 mXmppConnectionService.updateRosterUi();
230 }
231 } else if (mXmppConnectionService.isDataSaverDisabled()) {
232 mXmppConnectionService.fetchAvatar(account, avatar);
233 }
234 }
235 } else if (Namespace.NICK.equals(node)) {
236 final Element i = items.findChild("item");
237 final String nick = i == null ? null : i.findChildContent("nick", Namespace.NICK);
238 if (nick != null) {
239 setNick(account, from, nick);
240 }
241 } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
242 Element item = items.findChild("item");
243 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
244 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received PEP device list " + deviceIds + " update from " + from + ", processing... ");
245 final AxolotlService axolotlService = account.getAxolotlService();
246 axolotlService.registerDevices(from, deviceIds);
247 } else if (Namespace.BOOKMARKS.equals(node) && account.getJid().asBareJid().equals(from)) {
248 final var connection = account.getXmppConnection();
249 if (connection.getFeatures().bookmarksConversion()) {
250 if (connection.getFeatures().bookmarks2()) {
251 Log.w(
252 Config.LOGTAG,
253 account.getJid().asBareJid()
254 + ": received storage:bookmark notification even though we opted into bookmarks:1");
255 }
256 final Element i = items.findChild("item");
257 final Element storage =
258 i == null ? null : i.findChild("storage", Namespace.BOOKMARKS);
259 final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
260 mXmppConnectionService.processBookmarksInitial(account, bookmarks, true);
261 Log.d(
262 Config.LOGTAG,
263 account.getJid().asBareJid() + ": processing bookmark PEP event");
264 } else {
265 Log.d(
266 Config.LOGTAG,
267 account.getJid().asBareJid()
268 + ": ignoring bookmark PEP event because bookmark conversion was not detected");
269 }
270 } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
271 final Element item = items.findChild("item");
272 final Element retract = items.findChild("retract");
273 if (item != null) {
274 final Bookmark bookmark = Bookmark.parseFromItem(item, account);
275 if (bookmark != null) {
276 account.putBookmark(bookmark);
277 mXmppConnectionService.processModifiedBookmark(bookmark);
278 mXmppConnectionService.updateConversationUi();
279 }
280 }
281 if (retract != null) {
282 final Jid id = InvalidJid.getNullForInvalid(retract.getAttributeAsJid("id"));
283 if (id != null) {
284 account.removeBookmark(id);
285 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmark for " + id);
286 mXmppConnectionService.processDeletedBookmark(account, id);
287 mXmppConnectionService.updateConversationUi();
288 }
289 }
290 } else if (Config.MESSAGE_DISPLAYED_SYNCHRONIZATION
291 && Namespace.MDS_DISPLAYED.equals(node)
292 && account.getJid().asBareJid().equals(from)) {
293 final Element item = items.findChild("item");
294 mXmppConnectionService.processMdsItem(account, item);
295 } else {
296 Log.d(
297 Config.LOGTAG,
298 account.getJid().asBareJid()
299 + " received pubsub notification for node="
300 + node);
301 }
302 }
303
304 private void parseDeleteEvent(final Element event, final Jid from, final Account account) {
305 final Element delete = event.findChild("delete");
306 final String node = delete == null ? null : delete.getAttribute("node");
307 if (Namespace.NICK.equals(node)) {
308 Log.d(Config.LOGTAG, "parsing nick delete event from " + from);
309 setNick(account, from, null);
310 } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
311 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmarks node");
312 deleteAllBookmarks(account);
313 } else if (Namespace.AVATAR_METADATA.equals(node) && account.getJid().asBareJid().equals(from)) {
314 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": deleted avatar metadata node");
315 }
316 }
317
318 private void parsePurgeEvent(final Element event, final Jid from, final Account account) {
319 final Element purge = event.findChild("purge");
320 final String node = purge == null ? null : purge.getAttribute("node");
321 if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
322 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": purged bookmarks");
323 deleteAllBookmarks(account);
324 }
325 }
326
327 private void deleteAllBookmarks(final Account account) {
328 final var previous = account.getBookmarkedJids();
329 account.setBookmarks(Collections.emptyMap());
330 mXmppConnectionService.processDeletedBookmarks(account, previous);
331 }
332
333 private void setNick(Account account, Jid user, String nick) {
334 if (user.asBareJid().equals(account.getJid().asBareJid())) {
335 account.setDisplayName(nick);
336 if (QuickConversationsService.isQuicksy()) {
337 mXmppConnectionService.getAvatarService().clear(account);
338 }
339 } else {
340 Contact contact = account.getRoster().getContact(user);
341 if (contact.setPresenceName(nick)) {
342 mXmppConnectionService.syncRoster(account);
343 mXmppConnectionService.getAvatarService().clear(contact);
344 }
345 }
346 mXmppConnectionService.updateConversationUi();
347 mXmppConnectionService.updateAccountUi();
348 }
349
350 private boolean handleErrorMessage(final Account account, final MessagePacket packet) {
351 if (packet.getType() == MessagePacket.TYPE_ERROR) {
352 if (packet.fromServer(account)) {
353 final Pair<MessagePacket, Long> forwarded = packet.getForwardedMessagePacket("received", Namespace.CARBONS);
354 if (forwarded != null) {
355 return handleErrorMessage(account, forwarded.first);
356 }
357 }
358 final Jid from = packet.getFrom();
359 final String id = packet.getId();
360 if (from != null && id != null) {
361 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
362 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
363 mXmppConnectionService.getJingleConnectionManager()
364 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.FAILED);
365 return true;
366 }
367 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX)) {
368 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX.length());
369 final String message = extractErrorMessage(packet);
370 mXmppConnectionService.getJingleConnectionManager().failProceed(account, from, sessionId, message);
371 return true;
372 }
373 mXmppConnectionService.markMessage(account,
374 from.asBareJid(),
375 id,
376 Message.STATUS_SEND_FAILED,
377 extractErrorMessage(packet));
378 final Element error = packet.findChild("error");
379 final boolean pingWorthyError = error != null && (error.hasChild("not-acceptable") || error.hasChild("remote-server-timeout") || error.hasChild("remote-server-not-found"));
380 if (pingWorthyError) {
381 Conversation conversation = mXmppConnectionService.find(account, from);
382 if (conversation != null && conversation.getMode() == Conversational.MODE_MULTI) {
383 if (conversation.getMucOptions().online()) {
384 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received ping worthy error for seemingly online muc at " + from);
385 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
386 }
387 }
388 }
389 }
390 return true;
391 }
392 return false;
393 }
394
395 @Override
396 public void onMessagePacketReceived(Account account, MessagePacket original) {
397 if (handleErrorMessage(account, original)) {
398 return;
399 }
400 final MessagePacket packet;
401 Long timestamp = null;
402 boolean isCarbon = false;
403 String serverMsgId = null;
404 final Element fin = original.findChild("fin", MessageArchiveService.Version.MAM_0.namespace);
405 if (fin != null) {
406 mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin, original.getFrom());
407 return;
408 }
409 final Element result = MessageArchiveService.Version.findResult(original);
410 final String queryId = result == null ? null : result.getAttribute("queryid");
411 final MessageArchiveService.Query query = queryId == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(queryId);
412 final boolean offlineMessagesRetrieved = account.getXmppConnection().isOfflineMessagesRetrieved();
413 if (query != null && query.validFrom(original.getFrom())) {
414 final Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", query.version.namespace);
415 if (f == null) {
416 return;
417 }
418 timestamp = f.second;
419 packet = f.first;
420 serverMsgId = result.getAttribute("id");
421 query.incrementMessageCount();
422 if (handleErrorMessage(account, packet)) {
423 return;
424 }
425 } else if (query != null) {
426 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received mam result with invalid from (" + original.getFrom() + ") or queryId (" + queryId + ")");
427 return;
428 } else if (original.fromServer(account)) {
429 Pair<MessagePacket, Long> f;
430 f = original.getForwardedMessagePacket("received", Namespace.CARBONS);
431 f = f == null ? original.getForwardedMessagePacket("sent", Namespace.CARBONS) : f;
432 packet = f != null ? f.first : original;
433 if (handleErrorMessage(account, packet)) {
434 return;
435 }
436 timestamp = f != null ? f.second : null;
437 isCarbon = f != null;
438 } else {
439 packet = original;
440 }
441
442 if (timestamp == null) {
443 timestamp = AbstractParser.parseTimestamp(original, AbstractParser.parseTimestamp(packet));
444 }
445 final LocalizedContent body = packet.getBody();
446 final Element mucUserElement = packet.findChild("x", Namespace.MUC_USER);
447 final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
448 final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
449 final Element oob = packet.findChild("x", Namespace.OOB);
450 final String oobUrl = oob != null ? oob.findChildContent("url") : null;
451 final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
452 final Element axolotlEncrypted = packet.findChildEnsureSingle(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
453 int status;
454 final Jid counterpart;
455 final Jid to = packet.getTo();
456 final Jid from = packet.getFrom();
457 final Element originId = packet.findChild("origin-id", Namespace.STANZA_IDS);
458 final String remoteMsgId;
459 if (originId != null && originId.getAttribute("id") != null) {
460 remoteMsgId = originId.getAttribute("id");
461 } else {
462 remoteMsgId = packet.getId();
463 }
464 boolean notify = false;
465
466 if (from == null || !InvalidJid.isValid(from) || !InvalidJid.isValid(to)) {
467 Log.e(Config.LOGTAG, "encountered invalid message from='" + from + "' to='" + to + "'");
468 return;
469 }
470
471 boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
472 if (query != null && !query.muc() && isTypeGroupChat) {
473 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": received groupchat (" + from + ") message on regular MAM request. skipping");
474 return;
475 }
476 boolean isMucStatusMessage = InvalidJid.hasValidFrom(packet) && from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
477 boolean selfAddressed;
478 if (packet.fromAccount(account)) {
479 status = Message.STATUS_SEND;
480 selfAddressed = to == null || account.getJid().asBareJid().equals(to.asBareJid());
481 if (selfAddressed) {
482 counterpart = from;
483 } else {
484 counterpart = to;
485 }
486 } else {
487 status = Message.STATUS_RECEIVED;
488 counterpart = from;
489 selfAddressed = false;
490 }
491
492 final Invite invite = extractInvite(packet);
493 if (invite != null) {
494 if (invite.jid.asBareJid().equals(account.getJid().asBareJid())) {
495 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": ignore invite to "+invite.jid+" because it matches account");
496 } else if (isTypeGroupChat) {
497 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring invite to " + invite.jid + " because it was received as group chat");
498 } else if (invite.direct && (mucUserElement != null || invite.inviter == null || mXmppConnectionService.isMuc(account, invite.inviter))) {
499 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring direct invite to " + invite.jid + " because it was received in MUC");
500 } else {
501 invite.execute(account);
502 return;
503 }
504 }
505
506 if ((body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || oobUrl != null) && !isMucStatusMessage) {
507 final boolean conversationIsProbablyMuc = isTypeGroupChat || mucUserElement != null || account.getXmppConnection().getMucServersWithholdAccount().contains(counterpart.getDomain().toEscapedString());
508 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), conversationIsProbablyMuc, false, query, false);
509 final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
510
511 if (serverMsgId == null) {
512 serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
513 }
514
515
516 if (selfAddressed) {
517 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, Message.STATUS_SEND_RECEIVED, serverMsgId)) {
518 return;
519 }
520 status = Message.STATUS_RECEIVED;
521 if (remoteMsgId != null && conversation.findMessageWithRemoteId(remoteMsgId, counterpart) != null) {
522 return;
523 }
524 }
525
526 if (isTypeGroupChat) {
527 if (conversation.getMucOptions().isSelf(counterpart)) {
528 status = Message.STATUS_SEND_RECEIVED;
529 isCarbon = true; //not really carbon but received from another resource
530 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId, body)) {
531 return;
532 } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
533 if (body != null) {
534 Message message = conversation.findSentMessageWithBody(body.content);
535 if (message != null) {
536 mXmppConnectionService.markMessage(message, status);
537 return;
538 }
539 }
540 }
541 } else {
542 status = Message.STATUS_RECEIVED;
543 }
544 }
545 final Message message;
546 if (pgpEncrypted != null && Config.supportOpenPgp()) {
547 message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
548 } else if (axolotlEncrypted != null && Config.supportOmemo()) {
549 Jid origin;
550 Set<Jid> fallbacksBySourceId = Collections.emptySet();
551 if (conversationMultiMode) {
552 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
553 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
554 if (origin == null) {
555 try {
556 fallbacksBySourceId = account.getAxolotlService().findCounterpartsBySourceId(XmppAxolotlMessage.parseSourceId(axolotlEncrypted));
557 } catch (IllegalArgumentException e) {
558 //ignoring
559 }
560 }
561 if (origin == null && fallbacksBySourceId.size() == 0) {
562 Log.d(Config.LOGTAG, "axolotl message in anonymous conference received and no possible fallbacks");
563 return;
564 }
565 } else {
566 fallbacksBySourceId = Collections.emptySet();
567 origin = from;
568 }
569
570 final boolean liveMessage = query == null && !isTypeGroupChat && mucUserElement == null;
571 final boolean checkedForDuplicates = liveMessage || (serverMsgId != null && remoteMsgId != null && !conversation.possibleDuplicate(serverMsgId, remoteMsgId));
572
573 if (origin != null) {
574 message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status, checkedForDuplicates, query != null);
575 } else {
576 Message trial = null;
577 for (Jid fallback : fallbacksBySourceId) {
578 trial = parseAxolotlChat(axolotlEncrypted, fallback, conversation, status, checkedForDuplicates && fallbacksBySourceId.size() == 1, query != null);
579 if (trial != null) {
580 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": decoded muc message using fallback");
581 origin = fallback;
582 break;
583 }
584 }
585 message = trial;
586 }
587 if (message == null) {
588 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
589 mXmppConnectionService.updateConversationUi();
590 }
591 if (query != null && status == Message.STATUS_SEND && remoteMsgId != null) {
592 Message previouslySent = conversation.findSentMessageWithUuid(remoteMsgId);
593 if (previouslySent != null && previouslySent.getServerMsgId() == null && serverMsgId != null) {
594 previouslySent.setServerMsgId(serverMsgId);
595 mXmppConnectionService.databaseBackend.updateMessage(previouslySent, false);
596 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered previously sent OMEMO message without serverId. updating...");
597 }
598 }
599 return;
600 }
601 if (conversationMultiMode) {
602 message.setTrueCounterpart(origin);
603 }
604 } else if (body == null && oobUrl != null) {
605 message = new Message(conversation, oobUrl, Message.ENCRYPTION_NONE, status);
606 message.setOob(true);
607 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
608 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
609 }
610 } else {
611 message = new Message(conversation, body.content, Message.ENCRYPTION_NONE, status);
612 if (body.count > 1) {
613 message.setBodyLanguage(body.language);
614 }
615 }
616
617 message.setCounterpart(counterpart);
618 message.setRemoteMsgId(remoteMsgId);
619 message.setServerMsgId(serverMsgId);
620 message.setCarbon(isCarbon);
621 message.setTime(timestamp);
622 if (body != null && body.content != null && body.content.equals(oobUrl)) {
623 message.setOob(true);
624 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
625 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
626 }
627 }
628 message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
629 if (conversationMultiMode) {
630 message.setMucUser(conversation.getMucOptions().findUserByFullJid(counterpart));
631 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
632 Jid trueCounterpart;
633 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
634 trueCounterpart = message.getTrueCounterpart();
635 } else if (query != null && query.safeToExtractTrueCounterpart()) {
636 trueCounterpart = getTrueCounterpart(mucUserElement, fallback);
637 } else {
638 trueCounterpart = fallback;
639 }
640 if (trueCounterpart != null && isTypeGroupChat) {
641 if (trueCounterpart.asBareJid().equals(account.getJid().asBareJid())) {
642 status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
643 } else {
644 status = Message.STATUS_RECEIVED;
645 message.setCarbon(false);
646 }
647 }
648 message.setStatus(status);
649 message.setTrueCounterpart(trueCounterpart);
650 if (!isTypeGroupChat) {
651 message.setType(Message.TYPE_PRIVATE);
652 }
653 } else {
654 updateLastseen(account, from);
655 }
656
657 if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
658 final Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
659 counterpart,
660 message.getStatus() == Message.STATUS_RECEIVED,
661 message.isCarbon());
662 if (replacedMessage != null) {
663 final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
664 || replacedMessage.getFingerprint().equals(message.getFingerprint());
665 final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
666 && message.getTrueCounterpart() != null
667 && replacedMessage.getTrueCounterpart().asBareJid().equals(message.getTrueCounterpart().asBareJid());
668 final boolean mucUserMatches = query == null && replacedMessage.sameMucUser(message); //can not be checked when using mam
669 final boolean duplicate = conversation.hasDuplicateMessage(message);
670 if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode || mucUserMatches) && !duplicate) {
671 Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
672 synchronized (replacedMessage) {
673 final String uuid = replacedMessage.getUuid();
674 replacedMessage.setUuid(UUID.randomUUID().toString());
675 replacedMessage.setBody(message.getBody());
676 replacedMessage.putEdited(replacedMessage.getRemoteMsgId(), replacedMessage.getServerMsgId());
677 replacedMessage.setRemoteMsgId(remoteMsgId);
678 if (replacedMessage.getServerMsgId() == null || message.getServerMsgId() != null) {
679 replacedMessage.setServerMsgId(message.getServerMsgId());
680 }
681 replacedMessage.setEncryption(message.getEncryption());
682 if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
683 replacedMessage.markUnread();
684 }
685 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
686 mXmppConnectionService.updateMessage(replacedMessage, uuid);
687 if (mXmppConnectionService.confirmMessages()
688 && replacedMessage.getStatus() == Message.STATUS_RECEIVED
689 && (replacedMessage.trusted() || replacedMessage.isPrivateMessage()) //TODO do we really want to send receipts for all PMs?
690 && remoteMsgId != null
691 && !selfAddressed
692 && !isTypeGroupChat) {
693 processMessageReceipts(account, packet, remoteMsgId, query);
694 }
695 if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
696 conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
697 conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
698 }
699 }
700 mXmppConnectionService.getNotificationService().updateNotification();
701 return;
702 } else {
703 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received message correction but verification didn't check out");
704 }
705 }
706 }
707
708 long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate();
709 if (deletionDate != 0 && message.getTimeSent() < deletionDate) {
710 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping message from " + message.getCounterpart().toString() + " because it was sent prior to our deletion date");
711 return;
712 }
713
714 boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay", "urn:xmpp:delay"))
715 || message.isPrivateMessage()
716 || message.getServerMsgId() != null
717 || (query == null && mXmppConnectionService.getMessageArchiveService().isCatchupInProgress(conversation));
718 if (checkForDuplicates) {
719 final Message duplicate = conversation.findDuplicateMessage(message);
720 if (duplicate != null) {
721 final boolean serverMsgIdUpdated;
722 if (duplicate.getStatus() != Message.STATUS_RECEIVED
723 && duplicate.getUuid().equals(message.getRemoteMsgId())
724 && duplicate.getServerMsgId() == null
725 && message.getServerMsgId() != null) {
726 duplicate.setServerMsgId(message.getServerMsgId());
727 if (mXmppConnectionService.databaseBackend.updateMessage(duplicate, false)) {
728 serverMsgIdUpdated = true;
729 } else {
730 serverMsgIdUpdated = false;
731 Log.e(Config.LOGTAG, "failed to update message");
732 }
733 } else {
734 serverMsgIdUpdated = false;
735 }
736 Log.d(Config.LOGTAG, "skipping duplicate message with " + message.getCounterpart() + ". serverMsgIdUpdated=" + serverMsgIdUpdated);
737 return;
738 }
739 }
740
741 if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
742 conversation.prepend(query.getActualInThisQuery(), message);
743 } else {
744 conversation.add(message);
745 }
746 if (query != null) {
747 query.incrementActualMessageCount();
748 }
749
750 if (query == null || query.isCatchup()) { //either no mam or catchup
751 if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
752 mXmppConnectionService.markRead(conversation);
753 if (query == null) {
754 activateGracePeriod(account);
755 }
756 } else {
757 message.markUnread();
758 notify = true;
759 }
760 }
761
762 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
763 notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
764 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE || message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
765 notify = false;
766 }
767
768 if (query == null) {
769 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
770 mXmppConnectionService.updateConversationUi();
771 }
772
773 if (mXmppConnectionService.confirmMessages()
774 && message.getStatus() == Message.STATUS_RECEIVED
775 && (message.trusted() || message.isPrivateMessage())
776 && remoteMsgId != null
777 && !selfAddressed
778 && !isTypeGroupChat) {
779 processMessageReceipts(account, packet, remoteMsgId, query);
780 }
781
782 mXmppConnectionService.databaseBackend.createMessage(message);
783 final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
784 if (message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
785 manager.createNewDownloadConnection(message);
786 } else if (notify) {
787 if (query != null && query.isCatchup()) {
788 mXmppConnectionService.getNotificationService().pushFromBacklog(message);
789 } else {
790 mXmppConnectionService.getNotificationService().push(message);
791 }
792 }
793 } else if (!packet.hasChild("body")) { //no body
794
795 final Conversation conversation = mXmppConnectionService.find(account, from.asBareJid());
796 if (axolotlEncrypted != null) {
797 Jid origin;
798 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
799 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
800 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
801 if (origin == null) {
802 Log.d(Config.LOGTAG, "omemo key transport message in anonymous conference received");
803 return;
804 }
805 } else if (isTypeGroupChat) {
806 return;
807 } else {
808 origin = from;
809 }
810 try {
811 final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.asBareJid());
812 account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
813 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": omemo key transport message received from " + origin);
814 } catch (Exception e) {
815 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": invalid omemo key transport message received " + e.getMessage());
816 return;
817 }
818 }
819
820 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
821 mXmppConnectionService.updateConversationUi();
822 }
823
824 if (isTypeGroupChat) {
825 if (packet.hasChild("subject") && !packet.hasChild("thread")) { // We already know it has no body per above
826 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
827 conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
828 final LocalizedContent subject = packet.findInternationalizedChildContentInDefaultNamespace("subject");
829 if (subject != null && conversation.getMucOptions().setSubject(subject.content)) {
830 mXmppConnectionService.updateConversation(conversation);
831 }
832 mXmppConnectionService.updateConversationUi();
833 return;
834 }
835 }
836 }
837 if (conversation != null && mucUserElement != null && InvalidJid.hasValidFrom(packet) && from.isBareJid()) {
838 for (Element child : mucUserElement.getChildren()) {
839 if ("status".equals(child.getName())) {
840 try {
841 int code = Integer.parseInt(child.getAttribute("code"));
842 if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
843 mXmppConnectionService.fetchConferenceConfiguration(conversation);
844 break;
845 }
846 } catch (Exception e) {
847 //ignored
848 }
849 } else if ("item".equals(child.getName())) {
850 MucOptions.User user = AbstractParser.parseItem(conversation, child);
851 Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for "
852 + user.getRealJid() + " to " + user.getAffiliation() + " in "
853 + conversation.getJid().asBareJid());
854 if (!user.realJidMatchesAccount()) {
855 boolean isNew = conversation.getMucOptions().updateUser(user);
856 mXmppConnectionService.getAvatarService().clear(conversation);
857 mXmppConnectionService.updateMucRosterUi();
858 mXmppConnectionService.updateConversationUi();
859 Contact contact = user.getContact();
860 if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
861 Jid jid = user.getRealJid();
862 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
863 if (cryptoTargets.remove(user.getRealJid())) {
864 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
865 conversation.setAcceptedCryptoTargets(cryptoTargets);
866 mXmppConnectionService.updateConversation(conversation);
867 }
868 } else if (isNew
869 && user.getRealJid() != null
870 && conversation.getMucOptions().isPrivateAndNonAnonymous()
871 && (contact == null || !contact.mutualPresenceSubscription())
872 && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
873 account.getAxolotlService().fetchDeviceIds(user.getRealJid());
874 }
875 }
876 }
877 }
878 }
879 if (!isTypeGroupChat) {
880 for (Element child : packet.getChildren()) {
881 if (Namespace.JINGLE_MESSAGE.equals(child.getNamespace()) && JINGLE_MESSAGE_ELEMENT_NAMES.contains(child.getName())) {
882 final String action = child.getName();
883 final String sessionId = child.getAttribute("id");
884 if (sessionId == null) {
885 break;
886 }
887 if (query == null && offlineMessagesRetrieved) {
888 if (serverMsgId == null) {
889 serverMsgId = extractStanzaId(account, packet);
890 }
891 mXmppConnectionService
892 .getJingleConnectionManager()
893 .deliverMessage(
894 account,
895 packet.getTo(),
896 packet.getFrom(),
897 child,
898 remoteMsgId,
899 serverMsgId,
900 timestamp);
901 final Contact contact = account.getRoster().getContact(from);
902 if (mXmppConnectionService.confirmMessages()
903 && !contact.isSelf()
904 && remoteMsgId != null
905 && contact.showInContactList()) {
906 processMessageReceipts(account, packet, remoteMsgId, null);
907 }
908 } else if ((query != null && query.isCatchup()) || !offlineMessagesRetrieved) {
909 if ("propose".equals(action)) {
910 final Element description = child.findChild("description");
911 final String namespace =
912 description == null ? null : description.getNamespace();
913 if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
914 final Conversation c =
915 mXmppConnectionService.findOrCreateConversation(
916 account, counterpart.asBareJid(), false, false);
917 final Message preExistingMessage =
918 c.findRtpSession(sessionId, status);
919 if (preExistingMessage != null) {
920 preExistingMessage.setServerMsgId(serverMsgId);
921 mXmppConnectionService.updateMessage(preExistingMessage);
922 break;
923 }
924 final Message message =
925 new Message(
926 c, status, Message.TYPE_RTP_SESSION, sessionId);
927 message.setServerMsgId(serverMsgId);
928 message.setTime(timestamp);
929 message.setBody(new RtpSessionStatus(false, 0).toString());
930 c.add(message);
931 mXmppConnectionService.databaseBackend.createMessage(message);
932 }
933 } else if ("proceed".equals(action)) {
934 // status needs to be flipped to find the original propose
935 final Conversation c =
936 mXmppConnectionService.findOrCreateConversation(
937 account, counterpart.asBareJid(), false, false);
938 final int s =
939 packet.fromAccount(account)
940 ? Message.STATUS_RECEIVED
941 : Message.STATUS_SEND;
942 final Message message = c.findRtpSession(sessionId, s);
943 if (message != null) {
944 message.setBody(new RtpSessionStatus(true, 0).toString());
945 if (serverMsgId != null) {
946 message.setServerMsgId(serverMsgId);
947 }
948 message.setTime(timestamp);
949 mXmppConnectionService.updateMessage(message, true);
950 } else {
951 Log.d(
952 Config.LOGTAG,
953 "unable to find original rtp session message for received propose");
954 }
955
956 } else if ("finish".equals(action)) {
957 Log.d(
958 Config.LOGTAG,
959 "received JMI 'finish' during MAM catch-up. Can be used to update success/failure and duration");
960 }
961 } else {
962 //MAM reloads (non catchups
963 if ("propose".equals(action)) {
964 final Element description = child.findChild("description");
965 final String namespace = description == null ? null : description.getNamespace();
966 if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
967 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
968 final Message preExistingMessage = c.findRtpSession(sessionId, status);
969 if (preExistingMessage != null) {
970 preExistingMessage.setServerMsgId(serverMsgId);
971 mXmppConnectionService.updateMessage(preExistingMessage);
972 break;
973 }
974 final Message message = new Message(
975 c,
976 status,
977 Message.TYPE_RTP_SESSION,
978 sessionId
979 );
980 message.setServerMsgId(serverMsgId);
981 message.setTime(timestamp);
982 message.setBody(new RtpSessionStatus(true, 0).toString());
983 if (query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
984 c.prepend(query.getActualInThisQuery(), message);
985 } else {
986 c.add(message);
987 }
988 query.incrementActualMessageCount();
989 mXmppConnectionService.databaseBackend.createMessage(message);
990 }
991 }
992 }
993 break;
994 }
995 }
996 }
997 }
998
999 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
1000 if (received == null) {
1001 received = packet.findChild("received", "urn:xmpp:receipts");
1002 }
1003 if (received != null) {
1004 String id = received.getAttribute("id");
1005 if (packet.fromAccount(account)) {
1006 if (query != null && id != null && packet.getTo() != null) {
1007 query.removePendingReceiptRequest(new ReceiptRequest(packet.getTo(), id));
1008 }
1009 } else if (id != null) {
1010 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
1011 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
1012 mXmppConnectionService.getJingleConnectionManager()
1013 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.DISCOVERED);
1014 } else {
1015 mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_RECEIVED);
1016 }
1017 }
1018 }
1019 final Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
1020 if (displayed != null) {
1021 final String id = displayed.getAttribute("id");
1022 final Jid sender = InvalidJid.getNullForInvalid(displayed.getAttributeAsJid("sender"));
1023 if (packet.fromAccount(account) && !selfAddressed) {
1024 final Conversation c =
1025 mXmppConnectionService.find(account, counterpart.asBareJid());
1026 final Message message =
1027 (c == null || id == null) ? null : c.findReceivedWithRemoteId(id);
1028 if (message != null && (query == null || query.isCatchup())) {
1029 mXmppConnectionService.markReadUpTo(c, message);
1030 }
1031 if (query == null) {
1032 activateGracePeriod(account);
1033 }
1034 } else if (isTypeGroupChat) {
1035 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1036 final Message message;
1037 if (conversation != null && id != null) {
1038 if (sender != null) {
1039 message = conversation.findMessageWithRemoteId(id, sender);
1040 } else {
1041 message = conversation.findMessageWithServerMsgId(id);
1042 }
1043 } else {
1044 message = null;
1045 }
1046 if (message != null) {
1047 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
1048 final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
1049 final boolean trueJidMatchesAccount = account.getJid().asBareJid().equals(trueJid == null ? null : trueJid.asBareJid());
1050 if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
1051 if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
1052 mXmppConnectionService.markReadUpTo(conversation, message);
1053 }
1054 } else if (!counterpart.isBareJid() && trueJid != null) {
1055 final ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
1056 if (message.addReadByMarker(readByMarker)) {
1057 final var mucOptions = conversation.getMucOptions();
1058 final var everyone = ImmutableSet.copyOf(mucOptions.getMembers(false));
1059 final var readyBy = message.getReadyByTrue();
1060 final var mStatus = message.getStatus();
1061 if (mucOptions.isPrivateAndNonAnonymous()
1062 && (mStatus == Message.STATUS_SEND_RECEIVED
1063 || mStatus == Message.STATUS_SEND)
1064 && readyBy.containsAll(everyone)) {
1065 message.setStatus(Message.STATUS_SEND_DISPLAYED);
1066 }
1067 mXmppConnectionService.updateMessage(message, false);
1068 }
1069 }
1070 }
1071 } else {
1072 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_DISPLAYED);
1073 Message message = displayedMessage == null ? null : displayedMessage.prev();
1074 while (message != null
1075 && message.getStatus() == Message.STATUS_SEND_RECEIVED
1076 && message.getTimeSent() < displayedMessage.getTimeSent()) {
1077 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
1078 message = message.prev();
1079 }
1080 if (displayedMessage != null && selfAddressed) {
1081 dismissNotification(account, counterpart, query, id);
1082 }
1083 }
1084 }
1085
1086 final Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
1087 if (event != null && InvalidJid.hasValidFrom(original) && original.getFrom().isBareJid()) {
1088 if (event.hasChild("items")) {
1089 parseEvent(event, original.getFrom(), account);
1090 } else if (event.hasChild("delete")) {
1091 parseDeleteEvent(event, original.getFrom(), account);
1092 } else if (event.hasChild("purge")) {
1093 parsePurgeEvent(event, original.getFrom(), account);
1094 }
1095 }
1096
1097 final String nick = packet.findChildContent("nick", Namespace.NICK);
1098 if (nick != null && InvalidJid.hasValidFrom(original)) {
1099 if (mXmppConnectionService.isMuc(account, from)) {
1100 return;
1101 }
1102 final Contact contact = account.getRoster().getContact(from);
1103 if (contact.setPresenceName(nick)) {
1104 mXmppConnectionService.syncRoster(account);
1105 mXmppConnectionService.getAvatarService().clear(contact);
1106 }
1107 }
1108 }
1109
1110 private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query, final String id) {
1111 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1112 if (conversation != null && (query == null || query.isCatchup())) {
1113 final String displayableId = conversation.findMostRecentRemoteDisplayableId();
1114 if (displayableId != null && displayableId.equals(id)) {
1115 mXmppConnectionService.markRead(conversation);
1116 } else {
1117 Log.w(Config.LOGTAG, account.getJid().asBareJid() + ": received dismissing display marker that did not match our last id in that conversation");
1118 }
1119 }
1120 }
1121
1122 private void processMessageReceipts(final Account account, final MessagePacket packet, final String remoteMsgId, MessageArchiveService.Query query) {
1123 final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
1124 final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
1125 if (query == null) {
1126 final ArrayList<String> receiptsNamespaces = new ArrayList<>();
1127 if (markable) {
1128 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
1129 }
1130 if (request) {
1131 receiptsNamespaces.add("urn:xmpp:receipts");
1132 }
1133 if (receiptsNamespaces.size() > 0) {
1134 final MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
1135 packet.getFrom(),
1136 remoteMsgId,
1137 receiptsNamespaces,
1138 packet.getType());
1139 mXmppConnectionService.sendMessagePacket(account, receipt);
1140 }
1141 } else if (query.isCatchup()) {
1142 if (request) {
1143 query.addPendingReceiptRequest(new ReceiptRequest(packet.getFrom(), remoteMsgId));
1144 }
1145 }
1146 }
1147
1148 private void activateGracePeriod(Account account) {
1149 long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
1150 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
1151 account.activateGracePeriod(duration);
1152 }
1153
1154 private class Invite {
1155 final Jid jid;
1156 final String password;
1157 final boolean direct;
1158 final Jid inviter;
1159
1160 Invite(Jid jid, String password, boolean direct, Jid inviter) {
1161 this.jid = jid;
1162 this.password = password;
1163 this.direct = direct;
1164 this.inviter = inviter;
1165 }
1166
1167 public boolean execute(final Account account) {
1168 if (this.jid == null) {
1169 return false;
1170 }
1171 final Contact contact =
1172 this.inviter != null ? account.getRoster().getContact(this.inviter) : null;
1173 if (contact != null && contact.isBlocked()) {
1174 Log.d(
1175 Config.LOGTAG,
1176 account.getJid().asBareJid()
1177 + ": ignore invite from "
1178 + contact.getJid()
1179 + " because contact is blocked");
1180 return false;
1181 }
1182 final AppSettings appSettings = new AppSettings(mXmppConnectionService);
1183 if ((contact != null && contact.showInContactList())
1184 || appSettings.isAcceptInvitesFromStrangers()) {
1185 final Conversation conversation =
1186 mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
1187 if (conversation.getMucOptions().online()) {
1188 Log.d(
1189 Config.LOGTAG,
1190 account.getJid().asBareJid()
1191 + ": received invite to "
1192 + jid
1193 + " but muc is considered to be online");
1194 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
1195 } else {
1196 conversation.getMucOptions().setPassword(password);
1197 mXmppConnectionService.databaseBackend.updateConversation(conversation);
1198 mXmppConnectionService.joinMuc(
1199 conversation, contact != null && contact.showInContactList());
1200 mXmppConnectionService.updateConversationUi();
1201 }
1202 return true;
1203 } else {
1204 Log.d(
1205 Config.LOGTAG,
1206 account.getJid().asBareJid()
1207 + ": ignoring invite from "
1208 + this.inviter
1209 + " because we are not accepting invites from strangers. direct="
1210 + direct);
1211 return false;
1212 }
1213 }
1214 }
1215}