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