MessageParser.java

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