1package eu.siacs.conversations.parser;
2
3import android.util.Log;
4import android.util.Pair;
5
6import com.cheogram.android.BobTransfer;
7
8import java.io.File;
9import java.net.URISyntaxException;
10import java.text.SimpleDateFormat;
11import java.util.ArrayList;
12import java.util.Arrays;
13import java.util.Collections;
14import java.util.Date;
15import java.util.LinkedHashSet;
16import java.util.List;
17import java.util.Locale;
18import java.util.Map;
19import java.util.Set;
20import java.util.UUID;
21
22import io.ipfs.cid.Cid;
23
24import eu.siacs.conversations.Config;
25import eu.siacs.conversations.R;
26import eu.siacs.conversations.crypto.axolotl.AxolotlService;
27import eu.siacs.conversations.crypto.axolotl.BrokenSessionException;
28import eu.siacs.conversations.crypto.axolotl.NotEncryptedForThisDeviceException;
29import eu.siacs.conversations.crypto.axolotl.OutdatedSenderException;
30import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
31import eu.siacs.conversations.entities.Account;
32import eu.siacs.conversations.entities.Bookmark;
33import eu.siacs.conversations.entities.Contact;
34import eu.siacs.conversations.entities.Conversation;
35import eu.siacs.conversations.entities.Conversational;
36import eu.siacs.conversations.entities.Message;
37import eu.siacs.conversations.entities.MucOptions;
38import eu.siacs.conversations.entities.ReadByMarker;
39import eu.siacs.conversations.entities.ReceiptRequest;
40import eu.siacs.conversations.entities.RtpSessionStatus;
41import eu.siacs.conversations.http.HttpConnectionManager;
42import eu.siacs.conversations.services.MessageArchiveService;
43import eu.siacs.conversations.services.QuickConversationsService;
44import eu.siacs.conversations.services.XmppConnectionService;
45import eu.siacs.conversations.utils.CryptoHelper;
46import eu.siacs.conversations.xml.Element;
47import eu.siacs.conversations.xml.LocalizedContent;
48import eu.siacs.conversations.xml.Namespace;
49import eu.siacs.conversations.xmpp.InvalidJid;
50import eu.siacs.conversations.xmpp.Jid;
51import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
52import eu.siacs.conversations.xmpp.chatstate.ChatState;
53import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
54import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
55import eu.siacs.conversations.xmpp.pep.Avatar;
56import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
57
58public class MessageParser extends AbstractParser implements OnMessagePacketReceived {
59
60 private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
61
62 private static final List<String> JINGLE_MESSAGE_ELEMENT_NAMES = Arrays.asList("accept", "propose", "proceed", "reject", "retract");
63
64 public MessageParser(XmppConnectionService service) {
65 super(service);
66 }
67
68 private static String extractStanzaId(Element packet, boolean isTypeGroupChat, Conversation conversation) {
69 final Jid by;
70 final boolean safeToExtract;
71 if (isTypeGroupChat) {
72 by = conversation.getJid().asBareJid();
73 safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
74 } else {
75 Account account = conversation.getAccount();
76 by = account.getJid().asBareJid();
77 safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
78 }
79 return safeToExtract ? extractStanzaId(packet, by) : null;
80 }
81
82 private static String extractStanzaId(Account account, Element packet) {
83 final boolean safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
84 return safeToExtract ? extractStanzaId(packet, account.getJid().asBareJid()) : null;
85 }
86
87 private static String extractStanzaId(Element packet, Jid by) {
88 for (Element child : packet.getChildren()) {
89 if (child.getName().equals("stanza-id")
90 && Namespace.STANZA_IDS.equals(child.getNamespace())
91 && by.equals(InvalidJid.getNullForInvalid(child.getAttributeAsJid("by")))) {
92 return child.getAttribute("id");
93 }
94 }
95 return null;
96 }
97
98 private static Jid getTrueCounterpart(Element mucUserElement, Jid fallback) {
99 final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
100 Jid result = item == null ? null : InvalidJid.getNullForInvalid(item.getAttributeAsJid("jid"));
101 return result != null ? result : fallback;
102 }
103
104 private boolean extractChatState(Conversation c, final boolean isTypeGroupChat, final MessagePacket packet) {
105 ChatState state = ChatState.parse(packet);
106 if (state != null && c != null) {
107 final Account account = c.getAccount();
108 final Jid from = packet.getFrom();
109 if (from.asBareJid().equals(account.getJid().asBareJid())) {
110 c.setOutgoingChatState(state);
111 if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
112 if (c.getContact().isSelf()) {
113 return false;
114 }
115 mXmppConnectionService.markRead(c);
116 activateGracePeriod(account);
117 }
118 return false;
119 } else {
120 if (isTypeGroupChat) {
121 MucOptions.User user = c.getMucOptions().findUserByFullJid(from);
122 if (user != null) {
123 return user.setChatState(state);
124 } else {
125 return false;
126 }
127 } else {
128 return c.setIncomingChatState(state);
129 }
130 }
131 }
132 return false;
133 }
134
135 private Message parseAxolotlChat(Element axolotlMessage, Jid from, Conversation conversation, int status, final boolean checkedForDuplicates, boolean postpone) {
136 final AxolotlService service = conversation.getAccount().getAxolotlService();
137 final XmppAxolotlMessage xmppAxolotlMessage;
138 try {
139 xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.asBareJid());
140 } catch (Exception e) {
141 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": invalid omemo message received " + e.getMessage());
142 return null;
143 }
144 if (xmppAxolotlMessage.hasPayload()) {
145 final XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage;
146 try {
147 plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage, postpone);
148 } catch (BrokenSessionException e) {
149 if (checkedForDuplicates) {
150 if (service.trustedOrPreviouslyResponded(from.asBareJid())) {
151 service.reportBrokenSessionException(e, postpone);
152 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
153 } else {
154 Log.d(Config.LOGTAG, "ignoring broken session exception because contact was not trusted");
155 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
156 }
157 } else {
158 Log.d(Config.LOGTAG, "ignoring broken session exception because checkForDuplicates failed");
159 return null;
160 }
161 } catch (NotEncryptedForThisDeviceException e) {
162 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE, status);
163 } catch (OutdatedSenderException e) {
164 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
165 }
166 if (plaintextMessage != null) {
167 Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
168 finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
169 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount()) + " Received Message with session fingerprint: " + plaintextMessage.getFingerprint());
170 return finishedMessage;
171 }
172 } else {
173 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": received OMEMO key transport message");
174 service.processReceivingKeyTransportMessage(xmppAxolotlMessage, postpone);
175 }
176 return null;
177 }
178
179 private Invite extractInvite(Element message) {
180 final Element mucUser = message.findChild("x", Namespace.MUC_USER);
181 if (mucUser != null) {
182 Element invite = mucUser.findChild("invite");
183 if (invite != null) {
184 String password = mucUser.findChildContent("password");
185 Jid from = InvalidJid.getNullForInvalid(invite.getAttributeAsJid("from"));
186 Jid room = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
187 if (room == null) {
188 return null;
189 }
190 return new Invite(room, password, false, from);
191 }
192 }
193 final Element conference = message.findChild("x", "jabber:x:conference");
194 if (conference != null) {
195 Jid from = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
196 Jid room = InvalidJid.getNullForInvalid(conference.getAttributeAsJid("jid"));
197 if (room == null) {
198 return null;
199 }
200 return new Invite(room, conference.getAttribute("password"), true, from);
201 }
202 return null;
203 }
204
205 private void parseEvent(final Element event, final Jid from, final Account account) {
206 final Element items = event.findChild("items");
207 final String node = items == null ? null : items.getAttribute("node");
208 if ("urn:xmpp:avatar:metadata".equals(node)) {
209 Avatar avatar = Avatar.parseMetadata(items);
210 if (avatar != null) {
211 avatar.owner = from.asBareJid();
212 if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
213 if (account.getJid().asBareJid().equals(from)) {
214 if (account.setAvatar(avatar.getFilename())) {
215 mXmppConnectionService.databaseBackend.updateAccount(account);
216 mXmppConnectionService.notifyAccountAvatarHasChanged(account);
217 }
218 mXmppConnectionService.getAvatarService().clear(account);
219 mXmppConnectionService.updateConversationUi();
220 mXmppConnectionService.updateAccountUi();
221 } else {
222 final Contact contact = account.getRoster().getContact(from);
223 contact.setAvatar(avatar);
224 mXmppConnectionService.syncRoster(account);
225 mXmppConnectionService.getAvatarService().clear(contact);
226 mXmppConnectionService.updateConversationUi();
227 mXmppConnectionService.updateRosterUi();
228 }
229 } else if (mXmppConnectionService.isDataSaverDisabled()) {
230 mXmppConnectionService.fetchAvatar(account, avatar);
231 }
232 }
233 } else if (Namespace.NICK.equals(node)) {
234 final Element i = items.findChild("item");
235 final String nick = i == null ? null : i.findChildContent("nick", Namespace.NICK);
236 if (nick != null) {
237 setNick(account, from, nick);
238 }
239 } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
240 Element item = items.findChild("item");
241 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
242 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received PEP device list " + deviceIds + " update from " + from + ", processing... ");
243 final AxolotlService axolotlService = account.getAxolotlService();
244 axolotlService.registerDevices(from, deviceIds);
245 } else if (Namespace.BOOKMARKS.equals(node) && account.getJid().asBareJid().equals(from)) {
246 if (account.getXmppConnection().getFeatures().bookmarksConversion()) {
247 final Element i = items.findChild("item");
248 final Element storage = i == null ? null : i.findChild("storage", Namespace.BOOKMARKS);
249 Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
250 mXmppConnectionService.processBookmarksInitial(account, bookmarks, true);
251 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": processing bookmark PEP event");
252 } else {
253 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring bookmark PEP event because bookmark conversion was not detected");
254 }
255 } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
256 final Element item = items.findChild("item");
257 final Element retract = items.findChild("retract");
258 if (item != null) {
259 final Bookmark bookmark = Bookmark.parseFromItem(item, account);
260 if (bookmark != null) {
261 account.putBookmark(bookmark);
262 mXmppConnectionService.processModifiedBookmark(bookmark);
263 mXmppConnectionService.updateConversationUi();
264 }
265 }
266 if (retract != null) {
267 final Jid id = InvalidJid.getNullForInvalid(retract.getAttributeAsJid("id"));
268 if (id != null) {
269 account.removeBookmark(id);
270 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmark for " + id);
271 mXmppConnectionService.processDeletedBookmark(account, id);
272 mXmppConnectionService.updateConversationUi();
273 }
274 }
275 } else {
276 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " received pubsub notification for node=" + node);
277 }
278 }
279
280 private void parseDeleteEvent(final Element event, final Jid from, final Account account) {
281 final Element delete = event.findChild("delete");
282 final String node = delete == null ? null : delete.getAttribute("node");
283 if (Namespace.NICK.equals(node)) {
284 Log.d(Config.LOGTAG, "parsing nick delete event from " + from);
285 setNick(account, from, null);
286 } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
287 account.setBookmarks(Collections.emptyMap());
288 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmarks node");
289 } else if (Namespace.AVATAR_METADATA.equals(node) && account.getJid().asBareJid().equals(from)) {
290 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": deleted avatar metadata node");
291 }
292 }
293
294 private void parsePurgeEvent(final Element event, final Jid from, final Account account) {
295 final Element purge = event.findChild("purge");
296 final String node = purge == null ? null : purge.getAttribute("node");
297 if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
298 account.setBookmarks(Collections.emptyMap());
299 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": purged bookmarks");
300 }
301 }
302
303 private void setNick(Account account, Jid user, String nick) {
304 if (user.asBareJid().equals(account.getJid().asBareJid())) {
305 account.setDisplayName(nick);
306 if (QuickConversationsService.isQuicksy()) {
307 mXmppConnectionService.getAvatarService().clear(account);
308 }
309 } else {
310 Contact contact = account.getRoster().getContact(user);
311 if (contact.setPresenceName(nick)) {
312 mXmppConnectionService.syncRoster(account);
313 mXmppConnectionService.getAvatarService().clear(contact);
314 }
315 }
316 mXmppConnectionService.updateConversationUi();
317 mXmppConnectionService.updateAccountUi();
318 }
319
320 private boolean handleErrorMessage(final Account account, final MessagePacket packet) {
321 if (packet.getType() == MessagePacket.TYPE_ERROR) {
322 if (packet.fromServer(account)) {
323 final Pair<MessagePacket, Long> forwarded = packet.getForwardedMessagePacket("received", Namespace.CARBONS);
324 if (forwarded != null) {
325 return handleErrorMessage(account, forwarded.first);
326 }
327 }
328 final Jid from = packet.getFrom();
329 final String id = packet.getId();
330 if (from != null && id != null) {
331 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
332 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
333 mXmppConnectionService.getJingleConnectionManager()
334 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.FAILED);
335 return true;
336 }
337 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX)) {
338 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX.length());
339 final String message = extractErrorMessage(packet);
340 mXmppConnectionService.getJingleConnectionManager().failProceed(account, from, sessionId, message);
341 return true;
342 }
343 mXmppConnectionService.markMessage(account,
344 from.asBareJid(),
345 id,
346 Message.STATUS_SEND_FAILED,
347 extractErrorMessage(packet));
348 final Element error = packet.findChild("error");
349 final boolean pingWorthyError = error != null && (error.hasChild("not-acceptable") || error.hasChild("remote-server-timeout") || error.hasChild("remote-server-not-found"));
350 if (pingWorthyError) {
351 Conversation conversation = mXmppConnectionService.find(account, from);
352 if (conversation != null && conversation.getMode() == Conversational.MODE_MULTI) {
353 if (conversation.getMucOptions().online()) {
354 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received ping worthy error for seemingly online muc at " + from);
355 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
356 }
357 }
358 }
359 }
360 return true;
361 }
362 return false;
363 }
364
365 @Override
366 public void onMessagePacketReceived(Account account, MessagePacket original) {
367 if (handleErrorMessage(account, original)) {
368 return;
369 }
370 final MessagePacket packet;
371 Long timestamp = null;
372 boolean isCarbon = false;
373 String serverMsgId = null;
374 final Element fin = original.findChild("fin", MessageArchiveService.Version.MAM_0.namespace);
375 if (fin != null) {
376 mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin, original.getFrom());
377 return;
378 }
379 final Element result = MessageArchiveService.Version.findResult(original);
380 final String queryId = result == null ? null : result.getAttribute("queryid");
381 final MessageArchiveService.Query query = queryId == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(queryId);
382 if (query != null && query.validFrom(original.getFrom())) {
383 final Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", query.version.namespace);
384 if (f == null) {
385 return;
386 }
387 timestamp = f.second;
388 packet = f.first;
389 serverMsgId = result.getAttribute("id");
390 query.incrementMessageCount();
391 if (handleErrorMessage(account, packet)) {
392 return;
393 }
394 } else if (query != null) {
395 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received mam result with invalid from (" + original.getFrom() + ") or queryId (" + queryId + ")");
396 return;
397 } else if (original.fromServer(account)) {
398 Pair<MessagePacket, Long> f;
399 f = original.getForwardedMessagePacket("received", Namespace.CARBONS);
400 f = f == null ? original.getForwardedMessagePacket("sent", Namespace.CARBONS) : f;
401 packet = f != null ? f.first : original;
402 if (handleErrorMessage(account, packet)) {
403 return;
404 }
405 timestamp = f != null ? f.second : null;
406 isCarbon = f != null;
407 } else {
408 packet = original;
409 }
410
411 if (timestamp == null) {
412 timestamp = AbstractParser.parseTimestamp(original, AbstractParser.parseTimestamp(packet));
413 }
414 final Element mucUserElement = packet.findChild("x", Namespace.MUC_USER);
415 final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
416 final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
417 Set<Message.FileParams> attachments = new LinkedHashSet<>();
418 for (Element child : packet.getChildren()) {
419 // SIMS first so they get preference in the set
420 if (child.getName().equals("reference") && child.getNamespace().equals("urn:xmpp:reference:0")) {
421 if (child.findChild("media-sharing", "urn:xmpp:sims:1") != null) {
422 attachments.add(new Message.FileParams(child));
423 }
424 }
425 }
426 for (Element child : packet.getChildren()) {
427 if (child.getName().equals("x") && child.getNamespace().equals(Namespace.OOB)) {
428 attachments.add(new Message.FileParams(child));
429 }
430 }
431 String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
432 if (replacementId == null) {
433 Element fasten = packet.findChild("apply-to", "urn:xmpp:fasten:0");
434 if (fasten != null && (fasten.findChild("retract", "urn:xmpp:message-retract:0") != null || fasten.findChild("urn:xmpp:message-moderate:0") != null)) {
435 replacementId = fasten.getAttribute("id");
436 packet.setBody("");
437 }
438 }
439 final LocalizedContent body = packet.getBody();
440
441 final Element axolotlEncrypted = packet.findChildEnsureSingle(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
442 int status;
443 final Jid counterpart;
444 final Jid to = packet.getTo();
445 final Jid from = packet.getFrom();
446 final Element originId = packet.findChild("origin-id", Namespace.STANZA_IDS);
447 final String remoteMsgId;
448 if (originId != null && originId.getAttribute("id") != null) {
449 remoteMsgId = originId.getAttribute("id");
450 } else {
451 remoteMsgId = packet.getId();
452 }
453 boolean notify = false;
454
455 Element html = original.findChild("html", "http://jabber.org/protocol/xhtml-im");
456 if (html != null && html.findChild("body", "http://www.w3.org/1999/xhtml") == null) {
457 html = null;
458 }
459
460 if (from == null || !InvalidJid.isValid(from) || !InvalidJid.isValid(to)) {
461 Log.e(Config.LOGTAG, "encountered invalid message from='" + from + "' to='" + to + "'");
462 return;
463 }
464
465 boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
466 if (query != null && !query.muc() && isTypeGroupChat) {
467 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": received groupchat (" + from + ") message on regular MAM request. skipping");
468 return;
469 }
470 boolean isMucStatusMessage = InvalidJid.hasValidFrom(packet) && from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
471 boolean selfAddressed;
472 if (packet.fromAccount(account)) {
473 status = Message.STATUS_SEND;
474 selfAddressed = to == null || account.getJid().asBareJid().equals(to.asBareJid());
475 if (selfAddressed) {
476 counterpart = from;
477 } else {
478 counterpart = to != null ? to : account.getJid();
479 }
480 } else {
481 status = Message.STATUS_RECEIVED;
482 counterpart = from;
483 selfAddressed = false;
484 }
485
486 final Invite invite = extractInvite(packet);
487 if (invite != null) {
488 if (isTypeGroupChat) {
489 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring invite to " + invite.jid + " because type=groupchat");
490 } else if (invite.direct && (mucUserElement != null || invite.inviter == null || mXmppConnectionService.isMuc(account, invite.inviter))) {
491 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring direct invite to " + invite.jid + " because it was received in MUC");
492 } else {
493 invite.execute(account);
494 return;
495 }
496 }
497
498 if ((body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || !attachments.isEmpty() || html != null) && !isMucStatusMessage) {
499 final boolean conversationIsProbablyMuc = isTypeGroupChat || mucUserElement != null || account.getXmppConnection().getMucServersWithholdAccount().contains(counterpart.getDomain().toEscapedString());
500 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), conversationIsProbablyMuc, false, query, false);
501 final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
502
503 if (serverMsgId == null) {
504 serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
505 }
506
507
508 if (selfAddressed) {
509 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, Message.STATUS_SEND_RECEIVED, serverMsgId)) {
510 return;
511 }
512 status = Message.STATUS_RECEIVED;
513 if (remoteMsgId != null && conversation.findMessageWithRemoteId(remoteMsgId, counterpart) != null) {
514 return;
515 }
516 }
517
518 if (isTypeGroupChat) {
519 if (conversation.getMucOptions().isSelf(counterpart)) {
520 status = Message.STATUS_SEND_RECEIVED;
521 isCarbon = true; //not really carbon but received from another resource
522 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId, body)) {
523 return;
524 } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
525 if (body != null) {
526 Message message = conversation.findSentMessageWithBody(body.content);
527 if (message != null) {
528 mXmppConnectionService.markMessage(message, status);
529 return;
530 }
531 }
532 }
533 } else {
534 status = Message.STATUS_RECEIVED;
535 }
536 }
537 final Message message;
538 if (pgpEncrypted != null && Config.supportOpenPgp()) {
539 message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
540 } else if (axolotlEncrypted != null && Config.supportOmemo()) {
541 Jid origin;
542 Set<Jid> fallbacksBySourceId = Collections.emptySet();
543 if (conversationMultiMode) {
544 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
545 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
546 if (origin == null) {
547 try {
548 fallbacksBySourceId = account.getAxolotlService().findCounterpartsBySourceId(XmppAxolotlMessage.parseSourceId(axolotlEncrypted));
549 } catch (IllegalArgumentException e) {
550 //ignoring
551 }
552 }
553 if (origin == null && fallbacksBySourceId.size() == 0) {
554 Log.d(Config.LOGTAG, "axolotl message in anonymous conference received and no possible fallbacks");
555 return;
556 }
557 } else {
558 fallbacksBySourceId = Collections.emptySet();
559 origin = from;
560 }
561
562 final boolean liveMessage = query == null && !isTypeGroupChat && mucUserElement == null;
563 final boolean checkedForDuplicates = liveMessage || (serverMsgId != null && remoteMsgId != null && !conversation.possibleDuplicate(serverMsgId, remoteMsgId));
564
565 if (origin != null) {
566 message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status, checkedForDuplicates, query != null);
567 } else {
568 Message trial = null;
569 for (Jid fallback : fallbacksBySourceId) {
570 trial = parseAxolotlChat(axolotlEncrypted, fallback, conversation, status, checkedForDuplicates && fallbacksBySourceId.size() == 1, query != null);
571 if (trial != null) {
572 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": decoded muc message using fallback");
573 origin = fallback;
574 break;
575 }
576 }
577 message = trial;
578 }
579 if (message == null) {
580 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
581 mXmppConnectionService.updateConversationUi();
582 }
583 if (query != null && status == Message.STATUS_SEND && remoteMsgId != null) {
584 Message previouslySent = conversation.findSentMessageWithUuid(remoteMsgId);
585 if (previouslySent != null && previouslySent.getServerMsgId() == null && serverMsgId != null) {
586 previouslySent.setServerMsgId(serverMsgId);
587 mXmppConnectionService.databaseBackend.updateMessage(previouslySent, false);
588 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered previously sent OMEMO message without serverId. updating...");
589 }
590 }
591 return;
592 }
593 if (conversationMultiMode) {
594 message.setTrueCounterpart(origin);
595 }
596 } else if (body == null && !attachments.isEmpty()) {
597 message = new Message(conversation, "", Message.ENCRYPTION_NONE, status);
598 } else {
599 message = new Message(conversation, body == null ? "HTML-only message" : body.content, Message.ENCRYPTION_NONE, status);
600 if (body != null && body.count > 1) {
601 message.setBodyLanguage(body.language);
602 }
603 }
604
605 Element addresses = packet.findChild("addresses", "http://jabber.org/protocol/address");
606 if (status == Message.STATUS_RECEIVED && addresses != null) {
607 for (Element address : addresses.getChildren()) {
608 if (!address.getName().equals("address") || !address.getNamespace().equals("http://jabber.org/protocol/address")) continue;
609
610 if (address.getAttribute("type").equals("ofrom") && address.getAttribute("jid") != null) {
611 Jid ofrom = address.getAttributeAsJid("jid");
612 if (InvalidJid.isValid(ofrom) && ofrom.getDomain().equals(counterpart.getDomain()) &&
613 conversation.getAccount().getRoster().getContact(counterpart.getDomain()).getPresences().anySupport("http://jabber.org/protocol/address")) {
614
615 message.setTrueCounterpart(ofrom);
616 }
617 }
618 }
619 }
620
621 if (html != null) message.addPayload(html);
622 message.setSubject(original.findChildContent("subject"));
623 message.setCounterpart(counterpart);
624 message.setRemoteMsgId(remoteMsgId);
625 message.setServerMsgId(serverMsgId);
626 message.setCarbon(isCarbon);
627 message.setTime(timestamp);
628 if (!attachments.isEmpty()) {
629 message.setFileParams(attachments.iterator().next());
630 if (CryptoHelper.isPgpEncryptedUrl(message.getFileParams().url)) {
631 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
632 }
633 }
634 message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
635 for (Element el : packet.getChildren()) {
636 if (el.getName().equals("query") && el.getNamespace().equals("http://jabber.org/protocol/disco#items") && el.getAttribute("node").equals("http://jabber.org/protocol/commands")) {
637 message.addPayload(el);
638 }
639 if (el.getName().equals("thread") && (el.getNamespace() == null || el.getNamespace().equals("jabber:client"))) {
640 el.setAttribute("xmlns", "jabber:client");
641 message.addPayload(el);
642 }
643 }
644 if (conversationMultiMode) {
645 message.setMucUser(conversation.getMucOptions().findUserByFullJid(counterpart));
646 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
647 Jid trueCounterpart;
648 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
649 trueCounterpart = message.getTrueCounterpart();
650 } else if (query != null && query.safeToExtractTrueCounterpart()) {
651 trueCounterpart = getTrueCounterpart(mucUserElement, fallback);
652 } else {
653 trueCounterpart = fallback;
654 }
655 if (trueCounterpart != null && isTypeGroupChat) {
656 if (trueCounterpart.asBareJid().equals(account.getJid().asBareJid())) {
657 status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
658 } else {
659 status = Message.STATUS_RECEIVED;
660 message.setCarbon(false);
661 }
662 }
663 message.setStatus(status);
664 message.setTrueCounterpart(trueCounterpart);
665 if (!isTypeGroupChat) {
666 message.setType(Message.TYPE_PRIVATE);
667 }
668 } else {
669 updateLastseen(account, from);
670 }
671
672 if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
673 final Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
674 counterpart,
675 message.getStatus() == Message.STATUS_RECEIVED,
676 message.isCarbon());
677 if (replacedMessage != null) {
678 final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
679 || replacedMessage.getFingerprint().equals(message.getFingerprint());
680 final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
681 && message.getTrueCounterpart() != null
682 && replacedMessage.getTrueCounterpart().asBareJid().equals(message.getTrueCounterpart().asBareJid());
683 final boolean mucUserMatches = query == null && replacedMessage.sameMucUser(message); //can not be checked when using mam
684 final boolean duplicate = conversation.hasDuplicateMessage(message);
685 if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode || mucUserMatches) && !duplicate) {
686 Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
687 synchronized (replacedMessage) {
688 final String uuid = replacedMessage.getUuid();
689 replacedMessage.setUuid(UUID.randomUUID().toString());
690 replacedMessage.setBody(message.getBody());
691 replacedMessage.putEdited(replacedMessage.getRemoteMsgId(), replacedMessage.getServerMsgId());
692 replacedMessage.setRemoteMsgId(remoteMsgId);
693 if (replacedMessage.getServerMsgId() == null || message.getServerMsgId() != null) {
694 replacedMessage.setServerMsgId(message.getServerMsgId());
695 }
696 replacedMessage.setEncryption(message.getEncryption());
697 if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
698 replacedMessage.markUnread();
699 }
700 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
701 mXmppConnectionService.updateMessage(replacedMessage, uuid);
702 if (mXmppConnectionService.confirmMessages()
703 && replacedMessage.getStatus() == Message.STATUS_RECEIVED
704 && (replacedMessage.trusted() || replacedMessage.isPrivateMessage()) //TODO do we really want to send receipts for all PMs?
705 && remoteMsgId != null
706 && !selfAddressed
707 && !isTypeGroupChat) {
708 processMessageReceipts(account, packet, remoteMsgId, query);
709 }
710 if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
711 conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
712 conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
713 }
714 }
715 mXmppConnectionService.getNotificationService().updateNotification();
716 return;
717 } else {
718 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received message correction but verification didn't check out");
719 }
720 }
721 }
722
723 long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate();
724 if (deletionDate != 0 && message.getTimeSent() < deletionDate) {
725 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping message from " + message.getCounterpart().toString() + " because it was sent prior to our deletion date");
726 return;
727 }
728
729 boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay", "urn:xmpp:delay"))
730 || message.isPrivateMessage()
731 || message.getServerMsgId() != null
732 || (query == null && mXmppConnectionService.getMessageArchiveService().isCatchupInProgress(conversation));
733 if (checkForDuplicates) {
734 final Message duplicate = conversation.findDuplicateMessage(message);
735 if (duplicate != null) {
736 final boolean serverMsgIdUpdated;
737 if (duplicate.getStatus() != Message.STATUS_RECEIVED
738 && duplicate.getUuid().equals(message.getRemoteMsgId())
739 && duplicate.getServerMsgId() == null
740 && message.getServerMsgId() != null) {
741 duplicate.setServerMsgId(message.getServerMsgId());
742 if (mXmppConnectionService.databaseBackend.updateMessage(duplicate, false)) {
743 serverMsgIdUpdated = true;
744 } else {
745 serverMsgIdUpdated = false;
746 Log.e(Config.LOGTAG, "failed to update message");
747 }
748 } else {
749 serverMsgIdUpdated = false;
750 }
751 Log.d(Config.LOGTAG, "skipping duplicate message with " + message.getCounterpart() + ". serverMsgIdUpdated=" + serverMsgIdUpdated);
752 return;
753 }
754 }
755
756 if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
757 conversation.prepend(query.getActualInThisQuery(), message);
758 } else {
759 conversation.add(message);
760 }
761 if (query != null) {
762 query.incrementActualMessageCount();
763 }
764
765 if (query == null || query.isCatchup()) { //either no mam or catchup
766 if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
767 mXmppConnectionService.markRead(conversation);
768 if (query == null) {
769 activateGracePeriod(account);
770 }
771 } else {
772 message.markUnread();
773 notify = true;
774 }
775 }
776
777 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
778 notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
779 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE || message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
780 notify = false;
781 }
782
783 if (query == null) {
784 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
785 mXmppConnectionService.updateConversationUi();
786 }
787
788 if (mXmppConnectionService.confirmMessages()
789 && message.getStatus() == Message.STATUS_RECEIVED
790 && (message.trusted() || message.isPrivateMessage())
791 && remoteMsgId != null
792 && !selfAddressed
793 && !isTypeGroupChat) {
794 processMessageReceipts(account, packet, remoteMsgId, query);
795 }
796
797 if (message.getFileParams() != null) {
798 for (Cid cid : message.getFileParams().getCids()) {
799 File f = mXmppConnectionService.getFileForCid(cid);
800 if (f != null && f.canRead()) {
801 message.setRelativeFilePath(f.getAbsolutePath());
802 mXmppConnectionService.getFileBackend().updateFileParams(message, null, false);
803 break;
804 }
805 }
806 }
807
808 mXmppConnectionService.databaseBackend.createMessage(message);
809
810 final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
811 if (message.getRelativeFilePath() == null && message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
812 if (message.getOob() != null && message.getOob().getScheme().equalsIgnoreCase("cid")) {
813 try {
814 BobTransfer transfer = new BobTransfer.ForMessage(message, mXmppConnectionService);
815 message.setTransferable(transfer);
816 transfer.start();
817 } catch (URISyntaxException e) {
818 Log.d(Config.LOGTAG, "BobTransfer failed to parse URI");
819 }
820 } else {
821 manager.createNewDownloadConnection(message);
822 }
823 } else if (notify) {
824 if (query != null && query.isCatchup()) {
825 mXmppConnectionService.getNotificationService().pushFromBacklog(message);
826 } else {
827 mXmppConnectionService.getNotificationService().push(message);
828 }
829 }
830 } else if (!packet.hasChild("body")) { //no body
831
832 final Conversation conversation = mXmppConnectionService.find(account, from.asBareJid());
833 if (axolotlEncrypted != null) {
834 Jid origin;
835 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
836 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
837 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
838 if (origin == null) {
839 Log.d(Config.LOGTAG, "omemo key transport message in anonymous conference received");
840 return;
841 }
842 } else if (isTypeGroupChat) {
843 return;
844 } else {
845 origin = from;
846 }
847 try {
848 final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.asBareJid());
849 account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
850 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": omemo key transport message received from " + origin);
851 } catch (Exception e) {
852 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": invalid omemo key transport message received " + e.getMessage());
853 return;
854 }
855 }
856
857 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
858 mXmppConnectionService.updateConversationUi();
859 }
860
861 if (isTypeGroupChat) {
862 if (packet.hasChild("subject")) { //TODO usually we would want to check for lack of body; however some servers do set a body :(
863 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
864 conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
865 final LocalizedContent subject = packet.findInternationalizedChildContentInDefaultNamespace("subject");
866 if (subject != null && conversation.getMucOptions().setSubject(subject.content)) {
867 mXmppConnectionService.updateConversation(conversation);
868 }
869 mXmppConnectionService.updateConversationUi();
870 return;
871 }
872 }
873 }
874 if (conversation != null && mucUserElement != null && InvalidJid.hasValidFrom(packet) && from.isBareJid()) {
875 for (Element child : mucUserElement.getChildren()) {
876 if ("status".equals(child.getName())) {
877 try {
878 int code = Integer.parseInt(child.getAttribute("code"));
879 if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
880 mXmppConnectionService.fetchConferenceConfiguration(conversation);
881 break;
882 }
883 } catch (Exception e) {
884 //ignored
885 }
886 } else if ("item".equals(child.getName())) {
887 MucOptions.User user = AbstractParser.parseItem(conversation, child);
888 Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for "
889 + user.getRealJid() + " to " + user.getAffiliation() + " in "
890 + conversation.getJid().asBareJid());
891 if (!user.realJidMatchesAccount()) {
892 boolean isNew = conversation.getMucOptions().updateUser(user);
893 mXmppConnectionService.getAvatarService().clear(conversation);
894 mXmppConnectionService.updateMucRosterUi();
895 mXmppConnectionService.updateConversationUi();
896 Contact contact = user.getContact();
897 if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
898 Jid jid = user.getRealJid();
899 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
900 if (cryptoTargets.remove(user.getRealJid())) {
901 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
902 conversation.setAcceptedCryptoTargets(cryptoTargets);
903 mXmppConnectionService.updateConversation(conversation);
904 }
905 } else if (isNew
906 && user.getRealJid() != null
907 && conversation.getMucOptions().isPrivateAndNonAnonymous()
908 && (contact == null || !contact.mutualPresenceSubscription())
909 && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
910 account.getAxolotlService().fetchDeviceIds(user.getRealJid());
911 }
912 }
913 }
914 }
915 }
916 if (!isTypeGroupChat) {
917 for (Element child : packet.getChildren()) {
918 if (Namespace.JINGLE_MESSAGE.equals(child.getNamespace()) && JINGLE_MESSAGE_ELEMENT_NAMES.contains(child.getName())) {
919 final String action = child.getName();
920 final String sessionId = child.getAttribute("id");
921 if (sessionId == null) {
922 break;
923 }
924 if (query == null) {
925 if (serverMsgId == null) {
926 serverMsgId = extractStanzaId(account, packet);
927 }
928 mXmppConnectionService.getJingleConnectionManager().deliverMessage(account, packet.getTo(), packet.getFrom(), child, remoteMsgId, serverMsgId, timestamp);
929 if (!account.getJid().asBareJid().equals(from.asBareJid()) && remoteMsgId != null) {
930 processMessageReceipts(account, packet, remoteMsgId, query);
931 }
932 } else if (query.isCatchup()) {
933 if ("propose".equals(action)) {
934 final Element description = child.findChild("description");
935 final String namespace = description == null ? null : description.getNamespace();
936 if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
937 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
938 final Message preExistingMessage = c.findRtpSession(sessionId, status);
939 if (preExistingMessage != null) {
940 preExistingMessage.setServerMsgId(serverMsgId);
941 mXmppConnectionService.updateMessage(preExistingMessage);
942 break;
943 }
944 final Message message = new Message(
945 c,
946 status,
947 Message.TYPE_RTP_SESSION,
948 sessionId
949 );
950 message.setServerMsgId(serverMsgId);
951 message.setTime(timestamp);
952 message.setBody(new RtpSessionStatus(false, 0).toString());
953 c.add(message);
954 mXmppConnectionService.databaseBackend.createMessage(message);
955 }
956 } else if ("proceed".equals(action)) {
957 //status needs to be flipped to find the original propose
958 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
959 final int s = packet.fromAccount(account) ? Message.STATUS_RECEIVED : Message.STATUS_SEND;
960 final Message message = c.findRtpSession(sessionId, s);
961 if (message != null) {
962 message.setBody(new RtpSessionStatus(true, 0).toString());
963 if (serverMsgId != null) {
964 message.setServerMsgId(serverMsgId);
965 }
966 message.setTime(timestamp);
967 mXmppConnectionService.updateMessage(message, true);
968 } else {
969 Log.d(Config.LOGTAG, "unable to find original rtp session message for received propose");
970 }
971
972 }
973 } else {
974 //MAM reloads (non catchups
975 if ("propose".equals(action)) {
976 final Element description = child.findChild("description");
977 final String namespace = description == null ? null : description.getNamespace();
978 if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
979 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
980 final Message preExistingMessage = c.findRtpSession(sessionId, status);
981 if (preExistingMessage != null) {
982 preExistingMessage.setServerMsgId(serverMsgId);
983 mXmppConnectionService.updateMessage(preExistingMessage);
984 break;
985 }
986 final Message message = new Message(
987 c,
988 status,
989 Message.TYPE_RTP_SESSION,
990 sessionId
991 );
992 message.setServerMsgId(serverMsgId);
993 message.setTime(timestamp);
994 message.setBody(new RtpSessionStatus(true, 0).toString());
995 if (query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
996 c.prepend(query.getActualInThisQuery(), message);
997 } else {
998 c.add(message);
999 }
1000 query.incrementActualMessageCount();
1001 mXmppConnectionService.databaseBackend.createMessage(message);
1002 }
1003 }
1004 }
1005 break;
1006 }
1007 }
1008 }
1009 }
1010
1011 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
1012 if (received == null) {
1013 received = packet.findChild("received", "urn:xmpp:receipts");
1014 }
1015 if (received != null) {
1016 String id = received.getAttribute("id");
1017 if (packet.fromAccount(account)) {
1018 if (query != null && id != null && packet.getTo() != null) {
1019 query.removePendingReceiptRequest(new ReceiptRequest(packet.getTo(), id));
1020 }
1021 } else if (id != null) {
1022 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
1023 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
1024 mXmppConnectionService.getJingleConnectionManager()
1025 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.DISCOVERED);
1026 } else {
1027 mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_RECEIVED);
1028 }
1029 }
1030 }
1031 Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
1032 if (displayed != null) {
1033 final String id = displayed.getAttribute("id");
1034 final Jid sender = InvalidJid.getNullForInvalid(displayed.getAttributeAsJid("sender"));
1035 if (packet.fromAccount(account) && !selfAddressed) {
1036 dismissNotification(account, counterpart, query, id);
1037 if (query == null) {
1038 activateGracePeriod(account);
1039 }
1040 } else if (isTypeGroupChat) {
1041 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1042 final Message message;
1043 if (conversation != null && id != null) {
1044 if (sender != null) {
1045 message = conversation.findMessageWithRemoteId(id, sender);
1046 } else {
1047 message = conversation.findMessageWithServerMsgId(id);
1048 }
1049 } else {
1050 message = null;
1051 }
1052 if (message != null) {
1053 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
1054 final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
1055 final boolean trueJidMatchesAccount = account.getJid().asBareJid().equals(trueJid == null ? null : trueJid.asBareJid());
1056 if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
1057 if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
1058 mXmppConnectionService.markRead(conversation);
1059 }
1060 } else if (!counterpart.isBareJid() && trueJid != null) {
1061 final ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
1062 if (message.addReadByMarker(readByMarker)) {
1063 mXmppConnectionService.updateMessage(message, false);
1064 }
1065 }
1066 }
1067 } else {
1068 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_DISPLAYED);
1069 Message message = displayedMessage == null ? null : displayedMessage.prev();
1070 while (message != null
1071 && message.getStatus() == Message.STATUS_SEND_RECEIVED
1072 && message.getTimeSent() < displayedMessage.getTimeSent()) {
1073 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
1074 message = message.prev();
1075 }
1076 if (displayedMessage != null && selfAddressed) {
1077 dismissNotification(account, counterpart, query, id);
1078 }
1079 }
1080 }
1081
1082 final Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
1083 if (event != null && InvalidJid.hasValidFrom(original) && original.getFrom().isBareJid()) {
1084 if (event.hasChild("items")) {
1085 parseEvent(event, original.getFrom(), account);
1086 } else if (event.hasChild("delete")) {
1087 parseDeleteEvent(event, original.getFrom(), account);
1088 } else if (event.hasChild("purge")) {
1089 parsePurgeEvent(event, original.getFrom(), account);
1090 }
1091 }
1092
1093 final String nick = packet.findChildContent("nick", Namespace.NICK);
1094 if (nick != null && InvalidJid.hasValidFrom(original)) {
1095 if (mXmppConnectionService.isMuc(account, from)) {
1096 return;
1097 }
1098 final Contact contact = account.getRoster().getContact(from);
1099 if (contact.setPresenceName(nick)) {
1100 mXmppConnectionService.syncRoster(account);
1101 mXmppConnectionService.getAvatarService().clear(contact);
1102 }
1103 }
1104 }
1105
1106 private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query, final String id) {
1107 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
1108 if (conversation != null && (query == null || query.isCatchup())) {
1109 final String displayableId = conversation.findMostRecentRemoteDisplayableId();
1110 if (displayableId != null && displayableId.equals(id)) {
1111 mXmppConnectionService.markRead(conversation);
1112 } else {
1113 Log.w(Config.LOGTAG, account.getJid().asBareJid() + ": received dismissing display marker that did not match our last id in that conversation");
1114 }
1115 }
1116 }
1117
1118 private void processMessageReceipts(final Account account, final MessagePacket packet, final String remoteMsgId, MessageArchiveService.Query query) {
1119 final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
1120 final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
1121 if (query == null) {
1122 final ArrayList<String> receiptsNamespaces = new ArrayList<>();
1123 if (markable) {
1124 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
1125 }
1126 if (request) {
1127 receiptsNamespaces.add("urn:xmpp:receipts");
1128 }
1129 if (receiptsNamespaces.size() > 0) {
1130 final MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
1131 packet.getFrom(),
1132 remoteMsgId,
1133 receiptsNamespaces,
1134 packet.getType());
1135 mXmppConnectionService.sendMessagePacket(account, receipt);
1136 }
1137 } else if (query.isCatchup()) {
1138 if (request) {
1139 query.addPendingReceiptRequest(new ReceiptRequest(packet.getFrom(), remoteMsgId));
1140 }
1141 }
1142 }
1143
1144 private void activateGracePeriod(Account account) {
1145 long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
1146 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
1147 account.activateGracePeriod(duration);
1148 }
1149
1150 private class Invite {
1151 final Jid jid;
1152 final String password;
1153 final boolean direct;
1154 final Jid inviter;
1155
1156 Invite(Jid jid, String password, boolean direct, Jid inviter) {
1157 this.jid = jid;
1158 this.password = password;
1159 this.direct = direct;
1160 this.inviter = inviter;
1161 }
1162
1163 public boolean execute(Account account) {
1164 if (jid != null) {
1165 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
1166 if (conversation.getMucOptions().online()) {
1167 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received invite to " + jid + " but muc is considered to be online");
1168 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
1169 } else {
1170 conversation.getMucOptions().setPassword(password);
1171 mXmppConnectionService.databaseBackend.updateConversation(conversation);
1172 final Contact contact = inviter != null ? account.getRoster().getContactFromContactList(inviter) : null;
1173 mXmppConnectionService.joinMuc(conversation, contact != null && contact.mutualPresenceSubscription());
1174 mXmppConnectionService.updateConversationUi();
1175 }
1176 return true;
1177 }
1178 return false;
1179 }
1180 }
1181}