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