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