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		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 (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				final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
437				Jid trueCounterpart;
438				if (Config.PARSE_REAL_JID_FROM_MUC_MAM && query != null && item != null) {
439					trueCounterpart = item.getAttributeAsJid("jid");
440					if (trueCounterpart != null) {
441						if (trueCounterpart.toBareJid().equals(account.getJid().toBareJid())) {
442							status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
443						} else {
444							status = Message.STATUS_RECEIVED;
445						}
446						message.setStatus(status);
447					}
448				} else {
449					trueCounterpart = conversation.getMucOptions().getTrueCounterpart(counterpart);
450				}
451				message.setTrueCounterpart(trueCounterpart);
452				if (!isTypeGroupChat) {
453					message.setType(Message.TYPE_PRIVATE);
454				}
455			} else {
456				updateLastseen(account, from);
457			}
458
459			if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
460				Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
461						counterpart,
462						message.getStatus() == Message.STATUS_RECEIVED,
463						message.isCarbon());
464				if (replacedMessage != null) {
465					final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
466							|| replacedMessage.getFingerprint().equals(message.getFingerprint());
467					final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
468							&& replacedMessage.getTrueCounterpart().equals(message.getTrueCounterpart());
469					if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode)) {
470						Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
471						final String uuid = replacedMessage.getUuid();
472						replacedMessage.setUuid(UUID.randomUUID().toString());
473						replacedMessage.setBody(message.getBody());
474						replacedMessage.setEdited(replacedMessage.getRemoteMsgId());
475						replacedMessage.setRemoteMsgId(remoteMsgId);
476						replacedMessage.setEncryption(message.getEncryption());
477						if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
478							replacedMessage.markUnread();
479						}
480						mXmppConnectionService.updateMessage(replacedMessage, uuid);
481						mXmppConnectionService.getNotificationService().updateNotification(false);
482						if (mXmppConnectionService.confirmMessages() && remoteMsgId != null && !isForwarded && !isTypeGroupChat) {
483							sendMessageReceipts(account, packet);
484						}
485						if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
486							conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
487						}
488						return;
489					} else {
490						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received message correction but verification didn't check out");
491					}
492				}
493			}
494
495			boolean checkForDuplicates = query != null
496					|| (isTypeGroupChat && packet.hasChild("delay","urn:xmpp:delay"))
497					|| message.getType() == Message.TYPE_PRIVATE;
498			if (checkForDuplicates && conversation.hasDuplicateMessage(message)) {
499				Log.d(Config.LOGTAG,"skipping duplicate message from "+message.getCounterpart().toString()+" "+message.getBody());
500				return;
501			}
502
503			if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
504				conversation.prepend(message);
505			} else {
506				conversation.add(message);
507			}
508
509			if (query == null || query.getWith() == null) { //either no mam or catchup
510				if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
511					mXmppConnectionService.markRead(conversation);
512					if (query == null) {
513						activateGracePeriod(account);
514					}
515				} else {
516					message.markUnread();
517					notify = true;
518				}
519			}
520
521			if (message.getEncryption() == Message.ENCRYPTION_PGP) {
522				notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
523			}
524
525			if (query == null) {
526				mXmppConnectionService.updateConversationUi();
527			}
528
529			if (mXmppConnectionService.confirmMessages() && remoteMsgId != null && !isForwarded && !isTypeGroupChat) {
530				sendMessageReceipts(account, packet);
531			}
532
533			if (message.getStatus() == Message.STATUS_RECEIVED
534					&& conversation.getOtrSession() != null
535					&& !conversation.getOtrSession().getSessionID().getUserID()
536					.equals(message.getCounterpart().getResourcepart())) {
537				conversation.endOtrIfNeeded();
538			}
539
540			if (message.getEncryption() == Message.ENCRYPTION_NONE || mXmppConnectionService.saveEncryptedMessages()) {
541				mXmppConnectionService.databaseBackend.createMessage(message);
542			}
543			final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
544			if (message.trusted() && message.treatAsDownloadable() != Message.Decision.NEVER && manager.getAutoAcceptFileSize() > 0) {
545				manager.createNewDownloadConnection(message);
546			} else if (notify) {
547				if (query == null) {
548					mXmppConnectionService.getNotificationService().push(message);
549				} else if (query.getWith() == null) { // mam catchup
550					mXmppConnectionService.getNotificationService().pushFromBacklog(message);
551				}
552			}
553		} else if (!packet.hasChild("body")){ //no body
554			Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
555			if (isTypeGroupChat) {
556				if (packet.hasChild("subject")) {
557					if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
558						conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
559						String subject = packet.findChildContent("subject");
560						conversation.getMucOptions().setSubject(subject);
561						final Bookmark bookmark = conversation.getBookmark();
562						if (bookmark != null && bookmark.getBookmarkName() == null) {
563							if (bookmark.setBookmarkName(subject)) {
564								mXmppConnectionService.pushBookmarks(account);
565							}
566						}
567						mXmppConnectionService.updateConversationUi();
568						return;
569					}
570				}
571			}
572			if (conversation != null && mucUserElement != null && from.isBareJid()) {
573				if (mucUserElement.hasChild("status")) {
574					for (Element child : mucUserElement.getChildren()) {
575						if (child.getName().equals("status")
576								&& MucOptions.STATUS_CODE_ROOM_CONFIG_CHANGED.equals(child.getAttribute("code"))) {
577							mXmppConnectionService.fetchConferenceConfiguration(conversation);
578						}
579					}
580				} else if (mucUserElement.hasChild("item")) {
581					for(Element child : mucUserElement.getChildren()) {
582						if ("item".equals(child.getName())) {
583							MucOptions.User user = AbstractParser.parseItem(conversation,child);
584							Log.d(Config.LOGTAG,account.getJid()+": changing affiliation for "
585									+user.getRealJid()+" to "+user.getAffiliation()+" in "
586									+conversation.getJid().toBareJid());
587							if (!user.realJidMatchesAccount()) {
588								conversation.getMucOptions().addUser(user);
589								mXmppConnectionService.getAvatarService().clear(conversation);
590								mXmppConnectionService.updateMucRosterUi();
591								mXmppConnectionService.updateConversationUi();
592							}
593						}
594					}
595				}
596			}
597		}
598
599
600
601		Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
602		if (received == null) {
603			received = packet.findChild("received", "urn:xmpp:receipts");
604		}
605		if (received != null && !packet.fromAccount(account)) {
606			mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
607		}
608		Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
609		if (displayed != null) {
610			if (packet.fromAccount(account)) {
611				Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
612				if (conversation != null) {
613					mXmppConnectionService.markRead(conversation);
614				}
615			} else {
616				final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
617				Message message = displayedMessage == null ? null : displayedMessage.prev();
618				while (message != null
619						&& message.getStatus() == Message.STATUS_SEND_RECEIVED
620						&& message.getTimeSent() < displayedMessage.getTimeSent()) {
621					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
622					message = message.prev();
623				}
624			}
625		}
626
627		Element event = packet.findChild("event", "http://jabber.org/protocol/pubsub#event");
628		if (event != null) {
629			parseEvent(event, from, account);
630		}
631
632		String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
633		if (nick != null) {
634			Contact contact = account.getRoster().getContact(from);
635			contact.setPresenceName(nick);
636		}
637	}
638
639	private void sendMessageReceipts(Account account, MessagePacket packet) {
640		ArrayList<String> receiptsNamespaces = new ArrayList<>();
641		if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
642			receiptsNamespaces.add("urn:xmpp:chat-markers:0");
643		}
644		if (packet.hasChild("request", "urn:xmpp:receipts")) {
645			receiptsNamespaces.add("urn:xmpp:receipts");
646		}
647		if (receiptsNamespaces.size() > 0) {
648			MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
649					packet,
650					receiptsNamespaces,
651					packet.getType());
652			mXmppConnectionService.sendMessagePacket(account, receipt);
653		}
654	}
655
656	private static SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");
657
658	private void activateGracePeriod(Account account) {
659		long duration = mXmppConnectionService.getPreferences().getLong("race_period_length", 144) * 1000;
660		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": activating grace period till "+TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
661		account.activateGracePeriod(duration);
662	}
663}