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