1package eu.siacs.conversations.parser;
2
3import android.util.Log;
4import android.util.Pair;
5
6import java.net.URL;
7import java.text.SimpleDateFormat;
8import java.util.ArrayList;
9import java.util.Arrays;
10import java.util.Collections;
11import java.util.Date;
12import java.util.List;
13import java.util.Locale;
14import java.util.Map;
15import java.util.Set;
16import java.util.UUID;
17
18import eu.siacs.conversations.Config;
19import eu.siacs.conversations.R;
20import eu.siacs.conversations.crypto.axolotl.AxolotlService;
21import eu.siacs.conversations.crypto.axolotl.BrokenSessionException;
22import eu.siacs.conversations.crypto.axolotl.NotEncryptedForThisDeviceException;
23import eu.siacs.conversations.crypto.axolotl.OutdatedSenderException;
24import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
25import eu.siacs.conversations.entities.Account;
26import eu.siacs.conversations.entities.Bookmark;
27import eu.siacs.conversations.entities.Contact;
28import eu.siacs.conversations.entities.Conversation;
29import eu.siacs.conversations.entities.Conversational;
30import eu.siacs.conversations.entities.Message;
31import eu.siacs.conversations.entities.MucOptions;
32import eu.siacs.conversations.entities.ReadByMarker;
33import eu.siacs.conversations.entities.ReceiptRequest;
34import eu.siacs.conversations.entities.RtpSessionStatus;
35import eu.siacs.conversations.http.HttpConnectionManager;
36import eu.siacs.conversations.services.MessageArchiveService;
37import eu.siacs.conversations.services.QuickConversationsService;
38import eu.siacs.conversations.services.XmppConnectionService;
39import eu.siacs.conversations.utils.CryptoHelper;
40import eu.siacs.conversations.xml.Element;
41import eu.siacs.conversations.xml.LocalizedContent;
42import eu.siacs.conversations.xml.Namespace;
43import eu.siacs.conversations.xmpp.InvalidJid;
44import eu.siacs.conversations.xmpp.Jid;
45import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
46import eu.siacs.conversations.xmpp.chatstate.ChatState;
47import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
48import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
49import eu.siacs.conversations.xmpp.pep.Avatar;
50import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
51
52public class MessageParser extends AbstractParser implements OnMessagePacketReceived {
53
54 private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
55
56 private static final List<String> JINGLE_MESSAGE_ELEMENT_NAMES = Arrays.asList("accept", "propose", "proceed", "reject", "retract");
57
58 public MessageParser(XmppConnectionService service) {
59 super(service);
60 }
61
62 private static String extractStanzaId(Element packet, boolean isTypeGroupChat, Conversation conversation) {
63 final Jid by;
64 final boolean safeToExtract;
65 if (isTypeGroupChat) {
66 by = conversation.getJid().asBareJid();
67 safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
68 } else {
69 Account account = conversation.getAccount();
70 by = account.getJid().asBareJid();
71 safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
72 }
73 return safeToExtract ? extractStanzaId(packet, by) : null;
74 }
75
76 private static String extractStanzaId(Account account, Element packet) {
77 final boolean safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
78 return safeToExtract ? extractStanzaId(packet, account.getJid().asBareJid()) : null;
79 }
80
81 private static String extractStanzaId(Element packet, Jid by) {
82 for (Element child : packet.getChildren()) {
83 if (child.getName().equals("stanza-id")
84 && Namespace.STANZA_IDS.equals(child.getNamespace())
85 && by.equals(InvalidJid.getNullForInvalid(child.getAttributeAsJid("by")))) {
86 return child.getAttribute("id");
87 }
88 }
89 return null;
90 }
91
92 private static Jid getTrueCounterpart(Element mucUserElement, Jid fallback) {
93 final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
94 Jid result = item == null ? null : InvalidJid.getNullForInvalid(item.getAttributeAsJid("jid"));
95 return result != null ? result : fallback;
96 }
97
98 private boolean extractChatState(Conversation c, final boolean isTypeGroupChat, final MessagePacket packet) {
99 ChatState state = ChatState.parse(packet);
100 if (state != null && c != null) {
101 final Account account = c.getAccount();
102 final Jid from = packet.getFrom();
103 if (from.asBareJid().equals(account.getJid().asBareJid())) {
104 c.setOutgoingChatState(state);
105 if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
106 if (c.getContact().isSelf()) {
107 return false;
108 }
109 mXmppConnectionService.markRead(c);
110 activateGracePeriod(account);
111 }
112 return false;
113 } else {
114 if (isTypeGroupChat) {
115 MucOptions.User user = c.getMucOptions().findUserByFullJid(from);
116 if (user != null) {
117 return user.setChatState(state);
118 } else {
119 return false;
120 }
121 } else {
122 return c.setIncomingChatState(state);
123 }
124 }
125 }
126 return false;
127 }
128
129 private Message parseAxolotlChat(Element axolotlMessage, Jid from, Conversation conversation, int status, final boolean checkedForDuplicates, boolean postpone) {
130 final AxolotlService service = conversation.getAccount().getAxolotlService();
131 final XmppAxolotlMessage xmppAxolotlMessage;
132 try {
133 xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.asBareJid());
134 } catch (Exception e) {
135 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": invalid omemo message received " + e.getMessage());
136 return null;
137 }
138 if (xmppAxolotlMessage.hasPayload()) {
139 final XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage;
140 try {
141 plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage, postpone);
142 } catch (BrokenSessionException e) {
143 if (checkedForDuplicates) {
144 if (service.trustedOrPreviouslyResponded(from.asBareJid())) {
145 service.reportBrokenSessionException(e, postpone);
146 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
147 } else {
148 Log.d(Config.LOGTAG, "ignoring broken session exception because contact was not trusted");
149 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
150 }
151 } else {
152 Log.d(Config.LOGTAG, "ignoring broken session exception because checkForDuplicates failed");
153 return null;
154 }
155 } catch (NotEncryptedForThisDeviceException e) {
156 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE, status);
157 } catch (OutdatedSenderException e) {
158 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
159 }
160 if (plaintextMessage != null) {
161 Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
162 finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
163 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount()) + " Received Message with session fingerprint: " + plaintextMessage.getFingerprint());
164 return finishedMessage;
165 }
166 } else {
167 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": received OMEMO key transport message");
168 service.processReceivingKeyTransportMessage(xmppAxolotlMessage, postpone);
169 }
170 return null;
171 }
172
173 private Invite extractInvite(Element message) {
174 final Element mucUser = message.findChild("x", Namespace.MUC_USER);
175 if (mucUser != null) {
176 Element invite = mucUser.findChild("invite");
177 if (invite != null) {
178 String password = mucUser.findChildContent("password");
179 Jid from = InvalidJid.getNullForInvalid(invite.getAttributeAsJid("from"));
180 Jid room = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
181 if (room == null) {
182 return null;
183 }
184 return new Invite(room, password, false, from);
185 }
186 }
187 final Element conference = message.findChild("x", "jabber:x:conference");
188 if (conference != null) {
189 Jid from = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
190 Jid room = InvalidJid.getNullForInvalid(conference.getAttributeAsJid("jid"));
191 if (room == null) {
192 return null;
193 }
194 return new Invite(room, conference.getAttribute("password"), true, from);
195 }
196 return null;
197 }
198
199 private void parseEvent(final Element event, final Jid from, final Account account) {
200 Element items = event.findChild("items");
201 String node = items == null ? null : items.getAttribute("node");
202 if ("urn:xmpp:avatar:metadata".equals(node)) {
203 Avatar avatar = Avatar.parseMetadata(items);
204 if (avatar != null) {
205 avatar.owner = from.asBareJid();
206 if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
207 if (account.getJid().asBareJid().equals(from)) {
208 if (account.setAvatar(avatar.getFilename())) {
209 mXmppConnectionService.databaseBackend.updateAccount(account);
210 mXmppConnectionService.notifyAccountAvatarHasChanged(account);
211 }
212 mXmppConnectionService.getAvatarService().clear(account);
213 mXmppConnectionService.updateConversationUi();
214 mXmppConnectionService.updateAccountUi();
215 } else {
216 final Contact contact = account.getRoster().getContact(from);
217 contact.setAvatar(avatar);
218 mXmppConnectionService.syncRoster(account);
219 mXmppConnectionService.getAvatarService().clear(contact);
220 mXmppConnectionService.updateConversationUi();
221 mXmppConnectionService.updateRosterUi();
222 }
223 } else if (mXmppConnectionService.isDataSaverDisabled()) {
224 mXmppConnectionService.fetchAvatar(account, avatar);
225 }
226 }
227 } else if (Namespace.NICK.equals(node)) {
228 final Element i = items.findChild("item");
229 final String nick = i == null ? null : i.findChildContent("nick", Namespace.NICK);
230 if (nick != null) {
231 setNick(account, from, nick);
232 }
233 } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
234 Element item = items.findChild("item");
235 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
236 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received PEP device list " + deviceIds + " update from " + from + ", processing... ");
237 AxolotlService axolotlService = account.getAxolotlService();
238 axolotlService.registerDevices(from, deviceIds);
239 } else if (Namespace.BOOKMARKS.equals(node) && account.getJid().asBareJid().equals(from)) {
240 if (account.getXmppConnection().getFeatures().bookmarksConversion()) {
241 final Element i = items.findChild("item");
242 final Element storage = i == null ? null : i.findChild("storage", Namespace.BOOKMARKS);
243 Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
244 mXmppConnectionService.processBookmarksInitial(account, bookmarks, true);
245 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": processing bookmark PEP event");
246 } else {
247 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring bookmark PEP event because bookmark conversion was not detected");
248 }
249 } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
250 final Element item = items.findChild("item");
251 final Element retract = items.findChild("retract");
252 if (item != null) {
253 final Bookmark bookmark = Bookmark.parseFromItem(item, account);
254 if (bookmark != null) {
255 account.putBookmark(bookmark);
256 mXmppConnectionService.processModifiedBookmark(bookmark);
257 mXmppConnectionService.updateConversationUi();
258 }
259 }
260 if (retract != null) {
261 final Jid id = InvalidJid.getNullForInvalid(retract.getAttributeAsJid("id"));
262 if (id != null) {
263 account.removeBookmark(id);
264 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmark for " + id);
265 mXmppConnectionService.processDeletedBookmark(account, id);
266 mXmppConnectionService.updateConversationUi();
267 }
268 }
269 } else {
270 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " received pubsub notification for node=" + node);
271 }
272 }
273
274 private void parseDeleteEvent(final Element event, final Jid from, final Account account) {
275 final Element delete = event.findChild("delete");
276 final String node = delete == null ? null : delete.getAttribute("node");
277 if (Namespace.NICK.equals(node)) {
278 Log.d(Config.LOGTAG, "parsing nick delete event from " + from);
279 setNick(account, from, null);
280 } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
281 account.setBookmarks(Collections.emptyMap());
282 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmarks node");
283 }
284 }
285
286 private void parsePurgeEvent(final Element event, final Jid from, final Account account) {
287 final Element purge = event.findChild("purge");
288 final String node = purge == null ? null : purge.getAttribute("node");
289 if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
290 account.setBookmarks(Collections.emptyMap());
291 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": purged bookmarks");
292 }
293 }
294
295 private void setNick(Account account, Jid user, String nick) {
296 if (user.asBareJid().equals(account.getJid().asBareJid())) {
297 account.setDisplayName(nick);
298 if (QuickConversationsService.isQuicksy()) {
299 mXmppConnectionService.getAvatarService().clear(account);
300 }
301 } else {
302 Contact contact = account.getRoster().getContact(user);
303 if (contact.setPresenceName(nick)) {
304 mXmppConnectionService.syncRoster(account);
305 mXmppConnectionService.getAvatarService().clear(contact);
306 }
307 }
308 mXmppConnectionService.updateConversationUi();
309 mXmppConnectionService.updateAccountUi();
310 }
311
312 private boolean handleErrorMessage(final Account account, final MessagePacket packet) {
313 if (packet.getType() == MessagePacket.TYPE_ERROR) {
314 if (packet.fromServer(account)) {
315 final Pair<MessagePacket, Long> forwarded = packet.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
316 if (forwarded != null) {
317 return handleErrorMessage(account, forwarded.first);
318 }
319 }
320 final Jid from = packet.getFrom();
321 final String id = packet.getId();
322 if (from != null && id != null) {
323 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
324 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
325 mXmppConnectionService.getJingleConnectionManager()
326 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.FAILED);
327 return true;
328 }
329 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX)) {
330 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX.length());
331 mXmppConnectionService.getJingleConnectionManager().failProceed(account, from, sessionId);
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)) {
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 final Contact contact = account.getRoster().getContact(from);
1017 if (contact.setPresenceName(nick)) {
1018 mXmppConnectionService.syncRoster(account);
1019 mXmppConnectionService.getAvatarService().clear(contact);
1020 }
1021 }
1022 }
1023
1024 private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query, final String id) {
1025 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1026 if (conversation != null && (query == null || query.isCatchup())) {
1027 final String displayableId = conversation.findMostRecentRemoteDisplayableId();
1028 if (displayableId != null && displayableId.equals(id)) {
1029 mXmppConnectionService.markRead(conversation);
1030 } else {
1031 Log.w(Config.LOGTAG, account.getJid().asBareJid() + ": received dismissing display marker that did not match our last id in that conversation");
1032 }
1033 }
1034 }
1035
1036 private void processMessageReceipts(final Account account, final MessagePacket packet, final String remoteMsgId, MessageArchiveService.Query query) {
1037 final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
1038 final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
1039 if (query == null) {
1040 final ArrayList<String> receiptsNamespaces = new ArrayList<>();
1041 if (markable) {
1042 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
1043 }
1044 if (request) {
1045 receiptsNamespaces.add("urn:xmpp:receipts");
1046 }
1047 if (receiptsNamespaces.size() > 0) {
1048 final MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
1049 packet.getFrom(),
1050 remoteMsgId,
1051 receiptsNamespaces,
1052 packet.getType());
1053 mXmppConnectionService.sendMessagePacket(account, receipt);
1054 }
1055 } else if (query.isCatchup()) {
1056 if (request) {
1057 query.addPendingReceiptRequest(new ReceiptRequest(packet.getFrom(), remoteMsgId));
1058 }
1059 }
1060 }
1061
1062 private void activateGracePeriod(Account account) {
1063 long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
1064 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
1065 account.activateGracePeriod(duration);
1066 }
1067
1068 private class Invite {
1069 final Jid jid;
1070 final String password;
1071 final boolean direct;
1072 final Jid inviter;
1073
1074 Invite(Jid jid, String password, boolean direct, Jid inviter) {
1075 this.jid = jid;
1076 this.password = password;
1077 this.direct = direct;
1078 this.inviter = inviter;
1079 }
1080
1081 public boolean execute(Account account) {
1082 if (jid != null) {
1083 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
1084 if (conversation.getMucOptions().online()) {
1085 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received invite to " + jid + " but muc is considered to be online");
1086 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
1087 } else {
1088 conversation.getMucOptions().setPassword(password);
1089 mXmppConnectionService.databaseBackend.updateConversation(conversation);
1090 final Contact contact = inviter != null ? account.getRoster().getContactFromContactList(inviter) : null;
1091 mXmppConnectionService.joinMuc(conversation, contact != null && contact.mutualPresenceSubscription());
1092 mXmppConnectionService.updateConversationUi();
1093 }
1094 return true;
1095 }
1096 return false;
1097 }
1098 }
1099}