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