MessageParser.java

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