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