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 = original.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 if (html != null) message.addPayload(html);
606 message.setSubject(original.findChildContent("subject"));
607 message.setCounterpart(counterpart);
608 message.setRemoteMsgId(remoteMsgId);
609 message.setServerMsgId(serverMsgId);
610 message.setCarbon(isCarbon);
611 message.setTime(timestamp);
612 if (!attachments.isEmpty()) {
613 message.setFileParams(attachments.iterator().next());
614 if (CryptoHelper.isPgpEncryptedUrl(message.getFileParams().url)) {
615 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
616 }
617 }
618 message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
619 for (Element el : packet.getChildren()) {
620 if (el.getName().equals("query") && el.getNamespace().equals("http://jabber.org/protocol/disco#items") && el.getAttribute("node").equals("http://jabber.org/protocol/commands")) {
621 message.addPayload(el);
622 }
623 if (el.getName().equals("thread") && (el.getNamespace() == null || el.getNamespace().equals("jabber:client"))) {
624 el.setAttribute("xmlns", "jabber:client");
625 message.addPayload(el);
626 }
627 }
628 if (conversationMultiMode) {
629 message.setMucUser(conversation.getMucOptions().findUserByFullJid(counterpart));
630 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
631 Jid trueCounterpart;
632 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
633 trueCounterpart = message.getTrueCounterpart();
634 } else if (query != null && query.safeToExtractTrueCounterpart()) {
635 trueCounterpart = getTrueCounterpart(mucUserElement, fallback);
636 } else {
637 trueCounterpart = fallback;
638 }
639 if (trueCounterpart != null && isTypeGroupChat) {
640 if (trueCounterpart.asBareJid().equals(account.getJid().asBareJid())) {
641 status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
642 } else {
643 status = Message.STATUS_RECEIVED;
644 message.setCarbon(false);
645 }
646 }
647 message.setStatus(status);
648 message.setTrueCounterpart(trueCounterpart);
649 if (!isTypeGroupChat) {
650 message.setType(Message.TYPE_PRIVATE);
651 }
652 } else {
653 updateLastseen(account, from);
654 }
655
656 if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
657 final Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
658 counterpart,
659 message.getStatus() == Message.STATUS_RECEIVED,
660 message.isCarbon());
661 if (replacedMessage != null) {
662 final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
663 || replacedMessage.getFingerprint().equals(message.getFingerprint());
664 final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
665 && message.getTrueCounterpart() != null
666 && replacedMessage.getTrueCounterpart().asBareJid().equals(message.getTrueCounterpart().asBareJid());
667 final boolean mucUserMatches = query == null && replacedMessage.sameMucUser(message); //can not be checked when using mam
668 final boolean duplicate = conversation.hasDuplicateMessage(message);
669 if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode || mucUserMatches) && !duplicate) {
670 Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
671 synchronized (replacedMessage) {
672 final String uuid = replacedMessage.getUuid();
673 replacedMessage.setUuid(UUID.randomUUID().toString());
674 replacedMessage.setBody(message.getBody());
675 replacedMessage.putEdited(replacedMessage.getRemoteMsgId(), replacedMessage.getServerMsgId());
676 replacedMessage.setRemoteMsgId(remoteMsgId);
677 if (replacedMessage.getServerMsgId() == null || message.getServerMsgId() != null) {
678 replacedMessage.setServerMsgId(message.getServerMsgId());
679 }
680 replacedMessage.setEncryption(message.getEncryption());
681 if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
682 replacedMessage.markUnread();
683 }
684 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
685 mXmppConnectionService.updateMessage(replacedMessage, uuid);
686 if (mXmppConnectionService.confirmMessages()
687 && replacedMessage.getStatus() == Message.STATUS_RECEIVED
688 && (replacedMessage.trusted() || replacedMessage.isPrivateMessage()) //TODO do we really want to send receipts for all PMs?
689 && remoteMsgId != null
690 && !selfAddressed
691 && !isTypeGroupChat) {
692 processMessageReceipts(account, packet, remoteMsgId, query);
693 }
694 if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
695 conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
696 conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
697 }
698 }
699 mXmppConnectionService.getNotificationService().updateNotification();
700 return;
701 } else {
702 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received message correction but verification didn't check out");
703 }
704 }
705 }
706
707 long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate();
708 if (deletionDate != 0 && message.getTimeSent() < deletionDate) {
709 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping message from " + message.getCounterpart().toString() + " because it was sent prior to our deletion date");
710 return;
711 }
712
713 boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay", "urn:xmpp:delay"))
714 || message.isPrivateMessage()
715 || message.getServerMsgId() != null
716 || (query == null && mXmppConnectionService.getMessageArchiveService().isCatchupInProgress(conversation));
717 if (checkForDuplicates) {
718 final Message duplicate = conversation.findDuplicateMessage(message);
719 if (duplicate != null) {
720 final boolean serverMsgIdUpdated;
721 if (duplicate.getStatus() != Message.STATUS_RECEIVED
722 && duplicate.getUuid().equals(message.getRemoteMsgId())
723 && duplicate.getServerMsgId() == null
724 && message.getServerMsgId() != null) {
725 duplicate.setServerMsgId(message.getServerMsgId());
726 if (mXmppConnectionService.databaseBackend.updateMessage(duplicate, false)) {
727 serverMsgIdUpdated = true;
728 } else {
729 serverMsgIdUpdated = false;
730 Log.e(Config.LOGTAG, "failed to update message");
731 }
732 } else {
733 serverMsgIdUpdated = false;
734 }
735 Log.d(Config.LOGTAG, "skipping duplicate message with " + message.getCounterpart() + ". serverMsgIdUpdated=" + serverMsgIdUpdated);
736 return;
737 }
738 }
739
740 if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
741 conversation.prepend(query.getActualInThisQuery(), message);
742 } else {
743 conversation.add(message);
744 }
745 if (query != null) {
746 query.incrementActualMessageCount();
747 }
748
749 if (query == null || query.isCatchup()) { //either no mam or catchup
750 if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
751 mXmppConnectionService.markRead(conversation);
752 if (query == null) {
753 activateGracePeriod(account);
754 }
755 } else {
756 message.markUnread();
757 notify = true;
758 }
759 }
760
761 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
762 notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
763 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE || message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
764 notify = false;
765 }
766
767 if (query == null) {
768 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
769 mXmppConnectionService.updateConversationUi();
770 }
771
772 if (mXmppConnectionService.confirmMessages()
773 && message.getStatus() == Message.STATUS_RECEIVED
774 && (message.trusted() || message.isPrivateMessage())
775 && remoteMsgId != null
776 && !selfAddressed
777 && !isTypeGroupChat) {
778 processMessageReceipts(account, packet, remoteMsgId, query);
779 }
780
781 if (message.getFileParams() != null) {
782 for (Cid cid : message.getFileParams().getCids()) {
783 File f = mXmppConnectionService.getFileForCid(cid);
784 if (f != null && f.canRead()) {
785 message.setRelativeFilePath(f.getAbsolutePath());
786 mXmppConnectionService.getFileBackend().updateFileParams(message, null, false);
787 break;
788 }
789 }
790 }
791
792 mXmppConnectionService.databaseBackend.createMessage(message);
793
794 final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
795 if (message.getRelativeFilePath() == null && message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
796 if (message.getOob() != null && message.getOob().getScheme().equalsIgnoreCase("cid")) {
797 try {
798 BobTransfer transfer = new BobTransfer.ForMessage(message, mXmppConnectionService);
799 message.setTransferable(transfer);
800 transfer.start();
801 } catch (URISyntaxException e) {
802 Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
803 }
804 } else {
805 manager.createNewDownloadConnection(message);
806 }
807 } else if (notify) {
808 if (query != null && query.isCatchup()) {
809 mXmppConnectionService.getNotificationService().pushFromBacklog(message);
810 } else {
811 mXmppConnectionService.getNotificationService().push(message);
812 }
813 }
814 } else if (!packet.hasChild("body")) { //no body
815
816 final Conversation conversation = mXmppConnectionService.find(account, from.asBareJid());
817 if (axolotlEncrypted != null) {
818 Jid origin;
819 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
820 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
821 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
822 if (origin == null) {
823 Log.d(Config.LOGTAG, "omemo key transport message in anonymous conference received");
824 return;
825 }
826 } else if (isTypeGroupChat) {
827 return;
828 } else {
829 origin = from;
830 }
831 try {
832 final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.asBareJid());
833 account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
834 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": omemo key transport message received from " + origin);
835 } catch (Exception e) {
836 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": invalid omemo key transport message received " + e.getMessage());
837 return;
838 }
839 }
840
841 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
842 mXmppConnectionService.updateConversationUi();
843 }
844
845 if (isTypeGroupChat) {
846 if (packet.hasChild("subject")) { //TODO usually we would want to check for lack of body; however some servers do set a body :(
847 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
848 conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
849 final LocalizedContent subject = packet.findInternationalizedChildContentInDefaultNamespace("subject");
850 if (subject != null && conversation.getMucOptions().setSubject(subject.content)) {
851 mXmppConnectionService.updateConversation(conversation);
852 }
853 mXmppConnectionService.updateConversationUi();
854 return;
855 }
856 }
857 }
858 if (conversation != null && mucUserElement != null && InvalidJid.hasValidFrom(packet) && from.isBareJid()) {
859 for (Element child : mucUserElement.getChildren()) {
860 if ("status".equals(child.getName())) {
861 try {
862 int code = Integer.parseInt(child.getAttribute("code"));
863 if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
864 mXmppConnectionService.fetchConferenceConfiguration(conversation);
865 break;
866 }
867 } catch (Exception e) {
868 //ignored
869 }
870 } else if ("item".equals(child.getName())) {
871 MucOptions.User user = AbstractParser.parseItem(conversation, child);
872 Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for "
873 + user.getRealJid() + " to " + user.getAffiliation() + " in "
874 + conversation.getJid().asBareJid());
875 if (!user.realJidMatchesAccount()) {
876 boolean isNew = conversation.getMucOptions().updateUser(user);
877 mXmppConnectionService.getAvatarService().clear(conversation);
878 mXmppConnectionService.updateMucRosterUi();
879 mXmppConnectionService.updateConversationUi();
880 Contact contact = user.getContact();
881 if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
882 Jid jid = user.getRealJid();
883 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
884 if (cryptoTargets.remove(user.getRealJid())) {
885 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
886 conversation.setAcceptedCryptoTargets(cryptoTargets);
887 mXmppConnectionService.updateConversation(conversation);
888 }
889 } else if (isNew
890 && user.getRealJid() != null
891 && conversation.getMucOptions().isPrivateAndNonAnonymous()
892 && (contact == null || !contact.mutualPresenceSubscription())
893 && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
894 account.getAxolotlService().fetchDeviceIds(user.getRealJid());
895 }
896 }
897 }
898 }
899 }
900 if (!isTypeGroupChat) {
901 for (Element child : packet.getChildren()) {
902 if (Namespace.JINGLE_MESSAGE.equals(child.getNamespace()) && JINGLE_MESSAGE_ELEMENT_NAMES.contains(child.getName())) {
903 final String action = child.getName();
904 final String sessionId = child.getAttribute("id");
905 if (sessionId == null) {
906 break;
907 }
908 if (query == null) {
909 if (serverMsgId == null) {
910 serverMsgId = extractStanzaId(account, packet);
911 }
912 mXmppConnectionService.getJingleConnectionManager().deliverMessage(account, packet.getTo(), packet.getFrom(), child, remoteMsgId, serverMsgId, timestamp);
913 if (!account.getJid().asBareJid().equals(from.asBareJid()) && remoteMsgId != null) {
914 processMessageReceipts(account, packet, remoteMsgId, query);
915 }
916 } else if (query.isCatchup()) {
917 if ("propose".equals(action)) {
918 final Element description = child.findChild("description");
919 final String namespace = description == null ? null : description.getNamespace();
920 if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
921 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
922 final Message preExistingMessage = c.findRtpSession(sessionId, status);
923 if (preExistingMessage != null) {
924 preExistingMessage.setServerMsgId(serverMsgId);
925 mXmppConnectionService.updateMessage(preExistingMessage);
926 break;
927 }
928 final Message message = new Message(
929 c,
930 status,
931 Message.TYPE_RTP_SESSION,
932 sessionId
933 );
934 message.setServerMsgId(serverMsgId);
935 message.setTime(timestamp);
936 message.setBody(new RtpSessionStatus(false, 0).toString());
937 c.add(message);
938 mXmppConnectionService.databaseBackend.createMessage(message);
939 }
940 } else if ("proceed".equals(action)) {
941 //status needs to be flipped to find the original propose
942 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
943 final int s = packet.fromAccount(account) ? Message.STATUS_RECEIVED : Message.STATUS_SEND;
944 final Message message = c.findRtpSession(sessionId, s);
945 if (message != null) {
946 message.setBody(new RtpSessionStatus(true, 0).toString());
947 if (serverMsgId != null) {
948 message.setServerMsgId(serverMsgId);
949 }
950 message.setTime(timestamp);
951 mXmppConnectionService.updateMessage(message, true);
952 } else {
953 Log.d(Config.LOGTAG, "unable to find original rtp session message for received propose");
954 }
955
956 }
957 } else {
958 //MAM reloads (non catchups
959 if ("propose".equals(action)) {
960 final Element description = child.findChild("description");
961 final String namespace = description == null ? null : description.getNamespace();
962 if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
963 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
964 final Message preExistingMessage = c.findRtpSession(sessionId, status);
965 if (preExistingMessage != null) {
966 preExistingMessage.setServerMsgId(serverMsgId);
967 mXmppConnectionService.updateMessage(preExistingMessage);
968 break;
969 }
970 final Message message = new Message(
971 c,
972 status,
973 Message.TYPE_RTP_SESSION,
974 sessionId
975 );
976 message.setServerMsgId(serverMsgId);
977 message.setTime(timestamp);
978 message.setBody(new RtpSessionStatus(true, 0).toString());
979 if (query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
980 c.prepend(query.getActualInThisQuery(), message);
981 } else {
982 c.add(message);
983 }
984 query.incrementActualMessageCount();
985 mXmppConnectionService.databaseBackend.createMessage(message);
986 }
987 }
988 }
989 break;
990 }
991 }
992 }
993 }
994
995 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
996 if (received == null) {
997 received = packet.findChild("received", "urn:xmpp:receipts");
998 }
999 if (received != null) {
1000 String id = received.getAttribute("id");
1001 if (packet.fromAccount(account)) {
1002 if (query != null && id != null && packet.getTo() != null) {
1003 query.removePendingReceiptRequest(new ReceiptRequest(packet.getTo(), id));
1004 }
1005 } else if (id != null) {
1006 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
1007 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
1008 mXmppConnectionService.getJingleConnectionManager()
1009 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.DISCOVERED);
1010 } else {
1011 mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_RECEIVED);
1012 }
1013 }
1014 }
1015 Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
1016 if (displayed != null) {
1017 final String id = displayed.getAttribute("id");
1018 final Jid sender = InvalidJid.getNullForInvalid(displayed.getAttributeAsJid("sender"));
1019 if (packet.fromAccount(account) && !selfAddressed) {
1020 dismissNotification(account, counterpart, query, id);
1021 if (query == null) {
1022 activateGracePeriod(account);
1023 }
1024 } else if (isTypeGroupChat) {
1025 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1026 final Message message;
1027 if (conversation != null && id != null) {
1028 if (sender != null) {
1029 message = conversation.findMessageWithRemoteId(id, sender);
1030 } else {
1031 message = conversation.findMessageWithServerMsgId(id);
1032 }
1033 } else {
1034 message = null;
1035 }
1036 if (message != null) {
1037 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
1038 final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
1039 final boolean trueJidMatchesAccount = account.getJid().asBareJid().equals(trueJid == null ? null : trueJid.asBareJid());
1040 if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
1041 if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
1042 mXmppConnectionService.markRead(conversation);
1043 }
1044 } else if (!counterpart.isBareJid() && trueJid != null) {
1045 final ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
1046 if (message.addReadByMarker(readByMarker)) {
1047 mXmppConnectionService.updateMessage(message, false);
1048 }
1049 }
1050 }
1051 } else {
1052 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_DISPLAYED);
1053 Message message = displayedMessage == null ? null : displayedMessage.prev();
1054 while (message != null
1055 && message.getStatus() == Message.STATUS_SEND_RECEIVED
1056 && message.getTimeSent() < displayedMessage.getTimeSent()) {
1057 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
1058 message = message.prev();
1059 }
1060 if (displayedMessage != null && selfAddressed) {
1061 dismissNotification(account, counterpart, query, id);
1062 }
1063 }
1064 }
1065
1066 final Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
1067 if (event != null && InvalidJid.hasValidFrom(original) && original.getFrom().isBareJid()) {
1068 if (event.hasChild("items")) {
1069 parseEvent(event, original.getFrom(), account);
1070 } else if (event.hasChild("delete")) {
1071 parseDeleteEvent(event, original.getFrom(), account);
1072 } else if (event.hasChild("purge")) {
1073 parsePurgeEvent(event, original.getFrom(), account);
1074 }
1075 }
1076
1077 final String nick = packet.findChildContent("nick", Namespace.NICK);
1078 if (nick != null && InvalidJid.hasValidFrom(original)) {
1079 if (mXmppConnectionService.isMuc(account, from)) {
1080 return;
1081 }
1082 final Contact contact = account.getRoster().getContact(from);
1083 if (contact.setPresenceName(nick)) {
1084 mXmppConnectionService.syncRoster(account);
1085 mXmppConnectionService.getAvatarService().clear(contact);
1086 }
1087 }
1088 }
1089
1090 private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query, final String id) {
1091 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1092 if (conversation != null && (query == null || query.isCatchup())) {
1093 final String displayableId = conversation.findMostRecentRemoteDisplayableId();
1094 if (displayableId != null && displayableId.equals(id)) {
1095 mXmppConnectionService.markRead(conversation);
1096 } else {
1097 Log.w(Config.LOGTAG, account.getJid().asBareJid() + ": received dismissing display marker that did not match our last id in that conversation");
1098 }
1099 }
1100 }
1101
1102 private void processMessageReceipts(final Account account, final MessagePacket packet, final String remoteMsgId, MessageArchiveService.Query query) {
1103 final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
1104 final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
1105 if (query == null) {
1106 final ArrayList<String> receiptsNamespaces = new ArrayList<>();
1107 if (markable) {
1108 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
1109 }
1110 if (request) {
1111 receiptsNamespaces.add("urn:xmpp:receipts");
1112 }
1113 if (receiptsNamespaces.size() > 0) {
1114 final MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
1115 packet.getFrom(),
1116 remoteMsgId,
1117 receiptsNamespaces,
1118 packet.getType());
1119 mXmppConnectionService.sendMessagePacket(account, receipt);
1120 }
1121 } else if (query.isCatchup()) {
1122 if (request) {
1123 query.addPendingReceiptRequest(new ReceiptRequest(packet.getFrom(), remoteMsgId));
1124 }
1125 }
1126 }
1127
1128 private void activateGracePeriod(Account account) {
1129 long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
1130 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
1131 account.activateGracePeriod(duration);
1132 }
1133
1134 private class Invite {
1135 final Jid jid;
1136 final String password;
1137 final boolean direct;
1138 final Jid inviter;
1139
1140 Invite(Jid jid, String password, boolean direct, Jid inviter) {
1141 this.jid = jid;
1142 this.password = password;
1143 this.direct = direct;
1144 this.inviter = inviter;
1145 }
1146
1147 public boolean execute(Account account) {
1148 if (jid != null) {
1149 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
1150 if (conversation.getMucOptions().online()) {
1151 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received invite to " + jid + " but muc is considered to be online");
1152 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
1153 } else {
1154 conversation.getMucOptions().setPassword(password);
1155 mXmppConnectionService.databaseBackend.updateConversation(conversation);
1156 final Contact contact = inviter != null ? account.getRoster().getContactFromContactList(inviter) : null;
1157 mXmppConnectionService.joinMuc(conversation, contact != null && contact.mutualPresenceSubscription());
1158 mXmppConnectionService.updateConversationUi();
1159 }
1160 return true;
1161 }
1162 return false;
1163 }
1164 }
1165}