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