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