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