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