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.HashSet;
20import java.util.LinkedHashSet;
21import java.util.List;
22import java.util.Locale;
23import java.util.Map;
24import java.util.Set;
25import java.util.UUID;
26import java.util.function.Consumer;
27import java.util.stream.Collectors;
28
29import io.ipfs.cid.Cid;
30
31import eu.siacs.conversations.AppSettings;
32import eu.siacs.conversations.Config;
33import eu.siacs.conversations.R;
34import eu.siacs.conversations.crypto.axolotl.AxolotlService;
35import eu.siacs.conversations.crypto.axolotl.BrokenSessionException;
36import eu.siacs.conversations.crypto.axolotl.NotEncryptedForThisDeviceException;
37import eu.siacs.conversations.crypto.axolotl.OutdatedSenderException;
38import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
39import eu.siacs.conversations.entities.Account;
40import eu.siacs.conversations.entities.Bookmark;
41import eu.siacs.conversations.entities.Contact;
42import eu.siacs.conversations.entities.Conversation;
43import eu.siacs.conversations.entities.Conversational;
44import eu.siacs.conversations.entities.DownloadableFile;
45import eu.siacs.conversations.entities.Message;
46import eu.siacs.conversations.entities.MucOptions;
47import eu.siacs.conversations.entities.Reaction;
48import eu.siacs.conversations.entities.ReadByMarker;
49import eu.siacs.conversations.entities.ReceiptRequest;
50import eu.siacs.conversations.entities.RtpSessionStatus;
51import eu.siacs.conversations.http.HttpConnectionManager;
52import eu.siacs.conversations.services.MessageArchiveService;
53import eu.siacs.conversations.services.QuickConversationsService;
54import eu.siacs.conversations.services.XmppConnectionService;
55import eu.siacs.conversations.utils.CryptoHelper;
56import eu.siacs.conversations.utils.Emoticons;
57import eu.siacs.conversations.xml.Element;
58import eu.siacs.conversations.xml.LocalizedContent;
59import eu.siacs.conversations.xml.Namespace;
60import eu.siacs.conversations.xmpp.InvalidJid;
61import eu.siacs.conversations.xmpp.Jid;
62import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
63import eu.siacs.conversations.xmpp.chatstate.ChatState;
64import eu.siacs.conversations.xmpp.forms.Data;
65import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
66import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
67import eu.siacs.conversations.xmpp.pep.Avatar;
68import im.conversations.android.xmpp.model.Extension;
69import im.conversations.android.xmpp.model.carbons.Received;
70import im.conversations.android.xmpp.model.carbons.Sent;
71import im.conversations.android.xmpp.model.forward.Forwarded;
72import im.conversations.android.xmpp.model.occupant.OccupantId;
73import im.conversations.android.xmpp.model.reactions.Reactions;
74
75public class MessageParser extends AbstractParser implements Consumer<im.conversations.android.xmpp.model.stanza.Message> {
76
77 private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
78
79 private static final List<String> JINGLE_MESSAGE_ELEMENT_NAMES =
80 Arrays.asList("accept", "propose", "proceed", "reject", "retract", "ringing", "finish");
81
82 public MessageParser(final XmppConnectionService service, final Account account) {
83 super(service, account);
84 }
85
86 private static String extractStanzaId(Element packet, boolean isTypeGroupChat, Conversation conversation) {
87 final Jid by;
88 final boolean safeToExtract;
89 if (isTypeGroupChat) {
90 by = conversation.getJid().asBareJid();
91 safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
92 } else {
93 Account account = conversation.getAccount();
94 by = account.getJid().asBareJid();
95 safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
96 }
97 return safeToExtract ? extractStanzaId(packet, by) : null;
98 }
99
100 private static String extractStanzaId(Account account, Element packet) {
101 final boolean safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
102 return safeToExtract ? extractStanzaId(packet, account.getJid().asBareJid()) : null;
103 }
104
105 private static String extractStanzaId(Element packet, Jid by) {
106 for (Element child : packet.getChildren()) {
107 if (child.getName().equals("stanza-id")
108 && Namespace.STANZA_IDS.equals(child.getNamespace())
109 && by.equals(InvalidJid.getNullForInvalid(child.getAttributeAsJid("by")))) {
110 return child.getAttribute("id");
111 }
112 }
113 return null;
114 }
115
116 private static Jid getTrueCounterpart(Element mucUserElement, Jid fallback) {
117 final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
118 Jid result = item == null ? null : InvalidJid.getNullForInvalid(item.getAttributeAsJid("jid"));
119 return result != null ? result : fallback;
120 }
121
122 private boolean extractChatState(Conversation c, final boolean isTypeGroupChat, final im.conversations.android.xmpp.model.stanza.Message packet) {
123 ChatState state = ChatState.parse(packet);
124 if (state != null && c != null) {
125 final Account account = c.getAccount();
126 final Jid from = packet.getFrom();
127 if (from.asBareJid().equals(account.getJid().asBareJid())) {
128 c.setOutgoingChatState(state);
129 if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
130 if (c.getContact().isSelf()) {
131 return false;
132 }
133 mXmppConnectionService.markRead(c);
134 activateGracePeriod(account);
135 }
136 return false;
137 } else {
138 if (isTypeGroupChat) {
139 MucOptions.User user = c.getMucOptions().findUserByFullJid(from);
140 if (user != null) {
141 return user.setChatState(state);
142 } else {
143 return false;
144 }
145 } else {
146 return c.setIncomingChatState(state);
147 }
148 }
149 }
150 return false;
151 }
152
153 private Message parseAxolotlChat(Element axolotlMessage, Jid from, Conversation conversation, int status, final boolean checkedForDuplicates, boolean postpone) {
154 final AxolotlService service = conversation.getAccount().getAxolotlService();
155 final XmppAxolotlMessage xmppAxolotlMessage;
156 try {
157 xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.asBareJid());
158 } catch (Exception e) {
159 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": invalid omemo message received " + e.getMessage());
160 return null;
161 }
162 if (xmppAxolotlMessage.hasPayload()) {
163 final XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage;
164 try {
165 plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage, postpone);
166 } catch (BrokenSessionException e) {
167 if (checkedForDuplicates) {
168 if (service.trustedOrPreviouslyResponded(from.asBareJid())) {
169 service.reportBrokenSessionException(e, postpone);
170 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
171 } else {
172 Log.d(Config.LOGTAG, "ignoring broken session exception because contact was not trusted");
173 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
174 }
175 } else {
176 Log.d(Config.LOGTAG, "ignoring broken session exception because checkForDuplicates failed");
177 return null;
178 }
179 } catch (NotEncryptedForThisDeviceException e) {
180 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE, status);
181 } catch (OutdatedSenderException e) {
182 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
183 }
184 if (plaintextMessage != null) {
185 Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
186 finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
187 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount()) + " Received Message with session fingerprint: " + plaintextMessage.getFingerprint());
188 return finishedMessage;
189 }
190 } else {
191 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": received OMEMO key transport message");
192 service.processReceivingKeyTransportMessage(xmppAxolotlMessage, postpone);
193 }
194 return null;
195 }
196
197 private Invite extractInvite(final Element message) {
198 final Element mucUser = message.findChild("x", Namespace.MUC_USER);
199 if (mucUser != null) {
200 final Element invite = mucUser.findChild("invite");
201 if (invite != null) {
202 final String password = mucUser.findChildContent("password");
203 final Jid from = InvalidJid.getNullForInvalid(invite.getAttributeAsJid("from"));
204 final Jid to = InvalidJid.getNullForInvalid(invite.getAttributeAsJid("to"));
205 if (to != null && from == null) {
206 Log.d(Config.LOGTAG,"do not parse outgoing mediated invite "+message);
207 return null;
208 }
209 final Jid room = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
210 if (room == null) {
211 return null;
212 }
213 return new Invite(room, password, false, from);
214 }
215 }
216 final Element conference = message.findChild("x", "jabber:x:conference");
217 if (conference != null) {
218 Jid from = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
219 Jid room = InvalidJid.getNullForInvalid(conference.getAttributeAsJid("jid"));
220 if (room == null) {
221 return null;
222 }
223 return new Invite(room, conference.getAttribute("password"), true, from);
224 }
225 return null;
226 }
227
228 private void parseEvent(final Element event, final Jid from, final Account account) {
229 final Element items = event.findChild("items");
230 final String node = items == null ? null : items.getAttribute("node");
231 if ("urn:xmpp:avatar:metadata".equals(node)) {
232 Avatar avatar = Avatar.parseMetadata(items);
233 if (avatar != null) {
234 avatar.owner = from.asBareJid();
235 if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
236 if (account.getJid().asBareJid().equals(from)) {
237 if (account.setAvatar(avatar.getFilename())) {
238 mXmppConnectionService.databaseBackend.updateAccount(account);
239 mXmppConnectionService.notifyAccountAvatarHasChanged(account);
240 }
241 mXmppConnectionService.getAvatarService().clear(account);
242 mXmppConnectionService.updateConversationUi();
243 mXmppConnectionService.updateAccountUi();
244 } else {
245 final Contact contact = account.getRoster().getContact(from);
246 contact.setAvatar(avatar);
247 mXmppConnectionService.syncRoster(account);
248 mXmppConnectionService.getAvatarService().clear(contact);
249 mXmppConnectionService.updateConversationUi();
250 mXmppConnectionService.updateRosterUi(XmppConnectionService.UpdateRosterReason.AVATAR);
251 }
252 } else if (mXmppConnectionService.isDataSaverDisabled()) {
253 mXmppConnectionService.fetchAvatar(account, avatar);
254 }
255 }
256 } else if (Namespace.NICK.equals(node)) {
257 final Element i = items.findChild("item");
258 final String nick = i == null ? null : i.findChildContent("nick", Namespace.NICK);
259 if (nick != null) {
260 setNick(account, from, nick);
261 }
262 } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
263 Element item = items.findChild("item");
264 final Set<Integer> deviceIds = IqParser.deviceIds(item);
265 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received PEP device list " + deviceIds + " update from " + from + ", processing... ");
266 final AxolotlService axolotlService = account.getAxolotlService();
267 axolotlService.registerDevices(from, deviceIds);
268 } else if (Namespace.BOOKMARKS.equals(node) && account.getJid().asBareJid().equals(from)) {
269 final var connection = account.getXmppConnection();
270 if (connection.getFeatures().bookmarksConversion()) {
271 if (connection.getFeatures().bookmarks2()) {
272 Log.w(
273 Config.LOGTAG,
274 account.getJid().asBareJid()
275 + ": received storage:bookmark notification even though we opted into bookmarks:1");
276 }
277 final Element i = items.findChild("item");
278 final Element storage =
279 i == null ? null : i.findChild("storage", Namespace.BOOKMARKS);
280 final Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
281 mXmppConnectionService.processBookmarksInitial(account, bookmarks, true);
282 Log.d(
283 Config.LOGTAG,
284 account.getJid().asBareJid() + ": processing bookmark PEP event");
285 } else {
286 Log.d(
287 Config.LOGTAG,
288 account.getJid().asBareJid()
289 + ": ignoring bookmark PEP event because bookmark conversion was not detected");
290 }
291 } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
292 final Element item = items.findChild("item");
293 final Element retract = items.findChild("retract");
294 if (item != null) {
295 final Bookmark bookmark = Bookmark.parseFromItem(item, account);
296 if (bookmark != null) {
297 account.putBookmark(bookmark);
298 mXmppConnectionService.processModifiedBookmark(bookmark);
299 mXmppConnectionService.updateConversationUi();
300 }
301 }
302 if (retract != null) {
303 final Jid id = InvalidJid.getNullForInvalid(retract.getAttributeAsJid("id"));
304 if (id != null) {
305 account.removeBookmark(id);
306 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmark for " + id);
307 mXmppConnectionService.processDeletedBookmark(account, id);
308 mXmppConnectionService.updateConversationUi();
309 }
310 }
311 } else if (Config.MESSAGE_DISPLAYED_SYNCHRONIZATION
312 && Namespace.MDS_DISPLAYED.equals(node)
313 && account.getJid().asBareJid().equals(from)) {
314 final Element item = items.findChild("item");
315 mXmppConnectionService.processMdsItem(account, item);
316 } else {
317 Log.d(
318 Config.LOGTAG,
319 account.getJid().asBareJid()
320 + " received pubsub notification for node="
321 + node);
322 }
323 }
324
325 private void parseDeleteEvent(final Element event, final Jid from, final Account account) {
326 final Element delete = event.findChild("delete");
327 final String node = delete == null ? null : delete.getAttribute("node");
328 if (Namespace.NICK.equals(node)) {
329 Log.d(Config.LOGTAG, "parsing nick delete event from " + from);
330 setNick(account, from, null);
331 } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
332 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmarks node");
333 deleteAllBookmarks(account);
334 } else if (Namespace.AVATAR_METADATA.equals(node) && account.getJid().asBareJid().equals(from)) {
335 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": deleted avatar metadata node");
336 }
337 }
338
339 private void parsePurgeEvent(final Element event, final Jid from, final Account account) {
340 final Element purge = event.findChild("purge");
341 final String node = purge == null ? null : purge.getAttribute("node");
342 if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
343 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": purged bookmarks");
344 deleteAllBookmarks(account);
345 }
346 }
347
348 private void deleteAllBookmarks(final Account account) {
349 final var previous = account.getBookmarkedJids();
350 account.setBookmarks(Collections.emptyMap());
351 mXmppConnectionService.processDeletedBookmarks(account, previous);
352 }
353
354 private void setNick(Account account, Jid user, String nick) {
355 if (user.asBareJid().equals(account.getJid().asBareJid())) {
356 account.setDisplayName(nick);
357 if (QuickConversationsService.isQuicksy()) {
358 mXmppConnectionService.getAvatarService().clear(account);
359 }
360 } else {
361 Contact contact = account.getRoster().getContact(user);
362 if (contact.setPresenceName(nick)) {
363 mXmppConnectionService.syncRoster(account);
364 mXmppConnectionService.getAvatarService().clear(contact);
365 }
366 }
367 mXmppConnectionService.updateConversationUi();
368 mXmppConnectionService.updateAccountUi();
369 }
370
371 private boolean handleErrorMessage(final Account account, final im.conversations.android.xmpp.model.stanza.Message packet) {
372 if (packet.getType() == im.conversations.android.xmpp.model.stanza.Message.Type.ERROR) {
373 if (packet.fromServer(account)) {
374 final var forwarded = getForwardedMessagePacket(packet,"received", Namespace.CARBONS);
375 if (forwarded != null) {
376 return handleErrorMessage(account, forwarded.first);
377 }
378 }
379 final Jid from = packet.getFrom();
380 final String id = packet.getId();
381 if (from != null && id != null) {
382 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
383 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
384 mXmppConnectionService.getJingleConnectionManager()
385 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.FAILED);
386 return true;
387 }
388 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX)) {
389 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX.length());
390 final String message = extractErrorMessage(packet);
391 mXmppConnectionService.getJingleConnectionManager().failProceed(account, from, sessionId, message);
392 return true;
393 }
394 mXmppConnectionService.markMessage(account,
395 from.asBareJid(),
396 id,
397 Message.STATUS_SEND_FAILED,
398 extractErrorMessage(packet));
399 final Element error = packet.findChild("error");
400 final boolean pingWorthyError = error != null && (error.hasChild("not-acceptable") || error.hasChild("remote-server-timeout") || error.hasChild("remote-server-not-found"));
401 if (pingWorthyError) {
402 Conversation conversation = mXmppConnectionService.find(account, from);
403 if (conversation != null && conversation.getMode() == Conversational.MODE_MULTI) {
404 if (conversation.getMucOptions().online()) {
405 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received ping worthy error for seemingly online muc at " + from);
406 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
407 }
408 }
409 }
410 }
411 return true;
412 }
413 return false;
414 }
415
416 @Override
417 public void accept(final im.conversations.android.xmpp.model.stanza.Message original) {
418 if (handleErrorMessage(account, original)) {
419 return;
420 }
421 final im.conversations.android.xmpp.model.stanza.Message packet;
422 Long timestamp = null;
423 boolean isCarbon = false;
424 String serverMsgId = null;
425 final Element fin = original.findChild("fin", MessageArchiveService.Version.MAM_0.namespace);
426 if (fin != null) {
427 mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin, original.getFrom());
428 return;
429 }
430 final Element result = MessageArchiveService.Version.findResult(original);
431 final String queryId = result == null ? null : result.getAttribute("queryid");
432 final MessageArchiveService.Query query = queryId == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(queryId);
433 final boolean offlineMessagesRetrieved = account.getXmppConnection().isOfflineMessagesRetrieved();
434 if (query != null && query.validFrom(original.getFrom())) {
435 final var f = getForwardedMessagePacket(original,"result", query.version.namespace);
436 if (f == null) {
437 return;
438 }
439 timestamp = f.second;
440 packet = f.first;
441 serverMsgId = result.getAttribute("id");
442 query.incrementMessageCount();
443 if (handleErrorMessage(account, packet)) {
444 return;
445 }
446 final var contact = packet.getFrom() == null || packet.getFrom() instanceof InvalidJid ? null : account.getRoster().getContact(packet.getFrom());
447 if (contact != null && contact.isBlocked()) {
448 Log.d(Config.LOGTAG, "Got MAM result from blocked contact, ignoring...");
449 return;
450 }
451 } else if (query != null) {
452 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received mam result with invalid from (" + original.getFrom() + ") or queryId (" + queryId + ")");
453 return;
454 } else if (original.fromServer(account)
455 && original.getType() != im.conversations.android.xmpp.model.stanza.Message.Type.GROUPCHAT) {
456 Pair<im.conversations.android.xmpp.model.stanza.Message, Long> f;
457 f = getForwardedMessagePacket(original, Received.class);
458 f = f == null ? getForwardedMessagePacket(original, Sent.class) : f;
459 packet = f != null ? f.first : original;
460 if (handleErrorMessage(account, packet)) {
461 return;
462 }
463 timestamp = f != null ? f.second : null;
464 isCarbon = f != null;
465 } else {
466 packet = original;
467 }
468
469 if (timestamp == null) {
470 timestamp = AbstractParser.parseTimestamp(original, AbstractParser.parseTimestamp(packet));
471 }
472 final Element mucUserElement = packet.findChild("x", Namespace.MUC_USER);
473 final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
474 Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
475 Set<Message.FileParams> attachments = new LinkedHashSet<>();
476 for (Element child : packet.getChildren()) {
477 // SIMS first so they get preference in the set
478 if (child.getName().equals("reference") && child.getNamespace().equals("urn:xmpp:reference:0")) {
479 if (child.findChild("media-sharing", "urn:xmpp:sims:1") != null) {
480 attachments.add(new Message.FileParams(child));
481 }
482 }
483 }
484 for (Element child : packet.getChildren()) {
485 if (child.getName().equals("x") && child.getNamespace().equals(Namespace.OOB)) {
486 attachments.add(new Message.FileParams(child));
487 }
488 }
489 String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
490 if (replacementId == null) {
491 final Element fasten = packet.findChild("apply-to", "urn:xmpp:fasten:0");
492 if (fasten != null) {
493 replaceElement = fasten.findChild("retract", "urn:xmpp:message-retract:0");
494 if (replaceElement == null) replaceElement = fasten.findChild("moderated", "urn:xmpp:message-moderate:0");
495 }
496 if (replaceElement == null) replaceElement = packet.findChild("retract", "urn:xmpp:message-retract:1");
497 if (replaceElement == null) replaceElement = packet.findChild("moderate", "urn:xmpp:message-moderate:1");
498 if (replaceElement != null) {
499 var reason = replaceElement.findChildContent("reason", "urn:xmpp:message-moderate:0");
500 if (reason == null) reason = replaceElement.findChildContent("reason", "urn:xmpp:message-moderate:1");
501 replacementId = (fasten == null ? replaceElement : fasten).getAttribute("id");
502 packet.setBody(reason == null ? "" : reason);
503 }
504 }
505 LocalizedContent body = packet.getBody();
506
507 final var reactions = packet.getExtension(Reactions.class);
508 final Element axolotlEncrypted = packet.findChildEnsureSingle(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
509 int status;
510 final Jid counterpart;
511 final Jid to = packet.getTo();
512 final Jid from = packet.getFrom();
513 final Element originId = packet.findChild("origin-id", Namespace.STANZA_IDS);
514 final String remoteMsgId;
515 if (originId != null && originId.getAttribute("id") != null) {
516 remoteMsgId = originId.getAttribute("id");
517 } else {
518 remoteMsgId = packet.getId();
519 }
520 boolean notify = false;
521
522 Element html = packet.findChild("html", "http://jabber.org/protocol/xhtml-im");
523 if (html != null && html.findChild("body", "http://www.w3.org/1999/xhtml") == null) {
524 html = null;
525 }
526
527 if (from == null || !InvalidJid.isValid(from) || !InvalidJid.isValid(to)) {
528 Log.e(Config.LOGTAG, "encountered invalid message from='" + from + "' to='" + to + "'");
529 return;
530 }
531
532 boolean isTypeGroupChat = packet.getType() == im.conversations.android.xmpp.model.stanza.Message.Type.GROUPCHAT;
533 if (query != null && !query.muc() && isTypeGroupChat) {
534 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": received groupchat (" + from + ") message on regular MAM request. skipping");
535 return;
536 }
537 boolean isMucStatusMessage = InvalidJid.hasValidFrom(packet) && from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
538 boolean selfAddressed;
539 if (packet.fromAccount(account)) {
540 status = Message.STATUS_SEND;
541 selfAddressed = to == null || account.getJid().asBareJid().equals(to.asBareJid());
542 if (selfAddressed) {
543 counterpart = from;
544 } else {
545 counterpart = to != null ? to : account.getJid();
546 }
547 } else {
548 status = Message.STATUS_RECEIVED;
549 counterpart = from;
550 selfAddressed = false;
551 }
552
553 final Invite invite = extractInvite(packet);
554 if (invite != null) {
555 if (invite.jid.asBareJid().equals(account.getJid().asBareJid())) {
556 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": ignore invite to "+invite.jid+" because it matches account");
557 } else if (isTypeGroupChat) {
558 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring invite to " + invite.jid + " because it was received as group chat");
559 } else if (invite.direct && (mucUserElement != null || invite.inviter == null || mXmppConnectionService.isMuc(account, invite.inviter))) {
560 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring direct invite to " + invite.jid + " because it was received in MUC");
561 } else {
562 invite.execute(account);
563 return;
564 }
565 }
566
567 final boolean conversationIsProbablyMuc = isTypeGroupChat || mucUserElement != null || account.getXmppConnection().getMucServersWithholdAccount().contains(counterpart.getDomain().toEscapedString());
568 final Element webxdc = packet.findChild("x", "urn:xmpp:webxdc:0");
569 final Element thread = packet.findChild("thread");
570 if (webxdc != null && thread != null) {
571 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), conversationIsProbablyMuc, false, query, false);
572 Jid webxdcSender = counterpart.asBareJid();
573 if (conversation.getMode() == Conversation.MODE_MULTI) {
574 if(conversation.getMucOptions().nonanonymous()) {
575 webxdcSender = conversation.getMucOptions().getTrueCounterpart(counterpart);
576 } else {
577 webxdcSender = counterpart;
578 }
579 }
580 final var document = webxdc.findChildContent("document", "urn:xmpp:webxdc:0");
581 final var summary = webxdc.findChildContent("summary", "urn:xmpp:webxdc:0");
582 final var payload = webxdc.findChildContent("json", "urn:xmpp:json:0");
583 if (document != null || summary != null || payload != null) {
584 mXmppConnectionService.insertWebxdcUpdate(new WebxdcUpdate(
585 conversation,
586 remoteMsgId,
587 counterpart,
588 thread,
589 body == null ? null : body.content,
590 document,
591 summary,
592 payload
593 ));
594 }
595
596 final var realtime = webxdc.findChildContent("data", "urn:xmpp:webxdc:0");
597 if (realtime != null) conversation.webxdcRealtimeData(thread, realtime);
598
599 mXmppConnectionService.updateConversationUi();
600 }
601
602 // Basic visibility for voice requests
603 if (body == null && html == null && pgpEncrypted == null && axolotlEncrypted == null && !isMucStatusMessage) {
604 final Element formEl = packet.findChild("x", "jabber:x:data");
605 if (formEl != null) {
606 final Data form = Data.parse(formEl);
607 final String role = form.getValue("muc#role");
608 final String nick = form.getValue("muc#roomnick");
609 if ("http://jabber.org/protocol/muc#request".equals(form.getFormType()) && "participant".equals(role)) {
610 body = new LocalizedContent("" + nick + " is requesting to speak", "en", 1);
611 }
612 }
613 }
614
615 if (reactions == null && (body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || !attachments.isEmpty() || html != null || (packet.hasChild("subject") && packet.hasChild("thread"))) && !isMucStatusMessage) {
616 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), conversationIsProbablyMuc, false, query, false);
617 final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
618
619 if (serverMsgId == null) {
620 serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
621 }
622
623
624 if (selfAddressed) {
625 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, Message.STATUS_SEND_RECEIVED, serverMsgId)) {
626 return;
627 }
628 status = Message.STATUS_RECEIVED;
629 if (remoteMsgId != null && conversation.findMessageWithRemoteId(remoteMsgId, counterpart) != null) {
630 return;
631 }
632 }
633
634 if (isTypeGroupChat) {
635 if (conversation.getMucOptions().isSelf(counterpart)) {
636 status = Message.STATUS_SEND_RECEIVED;
637 isCarbon = true; //not really carbon but received from another resource
638 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId, body, html, packet.findChildContent("subject"), packet.findChild("thread"), attachments)) {
639 return;
640 } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
641 if (body != null) {
642 Message message = conversation.findSentMessageWithBody(body.content);
643 if (message != null) {
644 mXmppConnectionService.markMessage(message, status);
645 return;
646 }
647 }
648 }
649 } else {
650 status = Message.STATUS_RECEIVED;
651 }
652 }
653 final Message message;
654 if (pgpEncrypted != null && Config.supportOpenPgp()) {
655 message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
656 } else if (axolotlEncrypted != null && Config.supportOmemo()) {
657 Jid origin;
658 Set<Jid> fallbacksBySourceId = Collections.emptySet();
659 if (conversationMultiMode) {
660 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
661 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
662 if (origin == null) {
663 try {
664 fallbacksBySourceId = account.getAxolotlService().findCounterpartsBySourceId(XmppAxolotlMessage.parseSourceId(axolotlEncrypted));
665 } catch (IllegalArgumentException e) {
666 //ignoring
667 }
668 }
669 if (origin == null && fallbacksBySourceId.size() == 0) {
670 Log.d(Config.LOGTAG, "axolotl message in anonymous conference received and no possible fallbacks");
671 return;
672 }
673 } else {
674 fallbacksBySourceId = Collections.emptySet();
675 origin = from;
676 }
677
678 final boolean liveMessage = query == null && !isTypeGroupChat && mucUserElement == null;
679 final boolean checkedForDuplicates = liveMessage || (serverMsgId != null && remoteMsgId != null && !conversation.possibleDuplicate(serverMsgId, remoteMsgId));
680
681 if (origin != null) {
682 message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status, checkedForDuplicates, query != null);
683 } else {
684 Message trial = null;
685 for (Jid fallback : fallbacksBySourceId) {
686 trial = parseAxolotlChat(axolotlEncrypted, fallback, conversation, status, checkedForDuplicates && fallbacksBySourceId.size() == 1, query != null);
687 if (trial != null) {
688 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": decoded muc message using fallback");
689 origin = fallback;
690 break;
691 }
692 }
693 message = trial;
694 }
695 if (message == null) {
696 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
697 mXmppConnectionService.updateConversationUi();
698 }
699 if (query != null && status == Message.STATUS_SEND && remoteMsgId != null) {
700 Message previouslySent = conversation.findSentMessageWithUuid(remoteMsgId);
701 if (previouslySent != null && previouslySent.getServerMsgId() == null && serverMsgId != null) {
702 previouslySent.setServerMsgId(serverMsgId);
703 mXmppConnectionService.databaseBackend.updateMessage(previouslySent, false);
704 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered previously sent OMEMO message without serverId. updating...");
705 }
706 }
707 return;
708 }
709 if (conversationMultiMode) {
710 message.setTrueCounterpart(origin);
711 }
712 } else if (body == null && !attachments.isEmpty()) {
713 message = new Message(conversation, "", Message.ENCRYPTION_NONE, status);
714 } else {
715 message = new Message(conversation, body == null ? null : body.content, Message.ENCRYPTION_NONE, status);
716 if (body != null && body.count > 1) {
717 message.setBodyLanguage(body.language);
718 }
719 }
720
721 Element addresses = packet.findChild("addresses", "http://jabber.org/protocol/address");
722 if (status == Message.STATUS_RECEIVED && addresses != null) {
723 for (Element address : addresses.getChildren()) {
724 if (!address.getName().equals("address") || !address.getNamespace().equals("http://jabber.org/protocol/address")) continue;
725
726 if (address.getAttribute("type").equals("ofrom") && address.getAttribute("jid") != null) {
727 Jid ofrom = address.getAttributeAsJid("jid");
728 if (InvalidJid.isValid(ofrom) && ofrom.getDomain().equals(counterpart.getDomain()) &&
729 conversation.getAccount().getRoster().getContact(counterpart.getDomain()).getPresences().anySupport("http://jabber.org/protocol/address")) {
730
731 message.setTrueCounterpart(ofrom);
732 }
733 }
734 }
735 }
736
737 if (html != null) message.addPayload(html);
738 message.setSubject(packet.findChildContent("subject"));
739 message.setCounterpart(counterpart);
740 message.setRemoteMsgId(remoteMsgId);
741 message.setServerMsgId(serverMsgId);
742 message.setCarbon(isCarbon);
743 message.setTime(timestamp);
744 if (!attachments.isEmpty()) {
745 message.setFileParams(attachments.iterator().next());
746 if (CryptoHelper.isPgpEncryptedUrl(message.getFileParams().url)) {
747 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
748 }
749 }
750 message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
751 for (Element el : packet.getChildren()) {
752 if ((el.getName().equals("query") && el.getNamespace().equals("http://jabber.org/protocol/disco#items") && el.getAttribute("node").equals("http://jabber.org/protocol/commands")) ||
753 (el.getName().equals("fallback") && el.getNamespace().equals("urn:xmpp:fallback:0"))) {
754 message.addPayload(el);
755 }
756 if (el.getName().equals("thread") && (el.getNamespace() == null || el.getNamespace().equals("jabber:client"))) {
757 el.setAttribute("xmlns", "jabber:client");
758 message.addPayload(el);
759 }
760 if (el.getName().equals("reply") && el.getNamespace() != null && el.getNamespace().equals("urn:xmpp:reply:0")) {
761 message.addPayload(el);
762 if (el.getAttribute("id") != null) {
763 for (final var parent : mXmppConnectionService.getMessageFuzzyIds(conversation, List.of(el.getAttribute("id"))).entrySet()) {
764 message.setInReplyTo(parent.getValue());
765 }
766 }
767 }
768 if (el.getName().equals("attention") && el.getNamespace() != null && el.getNamespace().equals("urn:xmpp:attention:0")) {
769 message.addPayload(el);
770 }
771 if (el.getName().equals("Description") && el.getNamespace() != null && el.getNamespace().equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#")) {
772 message.addPayload(el);
773 }
774 }
775 if (conversationMultiMode) {
776 final var mucOptions = conversation.getMucOptions();
777 final var occupantId =
778 mucOptions.occupantId() ? packet.getExtension(OccupantId.class) : null;
779 if (occupantId != null) {
780 message.setOccupantId(occupantId.getId());
781 }
782 message.setMucUser(mucOptions.findUserByFullJid(counterpart));
783 final Jid fallback = mucOptions.getTrueCounterpart(counterpart);
784 Jid trueCounterpart;
785 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
786 trueCounterpart = message.getTrueCounterpart();
787 } else if (query != null && query.safeToExtractTrueCounterpart()) {
788 trueCounterpart = getTrueCounterpart(mucUserElement, fallback);
789 } else {
790 trueCounterpart = fallback;
791 }
792 if (trueCounterpart != null && isTypeGroupChat) {
793 if (trueCounterpart.asBareJid().equals(account.getJid().asBareJid())) {
794 status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
795 } else {
796 status = Message.STATUS_RECEIVED;
797 message.setCarbon(false);
798 }
799 }
800 message.setStatus(status);
801 message.setTrueCounterpart(trueCounterpart);
802 if (!isTypeGroupChat) {
803 message.setType(Message.TYPE_PRIVATE);
804 }
805 } else {
806 updateLastseen(account, from);
807 }
808
809 if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
810 final Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId, counterpart);
811 if (replacedMessage != null) {
812 final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
813 || replacedMessage.getFingerprint().equals(message.getFingerprint());
814 final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
815 && message.getTrueCounterpart() != null
816 && replacedMessage.getTrueCounterpart().asBareJid().equals(message.getTrueCounterpart().asBareJid());
817 final boolean occupantIdMatch =
818 replacedMessage.getOccupantId() != null
819 && replacedMessage
820 .getOccupantId()
821 .equals(message.getOccupantId());
822 final boolean mucUserMatches = query == null && replacedMessage.sameMucUser(message); //can not be checked when using mam
823 final boolean duplicate = conversation.hasDuplicateMessage(message);
824 if (fingerprintsMatch && (trueCountersMatch || occupantIdMatch || !conversationMultiMode || mucUserMatches || counterpart.isBareJid()) && !duplicate) {
825 synchronized (replacedMessage) {
826 final String uuid = replacedMessage.getUuid();
827 replacedMessage.setUuid(UUID.randomUUID().toString());
828 replacedMessage.setBody(message.getBody());
829 replacedMessage.setSubject(message.getSubject());
830 replacedMessage.setThread(message.getThread());
831 replacedMessage.putEdited(replacedMessage.getRemoteMsgId(), replacedMessage.getServerMsgId());
832 replacedMessage.setRemoteMsgId(remoteMsgId);
833 if (replaceElement != null && !replaceElement.getName().equals("replace")) {
834 mXmppConnectionService.getFileBackend().deleteFile(replacedMessage);
835 mXmppConnectionService.evictPreview(message.getUuid());
836 List<Element> thumbs = replacedMessage.getFileParams() != null ? replacedMessage.getFileParams().getThumbnails() : null;
837 if (thumbs != null && !thumbs.isEmpty()) {
838 for (Element thumb : thumbs) {
839 Uri uri = Uri.parse(thumb.getAttribute("uri"));
840 if (uri.getScheme().equals("cid")) {
841 Cid cid = BobTransfer.cid(uri);
842 if (cid == null) continue;
843 DownloadableFile f = mXmppConnectionService.getFileForCid(cid);
844 if (f != null) {
845 mXmppConnectionService.evictPreview(f);
846 f.delete();
847 }
848 }
849 }
850 }
851 replacedMessage.clearPayloads();
852 replacedMessage.setFileParams(null);
853 replacedMessage.addPayload(replaceElement);
854 } else {
855 for (final var p : message.getPayloads()) {
856 replacedMessage.addPayload(p);
857 }
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 // TODO we don’t even use 'sender' any more. Remove this!
1227 final Jid sender = InvalidJid.getNullForInvalid(displayed.getAttributeAsJid("sender"));
1228 if (packet.fromAccount(account) && !selfAddressed) {
1229 final Conversation c =
1230 mXmppConnectionService.find(account, counterpart.asBareJid());
1231 final Message message =
1232 (c == null || id == null) ? null : c.findReceivedWithRemoteId(id);
1233 if (message != null && (query == null || query.isCatchup())) {
1234 mXmppConnectionService.markReadUpTo(c, message);
1235 }
1236 if (query == null) {
1237 activateGracePeriod(account);
1238 }
1239 } else if (isTypeGroupChat) {
1240 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1241 final Message message;
1242 if (conversation != null && id != null) {
1243 if (sender != null) {
1244 message = conversation.findMessageWithRemoteId(id, sender);
1245 } else {
1246 message = conversation.findMessageWithServerMsgId(id);
1247 }
1248 } else {
1249 message = null;
1250 }
1251 if (message != null) {
1252 // TODO use occupantId to extract true counterpart from presence
1253 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
1254 // TODO try to externalize mucTrueCounterpart
1255 final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
1256 final boolean trueJidMatchesAccount = account.getJid().asBareJid().equals(trueJid == null ? null : trueJid.asBareJid());
1257 if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
1258 if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
1259 mXmppConnectionService.markReadUpTo(conversation, message);
1260 }
1261 } else if (!counterpart.isBareJid() && trueJid != null) {
1262 final ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
1263 if (message.addReadByMarker(readByMarker)) {
1264 final var mucOptions = conversation.getMucOptions();
1265 final var everyone = ImmutableSet.copyOf(mucOptions.getMembers(false));
1266 final var readyBy = message.getReadyByTrue();
1267 final var mStatus = message.getStatus();
1268 if (mucOptions.isPrivateAndNonAnonymous()
1269 && (mStatus == Message.STATUS_SEND_RECEIVED
1270 || mStatus == Message.STATUS_SEND)
1271 && readyBy.containsAll(everyone)) {
1272 message.setStatus(Message.STATUS_SEND_DISPLAYED);
1273 }
1274 mXmppConnectionService.updateMessage(message, false);
1275 }
1276 }
1277 }
1278 } else {
1279 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_DISPLAYED);
1280 Message message = displayedMessage == null ? null : displayedMessage.prev();
1281 while (message != null
1282 && message.getStatus() == Message.STATUS_SEND_RECEIVED
1283 && message.getTimeSent() < displayedMessage.getTimeSent()) {
1284 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
1285 message = message.prev();
1286 }
1287 if (displayedMessage != null && selfAddressed) {
1288 dismissNotification(account, counterpart, query, id);
1289 }
1290 }
1291 }
1292
1293 if (reactions != null) {
1294 final String reactingTo = reactions.getId();
1295 final Conversation conversation =
1296 mXmppConnectionService.find(account, counterpart.asBareJid());
1297
1298 if (conversation != null) {
1299 if (isTypeGroupChat && conversation.getMode() == Conversational.MODE_MULTI) {
1300 final var mucOptions = conversation.getMucOptions();
1301 final var occupant =
1302 mucOptions.occupantId() ? packet.getExtension(OccupantId.class) : null;
1303 final var occupantId = occupant == null ? null : occupant.getId();
1304 final var message = conversation.findMessageWithServerMsgId(reactingTo);
1305 // TODO use occupant id for isSelf assessment
1306 final boolean isReceived = !mucOptions.isSelf(counterpart);
1307 if (occupantId != null && message != null) {
1308 final var newReactions = new HashSet<>(reactions.getReactions());
1309 newReactions.removeAll(message.getReactions().stream().filter(r -> occupantId.equals(r.occupantId)).map(r -> r.reaction).collect(Collectors.toList()));
1310 final var combinedReactions =
1311 Reaction.withOccupantId(
1312 message.getReactions(),
1313 reactions.getReactions(),
1314 isReceived,
1315 counterpart,
1316 null,
1317 occupantId,
1318 message.getRemoteMsgId());
1319 message.setReactions(combinedReactions);
1320 mXmppConnectionService.updateMessage(message, false);
1321 if (!isCarbon) mXmppConnectionService.getNotificationService().push(message, counterpart, occupantId, newReactions);
1322 } else {
1323 Log.d(Config.LOGTAG,"not found occupant or message");
1324 }
1325 } else if (conversation.getMode() == Conversational.MODE_SINGLE) {
1326 final var message = conversation.findMessageWithUuidOrRemoteId(reactingTo);
1327 final boolean isReceived;
1328 final Jid reactionFrom;
1329 if (packet.fromAccount(account)) {
1330 isReceived = false;
1331 reactionFrom = account.getJid().asBareJid();
1332 } else {
1333 isReceived = true;
1334 reactionFrom = counterpart;
1335 }
1336 packet.fromAccount(account);
1337 if (message != null) {
1338 final var newReactions = new HashSet<>(reactions.getReactions());
1339 newReactions.removeAll(message.getReactions().stream().filter(r -> reactionFrom.equals(r.from)).map(r -> r.reaction).collect(Collectors.toList()));
1340 final var combinedReactions =
1341 Reaction.withFrom(
1342 message.getReactions(),
1343 reactions.getReactions(),
1344 isReceived,
1345 reactionFrom,
1346 message.getRemoteMsgId());
1347 message.setReactions(combinedReactions);
1348 mXmppConnectionService.updateMessage(message, false);
1349 if (!isCarbon) mXmppConnectionService.getNotificationService().push(message, counterpart, null, newReactions);
1350 }
1351 }
1352 }
1353 }
1354
1355 final Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
1356 if (event != null && InvalidJid.hasValidFrom(original) && original.getFrom().isBareJid()) {
1357 if (event.hasChild("items")) {
1358 parseEvent(event, original.getFrom(), account);
1359 } else if (event.hasChild("delete")) {
1360 parseDeleteEvent(event, original.getFrom(), account);
1361 } else if (event.hasChild("purge")) {
1362 parsePurgeEvent(event, original.getFrom(), account);
1363 }
1364 }
1365
1366 final String nick = packet.findChildContent("nick", Namespace.NICK);
1367 if (nick != null && InvalidJid.hasValidFrom(original)) {
1368 if (mXmppConnectionService.isMuc(account, from)) {
1369 return;
1370 }
1371 final Contact contact = account.getRoster().getContact(from);
1372 if (contact.setPresenceName(nick)) {
1373 mXmppConnectionService.syncRoster(account);
1374 mXmppConnectionService.getAvatarService().clear(contact);
1375 }
1376 }
1377 }
1378
1379 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) {
1380 final var extension = original.getExtension(clazz);
1381 final var forwarded = extension == null ? null : extension.getExtension(Forwarded.class);
1382 if (forwarded == null) {
1383 return null;
1384 }
1385 final Long timestamp = AbstractParser.parseTimestamp(forwarded, null);
1386 final var forwardedMessage = forwarded.getMessage();
1387 if (forwardedMessage == null) {
1388 return null;
1389 }
1390 return new Pair<>(forwardedMessage,timestamp);
1391 }
1392
1393 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) {
1394 final Element wrapper = original.findChild(name, namespace);
1395 final var forwardedElement = wrapper == null ? null : wrapper.findChild("forwarded",Namespace.FORWARD);
1396 if (forwardedElement instanceof Forwarded forwarded) {
1397 final Long timestamp = AbstractParser.parseTimestamp(forwarded, null);
1398 final var forwardedMessage = forwarded.getMessage();
1399 if (forwardedMessage == null) {
1400 return null;
1401 }
1402 return new Pair<>(forwardedMessage,timestamp);
1403 }
1404 return null;
1405 }
1406
1407 private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query, final String id) {
1408 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1409 if (conversation != null && (query == null || query.isCatchup())) {
1410 final String displayableId = conversation.findMostRecentRemoteDisplayableId();
1411 if (displayableId != null && displayableId.equals(id)) {
1412 mXmppConnectionService.markRead(conversation);
1413 } else {
1414 Log.w(Config.LOGTAG, account.getJid().asBareJid() + ": received dismissing display marker that did not match our last id in that conversation");
1415 }
1416 }
1417 }
1418
1419 private void processMessageReceipts(final Account account, final im.conversations.android.xmpp.model.stanza.Message packet, final String remoteMsgId, MessageArchiveService.Query query) {
1420 final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
1421 final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
1422 if (query == null) {
1423 final ArrayList<String> receiptsNamespaces = new ArrayList<>();
1424 if (markable) {
1425 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
1426 }
1427 if (request) {
1428 receiptsNamespaces.add("urn:xmpp:receipts");
1429 }
1430 if (receiptsNamespaces.size() > 0) {
1431 final var receipt = mXmppConnectionService.getMessageGenerator().received(account,
1432 packet.getFrom(),
1433 remoteMsgId,
1434 receiptsNamespaces,
1435 packet.getType());
1436 mXmppConnectionService.sendMessagePacket(account, receipt);
1437 }
1438 } else if (query.isCatchup()) {
1439 if (request) {
1440 query.addPendingReceiptRequest(new ReceiptRequest(packet.getFrom(), remoteMsgId));
1441 }
1442 }
1443 }
1444
1445 private void activateGracePeriod(Account account) {
1446 long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
1447 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
1448 account.activateGracePeriod(duration);
1449 }
1450
1451 private class Invite {
1452 final Jid jid;
1453 final String password;
1454 final boolean direct;
1455 final Jid inviter;
1456
1457 Invite(Jid jid, String password, boolean direct, Jid inviter) {
1458 this.jid = jid;
1459 this.password = password;
1460 this.direct = direct;
1461 this.inviter = inviter;
1462 }
1463
1464 public boolean execute(final Account account) {
1465 if (this.jid == null) {
1466 return false;
1467 }
1468 final Contact contact = this.inviter != null ? account.getRoster().getContact(this.inviter) : null;
1469 if (contact != null && contact.isBlocked()) {
1470 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": ignore invite from "+contact.getJid()+" because contact is blocked");
1471 return false;
1472 }
1473 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
1474 conversation.setAttribute("inviter", inviter.toEscapedString());
1475 if (conversation.getMucOptions().online()) {
1476 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received invite to " + jid + " but muc is considered to be online");
1477 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
1478 } else {
1479 conversation.getMucOptions().setPassword(password);
1480 mXmppConnectionService.databaseBackend.updateConversation(conversation);
1481 mXmppConnectionService.joinMuc(conversation, contact != null && contact.showInContactList());
1482 mXmppConnectionService.updateConversationUi();
1483 }
1484 return true;
1485 }
1486 }
1487
1488 private static int parseInt(String value) {
1489 try {
1490 return Integer.parseInt(value);
1491 } catch (NumberFormatException e) {
1492 return 0;
1493 }
1494 }
1495}