MessageParser.java

  1package eu.siacs.conversations.parser;
  2
  3import android.os.Build;
  4import android.text.Html;
  5import android.util.Log;
  6import android.util.Pair;
  7
  8import net.java.otr4j.session.Session;
  9import net.java.otr4j.session.SessionStatus;
 10
 11import java.text.SimpleDateFormat;
 12import java.util.ArrayList;
 13import java.util.Arrays;
 14import java.util.Date;
 15import java.util.List;
 16import java.util.Locale;
 17import java.util.Set;
 18import java.util.UUID;
 19
 20import eu.siacs.conversations.Config;
 21import eu.siacs.conversations.R;
 22import eu.siacs.conversations.crypto.OtrService;
 23import eu.siacs.conversations.crypto.axolotl.AxolotlService;
 24import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
 25import eu.siacs.conversations.entities.Account;
 26import eu.siacs.conversations.entities.Bookmark;
 27import eu.siacs.conversations.entities.Contact;
 28import eu.siacs.conversations.entities.Conversation;
 29import eu.siacs.conversations.entities.Message;
 30import eu.siacs.conversations.entities.MucOptions;
 31import eu.siacs.conversations.entities.Presence;
 32import eu.siacs.conversations.entities.ServiceDiscoveryResult;
 33import eu.siacs.conversations.http.HttpConnectionManager;
 34import eu.siacs.conversations.services.MessageArchiveService;
 35import eu.siacs.conversations.services.XmppConnectionService;
 36import eu.siacs.conversations.utils.CryptoHelper;
 37import eu.siacs.conversations.xml.Namespace;
 38import eu.siacs.conversations.xml.Element;
 39import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 40import eu.siacs.conversations.xmpp.chatstate.ChatState;
 41import eu.siacs.conversations.xmpp.jid.Jid;
 42import eu.siacs.conversations.xmpp.pep.Avatar;
 43import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 44
 45public class MessageParser extends AbstractParser implements OnMessagePacketReceived {
 46
 47	private static final List<String> CLIENTS_SENDING_HTML_IN_OTR = Arrays.asList("Pidgin","Adium","Trillian");
 48
 49	public MessageParser(XmppConnectionService service) {
 50		super(service);
 51	}
 52
 53	private boolean extractChatState(Conversation c, final boolean isTypeGroupChat, final MessagePacket packet) {
 54		ChatState state = ChatState.parse(packet);
 55		if (state != null && c != null) {
 56			final Account account = c.getAccount();
 57			Jid from = packet.getFrom();
 58			if (from.toBareJid().equals(account.getJid().toBareJid())) {
 59				c.setOutgoingChatState(state);
 60				if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
 61					mXmppConnectionService.markRead(c);
 62					activateGracePeriod(account);
 63				}
 64				return false;
 65			} else {
 66				if (isTypeGroupChat) {
 67					MucOptions.User user = c.getMucOptions().findUserByFullJid(from);
 68					if (user != null) {
 69						return user.setChatState(state);
 70					} else {
 71						return false;
 72					}
 73				} else {
 74					return c.setIncomingChatState(state);
 75				}
 76			}
 77		}
 78		return false;
 79	}
 80
 81	private Message parseOtrChat(String body, Jid from, String id, Conversation conversation) {
 82		String presence;
 83		if (from.isBareJid()) {
 84			presence = "";
 85		} else {
 86			presence = from.getResourcepart();
 87		}
 88		if (body.matches("^\\?OTRv\\d{1,2}\\?.*")) {
 89			conversation.endOtrIfNeeded();
 90		}
 91		if (!conversation.hasValidOtrSession()) {
 92			conversation.startOtrSession(presence,false);
 93		} else {
 94			String foreignPresence = conversation.getOtrSession().getSessionID().getUserID();
 95			if (!foreignPresence.equals(presence)) {
 96				conversation.endOtrIfNeeded();
 97				conversation.startOtrSession(presence, false);
 98			}
 99		}
100		try {
101			conversation.setLastReceivedOtrMessageId(id);
102			Session otrSession = conversation.getOtrSession();
103			body = otrSession.transformReceiving(body);
104			SessionStatus status = otrSession.getSessionStatus();
105			if (body == null && status == SessionStatus.ENCRYPTED) {
106				mXmppConnectionService.onOtrSessionEstablished(conversation);
107				return null;
108			} else if (body == null && status == SessionStatus.FINISHED) {
109				conversation.resetOtrSession();
110				mXmppConnectionService.updateConversationUi();
111				return null;
112			} else if (body == null || (body.isEmpty())) {
113				return null;
114			}
115			if (body.startsWith(CryptoHelper.FILETRANSFER)) {
116				String key = body.substring(CryptoHelper.FILETRANSFER.length());
117				conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
118				return null;
119			}
120			if (clientMightSendHtml(conversation.getAccount(), from)) {
121				Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": received OTR message from bad behaving client. escaping HTML…");
122				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
123					body = Html.fromHtml(body,Html.FROM_HTML_MODE_LEGACY).toString();
124				} else {
125					body = Html.fromHtml(body).toString();
126				}
127			}
128
129			final OtrService otrService = conversation.getAccount().getOtrService();
130			Message finishedMessage = new Message(conversation, body, Message.ENCRYPTION_OTR, Message.STATUS_RECEIVED);
131			finishedMessage.setFingerprint(otrService.getFingerprint(otrSession.getRemotePublicKey()));
132			conversation.setLastReceivedOtrMessageId(null);
133
134			return finishedMessage;
135		} catch (Exception e) {
136			conversation.resetOtrSession();
137			return null;
138		}
139	}
140
141	private static boolean clientMightSendHtml(Account account, Jid from) {
142		String resource = from.getResourcepart();
143		if (resource == null) {
144			return false;
145		}
146		Presence presence = account.getRoster().getContact(from).getPresences().getPresences().get(resource);
147		ServiceDiscoveryResult disco = presence == null ? null : presence.getServiceDiscoveryResult();
148		if (disco == null) {
149			return false;
150		}
151		return hasIdentityKnowForSendingHtml(disco.getIdentities());
152	}
153
154	private static boolean hasIdentityKnowForSendingHtml(List<ServiceDiscoveryResult.Identity> identities) {
155		for(ServiceDiscoveryResult.Identity identity : identities) {
156			if (identity.getName() != null) {
157				if (CLIENTS_SENDING_HTML_IN_OTR.contains(identity.getName())) {
158					return true;
159				}
160			}
161		}
162		return false;
163	}
164
165	private Message parseAxolotlChat(Element axolotlMessage, Jid from,  Conversation conversation, int status) {
166		AxolotlService service = conversation.getAccount().getAxolotlService();
167		XmppAxolotlMessage xmppAxolotlMessage;
168		try {
169			xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.toBareJid());
170		} catch (Exception e) {
171			Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": invalid omemo message received "+e.getMessage());
172			return null;
173		}
174		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage);
175		if(plaintextMessage != null) {
176			Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
177			finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
178			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount())+" Received Message with session fingerprint: "+plaintextMessage.getFingerprint());
179			return finishedMessage;
180		} else {
181			return null;
182		}
183	}
184
185	private class Invite {
186		final Jid jid;
187		final String password;
188		final Contact inviter;
189		Invite(Jid jid, String password, Contact inviter) {
190			this.jid = jid;
191			this.password = password;
192			this.inviter = inviter;
193		}
194
195		public boolean execute(Account account) {
196			if (jid != null) {
197				Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
198				if (!conversation.getMucOptions().online()) {
199					conversation.getMucOptions().setPassword(password);
200					mXmppConnectionService.databaseBackend.updateConversation(conversation);
201					mXmppConnectionService.joinMuc(conversation, inviter != null && inviter.mutualPresenceSubscription());
202					mXmppConnectionService.updateConversationUi();
203				}
204				return true;
205			}
206			return false;
207		}
208	}
209
210	private Invite extractInvite(Account account, Element message) {
211		Element x = message.findChild("x", "http://jabber.org/protocol/muc#user");
212		if (x != null) {
213			Element invite = x.findChild("invite");
214			if (invite != null) {
215				Element pw = x.findChild("password");
216				Jid from = invite.getAttributeAsJid("from");
217				Contact contact = from == null ? null : account.getRoster().getContact(from);
218				return new Invite(message.getAttributeAsJid("from"), pw != null ? pw.getContent(): null, contact);
219			}
220		} else {
221			x = message.findChild("x","jabber:x:conference");
222			if (x != null) {
223				Jid from = message.getAttributeAsJid("from");
224				Contact contact = from == null ? null : account.getRoster().getContact(from);
225				return new Invite(x.getAttributeAsJid("jid"),x.getAttribute("password"),contact);
226			}
227		}
228		return null;
229	}
230
231	private static String extractStanzaId(Element packet, boolean isTypeGroupChat, Conversation conversation) {
232		final Jid by;
233		final boolean safeToExtract;
234		if (isTypeGroupChat) {
235			by = conversation.getJid().toBareJid();
236			safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
237		} else {
238			Account account = conversation.getAccount();
239			by = account.getJid().toBareJid();
240			safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
241		}
242		return safeToExtract ? extractStanzaId(packet, by) : null;
243	}
244
245	private static String extractStanzaId(Element packet, Jid by) {
246		for(Element child : packet.getChildren()) {
247			if (child.getName().equals("stanza-id")
248					&& Namespace.STANZA_IDS.equals(child.getNamespace())
249					&& by.equals(child.getAttributeAsJid("by"))) {
250				return child.getAttribute("id");
251			}
252		}
253		return null;
254	}
255
256	private void parseEvent(final Element event, final Jid from, final Account account) {
257		Element items = event.findChild("items");
258		String node = items == null ? null : items.getAttribute("node");
259		if ("urn:xmpp:avatar:metadata".equals(node)) {
260			Avatar avatar = Avatar.parseMetadata(items);
261			if (avatar != null) {
262				avatar.owner = from.toBareJid();
263				if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
264					if (account.getJid().toBareJid().equals(from)) {
265						if (account.setAvatar(avatar.getFilename())) {
266							mXmppConnectionService.databaseBackend.updateAccount(account);
267						}
268						mXmppConnectionService.getAvatarService().clear(account);
269						mXmppConnectionService.updateConversationUi();
270						mXmppConnectionService.updateAccountUi();
271					} else {
272						Contact contact = account.getRoster().getContact(from);
273						contact.setAvatar(avatar);
274						mXmppConnectionService.getAvatarService().clear(contact);
275						mXmppConnectionService.updateConversationUi();
276						mXmppConnectionService.updateRosterUi();
277					}
278				} else if (mXmppConnectionService.isDataSaverDisabled()) {
279					mXmppConnectionService.fetchAvatar(account, avatar);
280				}
281			}
282		} else if ("http://jabber.org/protocol/nick".equals(node)) {
283			Element i = items.findChild("item");
284			Element nick = i == null ? null : i.findChild("nick", "http://jabber.org/protocol/nick");
285			if (nick != null && nick.getContent() != null) {
286				Contact contact = account.getRoster().getContact(from);
287				contact.setPresenceName(nick.getContent());
288				mXmppConnectionService.getAvatarService().clear(account);
289				mXmppConnectionService.updateConversationUi();
290				mXmppConnectionService.updateAccountUi();
291			}
292		} else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
293
294			Element item = items.findChild("item");
295			Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
296			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received PEP device list ("+deviceIds+") update from "+ from + ", processing...");
297			AxolotlService axolotlService = account.getAxolotlService();
298			axolotlService.registerDevices(from, deviceIds);
299			mXmppConnectionService.updateAccountUi();
300		}
301	}
302
303	private boolean handleErrorMessage(Account account, MessagePacket packet) {
304		if (packet.getType() == MessagePacket.TYPE_ERROR) {
305			Jid from = packet.getFrom();
306			if (from != null) {
307				Message message = mXmppConnectionService.markMessage(account,
308						from.toBareJid(),
309						packet.getId(),
310						Message.STATUS_SEND_FAILED,
311						extractErrorMessage(packet));
312				if (message != null) {
313					if (message.getEncryption() == Message.ENCRYPTION_OTR) {
314						message.getConversation().endOtrIfNeeded();
315					}
316				}
317			}
318			return true;
319		}
320		return false;
321	}
322
323	@Override
324	public void onMessagePacketReceived(Account account, MessagePacket original) {
325		if (handleErrorMessage(account, original)) {
326			return;
327		}
328		final MessagePacket packet;
329		Long timestamp = null;
330		final boolean isForwarded;
331		boolean isCarbon = false;
332		String serverMsgId = null;
333		final Element fin = original.findChild("fin", Namespace.MAM_LEGACY);
334		if (fin != null) {
335			mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin,original.getFrom());
336			return;
337		}
338		final boolean mamLegacy = original.hasChild("result", Namespace.MAM_LEGACY);
339		final Element result = original.findChild("result",mamLegacy ? Namespace.MAM_LEGACY : Namespace.MAM);
340		final MessageArchiveService.Query query = result == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
341		if (query != null && query.validFrom(original.getFrom())) {
342			Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", mamLegacy ? Namespace.MAM_LEGACY : Namespace.MAM);
343			if (f == null) {
344				return;
345			}
346			timestamp = f.second;
347			packet = f.first;
348			isForwarded = true;
349			serverMsgId = result.getAttribute("id");
350			query.incrementMessageCount();
351		} else if (query != null) {
352			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received mam result from invalid sender");
353			return;
354		} else if (original.fromServer(account)) {
355			Pair<MessagePacket, Long> f;
356			f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
357			f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
358			packet = f != null ? f.first : original;
359			if (handleErrorMessage(account, packet)) {
360				return;
361			}
362			timestamp = f != null ? f.second : null;
363			isCarbon = f != null;
364			isForwarded = isCarbon;
365		} else {
366			packet = original;
367			isForwarded = false;
368		}
369
370		if (timestamp == null) {
371			timestamp = AbstractParser.parseTimestamp(original,AbstractParser.parseTimestamp(packet));
372		}
373		final String body = packet.getBody();
374		final Element mucUserElement = packet.findChild("x", "http://jabber.org/protocol/muc#user");
375		final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
376		final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
377		final Element oob = packet.findChild("x", Namespace.OOB);
378		final String oobUrl = oob != null ? oob.findChildContent("url") : null;
379		final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
380		final Element axolotlEncrypted = packet.findChild(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
381		int status;
382		final Jid counterpart;
383		final Jid to = packet.getTo();
384		final Jid from = packet.getFrom();
385		final Element originId = packet.findChild("origin-id",Namespace.STANZA_IDS);
386		final String remoteMsgId;
387		if (originId != null && originId.getAttribute("id") != null) {
388			remoteMsgId = originId.getAttribute("id");
389		} else {
390			remoteMsgId = packet.getId();
391		}
392		boolean notify = false;
393
394		if (from == null) {
395			Log.d(Config.LOGTAG,"no from in: "+packet.toString());
396			return;
397		}
398		
399		boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
400		boolean isProperlyAddressed = (to != null ) && (!to.isBareJid() || account.countPresences() == 0);
401		boolean isMucStatusMessage = from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
402		if (packet.fromAccount(account)) {
403			status = Message.STATUS_SEND;
404			counterpart = to != null ? to : account.getJid();
405		} else {
406			status = Message.STATUS_RECEIVED;
407			counterpart = from;
408		}
409
410		Invite invite = extractInvite(account, packet);
411		if (invite != null && invite.execute(account)) {
412			return;
413		}
414
415		if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet)) {
416			mXmppConnectionService.updateConversationUi();
417		}
418
419		if ((body != null || pgpEncrypted != null || axolotlEncrypted != null || oobUrl != null) && !isMucStatusMessage) {
420			final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat, false, query, false);
421			final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
422
423			if (serverMsgId == null) {
424				serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
425			}
426
427			if (isTypeGroupChat) {
428				if (conversation.getMucOptions().isSelf(counterpart)) {
429					status = Message.STATUS_SEND_RECEIVED;
430					isCarbon = true; //not really carbon but received from another resource
431					if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId)) {
432						return;
433					} else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
434						Message message = conversation.findSentMessageWithBody(packet.getBody());
435						if (message != null) {
436							mXmppConnectionService.markMessage(message, status);
437							return;
438						}
439					}
440				} else {
441					status = Message.STATUS_RECEIVED;
442				}
443			}
444			final Message message;
445			if (body != null && body.startsWith("?OTR") && Config.supportOtr()) {
446				if (!isForwarded && !isTypeGroupChat && isProperlyAddressed && !conversationMultiMode) {
447					message = parseOtrChat(body, from, remoteMsgId, conversation);
448					if (message == null) {
449						return;
450					}
451				} else {
452					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": ignoring OTR message from "+from+" isForwarded="+Boolean.toString(isForwarded)+", isProperlyAddressed="+Boolean.valueOf(isProperlyAddressed));
453					message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
454				}
455			} else if (pgpEncrypted != null && Config.supportOpenPgp()) {
456				message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
457			} else if (axolotlEncrypted != null && Config.supportOmemo()) {
458				Jid origin;
459				if (conversationMultiMode) {
460					final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
461					origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
462					if (origin == null) {
463						Log.d(Config.LOGTAG, "axolotl message in non anonymous conference received");
464						return;
465					}
466				} else {
467					origin = from;
468				}
469				message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status);
470				if (message == null) {
471					return;
472				}
473				if (conversationMultiMode) {
474					message.setTrueCounterpart(origin);
475				}
476			} else if (body == null && oobUrl != null) {
477				message = new Message(conversation, oobUrl, Message.ENCRYPTION_NONE, status);
478				message.setOob(true);
479				if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
480					message.setEncryption(Message.ENCRYPTION_DECRYPTED);
481				}
482			} else {
483				message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
484			}
485
486			message.setCounterpart(counterpart);
487			message.setRemoteMsgId(remoteMsgId);
488			message.setServerMsgId(serverMsgId);
489			message.setCarbon(isCarbon);
490			message.setTime(timestamp);
491			if (body != null && body.equals(oobUrl)) {
492				message.setOob(true);
493				if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
494					message.setEncryption(Message.ENCRYPTION_DECRYPTED);
495				}
496			}
497			message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
498			if (conversationMultiMode) {
499				final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
500				Jid trueCounterpart;
501				if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
502					trueCounterpart = message.getTrueCounterpart();
503				} else if (Config.PARSE_REAL_JID_FROM_MUC_MAM) {
504					trueCounterpart = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
505				} else {
506					trueCounterpart = fallback;
507				}
508				if (trueCounterpart != null && trueCounterpart.toBareJid().equals(account.getJid().toBareJid())) {
509					status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
510				}
511				message.setStatus(status);
512				message.setTrueCounterpart(trueCounterpart);
513				if (!isTypeGroupChat) {
514					message.setType(Message.TYPE_PRIVATE);
515				}
516			} else {
517				updateLastseen(account, from);
518			}
519
520			if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
521				Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
522						counterpart,
523						message.getStatus() == Message.STATUS_RECEIVED,
524						message.isCarbon());
525				if (replacedMessage != null) {
526					final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
527							|| replacedMessage.getFingerprint().equals(message.getFingerprint());
528					final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
529							&& replacedMessage.getTrueCounterpart().equals(message.getTrueCounterpart());
530					final boolean duplicate = conversation.hasDuplicateMessage(message);
531					if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode) && !duplicate) {
532						Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
533						synchronized (replacedMessage) {
534							final String uuid = replacedMessage.getUuid();
535							replacedMessage.setUuid(UUID.randomUUID().toString());
536							replacedMessage.setBody(message.getBody());
537							replacedMessage.setEdited(replacedMessage.getRemoteMsgId());
538							replacedMessage.setRemoteMsgId(remoteMsgId);
539							replacedMessage.setEncryption(message.getEncryption());
540							if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
541								replacedMessage.markUnread();
542							}
543							mXmppConnectionService.updateMessage(replacedMessage, uuid);
544							mXmppConnectionService.getNotificationService().updateNotification(false);
545							if (mXmppConnectionService.confirmMessages()
546									&& (replacedMessage.trusted() || replacedMessage.getType() == Message.TYPE_PRIVATE)
547									&& remoteMsgId != null
548									&& !isForwarded
549									&& !isTypeGroupChat) {
550								sendMessageReceipts(account, packet);
551							}
552							if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
553								conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
554								conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
555							}
556						}
557						return;
558					} else {
559						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received message correction but verification didn't check out");
560					}
561				}
562			}
563
564			long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate();
565			if (deletionDate != 0 && message.getTimeSent() < deletionDate) {
566				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping message from "+message.getCounterpart().toString()+" because it was sent prior to our deletion date");
567				return;
568			}
569
570			boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay","urn:xmpp:delay"))
571					|| message.getType() == Message.TYPE_PRIVATE
572					|| message.getServerMsgId() != null;
573			if (checkForDuplicates && conversation.hasDuplicateMessage(message)) {
574				Log.d(Config.LOGTAG,"skipping duplicate message from "+message.getCounterpart().toString()+" "+message.getBody());
575				return;
576			}
577
578			if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
579				conversation.prepend(message);
580			} else {
581				conversation.add(message);
582			}
583			if (query != null) {
584				query.incrementActualMessageCount();
585			}
586
587			if (query == null || query.isCatchup()) { //either no mam or catchup
588				if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
589					mXmppConnectionService.markRead(conversation);
590					if (query == null) {
591						activateGracePeriod(account);
592					}
593				} else {
594					message.markUnread();
595					notify = true;
596				}
597			}
598
599			if (message.getEncryption() == Message.ENCRYPTION_PGP) {
600				notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
601			}
602
603			if (query == null) {
604				mXmppConnectionService.updateConversationUi();
605			}
606
607			if (mXmppConnectionService.confirmMessages()
608					&& (message.trusted() || message.getType() == Message.TYPE_PRIVATE)
609					&& remoteMsgId != null
610					&& !isForwarded
611					&& !isTypeGroupChat) {
612				sendMessageReceipts(account, packet);
613			}
614
615			if (message.getStatus() == Message.STATUS_RECEIVED
616					&& conversation.getOtrSession() != null
617					&& !conversation.getOtrSession().getSessionID().getUserID()
618					.equals(message.getCounterpart().getResourcepart())) {
619				conversation.endOtrIfNeeded();
620			}
621
622			mXmppConnectionService.databaseBackend.createMessage(message);
623			final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
624			if (message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
625				manager.createNewDownloadConnection(message);
626			} else if (notify) {
627				if (query != null && query.isCatchup()) {
628					mXmppConnectionService.getNotificationService().pushFromBacklog(message);
629				} else {
630					mXmppConnectionService.getNotificationService().push(message);
631				}
632			}
633		} else if (!packet.hasChild("body")){ //no body
634			final Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
635			if (isTypeGroupChat) {
636				if (packet.hasChild("subject")) {
637					if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
638						conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
639						String subject = packet.findChildContent("subject");
640						conversation.getMucOptions().setSubject(subject);
641						final Bookmark bookmark = conversation.getBookmark();
642						if (bookmark != null && bookmark.getBookmarkName() == null) {
643							if (bookmark.setBookmarkName(subject)) {
644								mXmppConnectionService.pushBookmarks(account);
645							}
646						}
647						mXmppConnectionService.updateConversationUi();
648						return;
649					}
650				}
651			}
652			if (conversation != null && mucUserElement != null && from.isBareJid()) {
653				for (Element child : mucUserElement.getChildren()) {
654					if ("status".equals(child.getName())) {
655						try {
656							int code = Integer.parseInt(child.getAttribute("code"));
657							if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
658								mXmppConnectionService.fetchConferenceConfiguration(conversation);
659								break;
660							}
661						} catch (Exception e) {
662							//ignored
663						}
664					} else if ("item".equals(child.getName())) {
665						MucOptions.User user = AbstractParser.parseItem(conversation,child);
666						Log.d(Config.LOGTAG,account.getJid()+": changing affiliation for "
667								+user.getRealJid()+" to "+user.getAffiliation()+" in "
668								+conversation.getJid().toBareJid());
669						if (!user.realJidMatchesAccount()) {
670							boolean isNew =conversation.getMucOptions().updateUser(user);
671							mXmppConnectionService.getAvatarService().clear(conversation);
672							mXmppConnectionService.updateMucRosterUi();
673							mXmppConnectionService.updateConversationUi();
674							if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
675								Jid jid = user.getRealJid();
676								List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
677								if (cryptoTargets.remove(user.getRealJid())) {
678									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": removed "+jid+" from crypto targets of "+conversation.getName());
679									conversation.setAcceptedCryptoTargets(cryptoTargets);
680									mXmppConnectionService.updateConversation(conversation);
681								}
682							} else if (isNew && user.getRealJid() != null && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
683								account.getAxolotlService().fetchDeviceIds(user.getRealJid());
684							}
685						}
686					}
687				}
688			}
689		}
690
691
692
693		Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
694		if (received == null) {
695			received = packet.findChild("received", "urn:xmpp:receipts");
696		}
697		if (received != null && !packet.fromAccount(account)) {
698			mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
699		}
700		Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
701		if (displayed != null) {
702			if (packet.fromAccount(account)) {
703				Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
704				if (conversation != null && (query == null || query.isCatchup())) {
705					mXmppConnectionService.markRead(conversation);
706				}
707			} else {
708				final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
709				Message message = displayedMessage == null ? null : displayedMessage.prev();
710				while (message != null
711						&& message.getStatus() == Message.STATUS_SEND_RECEIVED
712						&& message.getTimeSent() < displayedMessage.getTimeSent()) {
713					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
714					message = message.prev();
715				}
716			}
717		}
718
719		Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
720		if (event != null) {
721			parseEvent(event, original.getFrom(), account);
722		}
723
724		String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
725		if (nick != null) {
726			Contact contact = account.getRoster().getContact(from);
727			contact.setPresenceName(nick);
728		}
729	}
730
731	private static Jid getTrueCounterpart(Element mucUserElement, Jid fallback) {
732		final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
733		Jid result = item == null ? null : item.getAttributeAsJid("jid");
734		return result != null ? result : fallback;
735	}
736
737	private void sendMessageReceipts(Account account, MessagePacket packet) {
738		ArrayList<String> receiptsNamespaces = new ArrayList<>();
739		if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
740			receiptsNamespaces.add("urn:xmpp:chat-markers:0");
741		}
742		if (packet.hasChild("request", "urn:xmpp:receipts")) {
743			receiptsNamespaces.add("urn:xmpp:receipts");
744		}
745		if (receiptsNamespaces.size() > 0) {
746			MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
747					packet,
748					receiptsNamespaces,
749					packet.getType());
750			mXmppConnectionService.sendMessagePacket(account, receipt);
751		}
752	}
753
754	private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
755
756	private void activateGracePeriod(Account account) {
757		long duration = mXmppConnectionService.getLongPreference("grace_period_length",R.integer.grace_period) * 1000;
758		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": activating grace period till "+TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
759		account.activateGracePeriod(duration);
760	}
761}