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