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