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