1package eu.siacs.conversations.parser;
2
3import android.util.Log;
4import android.util.Pair;
5
6import com.cheogram.android.BobTransfer;
7
8import java.net.URISyntaxException;
9import java.text.SimpleDateFormat;
10import java.util.ArrayList;
11import java.util.Arrays;
12import java.util.Collections;
13import java.util.Date;
14import java.util.List;
15import java.util.Locale;
16import java.util.Map;
17import java.util.Set;
18import java.util.UUID;
19
20import eu.siacs.conversations.Config;
21import eu.siacs.conversations.R;
22import eu.siacs.conversations.crypto.axolotl.AxolotlService;
23import eu.siacs.conversations.crypto.axolotl.BrokenSessionException;
24import eu.siacs.conversations.crypto.axolotl.NotEncryptedForThisDeviceException;
25import eu.siacs.conversations.crypto.axolotl.OutdatedSenderException;
26import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
27import eu.siacs.conversations.entities.Account;
28import eu.siacs.conversations.entities.Bookmark;
29import eu.siacs.conversations.entities.Contact;
30import eu.siacs.conversations.entities.Conversation;
31import eu.siacs.conversations.entities.Conversational;
32import eu.siacs.conversations.entities.Message;
33import eu.siacs.conversations.entities.MucOptions;
34import eu.siacs.conversations.entities.ReadByMarker;
35import eu.siacs.conversations.entities.ReceiptRequest;
36import eu.siacs.conversations.entities.RtpSessionStatus;
37import eu.siacs.conversations.http.HttpConnectionManager;
38import eu.siacs.conversations.services.MessageArchiveService;
39import eu.siacs.conversations.services.QuickConversationsService;
40import eu.siacs.conversations.services.XmppConnectionService;
41import eu.siacs.conversations.utils.CryptoHelper;
42import eu.siacs.conversations.xml.Element;
43import eu.siacs.conversations.xml.LocalizedContent;
44import eu.siacs.conversations.xml.Namespace;
45import eu.siacs.conversations.xmpp.InvalidJid;
46import eu.siacs.conversations.xmpp.Jid;
47import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
48import eu.siacs.conversations.xmpp.chatstate.ChatState;
49import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
50import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
51import eu.siacs.conversations.xmpp.pep.Avatar;
52import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
53
54public class MessageParser extends AbstractParser implements OnMessagePacketReceived {
55
56 private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
57
58 private static final List<String> JINGLE_MESSAGE_ELEMENT_NAMES = Arrays.asList("accept", "propose", "proceed", "reject", "retract");
59
60 public MessageParser(XmppConnectionService service) {
61 super(service);
62 }
63
64 private static String extractStanzaId(Element packet, boolean isTypeGroupChat, Conversation conversation) {
65 final Jid by;
66 final boolean safeToExtract;
67 if (isTypeGroupChat) {
68 by = conversation.getJid().asBareJid();
69 safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
70 } else {
71 Account account = conversation.getAccount();
72 by = account.getJid().asBareJid();
73 safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
74 }
75 return safeToExtract ? extractStanzaId(packet, by) : null;
76 }
77
78 private static String extractStanzaId(Account account, Element packet) {
79 final boolean safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
80 return safeToExtract ? extractStanzaId(packet, account.getJid().asBareJid()) : null;
81 }
82
83 private static String extractStanzaId(Element packet, Jid by) {
84 for (Element child : packet.getChildren()) {
85 if (child.getName().equals("stanza-id")
86 && Namespace.STANZA_IDS.equals(child.getNamespace())
87 && by.equals(InvalidJid.getNullForInvalid(child.getAttributeAsJid("by")))) {
88 return child.getAttribute("id");
89 }
90 }
91 return null;
92 }
93
94 private static Jid getTrueCounterpart(Element mucUserElement, Jid fallback) {
95 final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
96 Jid result = item == null ? null : InvalidJid.getNullForInvalid(item.getAttributeAsJid("jid"));
97 return result != null ? result : fallback;
98 }
99
100 private boolean extractChatState(Conversation c, final boolean isTypeGroupChat, final MessagePacket packet) {
101 ChatState state = ChatState.parse(packet);
102 if (state != null && c != null) {
103 final Account account = c.getAccount();
104 final Jid from = packet.getFrom();
105 if (from.asBareJid().equals(account.getJid().asBareJid())) {
106 c.setOutgoingChatState(state);
107 if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
108 if (c.getContact().isSelf()) {
109 return false;
110 }
111 mXmppConnectionService.markRead(c);
112 activateGracePeriod(account);
113 }
114 return false;
115 } else {
116 if (isTypeGroupChat) {
117 MucOptions.User user = c.getMucOptions().findUserByFullJid(from);
118 if (user != null) {
119 return user.setChatState(state);
120 } else {
121 return false;
122 }
123 } else {
124 return c.setIncomingChatState(state);
125 }
126 }
127 }
128 return false;
129 }
130
131 private Message parseAxolotlChat(Element axolotlMessage, Jid from, Conversation conversation, int status, final boolean checkedForDuplicates, boolean postpone) {
132 final AxolotlService service = conversation.getAccount().getAxolotlService();
133 final XmppAxolotlMessage xmppAxolotlMessage;
134 try {
135 xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.asBareJid());
136 } catch (Exception e) {
137 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": invalid omemo message received " + e.getMessage());
138 return null;
139 }
140 if (xmppAxolotlMessage.hasPayload()) {
141 final XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage;
142 try {
143 plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage, postpone);
144 } catch (BrokenSessionException e) {
145 if (checkedForDuplicates) {
146 if (service.trustedOrPreviouslyResponded(from.asBareJid())) {
147 service.reportBrokenSessionException(e, postpone);
148 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
149 } else {
150 Log.d(Config.LOGTAG, "ignoring broken session exception because contact was not trusted");
151 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
152 }
153 } else {
154 Log.d(Config.LOGTAG, "ignoring broken session exception because checkForDuplicates failed");
155 return null;
156 }
157 } catch (NotEncryptedForThisDeviceException e) {
158 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE, status);
159 } catch (OutdatedSenderException e) {
160 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
161 }
162 if (plaintextMessage != null) {
163 Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
164 finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
165 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount()) + " Received Message with session fingerprint: " + plaintextMessage.getFingerprint());
166 return finishedMessage;
167 }
168 } else {
169 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": received OMEMO key transport message");
170 service.processReceivingKeyTransportMessage(xmppAxolotlMessage, postpone);
171 }
172 return null;
173 }
174
175 private Invite extractInvite(Element message) {
176 final Element mucUser = message.findChild("x", Namespace.MUC_USER);
177 if (mucUser != null) {
178 Element invite = mucUser.findChild("invite");
179 if (invite != null) {
180 String password = mucUser.findChildContent("password");
181 Jid from = InvalidJid.getNullForInvalid(invite.getAttributeAsJid("from"));
182 Jid room = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
183 if (room == null) {
184 return null;
185 }
186 return new Invite(room, password, false, from);
187 }
188 }
189 final Element conference = message.findChild("x", "jabber:x:conference");
190 if (conference != null) {
191 Jid from = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
192 Jid room = InvalidJid.getNullForInvalid(conference.getAttributeAsJid("jid"));
193 if (room == null) {
194 return null;
195 }
196 return new Invite(room, conference.getAttribute("password"), true, from);
197 }
198 return null;
199 }
200
201 private void parseEvent(final Element event, final Jid from, final Account account) {
202 final Element items = event.findChild("items");
203 final String node = items == null ? null : items.getAttribute("node");
204 if ("urn:xmpp:avatar:metadata".equals(node)) {
205 Avatar avatar = Avatar.parseMetadata(items);
206 if (avatar != null) {
207 avatar.owner = from.asBareJid();
208 if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
209 if (account.getJid().asBareJid().equals(from)) {
210 if (account.setAvatar(avatar.getFilename())) {
211 mXmppConnectionService.databaseBackend.updateAccount(account);
212 mXmppConnectionService.notifyAccountAvatarHasChanged(account);
213 }
214 mXmppConnectionService.getAvatarService().clear(account);
215 mXmppConnectionService.updateConversationUi();
216 mXmppConnectionService.updateAccountUi();
217 } else {
218 final Contact contact = account.getRoster().getContact(from);
219 contact.setAvatar(avatar);
220 mXmppConnectionService.syncRoster(account);
221 mXmppConnectionService.getAvatarService().clear(contact);
222 mXmppConnectionService.updateConversationUi();
223 mXmppConnectionService.updateRosterUi();
224 }
225 } else if (mXmppConnectionService.isDataSaverDisabled()) {
226 mXmppConnectionService.fetchAvatar(account, avatar);
227 }
228 }
229 } else if (Namespace.NICK.equals(node)) {
230 final Element i = items.findChild("item");
231 final String nick = i == null ? null : i.findChildContent("nick", Namespace.NICK);
232 if (nick != null) {
233 setNick(account, from, nick);
234 }
235 } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
236 Element item = items.findChild("item");
237 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
238 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received PEP device list " + deviceIds + " update from " + from + ", processing... ");
239 AxolotlService axolotlService = account.getAxolotlService();
240 axolotlService.registerDevices(from, deviceIds);
241 } else if (Namespace.BOOKMARKS.equals(node) && account.getJid().asBareJid().equals(from)) {
242 if (account.getXmppConnection().getFeatures().bookmarksConversion()) {
243 final Element i = items.findChild("item");
244 final Element storage = i == null ? null : i.findChild("storage", Namespace.BOOKMARKS);
245 Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
246 mXmppConnectionService.processBookmarksInitial(account, bookmarks, true);
247 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": processing bookmark PEP event");
248 } else {
249 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring bookmark PEP event because bookmark conversion was not detected");
250 }
251 } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
252 final Element item = items.findChild("item");
253 final Element retract = items.findChild("retract");
254 if (item != null) {
255 final Bookmark bookmark = Bookmark.parseFromItem(item, account);
256 if (bookmark != null) {
257 account.putBookmark(bookmark);
258 mXmppConnectionService.processModifiedBookmark(bookmark);
259 mXmppConnectionService.updateConversationUi();
260 }
261 }
262 if (retract != null) {
263 final Jid id = InvalidJid.getNullForInvalid(retract.getAttributeAsJid("id"));
264 if (id != null) {
265 account.removeBookmark(id);
266 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmark for " + id);
267 mXmppConnectionService.processDeletedBookmark(account, id);
268 mXmppConnectionService.updateConversationUi();
269 }
270 }
271 } else {
272 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " received pubsub notification for node=" + node);
273 }
274 }
275
276 private void parseDeleteEvent(final Element event, final Jid from, final Account account) {
277 final Element delete = event.findChild("delete");
278 final String node = delete == null ? null : delete.getAttribute("node");
279 if (Namespace.NICK.equals(node)) {
280 Log.d(Config.LOGTAG, "parsing nick delete event from " + from);
281 setNick(account, from, null);
282 } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
283 account.setBookmarks(Collections.emptyMap());
284 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmarks node");
285 }
286 }
287
288 private void parsePurgeEvent(final Element event, final Jid from, final Account account) {
289 final Element purge = event.findChild("purge");
290 final String node = purge == null ? null : purge.getAttribute("node");
291 if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
292 account.setBookmarks(Collections.emptyMap());
293 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": purged bookmarks");
294 }
295 }
296
297 private void setNick(Account account, Jid user, String nick) {
298 if (user.asBareJid().equals(account.getJid().asBareJid())) {
299 account.setDisplayName(nick);
300 if (QuickConversationsService.isQuicksy()) {
301 mXmppConnectionService.getAvatarService().clear(account);
302 }
303 } else {
304 Contact contact = account.getRoster().getContact(user);
305 if (contact.setPresenceName(nick)) {
306 mXmppConnectionService.syncRoster(account);
307 mXmppConnectionService.getAvatarService().clear(contact);
308 }
309 }
310 mXmppConnectionService.updateConversationUi();
311 mXmppConnectionService.updateAccountUi();
312 }
313
314 private boolean handleErrorMessage(final Account account, final MessagePacket packet) {
315 if (packet.getType() == MessagePacket.TYPE_ERROR) {
316 if (packet.fromServer(account)) {
317 final Pair<MessagePacket, Long> forwarded = packet.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
318 if (forwarded != null) {
319 return handleErrorMessage(account, forwarded.first);
320 }
321 }
322 final Jid from = packet.getFrom();
323 final String id = packet.getId();
324 if (from != null && id != null) {
325 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
326 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
327 mXmppConnectionService.getJingleConnectionManager()
328 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.FAILED);
329 return true;
330 }
331 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX)) {
332 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX.length());
333 final String message = extractErrorMessage(packet);
334 mXmppConnectionService.getJingleConnectionManager().failProceed(account, from, sessionId, message);
335 return true;
336 }
337 mXmppConnectionService.markMessage(account,
338 from.asBareJid(),
339 id,
340 Message.STATUS_SEND_FAILED,
341 extractErrorMessage(packet));
342 final Element error = packet.findChild("error");
343 final boolean pingWorthyError = error != null && (error.hasChild("not-acceptable") || error.hasChild("remote-server-timeout") || error.hasChild("remote-server-not-found"));
344 if (pingWorthyError) {
345 Conversation conversation = mXmppConnectionService.find(account, from);
346 if (conversation != null && conversation.getMode() == Conversational.MODE_MULTI) {
347 if (conversation.getMucOptions().online()) {
348 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received ping worthy error for seemingly online muc at " + from);
349 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
350 }
351 }
352 }
353 }
354 return true;
355 }
356 return false;
357 }
358
359 @Override
360 public void onMessagePacketReceived(Account account, MessagePacket original) {
361 if (handleErrorMessage(account, original)) {
362 return;
363 }
364 final MessagePacket packet;
365 Long timestamp = null;
366 boolean isCarbon = false;
367 String serverMsgId = null;
368 final Element fin = original.findChild("fin", MessageArchiveService.Version.MAM_0.namespace);
369 if (fin != null) {
370 mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin, original.getFrom());
371 return;
372 }
373 final Element result = MessageArchiveService.Version.findResult(original);
374 final String queryId = result == null ? null : result.getAttribute("queryid");
375 final MessageArchiveService.Query query = queryId == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(queryId);
376 if (query != null && query.validFrom(original.getFrom())) {
377 final Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", query.version.namespace);
378 if (f == null) {
379 return;
380 }
381 timestamp = f.second;
382 packet = f.first;
383 serverMsgId = result.getAttribute("id");
384 query.incrementMessageCount();
385 if (handleErrorMessage(account, packet)) {
386 return;
387 }
388 } else if (query != null) {
389 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received mam result with invalid from (" + original.getFrom() + ") or queryId (" + queryId + ")");
390 return;
391 } else if (original.fromServer(account)) {
392 Pair<MessagePacket, Long> f;
393 f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
394 f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
395 packet = f != null ? f.first : original;
396 if (handleErrorMessage(account, packet)) {
397 return;
398 }
399 timestamp = f != null ? f.second : null;
400 isCarbon = f != null;
401 } else {
402 packet = original;
403 }
404
405 if (timestamp == null) {
406 timestamp = AbstractParser.parseTimestamp(original, AbstractParser.parseTimestamp(packet));
407 }
408 final LocalizedContent body = packet.getBody();
409 final Element mucUserElement = packet.findChild("x", Namespace.MUC_USER);
410 final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
411 final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
412 final Element oob = packet.findChild("x", Namespace.OOB);
413 final String oobUrl = oob != null ? oob.findChildContent("url") : null;
414 final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
415 final Element axolotlEncrypted = packet.findChildEnsureSingle(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
416 int status;
417 final Jid counterpart;
418 final Jid to = packet.getTo();
419 final Jid from = packet.getFrom();
420 final Element originId = packet.findChild("origin-id", Namespace.STANZA_IDS);
421 final String remoteMsgId;
422 if (originId != null && originId.getAttribute("id") != null) {
423 remoteMsgId = originId.getAttribute("id");
424 } else {
425 remoteMsgId = packet.getId();
426 }
427 boolean notify = false;
428
429 if (from == null || !InvalidJid.isValid(from) || !InvalidJid.isValid(to)) {
430 Log.e(Config.LOGTAG, "encountered invalid message from='" + from + "' to='" + to + "'");
431 return;
432 }
433
434 boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
435 if (query != null && !query.muc() && isTypeGroupChat) {
436 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": received groupchat (" + from + ") message on regular MAM request. skipping");
437 return;
438 }
439 boolean isMucStatusMessage = InvalidJid.hasValidFrom(packet) && from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
440 boolean selfAddressed;
441 if (packet.fromAccount(account)) {
442 status = Message.STATUS_SEND;
443 selfAddressed = to == null || account.getJid().asBareJid().equals(to.asBareJid());
444 if (selfAddressed) {
445 counterpart = from;
446 } else {
447 counterpart = to != null ? to : account.getJid();
448 }
449 } else {
450 status = Message.STATUS_RECEIVED;
451 counterpart = from;
452 selfAddressed = false;
453 }
454
455 final Invite invite = extractInvite(packet);
456 if (invite != null) {
457 if (isTypeGroupChat) {
458 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring invite to " + invite.jid + " because type=groupchat");
459 } else if (invite.direct && (mucUserElement != null || invite.inviter == null || mXmppConnectionService.isMuc(account, invite.inviter))) {
460 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring direct invite to " + invite.jid + " because it was received in MUC");
461 } else {
462 invite.execute(account);
463 return;
464 }
465 }
466
467 if ((body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || oobUrl != null) && !isMucStatusMessage) {
468 final boolean conversationIsProbablyMuc = isTypeGroupChat || mucUserElement != null || account.getXmppConnection().getMucServersWithholdAccount().contains(counterpart.getDomain().toEscapedString());
469 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), conversationIsProbablyMuc, false, query, false);
470 final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
471
472 if (serverMsgId == null) {
473 serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
474 }
475
476
477 if (selfAddressed) {
478 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, Message.STATUS_SEND_RECEIVED, serverMsgId)) {
479 return;
480 }
481 status = Message.STATUS_RECEIVED;
482 if (remoteMsgId != null && conversation.findMessageWithRemoteId(remoteMsgId, counterpart) != null) {
483 return;
484 }
485 }
486
487 if (isTypeGroupChat) {
488 if (conversation.getMucOptions().isSelf(counterpart)) {
489 status = Message.STATUS_SEND_RECEIVED;
490 isCarbon = true; //not really carbon but received from another resource
491 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId, body)) {
492 return;
493 } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
494 if (body != null) {
495 Message message = conversation.findSentMessageWithBody(body.content);
496 if (message != null) {
497 mXmppConnectionService.markMessage(message, status);
498 return;
499 }
500 }
501 }
502 } else {
503 status = Message.STATUS_RECEIVED;
504 }
505 }
506 final Message message;
507 if (pgpEncrypted != null && Config.supportOpenPgp()) {
508 message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
509 } else if (axolotlEncrypted != null && Config.supportOmemo()) {
510 Jid origin;
511 Set<Jid> fallbacksBySourceId = Collections.emptySet();
512 if (conversationMultiMode) {
513 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
514 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
515 if (origin == null) {
516 try {
517 fallbacksBySourceId = account.getAxolotlService().findCounterpartsBySourceId(XmppAxolotlMessage.parseSourceId(axolotlEncrypted));
518 } catch (IllegalArgumentException e) {
519 //ignoring
520 }
521 }
522 if (origin == null && fallbacksBySourceId.size() == 0) {
523 Log.d(Config.LOGTAG, "axolotl message in anonymous conference received and no possible fallbacks");
524 return;
525 }
526 } else {
527 fallbacksBySourceId = Collections.emptySet();
528 origin = from;
529 }
530
531 final boolean liveMessage = query == null && !isTypeGroupChat && mucUserElement == null;
532 final boolean checkedForDuplicates = liveMessage || (serverMsgId != null && remoteMsgId != null && !conversation.possibleDuplicate(serverMsgId, remoteMsgId));
533
534 if (origin != null) {
535 message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status, checkedForDuplicates, query != null);
536 } else {
537 Message trial = null;
538 for (Jid fallback : fallbacksBySourceId) {
539 trial = parseAxolotlChat(axolotlEncrypted, fallback, conversation, status, checkedForDuplicates && fallbacksBySourceId.size() == 1, query != null);
540 if (trial != null) {
541 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": decoded muc message using fallback");
542 origin = fallback;
543 break;
544 }
545 }
546 message = trial;
547 }
548 if (message == null) {
549 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
550 mXmppConnectionService.updateConversationUi();
551 }
552 if (query != null && status == Message.STATUS_SEND && remoteMsgId != null) {
553 Message previouslySent = conversation.findSentMessageWithUuid(remoteMsgId);
554 if (previouslySent != null && previouslySent.getServerMsgId() == null && serverMsgId != null) {
555 previouslySent.setServerMsgId(serverMsgId);
556 mXmppConnectionService.databaseBackend.updateMessage(previouslySent, false);
557 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered previously sent OMEMO message without serverId. updating...");
558 }
559 }
560 return;
561 }
562 if (conversationMultiMode) {
563 message.setTrueCounterpart(origin);
564 }
565 } else if (body == null && oobUrl != null) {
566 message = new Message(conversation, oobUrl, Message.ENCRYPTION_NONE, status);
567 message.setOob(oobUrl);
568 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
569 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
570 }
571 } else {
572 message = new Message(conversation, body.content, Message.ENCRYPTION_NONE, status);
573 if (body.count > 1) {
574 message.setBodyLanguage(body.language);
575 }
576 }
577
578 message.setSubject(original.findChildContent("subject"));
579 message.setCounterpart(counterpart);
580 message.setRemoteMsgId(remoteMsgId);
581 message.setServerMsgId(serverMsgId);
582 message.setCarbon(isCarbon);
583 message.setTime(timestamp);
584 if (oobUrl != null) {
585 message.setOob(oobUrl);
586 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
587 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
588 }
589 }
590 message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
591 for (Element el : packet.getChildren()) {
592 if (el.getName().equals("query") && el.getNamespace().equals("http://jabber.org/protocol/disco#items") && el.getAttribute("node").equals("http://jabber.org/protocol/commands")) {
593 message.addPayload(el);
594 }
595 }
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, remoteMsgId, 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, remoteMsgId, 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 if (message.getOob() != null && message.getOob().getScheme().equalsIgnoreCase("cid")) {
753 try {
754 BobTransfer transfer = new BobTransfer(message, mXmppConnectionService);
755 message.setTransferable(transfer);
756 transfer.start();
757 } catch (URISyntaxException e) {
758 Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
759 }
760 } else {
761 manager.createNewDownloadConnection(message);
762 }
763 } else if (notify) {
764 if (query != null && query.isCatchup()) {
765 mXmppConnectionService.getNotificationService().pushFromBacklog(message);
766 } else {
767 mXmppConnectionService.getNotificationService().push(message);
768 }
769 }
770 } else if (!packet.hasChild("body")) { //no body
771
772 final Conversation conversation = mXmppConnectionService.find(account, from.asBareJid());
773 if (axolotlEncrypted != null) {
774 Jid origin;
775 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
776 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
777 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
778 if (origin == null) {
779 Log.d(Config.LOGTAG, "omemo key transport message in anonymous conference received");
780 return;
781 }
782 } else if (isTypeGroupChat) {
783 return;
784 } else {
785 origin = from;
786 }
787 try {
788 final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.asBareJid());
789 account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
790 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": omemo key transport message received from " + origin);
791 } catch (Exception e) {
792 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": invalid omemo key transport message received " + e.getMessage());
793 return;
794 }
795 }
796
797 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
798 mXmppConnectionService.updateConversationUi();
799 }
800
801 if (isTypeGroupChat) {
802 if (packet.hasChild("subject")) { //TODO usually we would want to check for lack of body; however some servers do set a body :(
803 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
804 conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
805 final LocalizedContent subject = packet.findInternationalizedChildContentInDefaultNamespace("subject");
806 if (subject != null && conversation.getMucOptions().setSubject(subject.content)) {
807 mXmppConnectionService.updateConversation(conversation);
808 }
809 mXmppConnectionService.updateConversationUi();
810 return;
811 }
812 }
813 }
814 if (conversation != null && mucUserElement != null && InvalidJid.hasValidFrom(packet) && from.isBareJid()) {
815 for (Element child : mucUserElement.getChildren()) {
816 if ("status".equals(child.getName())) {
817 try {
818 int code = Integer.parseInt(child.getAttribute("code"));
819 if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
820 mXmppConnectionService.fetchConferenceConfiguration(conversation);
821 break;
822 }
823 } catch (Exception e) {
824 //ignored
825 }
826 } else if ("item".equals(child.getName())) {
827 MucOptions.User user = AbstractParser.parseItem(conversation, child);
828 Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for "
829 + user.getRealJid() + " to " + user.getAffiliation() + " in "
830 + conversation.getJid().asBareJid());
831 if (!user.realJidMatchesAccount()) {
832 boolean isNew = conversation.getMucOptions().updateUser(user);
833 mXmppConnectionService.getAvatarService().clear(conversation);
834 mXmppConnectionService.updateMucRosterUi();
835 mXmppConnectionService.updateConversationUi();
836 Contact contact = user.getContact();
837 if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
838 Jid jid = user.getRealJid();
839 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
840 if (cryptoTargets.remove(user.getRealJid())) {
841 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
842 conversation.setAcceptedCryptoTargets(cryptoTargets);
843 mXmppConnectionService.updateConversation(conversation);
844 }
845 } else if (isNew
846 && user.getRealJid() != null
847 && conversation.getMucOptions().isPrivateAndNonAnonymous()
848 && (contact == null || !contact.mutualPresenceSubscription())
849 && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
850 account.getAxolotlService().fetchDeviceIds(user.getRealJid());
851 }
852 }
853 }
854 }
855 }
856 if (!isTypeGroupChat) {
857 for (Element child : packet.getChildren()) {
858 if (Namespace.JINGLE_MESSAGE.equals(child.getNamespace()) && JINGLE_MESSAGE_ELEMENT_NAMES.contains(child.getName())) {
859 final String action = child.getName();
860 final String sessionId = child.getAttribute("id");
861 if (sessionId == null) {
862 break;
863 }
864 if (query == null) {
865 if (serverMsgId == null) {
866 serverMsgId = extractStanzaId(account, packet);
867 }
868 mXmppConnectionService.getJingleConnectionManager().deliverMessage(account, packet.getTo(), packet.getFrom(), child, remoteMsgId, serverMsgId, timestamp);
869 if (!account.getJid().asBareJid().equals(from.asBareJid()) && remoteMsgId != null) {
870 processMessageReceipts(account, packet, remoteMsgId, query);
871 }
872 } else if (query.isCatchup()) {
873 if ("propose".equals(action)) {
874 final Element description = child.findChild("description");
875 final String namespace = description == null ? null : description.getNamespace();
876 if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
877 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
878 final Message preExistingMessage = c.findRtpSession(sessionId, status);
879 if (preExistingMessage != null) {
880 preExistingMessage.setServerMsgId(serverMsgId);
881 mXmppConnectionService.updateMessage(preExistingMessage);
882 break;
883 }
884 final Message message = new Message(
885 c,
886 status,
887 Message.TYPE_RTP_SESSION,
888 sessionId
889 );
890 message.setServerMsgId(serverMsgId);
891 message.setTime(timestamp);
892 message.setBody(new RtpSessionStatus(false, 0).toString());
893 c.add(message);
894 mXmppConnectionService.databaseBackend.createMessage(message);
895 }
896 } else if ("proceed".equals(action)) {
897 //status needs to be flipped to find the original propose
898 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
899 final int s = packet.fromAccount(account) ? Message.STATUS_RECEIVED : Message.STATUS_SEND;
900 final Message message = c.findRtpSession(sessionId, s);
901 if (message != null) {
902 message.setBody(new RtpSessionStatus(true, 0).toString());
903 if (serverMsgId != null) {
904 message.setServerMsgId(serverMsgId);
905 }
906 message.setTime(timestamp);
907 mXmppConnectionService.updateMessage(message, true);
908 } else {
909 Log.d(Config.LOGTAG, "unable to find original rtp session message for received propose");
910 }
911
912 }
913 } else {
914 //MAM reloads (non catchups
915 if ("propose".equals(action)) {
916 final Element description = child.findChild("description");
917 final String namespace = description == null ? null : description.getNamespace();
918 if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
919 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
920 final Message preExistingMessage = c.findRtpSession(sessionId, status);
921 if (preExistingMessage != null) {
922 preExistingMessage.setServerMsgId(serverMsgId);
923 mXmppConnectionService.updateMessage(preExistingMessage);
924 break;
925 }
926 final Message message = new Message(
927 c,
928 status,
929 Message.TYPE_RTP_SESSION,
930 sessionId
931 );
932 message.setServerMsgId(serverMsgId);
933 message.setTime(timestamp);
934 message.setBody(new RtpSessionStatus(true, 0).toString());
935 if (query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
936 c.prepend(query.getActualInThisQuery(), message);
937 } else {
938 c.add(message);
939 }
940 query.incrementActualMessageCount();
941 mXmppConnectionService.databaseBackend.createMessage(message);
942 }
943 }
944 }
945 break;
946 }
947 }
948 }
949 }
950
951 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
952 if (received == null) {
953 received = packet.findChild("received", "urn:xmpp:receipts");
954 }
955 if (received != null) {
956 String id = received.getAttribute("id");
957 if (packet.fromAccount(account)) {
958 if (query != null && id != null && packet.getTo() != null) {
959 query.removePendingReceiptRequest(new ReceiptRequest(packet.getTo(), id));
960 }
961 } else if (id != null) {
962 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
963 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
964 mXmppConnectionService.getJingleConnectionManager()
965 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.DISCOVERED);
966 } else {
967 mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_RECEIVED);
968 }
969 }
970 }
971 Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
972 if (displayed != null) {
973 final String id = displayed.getAttribute("id");
974 final Jid sender = InvalidJid.getNullForInvalid(displayed.getAttributeAsJid("sender"));
975 if (packet.fromAccount(account) && !selfAddressed) {
976 dismissNotification(account, counterpart, query, id);
977 if (query == null) {
978 activateGracePeriod(account);
979 }
980 } else if (isTypeGroupChat) {
981 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
982 final Message message;
983 if (conversation != null && id != null) {
984 if (sender != null) {
985 message = conversation.findMessageWithRemoteId(id, sender);
986 } else {
987 message = conversation.findMessageWithServerMsgId(id);
988 }
989 } else {
990 message = null;
991 }
992 if (message != null) {
993 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
994 final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
995 final boolean trueJidMatchesAccount = account.getJid().asBareJid().equals(trueJid == null ? null : trueJid.asBareJid());
996 if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
997 if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
998 mXmppConnectionService.markRead(conversation);
999 }
1000 } else if (!counterpart.isBareJid() && trueJid != null) {
1001 final ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
1002 if (message.addReadByMarker(readByMarker)) {
1003 mXmppConnectionService.updateMessage(message, false);
1004 }
1005 }
1006 }
1007 } else {
1008 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_DISPLAYED);
1009 Message message = displayedMessage == null ? null : displayedMessage.prev();
1010 while (message != null
1011 && message.getStatus() == Message.STATUS_SEND_RECEIVED
1012 && message.getTimeSent() < displayedMessage.getTimeSent()) {
1013 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
1014 message = message.prev();
1015 }
1016 if (displayedMessage != null && selfAddressed) {
1017 dismissNotification(account, counterpart, query, id);
1018 }
1019 }
1020 }
1021
1022 final Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
1023 if (event != null && InvalidJid.hasValidFrom(original) && original.getFrom().isBareJid()) {
1024 if (event.hasChild("items")) {
1025 parseEvent(event, original.getFrom(), account);
1026 } else if (event.hasChild("delete")) {
1027 parseDeleteEvent(event, original.getFrom(), account);
1028 } else if (event.hasChild("purge")) {
1029 parsePurgeEvent(event, original.getFrom(), account);
1030 }
1031 }
1032
1033 final String nick = packet.findChildContent("nick", Namespace.NICK);
1034 if (nick != null && InvalidJid.hasValidFrom(original)) {
1035 if (mXmppConnectionService.isMuc(account, from)) {
1036 return;
1037 }
1038 final Contact contact = account.getRoster().getContact(from);
1039 if (contact.setPresenceName(nick)) {
1040 mXmppConnectionService.syncRoster(account);
1041 mXmppConnectionService.getAvatarService().clear(contact);
1042 }
1043 }
1044 }
1045
1046 private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query, final String id) {
1047 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1048 if (conversation != null && (query == null || query.isCatchup())) {
1049 final String displayableId = conversation.findMostRecentRemoteDisplayableId();
1050 if (displayableId != null && displayableId.equals(id)) {
1051 mXmppConnectionService.markRead(conversation);
1052 } else {
1053 Log.w(Config.LOGTAG, account.getJid().asBareJid() + ": received dismissing display marker that did not match our last id in that conversation");
1054 }
1055 }
1056 }
1057
1058 private void processMessageReceipts(final Account account, final MessagePacket packet, final String remoteMsgId, MessageArchiveService.Query query) {
1059 final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
1060 final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
1061 if (query == null) {
1062 final ArrayList<String> receiptsNamespaces = new ArrayList<>();
1063 if (markable) {
1064 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
1065 }
1066 if (request) {
1067 receiptsNamespaces.add("urn:xmpp:receipts");
1068 }
1069 if (receiptsNamespaces.size() > 0) {
1070 final MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
1071 packet.getFrom(),
1072 remoteMsgId,
1073 receiptsNamespaces,
1074 packet.getType());
1075 mXmppConnectionService.sendMessagePacket(account, receipt);
1076 }
1077 } else if (query.isCatchup()) {
1078 if (request) {
1079 query.addPendingReceiptRequest(new ReceiptRequest(packet.getFrom(), remoteMsgId));
1080 }
1081 }
1082 }
1083
1084 private void activateGracePeriod(Account account) {
1085 long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
1086 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
1087 account.activateGracePeriod(duration);
1088 }
1089
1090 private class Invite {
1091 final Jid jid;
1092 final String password;
1093 final boolean direct;
1094 final Jid inviter;
1095
1096 Invite(Jid jid, String password, boolean direct, Jid inviter) {
1097 this.jid = jid;
1098 this.password = password;
1099 this.direct = direct;
1100 this.inviter = inviter;
1101 }
1102
1103 public boolean execute(Account account) {
1104 if (jid != null) {
1105 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
1106 if (conversation.getMucOptions().online()) {
1107 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received invite to " + jid + " but muc is considered to be online");
1108 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
1109 } else {
1110 conversation.getMucOptions().setPassword(password);
1111 mXmppConnectionService.databaseBackend.updateConversation(conversation);
1112 final Contact contact = inviter != null ? account.getRoster().getContactFromContactList(inviter) : null;
1113 mXmppConnectionService.joinMuc(conversation, contact != null && contact.mutualPresenceSubscription());
1114 mXmppConnectionService.updateConversationUi();
1115 }
1116 return true;
1117 }
1118 return false;
1119 }
1120 }
1121}