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