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