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 =
56 Arrays.asList("accept", "propose", "proceed", "reject", "retract", "ringing");
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 final Element items = event.findChild("items");
201 final 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 final 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 } else if (Namespace.AVATAR_METADATA.equals(node) && account.getJid().asBareJid().equals(from)) {
284 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": deleted avatar metadata node");
285 }
286 }
287
288 private void parsePurgeEvent(final Element event, final Jid from, final Account account) {
289 final Element purge = event.findChild("purge");
290 final String node = purge == null ? null : purge.getAttribute("node");
291 if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
292 account.setBookmarks(Collections.emptyMap());
293 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": purged bookmarks");
294 }
295 }
296
297 private void setNick(Account account, Jid user, String nick) {
298 if (user.asBareJid().equals(account.getJid().asBareJid())) {
299 account.setDisplayName(nick);
300 if (QuickConversationsService.isQuicksy()) {
301 mXmppConnectionService.getAvatarService().clear(account);
302 }
303 } else {
304 Contact contact = account.getRoster().getContact(user);
305 if (contact.setPresenceName(nick)) {
306 mXmppConnectionService.syncRoster(account);
307 mXmppConnectionService.getAvatarService().clear(contact);
308 }
309 }
310 mXmppConnectionService.updateConversationUi();
311 mXmppConnectionService.updateAccountUi();
312 }
313
314 private boolean handleErrorMessage(final Account account, final MessagePacket packet) {
315 if (packet.getType() == MessagePacket.TYPE_ERROR) {
316 if (packet.fromServer(account)) {
317 final Pair<MessagePacket, Long> forwarded = packet.getForwardedMessagePacket("received", Namespace.CARBONS);
318 if (forwarded != null) {
319 return handleErrorMessage(account, forwarded.first);
320 }
321 }
322 final Jid from = packet.getFrom();
323 final String id = packet.getId();
324 if (from != null && id != null) {
325 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
326 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
327 mXmppConnectionService.getJingleConnectionManager()
328 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.FAILED);
329 return true;
330 }
331 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX)) {
332 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX.length());
333 final String message = extractErrorMessage(packet);
334 mXmppConnectionService.getJingleConnectionManager().failProceed(account, from, sessionId, message);
335 return true;
336 }
337 mXmppConnectionService.markMessage(account,
338 from.asBareJid(),
339 id,
340 Message.STATUS_SEND_FAILED,
341 extractErrorMessage(packet));
342 final Element error = packet.findChild("error");
343 final boolean pingWorthyError = error != null && (error.hasChild("not-acceptable") || error.hasChild("remote-server-timeout") || error.hasChild("remote-server-not-found"));
344 if (pingWorthyError) {
345 Conversation conversation = mXmppConnectionService.find(account, from);
346 if (conversation != null && conversation.getMode() == Conversational.MODE_MULTI) {
347 if (conversation.getMucOptions().online()) {
348 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received ping worthy error for seemingly online muc at " + from);
349 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
350 }
351 }
352 }
353 }
354 return true;
355 }
356 return false;
357 }
358
359 @Override
360 public void onMessagePacketReceived(Account account, MessagePacket original) {
361 if (handleErrorMessage(account, original)) {
362 return;
363 }
364 final MessagePacket packet;
365 Long timestamp = null;
366 boolean isCarbon = false;
367 String serverMsgId = null;
368 final Element fin = original.findChild("fin", MessageArchiveService.Version.MAM_0.namespace);
369 if (fin != null) {
370 mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin, original.getFrom());
371 return;
372 }
373 final Element result = MessageArchiveService.Version.findResult(original);
374 final String queryId = result == null ? null : result.getAttribute("queryid");
375 final MessageArchiveService.Query query = queryId == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(queryId);
376 if (query != null && query.validFrom(original.getFrom())) {
377 final Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", query.version.namespace);
378 if (f == null) {
379 return;
380 }
381 timestamp = f.second;
382 packet = f.first;
383 serverMsgId = result.getAttribute("id");
384 query.incrementMessageCount();
385 if (handleErrorMessage(account, packet)) {
386 return;
387 }
388 } else if (query != null) {
389 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received mam result with invalid from (" + original.getFrom() + ") or queryId (" + queryId + ")");
390 return;
391 } else if (original.fromServer(account)) {
392 Pair<MessagePacket, Long> f;
393 f = original.getForwardedMessagePacket("received", Namespace.CARBONS);
394 f = f == null ? original.getForwardedMessagePacket("sent", Namespace.CARBONS) : f;
395 packet = f != null ? f.first : original;
396 if (handleErrorMessage(account, packet)) {
397 return;
398 }
399 timestamp = f != null ? f.second : null;
400 isCarbon = f != null;
401 } else {
402 packet = original;
403 }
404
405 if (timestamp == null) {
406 timestamp = AbstractParser.parseTimestamp(original, AbstractParser.parseTimestamp(packet));
407 }
408 final LocalizedContent body = packet.getBody();
409 final Element mucUserElement = packet.findChild("x", Namespace.MUC_USER);
410 final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
411 final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
412 final Element oob = packet.findChild("x", Namespace.OOB);
413 final String oobUrl = oob != null ? oob.findChildContent("url") : null;
414 final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
415 final Element axolotlEncrypted = packet.findChildEnsureSingle(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
416 int status;
417 final Jid counterpart;
418 final Jid to = packet.getTo();
419 final Jid from = packet.getFrom();
420 final Element originId = packet.findChild("origin-id", Namespace.STANZA_IDS);
421 final String remoteMsgId;
422 if (originId != null && originId.getAttribute("id") != null) {
423 remoteMsgId = originId.getAttribute("id");
424 } else {
425 remoteMsgId = packet.getId();
426 }
427 boolean notify = false;
428
429 if (from == null || !InvalidJid.isValid(from) || !InvalidJid.isValid(to)) {
430 Log.e(Config.LOGTAG, "encountered invalid message from='" + from + "' to='" + to + "'");
431 return;
432 }
433
434 boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
435 if (query != null && !query.muc() && isTypeGroupChat) {
436 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": received groupchat (" + from + ") message on regular MAM request. skipping");
437 return;
438 }
439 boolean isMucStatusMessage = InvalidJid.hasValidFrom(packet) && from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
440 boolean selfAddressed;
441 if (packet.fromAccount(account)) {
442 status = Message.STATUS_SEND;
443 selfAddressed = to == null || account.getJid().asBareJid().equals(to.asBareJid());
444 if (selfAddressed) {
445 counterpart = from;
446 } else {
447 counterpart = to != null ? to : account.getJid();
448 }
449 } else {
450 status = Message.STATUS_RECEIVED;
451 counterpart = from;
452 selfAddressed = false;
453 }
454
455 final Invite invite = extractInvite(packet);
456 if (invite != null) {
457 if (isTypeGroupChat) {
458 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring invite to " + invite.jid + " because type=groupchat");
459 } else if (invite.direct && (mucUserElement != null || invite.inviter == null || mXmppConnectionService.isMuc(account, invite.inviter))) {
460 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring direct invite to " + invite.jid + " because it was received in MUC");
461 } else {
462 invite.execute(account);
463 return;
464 }
465 }
466
467 if ((body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || oobUrl != null) && !isMucStatusMessage) {
468 final boolean conversationIsProbablyMuc = isTypeGroupChat || mucUserElement != null || account.getXmppConnection().getMucServersWithholdAccount().contains(counterpart.getDomain().toEscapedString());
469 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), conversationIsProbablyMuc, false, query, false);
470 final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
471
472 if (serverMsgId == null) {
473 serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
474 }
475
476
477 if (selfAddressed) {
478 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, Message.STATUS_SEND_RECEIVED, serverMsgId)) {
479 return;
480 }
481 status = Message.STATUS_RECEIVED;
482 if (remoteMsgId != null && conversation.findMessageWithRemoteId(remoteMsgId, counterpart) != null) {
483 return;
484 }
485 }
486
487 if (isTypeGroupChat) {
488 if (conversation.getMucOptions().isSelf(counterpart)) {
489 status = Message.STATUS_SEND_RECEIVED;
490 isCarbon = true; //not really carbon but received from another resource
491 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId, body)) {
492 return;
493 } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
494 if (body != null) {
495 Message message = conversation.findSentMessageWithBody(body.content);
496 if (message != null) {
497 mXmppConnectionService.markMessage(message, status);
498 return;
499 }
500 }
501 }
502 } else {
503 status = Message.STATUS_RECEIVED;
504 }
505 }
506 final Message message;
507 if (pgpEncrypted != null && Config.supportOpenPgp()) {
508 message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
509 } else if (axolotlEncrypted != null && Config.supportOmemo()) {
510 Jid origin;
511 Set<Jid> fallbacksBySourceId = Collections.emptySet();
512 if (conversationMultiMode) {
513 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
514 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
515 if (origin == null) {
516 try {
517 fallbacksBySourceId = account.getAxolotlService().findCounterpartsBySourceId(XmppAxolotlMessage.parseSourceId(axolotlEncrypted));
518 } catch (IllegalArgumentException e) {
519 //ignoring
520 }
521 }
522 if (origin == null && fallbacksBySourceId.size() == 0) {
523 Log.d(Config.LOGTAG, "axolotl message in anonymous conference received and no possible fallbacks");
524 return;
525 }
526 } else {
527 fallbacksBySourceId = Collections.emptySet();
528 origin = from;
529 }
530
531 final boolean liveMessage = query == null && !isTypeGroupChat && mucUserElement == null;
532 final boolean checkedForDuplicates = liveMessage || (serverMsgId != null && remoteMsgId != null && !conversation.possibleDuplicate(serverMsgId, remoteMsgId));
533
534 if (origin != null) {
535 message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status, checkedForDuplicates, query != null);
536 } else {
537 Message trial = null;
538 for (Jid fallback : fallbacksBySourceId) {
539 trial = parseAxolotlChat(axolotlEncrypted, fallback, conversation, status, checkedForDuplicates && fallbacksBySourceId.size() == 1, query != null);
540 if (trial != null) {
541 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": decoded muc message using fallback");
542 origin = fallback;
543 break;
544 }
545 }
546 message = trial;
547 }
548 if (message == null) {
549 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
550 mXmppConnectionService.updateConversationUi();
551 }
552 if (query != null && status == Message.STATUS_SEND && remoteMsgId != null) {
553 Message previouslySent = conversation.findSentMessageWithUuid(remoteMsgId);
554 if (previouslySent != null && previouslySent.getServerMsgId() == null && serverMsgId != null) {
555 previouslySent.setServerMsgId(serverMsgId);
556 mXmppConnectionService.databaseBackend.updateMessage(previouslySent, false);
557 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered previously sent OMEMO message without serverId. updating...");
558 }
559 }
560 return;
561 }
562 if (conversationMultiMode) {
563 message.setTrueCounterpart(origin);
564 }
565 } else if (body == null && oobUrl != null) {
566 message = new Message(conversation, oobUrl, Message.ENCRYPTION_NONE, status);
567 message.setOob(true);
568 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
569 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
570 }
571 } else {
572 message = new Message(conversation, body.content, Message.ENCRYPTION_NONE, status);
573 if (body.count > 1) {
574 message.setBodyLanguage(body.language);
575 }
576 }
577
578 message.setCounterpart(counterpart);
579 message.setRemoteMsgId(remoteMsgId);
580 message.setServerMsgId(serverMsgId);
581 message.setCarbon(isCarbon);
582 message.setTime(timestamp);
583 if (body != null && body.content != null && body.content.equals(oobUrl)) {
584 message.setOob(true);
585 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
586 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
587 }
588 }
589 message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
590 if (conversationMultiMode) {
591 message.setMucUser(conversation.getMucOptions().findUserByFullJid(counterpart));
592 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
593 Jid trueCounterpart;
594 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
595 trueCounterpart = message.getTrueCounterpart();
596 } else if (query != null && query.safeToExtractTrueCounterpart()) {
597 trueCounterpart = getTrueCounterpart(mucUserElement, fallback);
598 } else {
599 trueCounterpart = fallback;
600 }
601 if (trueCounterpart != null && isTypeGroupChat) {
602 if (trueCounterpart.asBareJid().equals(account.getJid().asBareJid())) {
603 status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
604 } else {
605 status = Message.STATUS_RECEIVED;
606 message.setCarbon(false);
607 }
608 }
609 message.setStatus(status);
610 message.setTrueCounterpart(trueCounterpart);
611 if (!isTypeGroupChat) {
612 message.setType(Message.TYPE_PRIVATE);
613 }
614 } else {
615 updateLastseen(account, from);
616 }
617
618 if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
619 final Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
620 counterpart,
621 message.getStatus() == Message.STATUS_RECEIVED,
622 message.isCarbon());
623 if (replacedMessage != null) {
624 final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
625 || replacedMessage.getFingerprint().equals(message.getFingerprint());
626 final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
627 && message.getTrueCounterpart() != null
628 && replacedMessage.getTrueCounterpart().asBareJid().equals(message.getTrueCounterpart().asBareJid());
629 final boolean mucUserMatches = query == null && replacedMessage.sameMucUser(message); //can not be checked when using mam
630 final boolean duplicate = conversation.hasDuplicateMessage(message);
631 if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode || mucUserMatches) && !duplicate) {
632 Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
633 synchronized (replacedMessage) {
634 final String uuid = replacedMessage.getUuid();
635 replacedMessage.setUuid(UUID.randomUUID().toString());
636 replacedMessage.setBody(message.getBody());
637 replacedMessage.putEdited(replacedMessage.getRemoteMsgId(), replacedMessage.getServerMsgId());
638 replacedMessage.setRemoteMsgId(remoteMsgId);
639 if (replacedMessage.getServerMsgId() == null || message.getServerMsgId() != null) {
640 replacedMessage.setServerMsgId(message.getServerMsgId());
641 }
642 replacedMessage.setEncryption(message.getEncryption());
643 if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
644 replacedMessage.markUnread();
645 }
646 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
647 mXmppConnectionService.updateMessage(replacedMessage, uuid);
648 if (mXmppConnectionService.confirmMessages()
649 && replacedMessage.getStatus() == Message.STATUS_RECEIVED
650 && (replacedMessage.trusted() || replacedMessage.isPrivateMessage()) //TODO do we really want to send receipts for all PMs?
651 && remoteMsgId != null
652 && !selfAddressed
653 && !isTypeGroupChat) {
654 processMessageReceipts(account, packet, remoteMsgId, query);
655 }
656 if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
657 conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
658 conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
659 }
660 }
661 mXmppConnectionService.getNotificationService().updateNotification();
662 return;
663 } else {
664 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received message correction but verification didn't check out");
665 }
666 }
667 }
668
669 long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate();
670 if (deletionDate != 0 && message.getTimeSent() < deletionDate) {
671 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping message from " + message.getCounterpart().toString() + " because it was sent prior to our deletion date");
672 return;
673 }
674
675 boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay", "urn:xmpp:delay"))
676 || message.isPrivateMessage()
677 || message.getServerMsgId() != null
678 || (query == null && mXmppConnectionService.getMessageArchiveService().isCatchupInProgress(conversation));
679 if (checkForDuplicates) {
680 final Message duplicate = conversation.findDuplicateMessage(message);
681 if (duplicate != null) {
682 final boolean serverMsgIdUpdated;
683 if (duplicate.getStatus() != Message.STATUS_RECEIVED
684 && duplicate.getUuid().equals(message.getRemoteMsgId())
685 && duplicate.getServerMsgId() == null
686 && message.getServerMsgId() != null) {
687 duplicate.setServerMsgId(message.getServerMsgId());
688 if (mXmppConnectionService.databaseBackend.updateMessage(duplicate, false)) {
689 serverMsgIdUpdated = true;
690 } else {
691 serverMsgIdUpdated = false;
692 Log.e(Config.LOGTAG, "failed to update message");
693 }
694 } else {
695 serverMsgIdUpdated = false;
696 }
697 Log.d(Config.LOGTAG, "skipping duplicate message with " + message.getCounterpart() + ". serverMsgIdUpdated=" + serverMsgIdUpdated);
698 return;
699 }
700 }
701
702 if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
703 conversation.prepend(query.getActualInThisQuery(), message);
704 } else {
705 conversation.add(message);
706 }
707 if (query != null) {
708 query.incrementActualMessageCount();
709 }
710
711 if (query == null || query.isCatchup()) { //either no mam or catchup
712 if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
713 mXmppConnectionService.markRead(conversation);
714 if (query == null) {
715 activateGracePeriod(account);
716 }
717 } else {
718 message.markUnread();
719 notify = true;
720 }
721 }
722
723 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
724 notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
725 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE || message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
726 notify = false;
727 }
728
729 if (query == null) {
730 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
731 mXmppConnectionService.updateConversationUi();
732 }
733
734 if (mXmppConnectionService.confirmMessages()
735 && message.getStatus() == Message.STATUS_RECEIVED
736 && (message.trusted() || message.isPrivateMessage())
737 && remoteMsgId != null
738 && !selfAddressed
739 && !isTypeGroupChat) {
740 processMessageReceipts(account, packet, remoteMsgId, query);
741 }
742
743 mXmppConnectionService.databaseBackend.createMessage(message);
744 final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
745 if (message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
746 manager.createNewDownloadConnection(message);
747 } else if (notify) {
748 if (query != null && query.isCatchup()) {
749 mXmppConnectionService.getNotificationService().pushFromBacklog(message);
750 } else {
751 mXmppConnectionService.getNotificationService().push(message);
752 }
753 }
754 } else if (!packet.hasChild("body")) { //no body
755
756 final Conversation conversation = mXmppConnectionService.find(account, from.asBareJid());
757 if (axolotlEncrypted != null) {
758 Jid origin;
759 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
760 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
761 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
762 if (origin == null) {
763 Log.d(Config.LOGTAG, "omemo key transport message in anonymous conference received");
764 return;
765 }
766 } else if (isTypeGroupChat) {
767 return;
768 } else {
769 origin = from;
770 }
771 try {
772 final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.asBareJid());
773 account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
774 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": omemo key transport message received from " + origin);
775 } catch (Exception e) {
776 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": invalid omemo key transport message received " + e.getMessage());
777 return;
778 }
779 }
780
781 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
782 mXmppConnectionService.updateConversationUi();
783 }
784
785 if (isTypeGroupChat) {
786 if (packet.hasChild("subject")) { //TODO usually we would want to check for lack of body; however some servers do set a body :(
787 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
788 conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
789 final LocalizedContent subject = packet.findInternationalizedChildContentInDefaultNamespace("subject");
790 if (subject != null && conversation.getMucOptions().setSubject(subject.content)) {
791 mXmppConnectionService.updateConversation(conversation);
792 }
793 mXmppConnectionService.updateConversationUi();
794 return;
795 }
796 }
797 }
798 if (conversation != null && mucUserElement != null && InvalidJid.hasValidFrom(packet) && from.isBareJid()) {
799 for (Element child : mucUserElement.getChildren()) {
800 if ("status".equals(child.getName())) {
801 try {
802 int code = Integer.parseInt(child.getAttribute("code"));
803 if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
804 mXmppConnectionService.fetchConferenceConfiguration(conversation);
805 break;
806 }
807 } catch (Exception e) {
808 //ignored
809 }
810 } else if ("item".equals(child.getName())) {
811 MucOptions.User user = AbstractParser.parseItem(conversation, child);
812 Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for "
813 + user.getRealJid() + " to " + user.getAffiliation() + " in "
814 + conversation.getJid().asBareJid());
815 if (!user.realJidMatchesAccount()) {
816 boolean isNew = conversation.getMucOptions().updateUser(user);
817 mXmppConnectionService.getAvatarService().clear(conversation);
818 mXmppConnectionService.updateMucRosterUi();
819 mXmppConnectionService.updateConversationUi();
820 Contact contact = user.getContact();
821 if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
822 Jid jid = user.getRealJid();
823 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
824 if (cryptoTargets.remove(user.getRealJid())) {
825 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
826 conversation.setAcceptedCryptoTargets(cryptoTargets);
827 mXmppConnectionService.updateConversation(conversation);
828 }
829 } else if (isNew
830 && user.getRealJid() != null
831 && conversation.getMucOptions().isPrivateAndNonAnonymous()
832 && (contact == null || !contact.mutualPresenceSubscription())
833 && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
834 account.getAxolotlService().fetchDeviceIds(user.getRealJid());
835 }
836 }
837 }
838 }
839 }
840 if (!isTypeGroupChat) {
841 for (Element child : packet.getChildren()) {
842 if (Namespace.JINGLE_MESSAGE.equals(child.getNamespace()) && JINGLE_MESSAGE_ELEMENT_NAMES.contains(child.getName())) {
843 final String action = child.getName();
844 final String sessionId = child.getAttribute("id");
845 if (sessionId == null) {
846 break;
847 }
848 if (query == null) {
849 if (serverMsgId == null) {
850 serverMsgId = extractStanzaId(account, packet);
851 }
852 mXmppConnectionService
853 .getJingleConnectionManager()
854 .deliverMessage(
855 account,
856 packet.getTo(),
857 packet.getFrom(),
858 child,
859 remoteMsgId,
860 serverMsgId,
861 timestamp);
862 final Contact contact = account.getRoster().getContact(from);
863 if (mXmppConnectionService.confirmMessages()
864 && !contact.isSelf()
865 && remoteMsgId != null
866 && contact.showInContactList()) {
867 processMessageReceipts(account, packet, remoteMsgId, null);
868 }
869 } else if (query.isCatchup()) {
870 if ("propose".equals(action)) {
871 final Element description = child.findChild("description");
872 final String namespace = description == null ? null : description.getNamespace();
873 if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
874 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
875 final Message preExistingMessage = c.findRtpSession(sessionId, status);
876 if (preExistingMessage != null) {
877 preExistingMessage.setServerMsgId(serverMsgId);
878 mXmppConnectionService.updateMessage(preExistingMessage);
879 break;
880 }
881 final Message message = new Message(
882 c,
883 status,
884 Message.TYPE_RTP_SESSION,
885 sessionId
886 );
887 message.setServerMsgId(serverMsgId);
888 message.setTime(timestamp);
889 message.setBody(new RtpSessionStatus(false, 0).toString());
890 c.add(message);
891 mXmppConnectionService.databaseBackend.createMessage(message);
892 }
893 } else if ("proceed".equals(action)) {
894 //status needs to be flipped to find the original propose
895 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
896 final int s = packet.fromAccount(account) ? Message.STATUS_RECEIVED : Message.STATUS_SEND;
897 final Message message = c.findRtpSession(sessionId, s);
898 if (message != null) {
899 message.setBody(new RtpSessionStatus(true, 0).toString());
900 if (serverMsgId != null) {
901 message.setServerMsgId(serverMsgId);
902 }
903 message.setTime(timestamp);
904 mXmppConnectionService.updateMessage(message, true);
905 } else {
906 Log.d(Config.LOGTAG, "unable to find original rtp session message for received propose");
907 }
908
909 }
910 } else {
911 //MAM reloads (non catchups
912 if ("propose".equals(action)) {
913 final Element description = child.findChild("description");
914 final String namespace = description == null ? null : description.getNamespace();
915 if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
916 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
917 final Message preExistingMessage = c.findRtpSession(sessionId, status);
918 if (preExistingMessage != null) {
919 preExistingMessage.setServerMsgId(serverMsgId);
920 mXmppConnectionService.updateMessage(preExistingMessage);
921 break;
922 }
923 final Message message = new Message(
924 c,
925 status,
926 Message.TYPE_RTP_SESSION,
927 sessionId
928 );
929 message.setServerMsgId(serverMsgId);
930 message.setTime(timestamp);
931 message.setBody(new RtpSessionStatus(true, 0).toString());
932 if (query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
933 c.prepend(query.getActualInThisQuery(), message);
934 } else {
935 c.add(message);
936 }
937 query.incrementActualMessageCount();
938 mXmppConnectionService.databaseBackend.createMessage(message);
939 }
940 }
941 }
942 break;
943 }
944 }
945 }
946 }
947
948 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
949 if (received == null) {
950 received = packet.findChild("received", "urn:xmpp:receipts");
951 }
952 if (received != null) {
953 String id = received.getAttribute("id");
954 if (packet.fromAccount(account)) {
955 if (query != null && id != null && packet.getTo() != null) {
956 query.removePendingReceiptRequest(new ReceiptRequest(packet.getTo(), id));
957 }
958 } else if (id != null) {
959 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
960 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
961 mXmppConnectionService.getJingleConnectionManager()
962 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.DISCOVERED);
963 } else {
964 mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_RECEIVED);
965 }
966 }
967 }
968 Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
969 if (displayed != null) {
970 final String id = displayed.getAttribute("id");
971 final Jid sender = InvalidJid.getNullForInvalid(displayed.getAttributeAsJid("sender"));
972 if (packet.fromAccount(account) && !selfAddressed) {
973 dismissNotification(account, counterpart, query, id);
974 if (query == null) {
975 activateGracePeriod(account);
976 }
977 } else if (isTypeGroupChat) {
978 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
979 final Message message;
980 if (conversation != null && id != null) {
981 if (sender != null) {
982 message = conversation.findMessageWithRemoteId(id, sender);
983 } else {
984 message = conversation.findMessageWithServerMsgId(id);
985 }
986 } else {
987 message = null;
988 }
989 if (message != null) {
990 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
991 final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
992 final boolean trueJidMatchesAccount = account.getJid().asBareJid().equals(trueJid == null ? null : trueJid.asBareJid());
993 if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
994 if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
995 mXmppConnectionService.markRead(conversation);
996 }
997 } else if (!counterpart.isBareJid() && trueJid != null) {
998 final ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
999 if (message.addReadByMarker(readByMarker)) {
1000 mXmppConnectionService.updateMessage(message, false);
1001 }
1002 }
1003 }
1004 } else {
1005 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_DISPLAYED);
1006 Message message = displayedMessage == null ? null : displayedMessage.prev();
1007 while (message != null
1008 && message.getStatus() == Message.STATUS_SEND_RECEIVED
1009 && message.getTimeSent() < displayedMessage.getTimeSent()) {
1010 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
1011 message = message.prev();
1012 }
1013 if (displayedMessage != null && selfAddressed) {
1014 dismissNotification(account, counterpart, query, id);
1015 }
1016 }
1017 }
1018
1019 final Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
1020 if (event != null && InvalidJid.hasValidFrom(original) && original.getFrom().isBareJid()) {
1021 if (event.hasChild("items")) {
1022 parseEvent(event, original.getFrom(), account);
1023 } else if (event.hasChild("delete")) {
1024 parseDeleteEvent(event, original.getFrom(), account);
1025 } else if (event.hasChild("purge")) {
1026 parsePurgeEvent(event, original.getFrom(), account);
1027 }
1028 }
1029
1030 final String nick = packet.findChildContent("nick", Namespace.NICK);
1031 if (nick != null && InvalidJid.hasValidFrom(original)) {
1032 if (mXmppConnectionService.isMuc(account, from)) {
1033 return;
1034 }
1035 final Contact contact = account.getRoster().getContact(from);
1036 if (contact.setPresenceName(nick)) {
1037 mXmppConnectionService.syncRoster(account);
1038 mXmppConnectionService.getAvatarService().clear(contact);
1039 }
1040 }
1041 }
1042
1043 private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query, final String id) {
1044 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1045 if (conversation != null && (query == null || query.isCatchup())) {
1046 final String displayableId = conversation.findMostRecentRemoteDisplayableId();
1047 if (displayableId != null && displayableId.equals(id)) {
1048 mXmppConnectionService.markRead(conversation);
1049 } else {
1050 Log.w(Config.LOGTAG, account.getJid().asBareJid() + ": received dismissing display marker that did not match our last id in that conversation");
1051 }
1052 }
1053 }
1054
1055 private void processMessageReceipts(final Account account, final MessagePacket packet, final String remoteMsgId, MessageArchiveService.Query query) {
1056 final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
1057 final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
1058 if (query == null) {
1059 final ArrayList<String> receiptsNamespaces = new ArrayList<>();
1060 if (markable) {
1061 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
1062 }
1063 if (request) {
1064 receiptsNamespaces.add("urn:xmpp:receipts");
1065 }
1066 if (receiptsNamespaces.size() > 0) {
1067 final MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
1068 packet.getFrom(),
1069 remoteMsgId,
1070 receiptsNamespaces,
1071 packet.getType());
1072 mXmppConnectionService.sendMessagePacket(account, receipt);
1073 }
1074 } else if (query.isCatchup()) {
1075 if (request) {
1076 query.addPendingReceiptRequest(new ReceiptRequest(packet.getFrom(), remoteMsgId));
1077 }
1078 }
1079 }
1080
1081 private void activateGracePeriod(Account account) {
1082 long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
1083 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
1084 account.activateGracePeriod(duration);
1085 }
1086
1087 private class Invite {
1088 final Jid jid;
1089 final String password;
1090 final boolean direct;
1091 final Jid inviter;
1092
1093 Invite(Jid jid, String password, boolean direct, Jid inviter) {
1094 this.jid = jid;
1095 this.password = password;
1096 this.direct = direct;
1097 this.inviter = inviter;
1098 }
1099
1100 public boolean execute(final Account account) {
1101 if (this.jid == null) {
1102 return false;
1103 }
1104 final Contact contact = this.inviter != null ? account.getRoster().getContact(this.inviter) : null;
1105 if (contact != null && contact.isBlocked()) {
1106 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": ignore invite from "+contact.getJid()+" because contact is blocked");
1107 return false;
1108 }
1109 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
1110 if (conversation.getMucOptions().online()) {
1111 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received invite to " + jid + " but muc is considered to be online");
1112 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
1113 } else {
1114 conversation.getMucOptions().setPassword(password);
1115 mXmppConnectionService.databaseBackend.updateConversation(conversation);
1116 mXmppConnectionService.joinMuc(conversation, contact != null && contact.showInContactList());
1117 mXmppConnectionService.updateConversationUi();
1118 }
1119 return true;
1120 }
1121 }
1122}