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.SimpleDateFormat;
 11import java.util.ArrayList;
 12import java.util.Arrays;
 13import java.util.Date;
 14import java.util.List;
 15import java.util.Locale;
 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.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(new String[]{"Pidgin","Adium"});
 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		Message finishedMessage = null;
151		AxolotlService service = conversation.getAccount().getAxolotlService();
152		XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.toBareJid());
153		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage);
154		if(plaintextMessage != null) {
155			finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
156			finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
157			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount())+" Received Message with session fingerprint: "+plaintextMessage.getFingerprint());
158		}
159
160		return finishedMessage;
161	}
162
163	private class Invite {
164		Jid jid;
165		String password;
166		Invite(Jid jid, String password) {
167			this.jid = jid;
168			this.password = password;
169		}
170
171		public boolean execute(Account account) {
172			if (jid != null) {
173				Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true);
174				if (!conversation.getMucOptions().online()) {
175					conversation.getMucOptions().setPassword(password);
176					mXmppConnectionService.databaseBackend.updateConversation(conversation);
177					mXmppConnectionService.joinMuc(conversation);
178					mXmppConnectionService.updateConversationUi();
179				}
180				return true;
181			}
182			return false;
183		}
184	}
185
186	private Invite extractInvite(Element message) {
187		Element x = message.findChild("x", "http://jabber.org/protocol/muc#user");
188		if (x != null) {
189			Element invite = x.findChild("invite");
190			if (invite != null) {
191				Element pw = x.findChild("password");
192				return new Invite(message.getAttributeAsJid("from"), pw != null ? pw.getContent(): null);
193			}
194		} else {
195			x = message.findChild("x","jabber:x:conference");
196			if (x != null) {
197				return new Invite(x.getAttributeAsJid("jid"),x.getAttribute("password"));
198			}
199		}
200		return null;
201	}
202
203	private static String extractStanzaId(Element packet, Jid by) {
204		for(Element child : packet.getChildren()) {
205			if (child.getName().equals("stanza-id")
206					&& "urn:xmpp:sid:0".equals(child.getNamespace())
207					&& by.equals(child.getAttributeAsJid("by"))) {
208				return child.getAttribute("id");
209			}
210		}
211		return null;
212	}
213
214	private void parseEvent(final Element event, final Jid from, final Account account) {
215		Element items = event.findChild("items");
216		String node = items == null ? null : items.getAttribute("node");
217		if ("urn:xmpp:avatar:metadata".equals(node)) {
218			Avatar avatar = Avatar.parseMetadata(items);
219			if (avatar != null) {
220				avatar.owner = from.toBareJid();
221				if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
222					if (account.getJid().toBareJid().equals(from)) {
223						if (account.setAvatar(avatar.getFilename())) {
224							mXmppConnectionService.databaseBackend.updateAccount(account);
225						}
226						mXmppConnectionService.getAvatarService().clear(account);
227						mXmppConnectionService.updateConversationUi();
228						mXmppConnectionService.updateAccountUi();
229					} else {
230						Contact contact = account.getRoster().getContact(from);
231						contact.setAvatar(avatar);
232						mXmppConnectionService.getAvatarService().clear(contact);
233						mXmppConnectionService.updateConversationUi();
234						mXmppConnectionService.updateRosterUi();
235					}
236				} else {
237					mXmppConnectionService.fetchAvatar(account, avatar);
238				}
239			}
240		} else if ("http://jabber.org/protocol/nick".equals(node)) {
241			Element i = items.findChild("item");
242			Element nick = i == null ? null : i.findChild("nick", "http://jabber.org/protocol/nick");
243			if (nick != null && nick.getContent() != null) {
244				Contact contact = account.getRoster().getContact(from);
245				contact.setPresenceName(nick.getContent());
246				mXmppConnectionService.getAvatarService().clear(account);
247				mXmppConnectionService.updateConversationUi();
248				mXmppConnectionService.updateAccountUi();
249			}
250		} else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
251			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received PEP device list update from "+ from + ", processing...");
252			Element item = items.findChild("item");
253			Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
254			AxolotlService axolotlService = account.getAxolotlService();
255			axolotlService.registerDevices(from, deviceIds);
256			mXmppConnectionService.updateAccountUi();
257		}
258	}
259
260	private boolean handleErrorMessage(Account account, MessagePacket packet) {
261		if (packet.getType() == MessagePacket.TYPE_ERROR) {
262			Jid from = packet.getFrom();
263			if (from != null) {
264				Element error = packet.findChild("error");
265				String text = error == null ? null : error.findChildContent("text");
266				if (text != null) {
267					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": sending message to "+ from+ " failed - " + text);
268				} else if (error != null) {
269					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": sending message to "+ from+ " failed - " + error);
270				}
271				Message message = mXmppConnectionService.markMessage(account,
272						from.toBareJid(),
273						packet.getId(),
274						Message.STATUS_SEND_FAILED);
275				if (message != null && message.getEncryption() == Message.ENCRYPTION_OTR) {
276					message.getConversation().endOtrIfNeeded();
277				}
278			}
279			return true;
280		}
281		return false;
282	}
283
284	@Override
285	public void onMessagePacketReceived(Account account, MessagePacket original) {
286		if (handleErrorMessage(account, original)) {
287			return;
288		}
289		final MessagePacket packet;
290		Long timestamp = null;
291		final boolean isForwarded;
292		boolean isCarbon = false;
293		String serverMsgId = null;
294		final Element fin = original.findChild("fin", "urn:xmpp:mam:0");
295		if (fin != null) {
296			mXmppConnectionService.getMessageArchiveService().processFin(fin,original.getFrom());
297			return;
298		}
299		final Element result = original.findChild("result","urn:xmpp:mam:0");
300		final MessageArchiveService.Query query = result == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
301		if (query != null && query.validFrom(original.getFrom())) {
302			Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", "urn:xmpp:mam:0");
303			if (f == null) {
304				return;
305			}
306			timestamp = f.second;
307			packet = f.first;
308			isForwarded = true;
309			serverMsgId = result.getAttribute("id");
310			query.incrementMessageCount();
311		} else if (query != null) {
312			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received mam result from invalid sender");
313			return;
314		} else if (original.fromServer(account)) {
315			Pair<MessagePacket, Long> f;
316			f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
317			f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
318			packet = f != null ? f.first : original;
319			if (handleErrorMessage(account, packet)) {
320				return;
321			}
322			timestamp = f != null ? f.second : null;
323			isCarbon = f != null;
324			isForwarded = isCarbon;
325		} else {
326			packet = original;
327			isForwarded = false;
328		}
329
330		if (timestamp == null) {
331			timestamp = AbstractParser.getTimestamp(packet, System.currentTimeMillis());
332		}
333		final String body = packet.getBody();
334		final Element mucUserElement = packet.findChild("x", "http://jabber.org/protocol/muc#user");
335		final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
336		final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
337		final Element oob = packet.findChild("x", "jabber:x:oob");
338		final boolean isOob = oob!= null && body != null && body.equals(oob.findChildContent("url"));
339		final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
340		final Element axolotlEncrypted = packet.findChild(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
341		int status;
342		final Jid counterpart;
343		final Jid to = packet.getTo();
344		final Jid from = packet.getFrom();
345		final String remoteMsgId = packet.getId();
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 (extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), packet)) {
369			mXmppConnectionService.updateConversationUi();
370		}
371
372		if ((body != null || pgpEncrypted != null || axolotlEncrypted != null) && !isMucStatusMessage) {
373			Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat, query);
374			final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
375			if (isTypeGroupChat) {
376				if (counterpart.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
377					status = Message.STATUS_SEND_RECEIVED;
378					isCarbon = true; //not really carbon but received from another resource
379					if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status)) {
380						return;
381					} else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
382						Message message = conversation.findSentMessageWithBody(packet.getBody());
383						if (message != null) {
384							mXmppConnectionService.markMessage(message, status);
385							return;
386						}
387					}
388				} else {
389					status = Message.STATUS_RECEIVED;
390				}
391			}
392			Message message;
393			if (body != null && body.startsWith("?OTR") && Config.supportOtr()) {
394				if (!isForwarded && !isTypeGroupChat && isProperlyAddressed && !conversationMultiMode) {
395					message = parseOtrChat(body, from, remoteMsgId, conversation);
396					if (message == null) {
397						return;
398					}
399				} else {
400					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": ignoring OTR message from "+from+" isForwarded="+Boolean.toString(isForwarded)+", isProperlyAddressed="+Boolean.valueOf(isProperlyAddressed));
401					message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
402				}
403			} else if (pgpEncrypted != null && Config.supportOpenPgp()) {
404				message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
405			} else if (axolotlEncrypted != null && Config.supportOmemo()) {
406				Jid origin;
407				if (conversationMultiMode) {
408					origin = conversation.getMucOptions().getTrueCounterpart(counterpart);
409					if (origin == null) {
410						Log.d(Config.LOGTAG,"axolotl message in non anonymous conference received");
411						return;
412					}
413				} else {
414					origin = from;
415				}
416				message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status);
417				if (message == null) {
418					return;
419				}
420			} else {
421				message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
422			}
423
424			if (serverMsgId == null) {
425				serverMsgId = extractStanzaId(packet, isTypeGroupChat ? conversation.getJid().toBareJid() : account.getServer());
426			}
427
428			message.setCounterpart(counterpart);
429			message.setRemoteMsgId(remoteMsgId);
430			message.setServerMsgId(serverMsgId);
431			message.setCarbon(isCarbon);
432			message.setTime(timestamp);
433			message.setOob(isOob);
434			message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
435			if (conversationMultiMode) {
436				Jid trueCounterpart = conversation.getMucOptions().getTrueCounterpart(counterpart);
437				message.setTrueCounterpart(trueCounterpart);
438				if (!isTypeGroupChat) {
439					message.setType(Message.TYPE_PRIVATE);
440				}
441			} else {
442				updateLastseen(timestamp, account, from);
443			}
444
445			if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
446				Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
447						counterpart,
448						message.getStatus() == Message.STATUS_RECEIVED,
449						message.isCarbon());
450				if (replacedMessage != null) {
451					final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
452							|| replacedMessage.getFingerprint().equals(message.getFingerprint());
453					final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
454							&& replacedMessage.getTrueCounterpart().equals(message.getTrueCounterpart());
455					if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode)) {
456						Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
457						final String uuid = replacedMessage.getUuid();
458						replacedMessage.setUuid(UUID.randomUUID().toString());
459						replacedMessage.setBody(message.getBody());
460						replacedMessage.setEdited(replacedMessage.getRemoteMsgId());
461						replacedMessage.setRemoteMsgId(remoteMsgId);
462						replacedMessage.setEncryption(message.getEncryption());
463						if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
464							replacedMessage.markUnread();
465						}
466						mXmppConnectionService.updateMessage(replacedMessage, uuid);
467						mXmppConnectionService.getNotificationService().updateNotification(false);
468						if (mXmppConnectionService.confirmMessages() && remoteMsgId != null && !isForwarded && !isTypeGroupChat) {
469							sendMessageReceipts(account, packet);
470						}
471						if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
472							conversation.getAccount().getPgpDecryptionService().add(replacedMessage);
473						}
474						return;
475					} else {
476						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received message correction but verification didn't check out");
477					}
478				}
479			}
480
481			boolean checkForDuplicates = query != null
482					|| (isTypeGroupChat && packet.hasChild("delay","urn:xmpp:delay"))
483					|| message.getType() == Message.TYPE_PRIVATE;
484			if (checkForDuplicates && conversation.hasDuplicateMessage(message)) {
485				Log.d(Config.LOGTAG,"skipping duplicate message from "+message.getCounterpart().toString()+" "+message.getBody());
486				return;
487			}
488
489			if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
490				conversation.prepend(message);
491			} else {
492				conversation.add(message);
493			}
494
495			if (message.getEncryption() == Message.ENCRYPTION_PGP) {
496				conversation.getAccount().getPgpDecryptionService().add(message);
497			}
498
499			if (query == null || query.getWith() == null) { //either no mam or catchup
500				if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
501					mXmppConnectionService.markRead(conversation);
502					if (query == null) {
503						activateGracePeriod(account);
504					}
505				} else {
506					message.markUnread();
507				}
508			}
509
510			if (query == null) {
511				mXmppConnectionService.updateConversationUi();
512			}
513
514			if (mXmppConnectionService.confirmMessages() && remoteMsgId != null && !isForwarded && !isTypeGroupChat) {
515				sendMessageReceipts(account, packet);
516			}
517
518			if (message.getStatus() == Message.STATUS_RECEIVED
519					&& conversation.getOtrSession() != null
520					&& !conversation.getOtrSession().getSessionID().getUserID()
521					.equals(message.getCounterpart().getResourcepart())) {
522				conversation.endOtrIfNeeded();
523			}
524
525			if (message.getEncryption() == Message.ENCRYPTION_NONE || mXmppConnectionService.saveEncryptedMessages()) {
526				mXmppConnectionService.databaseBackend.createMessage(message);
527			}
528			final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
529			if (message.trusted() && message.treatAsDownloadable() != Message.Decision.NEVER && manager.getAutoAcceptFileSize() > 0) {
530				manager.createNewDownloadConnection(message);
531			} else if (!message.isRead()) {
532				if (query == null) {
533					mXmppConnectionService.getNotificationService().push(message);
534				} else if (query.getWith() == null) { // mam catchup
535					mXmppConnectionService.getNotificationService().pushFromBacklog(message);
536				}
537			}
538		} else if (!packet.hasChild("body")){ //no body
539			if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
540				Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": " + packet+ " (carbon="+Boolean.toString(isCarbon)+")");
541			}
542			Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
543			if (isTypeGroupChat) {
544				if (packet.hasChild("subject")) {
545					if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
546						conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
547						String subject = packet.findChildContent("subject");
548						conversation.getMucOptions().setSubject(subject);
549						final Bookmark bookmark = conversation.getBookmark();
550						if (bookmark != null && bookmark.getBookmarkName() == null) {
551							if (bookmark.setBookmarkName(subject)) {
552								mXmppConnectionService.pushBookmarks(account);
553							}
554						}
555						mXmppConnectionService.updateConversationUi();
556						return;
557					}
558				}
559			}
560			if (conversation != null && mucUserElement != null && from.isBareJid()) {
561				if (mucUserElement.hasChild("status")) {
562					for (Element child : mucUserElement.getChildren()) {
563						if (child.getName().equals("status")
564								&& MucOptions.STATUS_CODE_ROOM_CONFIG_CHANGED.equals(child.getAttribute("code"))) {
565							mXmppConnectionService.fetchConferenceConfiguration(conversation);
566						}
567					}
568				} else if (mucUserElement.hasChild("item")) {
569					for(Element child : mucUserElement.getChildren()) {
570						if ("item".equals(child.getName())) {
571							MucOptions.User user = AbstractParser.parseItem(conversation,child);
572							Log.d(Config.LOGTAG,account.getJid()+": changing affiliation for "
573									+user.getRealJid()+" to "+user.getAffiliation()+" in "
574									+conversation.getJid().toBareJid());
575							if (!user.realJidMatchesAccount()) {
576								conversation.getMucOptions().addUser(user);
577								mXmppConnectionService.getAvatarService().clear(conversation);
578								mXmppConnectionService.updateMucRosterUi();
579								mXmppConnectionService.updateConversationUi();
580							}
581						}
582					}
583				}
584			}
585		}
586
587
588
589		Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
590		if (received == null) {
591			received = packet.findChild("received", "urn:xmpp:receipts");
592		}
593		if (received != null && !packet.fromAccount(account)) {
594			mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
595		}
596		Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
597		if (displayed != null) {
598			if (packet.fromAccount(account)) {
599				Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
600				if (conversation != null) {
601					mXmppConnectionService.markRead(conversation);
602				}
603			} else {
604				updateLastseen(timestamp, account, from);
605				final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
606				Message message = displayedMessage == null ? null : displayedMessage.prev();
607				while (message != null
608						&& message.getStatus() == Message.STATUS_SEND_RECEIVED
609						&& message.getTimeSent() < displayedMessage.getTimeSent()) {
610					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
611					message = message.prev();
612				}
613			}
614		}
615
616		Element event = packet.findChild("event", "http://jabber.org/protocol/pubsub#event");
617		if (event != null) {
618			parseEvent(event, from, account);
619		}
620
621		String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
622		if (nick != null) {
623			Contact contact = account.getRoster().getContact(from);
624			contact.setPresenceName(nick);
625		}
626	}
627
628	private void sendMessageReceipts(Account account, MessagePacket packet) {
629		ArrayList<String> receiptsNamespaces = new ArrayList<>();
630		if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
631			receiptsNamespaces.add("urn:xmpp:chat-markers:0");
632		}
633		if (packet.hasChild("request", "urn:xmpp:receipts")) {
634			receiptsNamespaces.add("urn:xmpp:receipts");
635		}
636		if (receiptsNamespaces.size() > 0) {
637			MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
638					packet,
639					receiptsNamespaces,
640					packet.getType());
641			mXmppConnectionService.sendMessagePacket(account, receipt);
642		}
643	}
644
645	private static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
646
647	private void activateGracePeriod(Account account) {
648		long duration = mXmppConnectionService.getPreferences().getLong("race_period_length", 144) * 1000;
649		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": activating grace period till "+TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
650		account.activateGracePeriod(duration);
651	}
652}