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