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