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