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.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
346		if (from == null) {
347			Log.d(Config.LOGTAG,"no from in: "+packet.toString());
348			return;
349		}
350		
351		boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
352		boolean isProperlyAddressed = (to != null ) && (!to.isBareJid() || account.countPresences() == 0);
353		boolean isMucStatusMessage = from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
354		if (packet.fromAccount(account)) {
355			status = Message.STATUS_SEND;
356			counterpart = to != null ? to : account.getJid();
357		} else {
358			status = Message.STATUS_RECEIVED;
359			counterpart = from;
360		}
361
362		Invite invite = extractInvite(packet);
363		if (invite != null && invite.execute(account)) {
364			return;
365		}
366
367		if (extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), packet)) {
368			mXmppConnectionService.updateConversationUi();
369		}
370
371		if ((body != null || pgpEncrypted != null || axolotlEncrypted != null) && !isMucStatusMessage) {
372			Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat, query);
373			final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
374			if (isTypeGroupChat) {
375				if (counterpart.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
376					status = Message.STATUS_SEND_RECEIVED;
377					isCarbon = true; //not really carbon but received from another resource
378					if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status)) {
379						return;
380					} else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
381						Message message = conversation.findSentMessageWithBody(packet.getBody());
382						if (message != null) {
383							mXmppConnectionService.markMessage(message, status);
384							return;
385						}
386					}
387				} else {
388					status = Message.STATUS_RECEIVED;
389				}
390			}
391			Message message;
392			if (body != null && body.startsWith("?OTR") && Config.supportOtr()) {
393				if (!isForwarded && !isTypeGroupChat && isProperlyAddressed && !conversationMultiMode) {
394					message = parseOtrChat(body, from, remoteMsgId, conversation);
395					if (message == null) {
396						return;
397					}
398				} else {
399					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": ignoring OTR message from "+from+" isForwarded="+Boolean.toString(isForwarded)+", isProperlyAddressed="+Boolean.valueOf(isProperlyAddressed));
400					message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
401				}
402			} else if (pgpEncrypted != null && Config.supportOpenPgp()) {
403				message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
404			} else if (axolotlEncrypted != null && Config.supportOmemo()) {
405				Jid origin;
406				if (conversationMultiMode) {
407					origin = conversation.getMucOptions().getTrueCounterpart(counterpart);
408					if (origin == null) {
409						Log.d(Config.LOGTAG,"axolotl message in non anonymous conference received");
410						return;
411					}
412				} else {
413					origin = from;
414				}
415				message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status);
416				if (message == null) {
417					return;
418				}
419			} else {
420				message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
421			}
422
423			if (serverMsgId == null) {
424				serverMsgId = extractStanzaId(packet, isTypeGroupChat ? conversation.getJid().toBareJid() : account.getServer());
425			}
426
427			message.setCounterpart(counterpart);
428			message.setRemoteMsgId(remoteMsgId);
429			message.setServerMsgId(serverMsgId);
430			message.setCarbon(isCarbon);
431			message.setTime(timestamp);
432			message.setOob(isOob);
433			message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
434			if (conversationMultiMode) {
435				final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
436				Jid trueCounterpart;
437				if (Config.PARSE_REAL_JID_FROM_MUC_MAM && query != null && item != null) {
438					trueCounterpart = item.getAttributeAsJid("jid");
439					if (trueCounterpart != null) {
440						if (trueCounterpart.toBareJid().equals(account.getJid().toBareJid())) {
441							status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
442						} else {
443							status = Message.STATUS_RECEIVED;
444						}
445						message.setStatus(status);
446					}
447				} else {
448					trueCounterpart = conversation.getMucOptions().getTrueCounterpart(counterpart);
449				}
450				message.setTrueCounterpart(trueCounterpart);
451				if (!isTypeGroupChat) {
452					message.setType(Message.TYPE_PRIVATE);
453				}
454			} else {
455				updateLastseen(account, from);
456			}
457
458			if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
459				Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
460						counterpart,
461						message.getStatus() == Message.STATUS_RECEIVED,
462						message.isCarbon());
463				if (replacedMessage != null) {
464					final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
465							|| replacedMessage.getFingerprint().equals(message.getFingerprint());
466					final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
467							&& replacedMessage.getTrueCounterpart().equals(message.getTrueCounterpart());
468					if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode)) {
469						Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
470						final String uuid = replacedMessage.getUuid();
471						replacedMessage.setUuid(UUID.randomUUID().toString());
472						replacedMessage.setBody(message.getBody());
473						replacedMessage.setEdited(replacedMessage.getRemoteMsgId());
474						replacedMessage.setRemoteMsgId(remoteMsgId);
475						replacedMessage.setEncryption(message.getEncryption());
476						if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
477							replacedMessage.markUnread();
478						}
479						mXmppConnectionService.updateMessage(replacedMessage, uuid);
480						mXmppConnectionService.getNotificationService().updateNotification(false);
481						if (mXmppConnectionService.confirmMessages() && remoteMsgId != null && !isForwarded && !isTypeGroupChat) {
482							sendMessageReceipts(account, packet);
483						}
484						if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
485							conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage);
486						}
487						return;
488					} else {
489						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received message correction but verification didn't check out");
490					}
491				}
492			}
493
494			boolean checkForDuplicates = query != null
495					|| (isTypeGroupChat && packet.hasChild("delay","urn:xmpp:delay"))
496					|| message.getType() == Message.TYPE_PRIVATE;
497			if (checkForDuplicates && conversation.hasDuplicateMessage(message)) {
498				Log.d(Config.LOGTAG,"skipping duplicate message from "+message.getCounterpart().toString()+" "+message.getBody());
499				return;
500			}
501
502			if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
503				conversation.prepend(message);
504			} else {
505				conversation.add(message);
506			}
507
508			if (message.getEncryption() == Message.ENCRYPTION_PGP) {
509				conversation.getAccount().getPgpDecryptionService().decrypt(message);
510			}
511
512			if (query == null || query.getWith() == null) { //either no mam or catchup
513				if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
514					mXmppConnectionService.markRead(conversation);
515					if (query == null) {
516						activateGracePeriod(account);
517					}
518				} else {
519					message.markUnread();
520				}
521			}
522
523			if (query == null) {
524				mXmppConnectionService.updateConversationUi();
525			}
526
527			if (mXmppConnectionService.confirmMessages() && remoteMsgId != null && !isForwarded && !isTypeGroupChat) {
528				sendMessageReceipts(account, packet);
529			}
530
531			if (message.getStatus() == Message.STATUS_RECEIVED
532					&& conversation.getOtrSession() != null
533					&& !conversation.getOtrSession().getSessionID().getUserID()
534					.equals(message.getCounterpart().getResourcepart())) {
535				conversation.endOtrIfNeeded();
536			}
537
538			if (message.getEncryption() == Message.ENCRYPTION_NONE || mXmppConnectionService.saveEncryptedMessages()) {
539				mXmppConnectionService.databaseBackend.createMessage(message);
540			}
541			final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
542			if (message.trusted() && message.treatAsDownloadable() != Message.Decision.NEVER && manager.getAutoAcceptFileSize() > 0) {
543				manager.createNewDownloadConnection(message);
544			} else if (!message.isRead()) {
545				if (query == null) {
546					mXmppConnectionService.getNotificationService().push(message);
547				} else if (query.getWith() == null) { // mam catchup
548					mXmppConnectionService.getNotificationService().pushFromBacklog(message);
549				}
550			}
551		} else if (!packet.hasChild("body")){ //no body
552			Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
553			if (isTypeGroupChat) {
554				if (packet.hasChild("subject")) {
555					if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
556						conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
557						String subject = packet.findChildContent("subject");
558						conversation.getMucOptions().setSubject(subject);
559						final Bookmark bookmark = conversation.getBookmark();
560						if (bookmark != null && bookmark.getBookmarkName() == null) {
561							if (bookmark.setBookmarkName(subject)) {
562								mXmppConnectionService.pushBookmarks(account);
563							}
564						}
565						mXmppConnectionService.updateConversationUi();
566						return;
567					}
568				}
569			}
570			if (conversation != null && mucUserElement != null && from.isBareJid()) {
571				if (mucUserElement.hasChild("status")) {
572					for (Element child : mucUserElement.getChildren()) {
573						if (child.getName().equals("status")
574								&& MucOptions.STATUS_CODE_ROOM_CONFIG_CHANGED.equals(child.getAttribute("code"))) {
575							mXmppConnectionService.fetchConferenceConfiguration(conversation);
576						}
577					}
578				} else if (mucUserElement.hasChild("item")) {
579					for(Element child : mucUserElement.getChildren()) {
580						if ("item".equals(child.getName())) {
581							MucOptions.User user = AbstractParser.parseItem(conversation,child);
582							Log.d(Config.LOGTAG,account.getJid()+": changing affiliation for "
583									+user.getRealJid()+" to "+user.getAffiliation()+" in "
584									+conversation.getJid().toBareJid());
585							if (!user.realJidMatchesAccount()) {
586								conversation.getMucOptions().addUser(user);
587								mXmppConnectionService.getAvatarService().clear(conversation);
588								mXmppConnectionService.updateMucRosterUi();
589								mXmppConnectionService.updateConversationUi();
590							}
591						}
592					}
593				}
594			}
595		}
596
597
598
599		Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
600		if (received == null) {
601			received = packet.findChild("received", "urn:xmpp:receipts");
602		}
603		if (received != null && !packet.fromAccount(account)) {
604			mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
605		}
606		Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
607		if (displayed != null) {
608			if (packet.fromAccount(account)) {
609				Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
610				if (conversation != null) {
611					mXmppConnectionService.markRead(conversation);
612				}
613			} else {
614				final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
615				Message message = displayedMessage == null ? null : displayedMessage.prev();
616				while (message != null
617						&& message.getStatus() == Message.STATUS_SEND_RECEIVED
618						&& message.getTimeSent() < displayedMessage.getTimeSent()) {
619					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
620					message = message.prev();
621				}
622			}
623		}
624
625		Element event = packet.findChild("event", "http://jabber.org/protocol/pubsub#event");
626		if (event != null) {
627			parseEvent(event, from, account);
628		}
629
630		String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
631		if (nick != null) {
632			Contact contact = account.getRoster().getContact(from);
633			contact.setPresenceName(nick);
634		}
635	}
636
637	private void sendMessageReceipts(Account account, MessagePacket packet) {
638		ArrayList<String> receiptsNamespaces = new ArrayList<>();
639		if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
640			receiptsNamespaces.add("urn:xmpp:chat-markers:0");
641		}
642		if (packet.hasChild("request", "urn:xmpp:receipts")) {
643			receiptsNamespaces.add("urn:xmpp:receipts");
644		}
645		if (receiptsNamespaces.size() > 0) {
646			MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
647					packet,
648					receiptsNamespaces,
649					packet.getType());
650			mXmppConnectionService.sendMessagePacket(account, receipt);
651		}
652	}
653
654	private static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
655
656	private void activateGracePeriod(Account account) {
657		long duration = mXmppConnectionService.getPreferences().getLong("race_period_length", 144) * 1000;
658		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": activating grace period till "+TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
659		account.activateGracePeriod(duration);
660	}
661}