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