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