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 replacedMessage.clearPayloads();
856 for (final var p : message.getPayloads()) {
857 replacedMessage.addPayload(p);
858 }
859 }
860 replacedMessage.setInReplyTo(message.getInReplyTo());
861 if (replacedMessage.getServerMsgId() == null || message.getServerMsgId() != null) {
862 replacedMessage.setServerMsgId(message.getServerMsgId());
863 }
864 replacedMessage.setEncryption(message.getEncryption());
865 if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
866 replacedMessage.markUnread();
867 }
868 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
869 mXmppConnectionService.updateMessage(replacedMessage, uuid);
870 if (mXmppConnectionService.confirmMessages()
871 && replacedMessage.getStatus() == Message.STATUS_RECEIVED
872 && (replacedMessage.trusted() || replacedMessage.isPrivateMessage()) //TODO do we really want to send receipts for all PMs?
873 && remoteMsgId != null
874 && !selfAddressed
875 && !isTypeGroupChat) {
876 processMessageReceipts(account, packet, remoteMsgId, query);
877 }
878 if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
879 conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
880 conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
881 }
882 }
883 mXmppConnectionService.getNotificationService().updateNotification();
884 return;
885 } else {
886 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received message correction but verification didn't check out");
887 }
888 } else if (message.getBody() == null || message.getBody().equals("") || message.getBody().equals(" ")) {
889 return;
890 }
891 if (replaceElement != null && !replaceElement.getName().equals("replace")) return;
892 }
893
894 boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay", "urn:xmpp:delay"))
895 || message.isPrivateMessage()
896 || message.getServerMsgId() != null
897 || (query == null && mXmppConnectionService.getMessageArchiveService().isCatchupInProgress(conversation));
898 if (checkForDuplicates) {
899 final Message duplicate = conversation.findDuplicateMessage(message);
900 if (duplicate != null) {
901 final boolean serverMsgIdUpdated;
902 if (duplicate.getStatus() != Message.STATUS_RECEIVED
903 && duplicate.getUuid().equals(message.getRemoteMsgId())
904 && duplicate.getServerMsgId() == null
905 && message.getServerMsgId() != null) {
906 duplicate.setServerMsgId(message.getServerMsgId());
907 if (mXmppConnectionService.databaseBackend.updateMessage(duplicate, false)) {
908 serverMsgIdUpdated = true;
909 } else {
910 serverMsgIdUpdated = false;
911 Log.e(Config.LOGTAG, "failed to update message");
912 }
913 } else {
914 serverMsgIdUpdated = false;
915 }
916 Log.d(Config.LOGTAG, "skipping duplicate message with " + message.getCounterpart() + ". serverMsgIdUpdated=" + serverMsgIdUpdated);
917 return;
918 }
919 }
920
921 if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
922 conversation.prepend(query.getActualInThisQuery(), message);
923 } else {
924 conversation.add(message);
925 }
926 if (query != null) {
927 query.incrementActualMessageCount();
928 }
929
930 if (query == null || query.isCatchup()) { //either no mam or catchup
931 if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
932 mXmppConnectionService.markRead(conversation);
933 if (query == null) {
934 activateGracePeriod(account);
935 }
936 } else {
937 message.markUnread();
938 notify = true;
939 }
940 }
941
942 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
943 notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
944 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE || message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
945 notify = false;
946 }
947
948 if (query == null) {
949 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
950 mXmppConnectionService.updateConversationUi();
951 }
952
953 if (mXmppConnectionService.confirmMessages()
954 && message.getStatus() == Message.STATUS_RECEIVED
955 && (message.trusted() || message.isPrivateMessage())
956 && remoteMsgId != null
957 && !selfAddressed
958 && !isTypeGroupChat) {
959 processMessageReceipts(account, packet, remoteMsgId, query);
960 }
961
962 if (message.getFileParams() != null) {
963 for (Cid cid : message.getFileParams().getCids()) {
964 File f = mXmppConnectionService.getFileForCid(cid);
965 if (f != null && f.canRead()) {
966 message.setRelativeFilePath(f.getAbsolutePath());
967 mXmppConnectionService.getFileBackend().updateFileParams(message, null, false);
968 break;
969 }
970 }
971 }
972
973 mXmppConnectionService.databaseBackend.createMessage(message);
974
975 final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
976 if (message.getRelativeFilePath() == null && message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
977 if (message.getOob() != null && "cid".equalsIgnoreCase(message.getOob().getScheme())) {
978 try {
979 BobTransfer transfer = new BobTransfer.ForMessage(message, mXmppConnectionService);
980 message.setTransferable(transfer);
981 transfer.start();
982 } catch (URISyntaxException e) {
983 Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
984 }
985 } else {
986 manager.createNewDownloadConnection(message);
987 }
988 } else if (notify) {
989 if (query != null && query.isCatchup()) {
990 mXmppConnectionService.getNotificationService().pushFromBacklog(message);
991 } else {
992 mXmppConnectionService.getNotificationService().push(message);
993 }
994 }
995 } else if (!packet.hasChild("body")) { //no body
996
997 final Conversation conversation = mXmppConnectionService.find(account, from.asBareJid());
998 if (axolotlEncrypted != null) {
999 Jid origin;
1000 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
1001 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
1002 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
1003 if (origin == null) {
1004 Log.d(Config.LOGTAG, "omemo key transport message in anonymous conference received");
1005 return;
1006 }
1007 } else if (isTypeGroupChat) {
1008 return;
1009 } else {
1010 origin = from;
1011 }
1012 try {
1013 final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.asBareJid());
1014 account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
1015 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": omemo key transport message received from " + origin);
1016 } catch (Exception e) {
1017 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": invalid omemo key transport message received " + e.getMessage());
1018 return;
1019 }
1020 }
1021
1022 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
1023 mXmppConnectionService.updateConversationUi();
1024 }
1025
1026 if (isTypeGroupChat) {
1027 if (packet.hasChild("subject") && !packet.hasChild("thread")) { // We already know it has no body per above
1028 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
1029 conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
1030 final LocalizedContent subject = packet.findInternationalizedChildContentInDefaultNamespace("subject");
1031 if (subject != null && conversation.getMucOptions().setSubject(subject.content)) {
1032 mXmppConnectionService.updateConversation(conversation);
1033 }
1034 mXmppConnectionService.updateConversationUi();
1035 return;
1036 }
1037 }
1038 }
1039 if (conversation != null && mucUserElement != null && InvalidJid.hasValidFrom(packet) && from.isBareJid()) {
1040 for (Element child : mucUserElement.getChildren()) {
1041 if ("status".equals(child.getName())) {
1042 try {
1043 int code = Integer.parseInt(child.getAttribute("code"));
1044 if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
1045 mXmppConnectionService.fetchConferenceConfiguration(conversation);
1046 break;
1047 }
1048 } catch (Exception e) {
1049 //ignored
1050 }
1051 } else if ("item".equals(child.getName())) {
1052 MucOptions.User user = AbstractParser.parseItem(conversation, child);
1053 Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for "
1054 + user.getRealJid() + " to " + user.getAffiliation() + " in "
1055 + conversation.getJid().asBareJid());
1056 if (!user.realJidMatchesAccount()) {
1057 boolean isNew = conversation.getMucOptions().updateUser(user);
1058 mXmppConnectionService.getAvatarService().clear(conversation);
1059 mXmppConnectionService.updateMucRosterUi();
1060 mXmppConnectionService.updateConversationUi();
1061 Contact contact = user.getContact();
1062 if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
1063 Jid jid = user.getRealJid();
1064 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
1065 if (cryptoTargets.remove(user.getRealJid())) {
1066 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
1067 conversation.setAcceptedCryptoTargets(cryptoTargets);
1068 mXmppConnectionService.updateConversation(conversation);
1069 }
1070 } else if (isNew
1071 && user.getRealJid() != null
1072 && conversation.getMucOptions().isPrivateAndNonAnonymous()
1073 && (contact == null || !contact.mutualPresenceSubscription())
1074 && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
1075 account.getAxolotlService().fetchDeviceIds(user.getRealJid());
1076 }
1077 }
1078 }
1079 }
1080 }
1081 if (!isTypeGroupChat) {
1082 for (Element child : packet.getChildren()) {
1083 if (Namespace.JINGLE_MESSAGE.equals(child.getNamespace()) && JINGLE_MESSAGE_ELEMENT_NAMES.contains(child.getName())) {
1084 final String action = child.getName();
1085 final String sessionId = child.getAttribute("id");
1086 if (sessionId == null) {
1087 break;
1088 }
1089 if (query == null && offlineMessagesRetrieved) {
1090 if (serverMsgId == null) {
1091 serverMsgId = extractStanzaId(account, packet);
1092 }
1093 mXmppConnectionService
1094 .getJingleConnectionManager()
1095 .deliverMessage(
1096 account,
1097 packet.getTo(),
1098 packet.getFrom(),
1099 child,
1100 remoteMsgId,
1101 serverMsgId,
1102 timestamp);
1103 final Contact contact = account.getRoster().getContact(from);
1104 // this is the same condition that is found in JingleRtpConnection for
1105 // the 'ringing' response. Responding with delivery receipts predates
1106 // the 'ringing' spec'd
1107 final boolean sendReceipts =
1108 (mXmppConnectionService.confirmMessages()
1109 && contact.showInContactList())
1110 || Config.JINGLE_MESSAGE_INIT_STRICT_OFFLINE_CHECK;
1111 if (remoteMsgId != null && !contact.isSelf() && sendReceipts) {
1112 processMessageReceipts(account, packet, remoteMsgId, null);
1113 }
1114 } else if ((query != null && query.isCatchup()) || !offlineMessagesRetrieved) {
1115 if ("propose".equals(action)) {
1116 final Element description = child.findChild("description");
1117 final String namespace =
1118 description == null ? null : description.getNamespace();
1119 if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
1120 final Conversation c =
1121 mXmppConnectionService.findOrCreateConversation(
1122 account, counterpart.asBareJid(), false, false);
1123 final Message preExistingMessage =
1124 c.findRtpSession(sessionId, status);
1125 if (preExistingMessage != null) {
1126 preExistingMessage.setServerMsgId(serverMsgId);
1127 mXmppConnectionService.updateMessage(preExistingMessage);
1128 break;
1129 }
1130 final Message message =
1131 new Message(
1132 c, status, Message.TYPE_RTP_SESSION, sessionId);
1133 message.setServerMsgId(serverMsgId);
1134 message.setTime(timestamp);
1135 message.setBody(new RtpSessionStatus(false, 0).toString());
1136 c.add(message);
1137 mXmppConnectionService.databaseBackend.createMessage(message);
1138 }
1139 } else if ("proceed".equals(action)) {
1140 // status needs to be flipped to find the original propose
1141 final Conversation c =
1142 mXmppConnectionService.findOrCreateConversation(
1143 account, counterpart.asBareJid(), false, false);
1144 final int s =
1145 packet.fromAccount(account)
1146 ? Message.STATUS_RECEIVED
1147 : Message.STATUS_SEND;
1148 final Message message = c.findRtpSession(sessionId, s);
1149 if (message != null) {
1150 message.setBody(new RtpSessionStatus(true, 0).toString());
1151 if (serverMsgId != null) {
1152 message.setServerMsgId(serverMsgId);
1153 }
1154 message.setTime(timestamp);
1155 mXmppConnectionService.updateMessage(message, true);
1156 } else {
1157 Log.d(
1158 Config.LOGTAG,
1159 "unable to find original rtp session message for received propose");
1160 }
1161
1162 } else if ("finish".equals(action)) {
1163 Log.d(
1164 Config.LOGTAG,
1165 "received JMI 'finish' during MAM catch-up. Can be used to update success/failure and duration");
1166 }
1167 } else {
1168 //MAM reloads (non catchups
1169 if ("propose".equals(action)) {
1170 final Element description = child.findChild("description");
1171 final String namespace = description == null ? null : description.getNamespace();
1172 if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
1173 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
1174 final Message preExistingMessage = c.findRtpSession(sessionId, status);
1175 if (preExistingMessage != null) {
1176 preExistingMessage.setServerMsgId(serverMsgId);
1177 mXmppConnectionService.updateMessage(preExistingMessage);
1178 break;
1179 }
1180 final Message message = new Message(
1181 c,
1182 status,
1183 Message.TYPE_RTP_SESSION,
1184 sessionId
1185 );
1186 message.setServerMsgId(serverMsgId);
1187 message.setTime(timestamp);
1188 message.setBody(new RtpSessionStatus(true, 0).toString());
1189 if (query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
1190 c.prepend(query.getActualInThisQuery(), message);
1191 } else {
1192 c.add(message);
1193 }
1194 query.incrementActualMessageCount();
1195 mXmppConnectionService.databaseBackend.createMessage(message);
1196 }
1197 }
1198 }
1199 break;
1200 }
1201 }
1202 }
1203 }
1204
1205 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
1206 if (received == null) {
1207 received = packet.findChild("received", "urn:xmpp:receipts");
1208 }
1209 if (received != null) {
1210 String id = received.getAttribute("id");
1211 if (packet.fromAccount(account)) {
1212 if (query != null && id != null && packet.getTo() != null) {
1213 query.removePendingReceiptRequest(new ReceiptRequest(packet.getTo(), id));
1214 }
1215 } else if (id != null) {
1216 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
1217 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
1218 mXmppConnectionService.getJingleConnectionManager()
1219 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.DISCOVERED);
1220 } else {
1221 mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_RECEIVED);
1222 }
1223 }
1224 }
1225 final Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
1226 if (displayed != null) {
1227 final String id = displayed.getAttribute("id");
1228 // TODO we don’t even use 'sender' any more. Remove this!
1229 final Jid sender = InvalidJid.getNullForInvalid(displayed.getAttributeAsJid("sender"));
1230 if (packet.fromAccount(account) && !selfAddressed) {
1231 final Conversation c =
1232 mXmppConnectionService.find(account, counterpart.asBareJid());
1233 final Message message =
1234 (c == null || id == null) ? null : c.findReceivedWithRemoteId(id);
1235 if (message != null && (query == null || query.isCatchup())) {
1236 mXmppConnectionService.markReadUpTo(c, message);
1237 }
1238 if (query == null) {
1239 activateGracePeriod(account);
1240 }
1241 } else if (isTypeGroupChat) {
1242 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1243 final Message message;
1244 if (conversation != null && id != null) {
1245 if (sender != null) {
1246 message = conversation.findMessageWithRemoteId(id, sender);
1247 } else {
1248 message = conversation.findMessageWithServerMsgId(id);
1249 }
1250 } else {
1251 message = null;
1252 }
1253 if (message != null) {
1254 // TODO use occupantId to extract true counterpart from presence
1255 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
1256 // TODO try to externalize mucTrueCounterpart
1257 final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
1258 final boolean trueJidMatchesAccount = account.getJid().asBareJid().equals(trueJid == null ? null : trueJid.asBareJid());
1259 if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
1260 if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
1261 mXmppConnectionService.markReadUpTo(conversation, message);
1262 }
1263 } else if (!counterpart.isBareJid() && trueJid != null) {
1264 final ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
1265 if (message.addReadByMarker(readByMarker)) {
1266 final var mucOptions = conversation.getMucOptions();
1267 final var everyone = ImmutableSet.copyOf(mucOptions.getMembers(false));
1268 final var readyBy = message.getReadyByTrue();
1269 final var mStatus = message.getStatus();
1270 if (mucOptions.isPrivateAndNonAnonymous()
1271 && (mStatus == Message.STATUS_SEND_RECEIVED
1272 || mStatus == Message.STATUS_SEND)
1273 && readyBy.containsAll(everyone)) {
1274 message.setStatus(Message.STATUS_SEND_DISPLAYED);
1275 }
1276 mXmppConnectionService.updateMessage(message, false);
1277 }
1278 }
1279 }
1280 } else {
1281 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_DISPLAYED);
1282 Message message = displayedMessage == null ? null : displayedMessage.prev();
1283 while (message != null
1284 && message.getStatus() == Message.STATUS_SEND_RECEIVED
1285 && message.getTimeSent() < displayedMessage.getTimeSent()) {
1286 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
1287 message = message.prev();
1288 }
1289 if (displayedMessage != null && selfAddressed) {
1290 dismissNotification(account, counterpart, query, id);
1291 }
1292 }
1293 }
1294
1295 if (reactions != null) {
1296 final String reactingTo = reactions.getId();
1297 final Conversation conversation =
1298 mXmppConnectionService.find(account, counterpart.asBareJid());
1299
1300 if (conversation != null) {
1301 if (isTypeGroupChat && conversation.getMode() == Conversational.MODE_MULTI) {
1302 final var mucOptions = conversation.getMucOptions();
1303 final var occupant =
1304 mucOptions.occupantId() ? packet.getExtension(OccupantId.class) : null;
1305 final var occupantId = occupant == null ? null : occupant.getId();
1306 final var message = conversation.findMessageWithServerMsgId(reactingTo);
1307 // TODO use occupant id for isSelf assessment
1308 final boolean isReceived = !mucOptions.isSelf(counterpart);
1309 if (occupantId != null && message != null) {
1310 final var newReactions = new HashSet<>(reactions.getReactions());
1311 newReactions.removeAll(message.getReactions().stream().filter(r -> occupantId.equals(r.occupantId)).map(r -> r.reaction).collect(Collectors.toList()));
1312 final var combinedReactions =
1313 Reaction.withOccupantId(
1314 message.getReactions(),
1315 reactions.getReactions(),
1316 isReceived,
1317 counterpart,
1318 null,
1319 occupantId,
1320 message.getRemoteMsgId());
1321 message.setReactions(combinedReactions);
1322 mXmppConnectionService.updateMessage(message, false);
1323 if (!isCarbon && !packet.fromAccount(account)) mXmppConnectionService.getNotificationService().push(message, counterpart, occupantId, newReactions);
1324 } else {
1325 Log.d(Config.LOGTAG,"not found occupant or message");
1326 }
1327 } else if (conversation.getMode() == Conversational.MODE_SINGLE) {
1328 final var message = conversation.findMessageWithUuidOrRemoteId(reactingTo);
1329 final boolean isReceived;
1330 final Jid reactionFrom;
1331 if (packet.fromAccount(account)) {
1332 isReceived = false;
1333 reactionFrom = account.getJid().asBareJid();
1334 } else {
1335 isReceived = true;
1336 reactionFrom = counterpart;
1337 }
1338 packet.fromAccount(account);
1339 if (message != null) {
1340 final var newReactions = new HashSet<>(reactions.getReactions());
1341 newReactions.removeAll(message.getReactions().stream().filter(r -> reactionFrom.equals(r.from)).map(r -> r.reaction).collect(Collectors.toList()));
1342 final var combinedReactions =
1343 Reaction.withFrom(
1344 message.getReactions(),
1345 reactions.getReactions(),
1346 isReceived,
1347 reactionFrom,
1348 message.getRemoteMsgId());
1349 message.setReactions(combinedReactions);
1350 mXmppConnectionService.updateMessage(message, false);
1351 if (!isCarbon && !packet.fromAccount(account)) mXmppConnectionService.getNotificationService().push(message, counterpart, null, newReactions);
1352 }
1353 }
1354 }
1355 }
1356
1357 final Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
1358 if (event != null && InvalidJid.hasValidFrom(original) && original.getFrom().isBareJid()) {
1359 if (event.hasChild("items")) {
1360 parseEvent(event, original.getFrom(), account);
1361 } else if (event.hasChild("delete")) {
1362 parseDeleteEvent(event, original.getFrom(), account);
1363 } else if (event.hasChild("purge")) {
1364 parsePurgeEvent(event, original.getFrom(), account);
1365 }
1366 }
1367
1368 final String nick = packet.findChildContent("nick", Namespace.NICK);
1369 if (nick != null && InvalidJid.hasValidFrom(original)) {
1370 if (mXmppConnectionService.isMuc(account, from)) {
1371 return;
1372 }
1373 final Contact contact = account.getRoster().getContact(from);
1374 if (contact.setPresenceName(nick)) {
1375 mXmppConnectionService.syncRoster(account);
1376 mXmppConnectionService.getAvatarService().clear(contact);
1377 }
1378 }
1379 }
1380
1381 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) {
1382 final var extension = original.getExtension(clazz);
1383 final var forwarded = extension == null ? null : extension.getExtension(Forwarded.class);
1384 if (forwarded == null) {
1385 return null;
1386 }
1387 final Long timestamp = AbstractParser.parseTimestamp(forwarded, null);
1388 final var forwardedMessage = forwarded.getMessage();
1389 if (forwardedMessage == null) {
1390 return null;
1391 }
1392 return new Pair<>(forwardedMessage,timestamp);
1393 }
1394
1395 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) {
1396 final Element wrapper = original.findChild(name, namespace);
1397 final var forwardedElement = wrapper == null ? null : wrapper.findChild("forwarded",Namespace.FORWARD);
1398 if (forwardedElement instanceof Forwarded forwarded) {
1399 final Long timestamp = AbstractParser.parseTimestamp(forwarded, null);
1400 final var forwardedMessage = forwarded.getMessage();
1401 if (forwardedMessage == null) {
1402 return null;
1403 }
1404 return new Pair<>(forwardedMessage,timestamp);
1405 }
1406 return null;
1407 }
1408
1409 private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query, final String id) {
1410 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1411 if (conversation != null && (query == null || query.isCatchup())) {
1412 final String displayableId = conversation.findMostRecentRemoteDisplayableId();
1413 if (displayableId != null && displayableId.equals(id)) {
1414 mXmppConnectionService.markRead(conversation);
1415 } else {
1416 Log.w(Config.LOGTAG, account.getJid().asBareJid() + ": received dismissing display marker that did not match our last id in that conversation");
1417 }
1418 }
1419 }
1420
1421 private void processMessageReceipts(final Account account, final im.conversations.android.xmpp.model.stanza.Message packet, final String remoteMsgId, MessageArchiveService.Query query) {
1422 final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
1423 final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
1424 if (query == null) {
1425 final ArrayList<String> receiptsNamespaces = new ArrayList<>();
1426 if (markable) {
1427 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
1428 }
1429 if (request) {
1430 receiptsNamespaces.add("urn:xmpp:receipts");
1431 }
1432 if (receiptsNamespaces.size() > 0) {
1433 final var receipt = mXmppConnectionService.getMessageGenerator().received(account,
1434 packet.getFrom(),
1435 remoteMsgId,
1436 receiptsNamespaces,
1437 packet.getType());
1438 mXmppConnectionService.sendMessagePacket(account, receipt);
1439 }
1440 } else if (query.isCatchup()) {
1441 if (request) {
1442 query.addPendingReceiptRequest(new ReceiptRequest(packet.getFrom(), remoteMsgId));
1443 }
1444 }
1445 }
1446
1447 private void activateGracePeriod(Account account) {
1448 long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
1449 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
1450 account.activateGracePeriod(duration);
1451 }
1452
1453 private class Invite {
1454 final Jid jid;
1455 final String password;
1456 final boolean direct;
1457 final Jid inviter;
1458
1459 Invite(Jid jid, String password, boolean direct, Jid inviter) {
1460 this.jid = jid;
1461 this.password = password;
1462 this.direct = direct;
1463 this.inviter = inviter;
1464 }
1465
1466 public boolean execute(final Account account) {
1467 if (this.jid == null) {
1468 return false;
1469 }
1470 final Contact contact = this.inviter != null ? account.getRoster().getContact(this.inviter) : null;
1471 if (contact != null && contact.isBlocked()) {
1472 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": ignore invite from "+contact.getJid()+" because contact is blocked");
1473 return false;
1474 }
1475 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
1476 conversation.setAttribute("inviter", inviter.toEscapedString());
1477 if (conversation.getMucOptions().online()) {
1478 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received invite to " + jid + " but muc is considered to be online");
1479 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
1480 } else {
1481 conversation.getMucOptions().setPassword(password);
1482 mXmppConnectionService.databaseBackend.updateConversation(conversation);
1483 mXmppConnectionService.joinMuc(conversation, contact != null && contact.showInContactList());
1484 mXmppConnectionService.updateConversationUi();
1485 }
1486 return true;
1487 }
1488 }
1489
1490 private static int parseInt(String value) {
1491 try {
1492 return Integer.parseInt(value);
1493 } catch (NumberFormatException e) {
1494 return 0;
1495 }
1496 }
1497}