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