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