MessageParser.java

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