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