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