1package eu.siacs.conversations.parser;
2
3import android.text.Html;
4import android.util.Log;
5import android.util.Pair;
6
7import net.java.otr4j.session.Session;
8import net.java.otr4j.session.SessionStatus;
9
10import java.text.SimpleDateFormat;
11import java.util.ArrayList;
12import java.util.Arrays;
13import java.util.Date;
14import java.util.List;
15import java.util.Set;
16import java.util.UUID;
17
18import eu.siacs.conversations.Config;
19import eu.siacs.conversations.crypto.OtrService;
20import eu.siacs.conversations.crypto.axolotl.AxolotlService;
21import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
22import eu.siacs.conversations.entities.Account;
23import eu.siacs.conversations.entities.Bookmark;
24import eu.siacs.conversations.entities.Contact;
25import eu.siacs.conversations.entities.Conversation;
26import eu.siacs.conversations.entities.Message;
27import eu.siacs.conversations.entities.MucOptions;
28import eu.siacs.conversations.entities.Presence;
29import eu.siacs.conversations.entities.ServiceDiscoveryResult;
30import eu.siacs.conversations.http.HttpConnectionManager;
31import eu.siacs.conversations.services.MessageArchiveService;
32import eu.siacs.conversations.services.XmppConnectionService;
33import eu.siacs.conversations.utils.CryptoHelper;
34import eu.siacs.conversations.xml.Namespace;
35import eu.siacs.conversations.xml.Element;
36import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
37import eu.siacs.conversations.xmpp.chatstate.ChatState;
38import eu.siacs.conversations.xmpp.jid.Jid;
39import eu.siacs.conversations.xmpp.pep.Avatar;
40import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
41
42public class MessageParser extends AbstractParser implements OnMessagePacketReceived {
43
44 private static final List<String> CLIENTS_SENDING_HTML_IN_OTR = Arrays.asList("Pidgin","Adium","Trillian");
45
46 public MessageParser(XmppConnectionService service) {
47 super(service);
48 }
49
50 private boolean extractChatState(Conversation conversation, final MessagePacket packet) {
51 ChatState state = ChatState.parse(packet);
52 if (state != null && conversation != null) {
53 final Account account = conversation.getAccount();
54 Jid from = packet.getFrom();
55 if (from.toBareJid().equals(account.getJid().toBareJid())) {
56 conversation.setOutgoingChatState(state);
57 if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
58 mXmppConnectionService.markRead(conversation);
59 activateGracePeriod(account);
60 }
61 return false;
62 } else {
63 return conversation.setIncomingChatState(state);
64 }
65 }
66 return false;
67 }
68
69 private Message parseOtrChat(String body, Jid from, String id, Conversation conversation) {
70 String presence;
71 if (from.isBareJid()) {
72 presence = "";
73 } else {
74 presence = from.getResourcepart();
75 }
76 if (body.matches("^\\?OTRv\\d{1,2}\\?.*")) {
77 conversation.endOtrIfNeeded();
78 }
79 if (!conversation.hasValidOtrSession()) {
80 conversation.startOtrSession(presence,false);
81 } else {
82 String foreignPresence = conversation.getOtrSession().getSessionID().getUserID();
83 if (!foreignPresence.equals(presence)) {
84 conversation.endOtrIfNeeded();
85 conversation.startOtrSession(presence, false);
86 }
87 }
88 try {
89 conversation.setLastReceivedOtrMessageId(id);
90 Session otrSession = conversation.getOtrSession();
91 body = otrSession.transformReceiving(body);
92 SessionStatus status = otrSession.getSessionStatus();
93 if (body == null && status == SessionStatus.ENCRYPTED) {
94 mXmppConnectionService.onOtrSessionEstablished(conversation);
95 return null;
96 } else if (body == null && status == SessionStatus.FINISHED) {
97 conversation.resetOtrSession();
98 mXmppConnectionService.updateConversationUi();
99 return null;
100 } else if (body == null || (body.isEmpty())) {
101 return null;
102 }
103 if (body.startsWith(CryptoHelper.FILETRANSFER)) {
104 String key = body.substring(CryptoHelper.FILETRANSFER.length());
105 conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
106 return null;
107 }
108 if (clientMightSendHtml(conversation.getAccount(), from)) {
109 Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": received OTR message from bad behaving client. escaping HTML…");
110 body = Html.fromHtml(body).toString();
111 }
112
113 final OtrService otrService = conversation.getAccount().getOtrService();
114 Message finishedMessage = new Message(conversation, body, Message.ENCRYPTION_OTR, Message.STATUS_RECEIVED);
115 finishedMessage.setFingerprint(otrService.getFingerprint(otrSession.getRemotePublicKey()));
116 conversation.setLastReceivedOtrMessageId(null);
117
118 return finishedMessage;
119 } catch (Exception e) {
120 conversation.resetOtrSession();
121 return null;
122 }
123 }
124
125 private static boolean clientMightSendHtml(Account account, Jid from) {
126 String resource = from.getResourcepart();
127 if (resource == null) {
128 return false;
129 }
130 Presence presence = account.getRoster().getContact(from).getPresences().getPresences().get(resource);
131 ServiceDiscoveryResult disco = presence == null ? null : presence.getServiceDiscoveryResult();
132 if (disco == null) {
133 return false;
134 }
135 return hasIdentityKnowForSendingHtml(disco.getIdentities());
136 }
137
138 private static boolean hasIdentityKnowForSendingHtml(List<ServiceDiscoveryResult.Identity> identities) {
139 for(ServiceDiscoveryResult.Identity identity : identities) {
140 if (identity.getName() != null) {
141 if (CLIENTS_SENDING_HTML_IN_OTR.contains(identity.getName())) {
142 return true;
143 }
144 }
145 }
146 return false;
147 }
148
149 private Message parseAxolotlChat(Element axolotlMessage, Jid from, Conversation conversation, int status) {
150 AxolotlService service = conversation.getAccount().getAxolotlService();
151 XmppAxolotlMessage xmppAxolotlMessage;
152 try {
153 xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.toBareJid());
154 } catch (Exception e) {
155 Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": invalid omemo message received "+e.getMessage());
156 return null;
157 }
158 XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage);
159 if(plaintextMessage != null) {
160 Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
161 finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
162 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount())+" Received Message with session fingerprint: "+plaintextMessage.getFingerprint());
163 return finishedMessage;
164 } else {
165 return null;
166 }
167 }
168
169 private class Invite {
170 final Jid jid;
171 final String password;
172 final Contact inviter;
173 Invite(Jid jid, String password, Contact inviter) {
174 this.jid = jid;
175 this.password = password;
176 this.inviter = inviter;
177 }
178
179 public boolean execute(Account account) {
180 if (jid != null) {
181 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true);
182 if (!conversation.getMucOptions().online()) {
183 conversation.getMucOptions().setPassword(password);
184 mXmppConnectionService.databaseBackend.updateConversation(conversation);
185 mXmppConnectionService.joinMuc(conversation, inviter != null && inviter.mutualPresenceSubscription());
186 mXmppConnectionService.updateConversationUi();
187 }
188 return true;
189 }
190 return false;
191 }
192 }
193
194 private Invite extractInvite(Account account, Element message) {
195 Element x = message.findChild("x", "http://jabber.org/protocol/muc#user");
196 if (x != null) {
197 Element invite = x.findChild("invite");
198 if (invite != null) {
199 Element pw = x.findChild("password");
200 Jid from = invite.getAttributeAsJid("from");
201 Contact contact = from == null ? null : account.getRoster().getContact(from);
202 return new Invite(message.getAttributeAsJid("from"), pw != null ? pw.getContent(): null, contact);
203 }
204 } else {
205 x = message.findChild("x","jabber:x:conference");
206 if (x != null) {
207 Jid from = message.getAttributeAsJid("from");
208 Contact contact = from == null ? null : account.getRoster().getContact(from);
209 return new Invite(x.getAttributeAsJid("jid"),x.getAttribute("password"),contact);
210 }
211 }
212 return null;
213 }
214
215 private static String extractStanzaid(Element packet, boolean isTypeGroupChat, Conversation conversation) {
216 final Jid by;
217 final boolean safeToExtract;
218 if (isTypeGroupChat) {
219 by = conversation.getJid().toBareJid();
220 safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
221 } else {
222 Account account = conversation.getAccount();
223 by = account.getJid().toBareJid();
224 safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
225 }
226 return safeToExtract ? extractStanzaId(packet, by) : null;
227 }
228
229 private static String extractStanzaId(Element packet, Jid by) {
230 for(Element child : packet.getChildren()) {
231 if (child.getName().equals("stanza-id")
232 && Namespace.STANZA_IDS.equals(child.getNamespace())
233 && by.equals(child.getAttributeAsJid("by"))) {
234 return child.getAttribute("id");
235 }
236 }
237 return null;
238 }
239
240 private void parseEvent(final Element event, final Jid from, final Account account) {
241 Element items = event.findChild("items");
242 String node = items == null ? null : items.getAttribute("node");
243 if ("urn:xmpp:avatar:metadata".equals(node)) {
244 Avatar avatar = Avatar.parseMetadata(items);
245 if (avatar != null) {
246 avatar.owner = from.toBareJid();
247 if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
248 if (account.getJid().toBareJid().equals(from)) {
249 if (account.setAvatar(avatar.getFilename())) {
250 mXmppConnectionService.databaseBackend.updateAccount(account);
251 }
252 mXmppConnectionService.getAvatarService().clear(account);
253 mXmppConnectionService.updateConversationUi();
254 mXmppConnectionService.updateAccountUi();
255 } else {
256 Contact contact = account.getRoster().getContact(from);
257 contact.setAvatar(avatar);
258 mXmppConnectionService.getAvatarService().clear(contact);
259 mXmppConnectionService.updateConversationUi();
260 mXmppConnectionService.updateRosterUi();
261 }
262 } else if (mXmppConnectionService.isDataSaverDisabled()) {
263 mXmppConnectionService.fetchAvatar(account, avatar);
264 }
265 }
266 } else if ("http://jabber.org/protocol/nick".equals(node)) {
267 Element i = items.findChild("item");
268 Element nick = i == null ? null : i.findChild("nick", "http://jabber.org/protocol/nick");
269 if (nick != null && nick.getContent() != null) {
270 Contact contact = account.getRoster().getContact(from);
271 contact.setPresenceName(nick.getContent());
272 mXmppConnectionService.getAvatarService().clear(account);
273 mXmppConnectionService.updateConversationUi();
274 mXmppConnectionService.updateAccountUi();
275 }
276 } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
277
278 Element item = items.findChild("item");
279 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
280 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received PEP device list ("+deviceIds+") update from "+ from + ", processing...");
281 AxolotlService axolotlService = account.getAxolotlService();
282 axolotlService.registerDevices(from, deviceIds);
283 mXmppConnectionService.updateAccountUi();
284 }
285 }
286
287 private boolean handleErrorMessage(Account account, MessagePacket packet) {
288 if (packet.getType() == MessagePacket.TYPE_ERROR) {
289 Jid from = packet.getFrom();
290 if (from != null) {
291 Message message = mXmppConnectionService.markMessage(account,
292 from.toBareJid(),
293 packet.getId(),
294 Message.STATUS_SEND_FAILED,
295 extractErrorMessage(packet));
296 if (message != null) {
297 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
298 message.getConversation().endOtrIfNeeded();
299 }
300 }
301 }
302 return true;
303 }
304 return false;
305 }
306
307 @Override
308 public void onMessagePacketReceived(Account account, MessagePacket original) {
309 if (handleErrorMessage(account, original)) {
310 return;
311 }
312 final MessagePacket packet;
313 Long timestamp = null;
314 final boolean isForwarded;
315 boolean isCarbon = false;
316 String serverMsgId = null;
317 final Element fin = original.findChild("fin", Namespace.MAM_LEGACY);
318 if (fin != null) {
319 mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin,original.getFrom());
320 return;
321 }
322 final boolean mamLegacy = original.hasChild("result", Namespace.MAM_LEGACY);
323 final Element result = original.findChild("result",mamLegacy ? Namespace.MAM_LEGACY : Namespace.MAM);
324 final MessageArchiveService.Query query = result == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
325 if (query != null && query.validFrom(original.getFrom())) {
326 Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", mamLegacy ? Namespace.MAM_LEGACY : Namespace.MAM);
327 if (f == null) {
328 return;
329 }
330 timestamp = f.second;
331 packet = f.first;
332 isForwarded = true;
333 serverMsgId = result.getAttribute("id");
334 query.incrementMessageCount();
335 } else if (query != null) {
336 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received mam result from invalid sender");
337 return;
338 } else if (original.fromServer(account)) {
339 Pair<MessagePacket, Long> f;
340 f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
341 f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
342 packet = f != null ? f.first : original;
343 if (handleErrorMessage(account, packet)) {
344 return;
345 }
346 timestamp = f != null ? f.second : null;
347 isCarbon = f != null;
348 isForwarded = isCarbon;
349 } else {
350 packet = original;
351 isForwarded = false;
352 }
353
354 if (timestamp == null) {
355 timestamp = AbstractParser.parseTimestamp(original,AbstractParser.parseTimestamp(packet));
356 }
357 final String body = packet.getBody();
358 final Element mucUserElement = packet.findChild("x", "http://jabber.org/protocol/muc#user");
359 final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
360 final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
361 final Element oob = packet.findChild("x", "jabber:x:oob");
362 final boolean isOob = oob!= null && body != null && body.equals(oob.findChildContent("url"));
363 final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
364 final Element axolotlEncrypted = packet.findChild(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
365 int status;
366 final Jid counterpart;
367 final Jid to = packet.getTo();
368 final Jid from = packet.getFrom();
369 final String remoteMsgId = packet.getId();
370 boolean notify = false;
371
372 if (from == null) {
373 Log.d(Config.LOGTAG,"no from in: "+packet.toString());
374 return;
375 }
376
377 boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
378 boolean isProperlyAddressed = (to != null ) && (!to.isBareJid() || account.countPresences() == 0);
379 boolean isMucStatusMessage = from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
380 if (packet.fromAccount(account)) {
381 status = Message.STATUS_SEND;
382 counterpart = to != null ? to : account.getJid();
383 } else {
384 status = Message.STATUS_RECEIVED;
385 counterpart = from;
386 }
387
388 Invite invite = extractInvite(account, packet);
389 if (invite != null && invite.execute(account)) {
390 return;
391 }
392
393 if (!isTypeGroupChat
394 && query == null
395 && extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), packet)) {
396 mXmppConnectionService.updateConversationUi();
397 }
398
399 if ((body != null || pgpEncrypted != null || axolotlEncrypted != null) && !isMucStatusMessage) {
400 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat, false, query);
401 final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
402
403 if (serverMsgId == null) {
404 extractStanzaid(packet, isTypeGroupChat, conversation);
405 }
406
407 if (isTypeGroupChat) {
408 if (counterpart.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
409 status = Message.STATUS_SEND_RECEIVED;
410 isCarbon = true; //not really carbon but received from another resource
411 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId)) {
412 return;
413 } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
414 Message message = conversation.findSentMessageWithBody(packet.getBody());
415 if (message != null) {
416 mXmppConnectionService.markMessage(message, status);
417 return;
418 }
419 }
420 } else {
421 status = Message.STATUS_RECEIVED;
422 }
423 }
424 final Message message;
425 if (body != null && body.startsWith("?OTR") && Config.supportOtr()) {
426 if (!isForwarded && !isTypeGroupChat && isProperlyAddressed && !conversationMultiMode) {
427 message = parseOtrChat(body, from, remoteMsgId, conversation);
428 if (message == null) {
429 return;
430 }
431 } else {
432 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": ignoring OTR message from "+from+" isForwarded="+Boolean.toString(isForwarded)+", isProperlyAddressed="+Boolean.valueOf(isProperlyAddressed));
433 message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
434 }
435 } else if (pgpEncrypted != null && Config.supportOpenPgp()) {
436 message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
437 } else if (axolotlEncrypted != null && Config.supportOmemo()) {
438 Jid origin;
439 if (conversationMultiMode) {
440 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
441 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
442 if (origin == null) {
443 Log.d(Config.LOGTAG,"axolotl message in non anonymous conference received");
444 return;
445 }
446 } else {
447 origin = from;
448 }
449 message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status);
450 if (message == null) {
451 return;
452 }
453 if (conversationMultiMode) {
454 message.setTrueCounterpart(origin);
455 }
456 } else {
457 message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
458 }
459
460 message.setCounterpart(counterpart);
461 message.setRemoteMsgId(remoteMsgId);
462 message.setServerMsgId(serverMsgId);
463 message.setCarbon(isCarbon);
464 message.setTime(timestamp);
465 message.setOob(isOob);
466 message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
467 if (conversationMultiMode) {
468 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
469 Jid trueCounterpart;
470 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
471 trueCounterpart = message.getTrueCounterpart();
472 } else if (Config.PARSE_REAL_JID_FROM_MUC_MAM) {
473 trueCounterpart = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
474 } else {
475 trueCounterpart = fallback;
476 }
477 if (trueCounterpart != null && trueCounterpart.toBareJid().equals(account.getJid().toBareJid())) {
478 status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
479 }
480 message.setStatus(status);
481 message.setTrueCounterpart(trueCounterpart);
482 if (!isTypeGroupChat) {
483 message.setType(Message.TYPE_PRIVATE);
484 }
485 } else {
486 updateLastseen(account, from);
487 }
488
489 if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
490 Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
491 counterpart,
492 message.getStatus() == Message.STATUS_RECEIVED,
493 message.isCarbon());
494 if (replacedMessage != null) {
495 final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
496 || replacedMessage.getFingerprint().equals(message.getFingerprint());
497 final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
498 && replacedMessage.getTrueCounterpart().equals(message.getTrueCounterpart());
499 final boolean duplicate = conversation.hasDuplicateMessage(message);
500 if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode) && !duplicate) {
501 Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
502 synchronized (replacedMessage) {
503 final String uuid = replacedMessage.getUuid();
504 replacedMessage.setUuid(UUID.randomUUID().toString());
505 replacedMessage.setBody(message.getBody());
506 replacedMessage.setEdited(replacedMessage.getRemoteMsgId());
507 replacedMessage.setRemoteMsgId(remoteMsgId);
508 replacedMessage.setEncryption(message.getEncryption());
509 if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
510 replacedMessage.markUnread();
511 }
512 mXmppConnectionService.updateMessage(replacedMessage, uuid);
513 mXmppConnectionService.getNotificationService().updateNotification(false);
514 if (mXmppConnectionService.confirmMessages()
515 && (replacedMessage.trusted() || replacedMessage.getType() == Message.TYPE_PRIVATE)
516 && remoteMsgId != null
517 && !isForwarded
518 && !isTypeGroupChat) {
519 sendMessageReceipts(account, packet);
520 }
521 if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
522 conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
523 conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
524 }
525 }
526 return;
527 } else {
528 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received message correction but verification didn't check out");
529 }
530 }
531 }
532
533 long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate();
534 if (deletionDate != 0 && message.getTimeSent() < deletionDate) {
535 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping message from "+message.getCounterpart().toString()+" because it was sent prior to our deletion date");
536 return;
537 }
538
539 boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay","urn:xmpp:delay"))
540 || message.getType() == Message.TYPE_PRIVATE
541 || message.getServerMsgId() != null;
542 if (checkForDuplicates && conversation.hasDuplicateMessage(message)) {
543 Log.d(Config.LOGTAG,"skipping duplicate message from "+message.getCounterpart().toString()+" "+message.getBody());
544 return;
545 }
546
547 if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
548 conversation.prepend(message);
549 } else {
550 conversation.add(message);
551 }
552 if (query != null) {
553 query.incrementActualMessageCount();
554 }
555
556 if (query == null || query.isCatchup()) { //either no mam or catchup
557 if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
558 mXmppConnectionService.markRead(conversation);
559 if (query == null) {
560 activateGracePeriod(account);
561 }
562 } else {
563 message.markUnread();
564 notify = true;
565 }
566 }
567
568 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
569 notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
570 }
571
572 if (query == null) {
573 mXmppConnectionService.updateConversationUi();
574 }
575
576 if (mXmppConnectionService.confirmMessages()
577 && (message.trusted() || message.getType() == Message.TYPE_PRIVATE)
578 && remoteMsgId != null
579 && !isForwarded
580 && !isTypeGroupChat) {
581 sendMessageReceipts(account, packet);
582 }
583
584 if (message.getStatus() == Message.STATUS_RECEIVED
585 && conversation.getOtrSession() != null
586 && !conversation.getOtrSession().getSessionID().getUserID()
587 .equals(message.getCounterpart().getResourcepart())) {
588 conversation.endOtrIfNeeded();
589 }
590
591 mXmppConnectionService.databaseBackend.createMessage(message);
592 final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
593 if (message.trusted() && message.treatAsDownloadable() != Message.Decision.NEVER && manager.getAutoAcceptFileSize() > 0) {
594 manager.createNewDownloadConnection(message);
595 } else if (notify) {
596 if (query == null) {
597 mXmppConnectionService.getNotificationService().push(message);
598 } else if (query.isCatchup()) { // mam catchup
599 mXmppConnectionService.getNotificationService().pushFromBacklog(message);
600 }
601 }
602 } else if (!packet.hasChild("body")){ //no body
603 Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
604 if (isTypeGroupChat) {
605 if (packet.hasChild("subject")) {
606 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
607 conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
608 String subject = packet.findChildContent("subject");
609 conversation.getMucOptions().setSubject(subject);
610 final Bookmark bookmark = conversation.getBookmark();
611 if (bookmark != null && bookmark.getBookmarkName() == null) {
612 if (bookmark.setBookmarkName(subject)) {
613 mXmppConnectionService.pushBookmarks(account);
614 }
615 }
616 mXmppConnectionService.updateConversationUi();
617 return;
618 }
619 }
620 }
621 if (conversation != null && mucUserElement != null && from.isBareJid()) {
622 for (Element child : mucUserElement.getChildren()) {
623 if ("status".equals(child.getName())) {
624 try {
625 int code = Integer.parseInt(child.getAttribute("code"));
626 if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
627 mXmppConnectionService.fetchConferenceConfiguration(conversation);
628 break;
629 }
630 } catch (Exception e) {
631 //ignored
632 }
633 } else if ("item".equals(child.getName())) {
634 MucOptions.User user = AbstractParser.parseItem(conversation,child);
635 Log.d(Config.LOGTAG,account.getJid()+": changing affiliation for "
636 +user.getRealJid()+" to "+user.getAffiliation()+" in "
637 +conversation.getJid().toBareJid());
638 if (!user.realJidMatchesAccount()) {
639 conversation.getMucOptions().updateUser(user);
640 mXmppConnectionService.getAvatarService().clear(conversation);
641 mXmppConnectionService.updateMucRosterUi();
642 mXmppConnectionService.updateConversationUi();
643 if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
644 Jid jid = user.getRealJid();
645 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
646 if (cryptoTargets.remove(user.getRealJid())) {
647 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": removed "+jid+" from crypto targets of "+conversation.getName());
648 conversation.setAcceptedCryptoTargets(cryptoTargets);
649 mXmppConnectionService.updateConversation(conversation);
650 }
651 }
652 }
653 }
654 }
655 }
656 }
657
658
659
660 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
661 if (received == null) {
662 received = packet.findChild("received", "urn:xmpp:receipts");
663 }
664 if (received != null && !packet.fromAccount(account)) {
665 mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
666 }
667 Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
668 if (displayed != null) {
669 if (packet.fromAccount(account)) {
670 Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
671 if (conversation != null) {
672 mXmppConnectionService.markRead(conversation);
673 }
674 } else {
675 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
676 Message message = displayedMessage == null ? null : displayedMessage.prev();
677 while (message != null
678 && message.getStatus() == Message.STATUS_SEND_RECEIVED
679 && message.getTimeSent() < displayedMessage.getTimeSent()) {
680 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
681 message = message.prev();
682 }
683 }
684 }
685
686 Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
687 if (event != null) {
688 parseEvent(event, original.getFrom(), account);
689 }
690
691 String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
692 if (nick != null) {
693 Contact contact = account.getRoster().getContact(from);
694 contact.setPresenceName(nick);
695 }
696 }
697
698 private static Jid getTrueCounterpart(Element mucUserElement, Jid fallback) {
699 final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
700 Jid result = item == null ? null : item.getAttributeAsJid("jid");
701 return result != null ? result : fallback;
702 }
703
704 private void sendMessageReceipts(Account account, MessagePacket packet) {
705 ArrayList<String> receiptsNamespaces = new ArrayList<>();
706 if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
707 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
708 }
709 if (packet.hasChild("request", "urn:xmpp:receipts")) {
710 receiptsNamespaces.add("urn:xmpp:receipts");
711 }
712 if (receiptsNamespaces.size() > 0) {
713 MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
714 packet,
715 receiptsNamespaces,
716 packet.getType());
717 mXmppConnectionService.sendMessagePacket(account, receipt);
718 }
719 }
720
721 private static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
722
723 private void activateGracePeriod(Account account) {
724 long duration = mXmppConnectionService.getPreferences().getLong("race_period_length", 144) * 1000;
725 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": activating grace period till "+TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
726 account.activateGracePeriod(duration);
727 }
728}