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