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