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