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