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.Set;
14import java.util.UUID;
15
16import eu.siacs.conversations.Config;
17import eu.siacs.conversations.R;
18import eu.siacs.conversations.crypto.axolotl.AxolotlService;
19import eu.siacs.conversations.crypto.axolotl.NotEncryptedForThisDeviceException;
20import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
21import eu.siacs.conversations.entities.Account;
22import eu.siacs.conversations.entities.Bookmark;
23import eu.siacs.conversations.entities.Contact;
24import eu.siacs.conversations.entities.Conversation;
25import eu.siacs.conversations.entities.Message;
26import eu.siacs.conversations.entities.MucOptions;
27import eu.siacs.conversations.entities.ReadByMarker;
28import eu.siacs.conversations.entities.ReceiptRequest;
29import eu.siacs.conversations.http.HttpConnectionManager;
30import eu.siacs.conversations.services.MessageArchiveService;
31import eu.siacs.conversations.services.XmppConnectionService;
32import eu.siacs.conversations.utils.CryptoHelper;
33import eu.siacs.conversations.xml.Namespace;
34import eu.siacs.conversations.xml.Element;
35import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
36import eu.siacs.conversations.xmpp.chatstate.ChatState;
37import eu.siacs.conversations.xmpp.pep.Avatar;
38import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
39import rocks.xmpp.addr.Jid;
40
41public class MessageParser extends AbstractParser implements OnMessagePacketReceived {
42
43 private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
44
45 public MessageParser(XmppConnectionService service) {
46 super(service);
47 }
48
49 private static String extractStanzaId(Element packet, boolean isTypeGroupChat, Conversation conversation) {
50 final Jid by;
51 final boolean safeToExtract;
52 if (isTypeGroupChat) {
53 by = conversation.getJid().asBareJid();
54 safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
55 } else {
56 Account account = conversation.getAccount();
57 by = account.getJid().asBareJid();
58 safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
59 }
60 return safeToExtract ? extractStanzaId(packet, by) : null;
61 }
62
63 private static String extractStanzaId(Element packet, Jid by) {
64 for (Element child : packet.getChildren()) {
65 if (child.getName().equals("stanza-id")
66 && Namespace.STANZA_IDS.equals(child.getNamespace())
67 && by.equals(child.getAttributeAsJid("by"))) {
68 return child.getAttribute("id");
69 }
70 }
71 return null;
72 }
73
74 private static Jid getTrueCounterpart(Element mucUserElement, Jid fallback) {
75 final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
76 Jid result = item == null ? null : item.getAttributeAsJid("jid");
77 return result != null ? result : fallback;
78 }
79
80 private boolean extractChatState(Conversation c, final boolean isTypeGroupChat, final MessagePacket packet) {
81 ChatState state = ChatState.parse(packet);
82 if (state != null && c != null) {
83 final Account account = c.getAccount();
84 Jid from = packet.getFrom();
85 if (from.asBareJid().equals(account.getJid().asBareJid())) {
86 c.setOutgoingChatState(state);
87 if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
88 mXmppConnectionService.markRead(c);
89 activateGracePeriod(account);
90 }
91 return false;
92 } else {
93 if (isTypeGroupChat) {
94 MucOptions.User user = c.getMucOptions().findUserByFullJid(from);
95 if (user != null) {
96 return user.setChatState(state);
97 } else {
98 return false;
99 }
100 } else {
101 return c.setIncomingChatState(state);
102 }
103 }
104 }
105 return false;
106 }
107
108 private Message parseAxolotlChat(Element axolotlMessage, Jid from, Conversation conversation, int status, boolean postpone) {
109 final AxolotlService service = conversation.getAccount().getAxolotlService();
110 final XmppAxolotlMessage xmppAxolotlMessage;
111 try {
112 xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.asBareJid());
113 } catch (Exception e) {
114 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": invalid omemo message received " + e.getMessage());
115 return null;
116 }
117 if (xmppAxolotlMessage.hasPayload()) {
118 final XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage;
119 try {
120 plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage, postpone);
121 } catch (NotEncryptedForThisDeviceException e) {
122 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE, status);
123 }
124 if (plaintextMessage != null) {
125 Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
126 finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
127 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount()) + " Received Message with session fingerprint: " + plaintextMessage.getFingerprint());
128 return finishedMessage;
129 }
130 } else {
131 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": received OMEMO key transport message");
132 service.processReceivingKeyTransportMessage(xmppAxolotlMessage, postpone);
133 }
134 return null;
135 }
136
137 private Invite extractInvite(Account account, Element message) {
138 Element x = message.findChild("x", "http://jabber.org/protocol/muc#user");
139 if (x != null) {
140 Element invite = x.findChild("invite");
141 if (invite != null) {
142 Element pw = x.findChild("password");
143 Jid from = invite.getAttributeAsJid("from");
144 Contact contact = from == null ? null : account.getRoster().getContact(from);
145 return new Invite(message.getAttributeAsJid("from"), pw != null ? pw.getContent() : null, contact);
146 }
147 } else {
148 x = message.findChild("x", "jabber:x:conference");
149 if (x != null) {
150 Jid from = message.getAttributeAsJid("from");
151 Contact contact = from == null ? null : account.getRoster().getContact(from);
152 return new Invite(x.getAttributeAsJid("jid"), x.getAttribute("password"), contact);
153 }
154 }
155 return null;
156 }
157
158 private void parseEvent(final Element event, final Jid from, final Account account) {
159 Element items = event.findChild("items");
160 String node = items == null ? null : items.getAttribute("node");
161 if ("urn:xmpp:avatar:metadata".equals(node)) {
162 Avatar avatar = Avatar.parseMetadata(items);
163 if (avatar != null) {
164 avatar.owner = from.asBareJid();
165 if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
166 if (account.getJid().asBareJid().equals(from)) {
167 if (account.setAvatar(avatar.getFilename())) {
168 mXmppConnectionService.databaseBackend.updateAccount(account);
169 }
170 mXmppConnectionService.getAvatarService().clear(account);
171 mXmppConnectionService.updateConversationUi();
172 mXmppConnectionService.updateAccountUi();
173 } else {
174 Contact contact = account.getRoster().getContact(from);
175 contact.setAvatar(avatar);
176 mXmppConnectionService.getAvatarService().clear(contact);
177 mXmppConnectionService.updateConversationUi();
178 mXmppConnectionService.updateRosterUi();
179 }
180 } else if (mXmppConnectionService.isDataSaverDisabled()) {
181 mXmppConnectionService.fetchAvatar(account, avatar);
182 }
183 }
184 } else if ("http://jabber.org/protocol/nick".equals(node)) {
185 final Element i = items.findChild("item");
186 final String nick = i == null ? null : i.findChildContent("nick", Namespace.NICK);
187 if (nick != null) {
188 Contact contact = account.getRoster().getContact(from);
189 if (contact.setPresenceName(nick)) {
190 mXmppConnectionService.getAvatarService().clear(contact);
191 }
192 mXmppConnectionService.updateConversationUi();
193 mXmppConnectionService.updateAccountUi();
194 }
195 } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
196 Element item = items.findChild("item");
197 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
198 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received PEP device list " + deviceIds + " update from " + from + ", processing... ");
199 AxolotlService axolotlService = account.getAxolotlService();
200 axolotlService.registerDevices(from, deviceIds);
201 mXmppConnectionService.updateAccountUi();
202 }
203 }
204
205 private boolean handleErrorMessage(Account account, MessagePacket packet) {
206 if (packet.getType() == MessagePacket.TYPE_ERROR) {
207 Jid from = packet.getFrom();
208 if (from != null) {
209 Message message = mXmppConnectionService.markMessage(account,
210 from.asBareJid(),
211 packet.getId(),
212 Message.STATUS_SEND_FAILED,
213 extractErrorMessage(packet));
214 }
215 return true;
216 }
217 return false;
218 }
219
220 @Override
221 public void onMessagePacketReceived(Account account, MessagePacket original) {
222 if (handleErrorMessage(account, original)) {
223 return;
224 }
225 final MessagePacket packet;
226 Long timestamp = null;
227 boolean isCarbon = false;
228 String serverMsgId = null;
229 final Element fin = original.findChild("fin", Namespace.MAM_LEGACY);
230 if (fin != null) {
231 mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin, original.getFrom());
232 return;
233 }
234 final boolean mamLegacy = original.hasChild("result", Namespace.MAM_LEGACY);
235 final Element result = original.findChild("result", mamLegacy ? Namespace.MAM_LEGACY : Namespace.MAM);
236 final MessageArchiveService.Query query = result == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
237 if (query != null && query.validFrom(original.getFrom())) {
238 Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", mamLegacy ? Namespace.MAM_LEGACY : Namespace.MAM);
239 if (f == null) {
240 return;
241 }
242 timestamp = f.second;
243 packet = f.first;
244 serverMsgId = result.getAttribute("id");
245 query.incrementMessageCount();
246 } else if (query != null) {
247 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received mam result from invalid sender");
248 return;
249 } else if (original.fromServer(account)) {
250 Pair<MessagePacket, Long> f;
251 f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
252 f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
253 packet = f != null ? f.first : original;
254 if (handleErrorMessage(account, packet)) {
255 return;
256 }
257 timestamp = f != null ? f.second : null;
258 isCarbon = f != null;
259 } else {
260 packet = original;
261 }
262
263 if (timestamp == null) {
264 timestamp = AbstractParser.parseTimestamp(original, AbstractParser.parseTimestamp(packet));
265 }
266 final String body = packet.getBody();
267 final Element mucUserElement = packet.findChild("x", "http://jabber.org/protocol/muc#user");
268 final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
269 final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
270 final Element oob = packet.findChild("x", Namespace.OOB);
271 final String oobUrl = oob != null ? oob.findChildContent("url") : null;
272 final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
273 final Element axolotlEncrypted = packet.findChild(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
274 int status;
275 final Jid counterpart;
276 final Jid to = packet.getTo();
277 final Jid from = packet.getFrom();
278 final Element originId = packet.findChild("origin-id", Namespace.STANZA_IDS);
279 final String remoteMsgId;
280 if (originId != null && originId.getAttribute("id") != null) {
281 remoteMsgId = originId.getAttribute("id");
282 } else {
283 remoteMsgId = packet.getId();
284 }
285 boolean notify = false;
286
287 if (from == null) {
288 Log.d(Config.LOGTAG, "no from in: " + packet.toString());
289 return;
290 }
291
292 boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
293 if (query != null && !query.muc() && isTypeGroupChat) {
294 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": received groupchat (" + from + ") message on regular MAM request. skipping");
295 return;
296 }
297 boolean isMucStatusMessage = from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
298 boolean selfAddressed;
299 if (packet.fromAccount(account)) {
300 status = Message.STATUS_SEND;
301 selfAddressed = to == null || account.getJid().asBareJid().equals(to.asBareJid());
302 if (selfAddressed) {
303 counterpart = from;
304 } else {
305 counterpart = to != null ? to : account.getJid();
306 }
307 } else {
308 status = Message.STATUS_RECEIVED;
309 counterpart = from;
310 selfAddressed = false;
311 }
312
313 Invite invite = extractInvite(account, packet);
314 if (invite != null && invite.execute(account)) {
315 return;
316 }
317
318 if ((body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || oobUrl != null) && !isMucStatusMessage) {
319 final boolean conversationIsProbablyMuc = isTypeGroupChat || mucUserElement != null || account.getXmppConnection().getMucServersWithholdAccount().contains(counterpart.getDomain());
320 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), conversationIsProbablyMuc, false, query, false);
321 final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
322
323 if (serverMsgId == null) {
324 serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
325 }
326
327
328 if (selfAddressed) {
329 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, Message.STATUS_SEND_RECEIVED, serverMsgId)) {
330 return;
331 }
332 status = Message.STATUS_RECEIVED;
333 if (remoteMsgId != null && conversation.findMessageWithRemoteId(remoteMsgId, counterpart) != null) {
334 return;
335 }
336 }
337
338 if (isTypeGroupChat) {
339 if (conversation.getMucOptions().isSelf(counterpart)) {
340 status = Message.STATUS_SEND_RECEIVED;
341 isCarbon = true; //not really carbon but received from another resource
342 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId)) {
343 return;
344 } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
345 Message message = conversation.findSentMessageWithBody(packet.getBody());
346 if (message != null) {
347 mXmppConnectionService.markMessage(message, status);
348 return;
349 }
350 }
351 } else {
352 status = Message.STATUS_RECEIVED;
353 }
354 }
355 final Message message;
356 if (pgpEncrypted != null && Config.supportOpenPgp()) {
357 message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
358 } else if (axolotlEncrypted != null && Config.supportOmemo()) {
359 Jid origin;
360 Set<Jid> fallbacksBySourceId = Collections.emptySet();
361 if (conversationMultiMode) {
362 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
363 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
364 if (origin == null) {
365 try {
366 fallbacksBySourceId = account.getAxolotlService().findCounterpartsBySourceId(XmppAxolotlMessage.parseSourceId(axolotlEncrypted));
367 } catch (IllegalArgumentException e) {
368 //ignoring
369 }
370 }
371 if (origin == null && fallbacksBySourceId.size() == 0) {
372 Log.d(Config.LOGTAG, "axolotl message in anonymous conference received and no possible fallbacks");
373 return;
374 }
375 } else {
376 fallbacksBySourceId = Collections.emptySet();
377 origin = from;
378 }
379 if (origin != null) {
380 message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status, query != null);
381 } else {
382 Message trial = null;
383 for (Jid fallback : fallbacksBySourceId) {
384 trial = parseAxolotlChat(axolotlEncrypted, fallback, conversation, status, query != null);
385 if (trial != null) {
386 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": decoded muc message using fallback");
387 origin = fallback;
388 break;
389 }
390 }
391 message = trial;
392 }
393 if (message == null) {
394 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
395 mXmppConnectionService.updateConversationUi();
396 }
397 if (query != null && status == Message.STATUS_SEND && remoteMsgId != null) {
398 Message previouslySent = conversation.findSentMessageWithUuid(remoteMsgId);
399 if (previouslySent != null && previouslySent.getServerMsgId() == null && serverMsgId != null) {
400 previouslySent.setServerMsgId(serverMsgId);
401 mXmppConnectionService.databaseBackend.updateMessage(previouslySent);
402 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered previously sent OMEMO message without serverId. updating...");
403 }
404 }
405 return;
406 }
407 if (conversationMultiMode) {
408 message.setTrueCounterpart(origin);
409 }
410 } else if (body == null && oobUrl != null) {
411 message = new Message(conversation, oobUrl, Message.ENCRYPTION_NONE, status);
412 message.setOob(true);
413 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
414 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
415 }
416 } else {
417 message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
418 }
419
420 message.setCounterpart(counterpart);
421 message.setRemoteMsgId(remoteMsgId);
422 message.setServerMsgId(serverMsgId);
423 message.setCarbon(isCarbon);
424 message.setTime(timestamp);
425 if (body != null && body.equals(oobUrl)) {
426 message.setOob(true);
427 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
428 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
429 }
430 }
431 message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
432 if (conversationMultiMode) {
433 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
434 Jid trueCounterpart;
435 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
436 trueCounterpart = message.getTrueCounterpart();
437 } else if (query != null && query.safeToExtractTrueCounterpart()) {
438 trueCounterpart = getTrueCounterpart(mucUserElement, fallback);
439 } else {
440 trueCounterpart = fallback;
441 }
442 if (trueCounterpart != null && trueCounterpart.asBareJid().equals(account.getJid().asBareJid())) {
443 status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
444 }
445 message.setStatus(status);
446 message.setTrueCounterpart(trueCounterpart);
447 if (!isTypeGroupChat) {
448 message.setType(Message.TYPE_PRIVATE);
449 }
450 } else {
451 updateLastseen(account, from);
452 }
453
454 if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
455 final Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
456 counterpart,
457 message.getStatus() == Message.STATUS_RECEIVED,
458 message.isCarbon());
459 if (replacedMessage != null) {
460 final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
461 || replacedMessage.getFingerprint().equals(message.getFingerprint());
462 final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
463 && replacedMessage.getTrueCounterpart().equals(message.getTrueCounterpart());
464 final boolean duplicate = conversation.hasDuplicateMessage(message);
465 if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode) && !duplicate) {
466 Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
467 synchronized (replacedMessage) {
468 final String uuid = replacedMessage.getUuid();
469 replacedMessage.setUuid(UUID.randomUUID().toString());
470 replacedMessage.setBody(message.getBody());
471 replacedMessage.setEdited(replacedMessage.getRemoteMsgId());
472 replacedMessage.setRemoteMsgId(remoteMsgId);
473 if (replacedMessage.getServerMsgId() == null || message.getServerMsgId() != null) {
474 replacedMessage.setServerMsgId(message.getServerMsgId());
475 }
476 replacedMessage.setEncryption(message.getEncryption());
477 if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
478 replacedMessage.markUnread();
479 }
480 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
481 mXmppConnectionService.updateMessage(replacedMessage, uuid);
482 mXmppConnectionService.getNotificationService().updateNotification(false);
483 if (mXmppConnectionService.confirmMessages()
484 && replacedMessage.getStatus() == Message.STATUS_RECEIVED
485 && (replacedMessage.trusted() || replacedMessage.getType() == Message.TYPE_PRIVATE)
486 && remoteMsgId != null
487 && !selfAddressed
488 && !isTypeGroupChat) {
489 processMessageReceipts(account, packet, query);
490 }
491 if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
492 conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
493 conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
494 }
495 }
496 return;
497 } else {
498 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received message correction but verification didn't check out");
499 }
500 }
501 }
502
503 long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate();
504 if (deletionDate != 0 && message.getTimeSent() < deletionDate) {
505 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping message from " + message.getCounterpart().toString() + " because it was sent prior to our deletion date");
506 return;
507 }
508
509 boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay", "urn:xmpp:delay"))
510 || message.getType() == Message.TYPE_PRIVATE
511 || message.getServerMsgId() != null;
512 if (checkForDuplicates) {
513 final Message duplicate = conversation.findDuplicateMessage(message);
514 if (duplicate != null) {
515 final boolean serverMsgIdUpdated;
516 if (duplicate.getStatus() != Message.STATUS_RECEIVED
517 && duplicate.getUuid().equals(message.getRemoteMsgId())
518 && duplicate.getServerMsgId() == null
519 && message.getServerMsgId() != null) {
520 duplicate.setServerMsgId(message.getServerMsgId());
521 mXmppConnectionService.databaseBackend.updateMessage(message);
522 serverMsgIdUpdated = true;
523 } else {
524 serverMsgIdUpdated = false;
525 }
526 Log.d(Config.LOGTAG, "skipping duplicate message with " + message.getCounterpart() + ". serverMsgIdUpdated=" + Boolean.toString(serverMsgIdUpdated));
527 return;
528 }
529 }
530
531 if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
532 conversation.prepend(query.getActualInThisQuery(), message);
533 } else {
534 conversation.add(message);
535 }
536 if (query != null) {
537 query.incrementActualMessageCount();
538 }
539
540 if (query == null || query.isCatchup()) { //either no mam or catchup
541 if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
542 mXmppConnectionService.markRead(conversation);
543 if (query == null) {
544 activateGracePeriod(account);
545 }
546 } else {
547 message.markUnread();
548 notify = true;
549 }
550 }
551
552 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
553 notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
554 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE) {
555 notify = false;
556 }
557
558 if (query == null) {
559 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
560 mXmppConnectionService.updateConversationUi();
561 }
562
563 if (mXmppConnectionService.confirmMessages()
564 && message.getStatus() == Message.STATUS_RECEIVED
565 && (message.trusted() || message.getType() == Message.TYPE_PRIVATE)
566 && remoteMsgId != null
567 && !selfAddressed
568 && !isTypeGroupChat) {
569 processMessageReceipts(account, packet, query);
570 }
571
572 mXmppConnectionService.databaseBackend.createMessage(message);
573 final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
574 if (message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
575 manager.createNewDownloadConnection(message);
576 } else if (notify) {
577 if (query != null && query.isCatchup()) {
578 mXmppConnectionService.getNotificationService().pushFromBacklog(message);
579 } else {
580 mXmppConnectionService.getNotificationService().push(message);
581 }
582 }
583 } else if (!packet.hasChild("body")) { //no body
584
585 final Conversation conversation = mXmppConnectionService.find(account, from.asBareJid());
586 if (axolotlEncrypted != null) {
587 Jid origin;
588 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
589 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
590 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
591 if (origin == null) {
592 Log.d(Config.LOGTAG, "omemo key transport message in anonymous conference received");
593 return;
594 }
595 } else if (isTypeGroupChat) {
596 return;
597 } else {
598 origin = from;
599 }
600 try {
601 final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.asBareJid());
602 account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
603 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": omemo key transport message received from " + origin);
604 } catch (Exception e) {
605 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": invalid omemo key transport message received " + e.getMessage());
606 return;
607 }
608 }
609
610 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
611 mXmppConnectionService.updateConversationUi();
612 }
613
614 if (isTypeGroupChat) {
615 if (packet.hasChild("subject")) {
616 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
617 conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
618 String subject = packet.findInternationalizedChildContent("subject");
619 if (conversation.getMucOptions().setSubject(subject)) {
620 mXmppConnectionService.updateConversation(conversation);
621 }
622 final Bookmark bookmark = conversation.getBookmark();
623 if (bookmark != null && bookmark.getBookmarkName() == null) {
624 if (bookmark.setBookmarkName(subject)) {
625 mXmppConnectionService.pushBookmarks(account);
626 }
627 }
628 mXmppConnectionService.updateConversationUi();
629 return;
630 }
631 }
632 }
633 if (conversation != null && mucUserElement != null && from.isBareJid()) {
634 for (Element child : mucUserElement.getChildren()) {
635 if ("status".equals(child.getName())) {
636 try {
637 int code = Integer.parseInt(child.getAttribute("code"));
638 if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
639 mXmppConnectionService.fetchConferenceConfiguration(conversation);
640 break;
641 }
642 } catch (Exception e) {
643 //ignored
644 }
645 } else if ("item".equals(child.getName())) {
646 MucOptions.User user = AbstractParser.parseItem(conversation, child);
647 Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for "
648 + user.getRealJid() + " to " + user.getAffiliation() + " in "
649 + conversation.getJid().asBareJid());
650 if (!user.realJidMatchesAccount()) {
651 boolean isNew = conversation.getMucOptions().updateUser(user);
652 mXmppConnectionService.getAvatarService().clear(conversation);
653 mXmppConnectionService.updateMucRosterUi();
654 mXmppConnectionService.updateConversationUi();
655 Contact contact = user.getContact();
656 if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
657 Jid jid = user.getRealJid();
658 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
659 if (cryptoTargets.remove(user.getRealJid())) {
660 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
661 conversation.setAcceptedCryptoTargets(cryptoTargets);
662 mXmppConnectionService.updateConversation(conversation);
663 }
664 } else if (isNew
665 && user.getRealJid() != null
666 && conversation.getMucOptions().isPrivateAndNonAnonymous()
667 && (contact == null || !contact.mutualPresenceSubscription())
668 && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
669 account.getAxolotlService().fetchDeviceIds(user.getRealJid());
670 }
671 }
672 }
673 }
674 }
675 }
676
677 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
678 if (received == null) {
679 received = packet.findChild("received", "urn:xmpp:receipts");
680 }
681 if (received != null) {
682 String id = received.getAttribute("id");
683 if (packet.fromAccount(account)) {
684 if (query != null && id != null && packet.getTo() != null) {
685 query.removePendingReceiptRequest(new ReceiptRequest(packet.getTo(), id));
686 }
687 } else {
688 mXmppConnectionService.markMessage(account, from.asBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
689 }
690 }
691 Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
692 if (displayed != null) {
693 final String id = displayed.getAttribute("id");
694 final Jid sender = displayed.getAttributeAsJid("sender");
695 if (packet.fromAccount(account) && !selfAddressed) {
696 dismissNotification(account, counterpart, query);
697 } else if (isTypeGroupChat) {
698 Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
699 if (conversation != null && id != null && sender != null) {
700 Message message = conversation.findMessageWithRemoteId(id, sender);
701 if (message != null) {
702 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
703 final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
704 final boolean trueJidMatchesAccount = account.getJid().asBareJid().equals(trueJid == null ? null : trueJid.asBareJid());
705 if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
706 if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
707 mXmppConnectionService.markRead(conversation);
708 }
709 } else if (!counterpart.isBareJid() && trueJid != null) {
710 ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
711 if (message.addReadByMarker(readByMarker)) {
712 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": added read by (" + readByMarker.getRealJid() + ") to message '" + message.getBody() + "'");
713 mXmppConnectionService.updateMessage(message);
714 }
715 }
716 }
717 }
718 } else {
719 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_DISPLAYED);
720 Message message = displayedMessage == null ? null : displayedMessage.prev();
721 while (message != null
722 && message.getStatus() == Message.STATUS_SEND_RECEIVED
723 && message.getTimeSent() < displayedMessage.getTimeSent()) {
724 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
725 message = message.prev();
726 }
727 if (displayedMessage != null && selfAddressed) {
728 dismissNotification(account, counterpart, query);
729 }
730 }
731 }
732
733 Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
734 if (event != null) {
735 parseEvent(event, original.getFrom(), account);
736 }
737
738 final String nick = packet.findChildContent("nick", Namespace.NICK);
739 if (nick != null) {
740 Contact contact = account.getRoster().getContact(from);
741 if (contact.setPresenceName(nick)) {
742 mXmppConnectionService.getAvatarService().clear(contact);
743 }
744 }
745 }
746
747 private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query) {
748 Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
749 if (conversation != null && (query == null || query.isCatchup())) {
750 mXmppConnectionService.markRead(conversation); //TODO only mark messages read that are older than timestamp
751 }
752 }
753
754 private void processMessageReceipts(Account account, MessagePacket packet, MessageArchiveService.Query query) {
755 final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
756 final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
757 if (query == null) {
758 final ArrayList<String> receiptsNamespaces = new ArrayList<>();
759 if (markable) {
760 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
761 }
762 if (request) {
763 receiptsNamespaces.add("urn:xmpp:receipts");
764 }
765 if (receiptsNamespaces.size() > 0) {
766 MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
767 packet,
768 receiptsNamespaces,
769 packet.getType());
770 mXmppConnectionService.sendMessagePacket(account, receipt);
771 }
772 } else if (query.isCatchup()) {
773 if (request) {
774 query.addPendingReceiptRequest(new ReceiptRequest(packet.getFrom(), packet.getId()));
775 }
776 }
777 }
778
779 private void activateGracePeriod(Account account) {
780 long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
781 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
782 account.activateGracePeriod(duration);
783 }
784
785 private class Invite {
786 final Jid jid;
787 final String password;
788 final Contact inviter;
789
790 Invite(Jid jid, String password, Contact inviter) {
791 this.jid = jid;
792 this.password = password;
793 this.inviter = inviter;
794 }
795
796 public boolean execute(Account account) {
797 if (jid != null) {
798 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
799 if (!conversation.getMucOptions().online()) {
800 conversation.getMucOptions().setPassword(password);
801 mXmppConnectionService.databaseBackend.updateConversation(conversation);
802 mXmppConnectionService.joinMuc(conversation, inviter != null && inviter.mutualPresenceSubscription());
803 mXmppConnectionService.updateConversationUi();
804 }
805 return true;
806 }
807 return false;
808 }
809 }
810}