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