MessageParser.java

  1package eu.siacs.conversations.parser;
  2
  3import android.util.Log;
  4import android.util.Pair;
  5
  6import net.java.otr4j.session.Session;
  7import net.java.otr4j.session.SessionStatus;
  8
  9import eu.siacs.conversations.Config;
 10import eu.siacs.conversations.entities.Account;
 11import eu.siacs.conversations.entities.Contact;
 12import eu.siacs.conversations.entities.Conversation;
 13import eu.siacs.conversations.entities.Message;
 14import eu.siacs.conversations.entities.MucOptions;
 15import eu.siacs.conversations.http.HttpConnectionManager;
 16import eu.siacs.conversations.services.MessageArchiveService;
 17import eu.siacs.conversations.services.XmppConnectionService;
 18import eu.siacs.conversations.utils.CryptoHelper;
 19import eu.siacs.conversations.xml.Element;
 20import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 21import eu.siacs.conversations.xmpp.chatstate.ChatState;
 22import eu.siacs.conversations.xmpp.jid.Jid;
 23import eu.siacs.conversations.xmpp.pep.Avatar;
 24import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 25
 26public class MessageParser extends AbstractParser implements
 27		OnMessagePacketReceived {
 28	public MessageParser(XmppConnectionService service) {
 29		super(service);
 30	}
 31
 32	private boolean extractChatState(Conversation conversation, final MessagePacket packet) {
 33		ChatState state = ChatState.parse(packet);
 34		if (state != null && conversation != null) {
 35			final Account account = conversation.getAccount();
 36			Jid from = packet.getFrom();
 37			if (from.toBareJid().equals(account.getJid().toBareJid())) {
 38				conversation.setOutgoingChatState(state);
 39				return false;
 40			} else {
 41				return conversation.setIncomingChatState(state);
 42			}
 43		}
 44		return false;
 45	}
 46
 47	private Message parseOtrChat(String body, Jid from, String id, Conversation conversation) {
 48		String presence;
 49		if (from.isBareJid()) {
 50			presence = "";
 51		} else {
 52			presence = from.getResourcepart();
 53		}
 54		if (body.matches("^\\?OTRv\\d{1,2}\\?.*")) {
 55			conversation.endOtrIfNeeded();
 56		}
 57		if (!conversation.hasValidOtrSession()) {
 58			conversation.startOtrSession(presence,false);
 59		} else {
 60			String foreignPresence = conversation.getOtrSession().getSessionID().getUserID();
 61			if (!foreignPresence.equals(presence)) {
 62				conversation.endOtrIfNeeded();
 63				conversation.startOtrSession(presence, false);
 64			}
 65		}
 66		try {
 67			conversation.setLastReceivedOtrMessageId(id);
 68			Session otrSession = conversation.getOtrSession();
 69			SessionStatus before = otrSession.getSessionStatus();
 70			body = otrSession.transformReceiving(body);
 71			SessionStatus after = otrSession.getSessionStatus();
 72			if ((before != after) && (after == SessionStatus.ENCRYPTED)) {
 73				conversation.setNextEncryption(Message.ENCRYPTION_OTR);
 74				mXmppConnectionService.onOtrSessionEstablished(conversation);
 75			} else if ((before != after) && (after == SessionStatus.FINISHED)) {
 76				conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 77				conversation.resetOtrSession();
 78				mXmppConnectionService.updateConversationUi();
 79			}
 80			if ((body == null) || (body.isEmpty())) {
 81				return null;
 82			}
 83			if (body.startsWith(CryptoHelper.FILETRANSFER)) {
 84				String key = body.substring(CryptoHelper.FILETRANSFER.length());
 85				conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
 86				return null;
 87			}
 88			Message finishedMessage = new Message(conversation, body, Message.ENCRYPTION_OTR, Message.STATUS_RECEIVED);
 89			conversation.setLastReceivedOtrMessageId(null);
 90			return finishedMessage;
 91		} catch (Exception e) {
 92			conversation.resetOtrSession();
 93			return null;
 94		}
 95	}
 96
 97	private class Invite {
 98		Jid jid;
 99		String password;
100		Invite(Jid jid, String password) {
101			this.jid = jid;
102			this.password = password;
103		}
104
105		public boolean execute(Account account) {
106			if (jid != null) {
107				Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true);
108				if (!conversation.getMucOptions().online()) {
109					conversation.getMucOptions().setPassword(password);
110					mXmppConnectionService.databaseBackend.updateConversation(conversation);
111					mXmppConnectionService.joinMuc(conversation);
112					mXmppConnectionService.updateConversationUi();
113				}
114				return true;
115			}
116			return false;
117		}
118	}
119
120	private Invite extractInvite(Element message) {
121		Element x = message.findChild("x", "http://jabber.org/protocol/muc#user");
122		if (x != null) {
123			Element invite = x.findChild("invite");
124			if (invite != null) {
125				Element pw = x.findChild("password");
126				return new Invite(message.getAttributeAsJid("from"), pw != null ? pw.getContent(): null);
127			}
128		} else {
129			x = message.findChild("x","jabber:x:conference");
130			if (x != null) {
131				return new Invite(x.getAttributeAsJid("jid"),x.getAttribute("password"));
132			}
133		}
134		return null;
135	}
136
137	private void parseEvent(final Element event, final Jid from, final Account account) {
138		Element items = event.findChild("items");
139		String node = items == null ? null : items.getAttribute("node");
140		if ("urn:xmpp:avatar:metadata".equals(node)) {
141			Avatar avatar = Avatar.parseMetadata(items);
142			if (avatar != null) {
143				avatar.owner = from;
144				if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
145					if (account.getJid().toBareJid().equals(from)) {
146						if (account.setAvatar(avatar.getFilename())) {
147							mXmppConnectionService.databaseBackend.updateAccount(account);
148						}
149						mXmppConnectionService.getAvatarService().clear(account);
150						mXmppConnectionService.updateConversationUi();
151						mXmppConnectionService.updateAccountUi();
152					} else {
153						Contact contact = account.getRoster().getContact(from);
154						contact.setAvatar(avatar);
155						mXmppConnectionService.getAvatarService().clear(contact);
156						mXmppConnectionService.updateConversationUi();
157						mXmppConnectionService.updateRosterUi();
158					}
159				} else {
160					mXmppConnectionService.fetchAvatar(account, avatar);
161				}
162			}
163		} else if ("http://jabber.org/protocol/nick".equals(node)) {
164			Element i = items.findChild("item");
165			Element nick = i == null ? null : i.findChild("nick", "http://jabber.org/protocol/nick");
166			if (nick != null) {
167				Contact contact = account.getRoster().getContact(from);
168				contact.setPresenceName(nick.getContent());
169				mXmppConnectionService.getAvatarService().clear(account);
170				mXmppConnectionService.updateConversationUi();
171				mXmppConnectionService.updateAccountUi();
172			}
173		}
174	}
175
176	private boolean handleErrorMessage(Account account, MessagePacket packet) {
177		if (packet.getType() == MessagePacket.TYPE_ERROR) {
178			Jid from = packet.getFrom();
179			if (from != null) {
180				mXmppConnectionService.markMessage(account, from.toBareJid(), packet.getId(), Message.STATUS_SEND_FAILED);
181			}
182			return true;
183		}
184		return false;
185	}
186
187	@Override
188	public void onMessagePacketReceived(Account account, MessagePacket original) {
189		if (handleErrorMessage(account, original)) {
190			return;
191		}
192		final MessagePacket packet;
193		Long timestamp = null;
194		final boolean isForwarded;
195		String serverMsgId = null;
196		final Element fin = original.findChild("fin", "urn:xmpp:mam:0");
197		if (fin != null) {
198			mXmppConnectionService.getMessageArchiveService().processFin(fin,original.getFrom());
199			return;
200		}
201		final Element result = original.findChild("result","urn:xmpp:mam:0");
202		final MessageArchiveService.Query query = result == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
203		if (query != null && query.validFrom(original.getFrom())) {
204			Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", "urn:xmpp:mam:0");
205			if (f == null) {
206				return;
207			}
208			timestamp = f.second;
209			packet = f.first;
210			isForwarded = true;
211			serverMsgId = result.getAttribute("id");
212			query.incrementTotalCount();
213		} else if (query != null) {
214			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received mam result from invalid sender");
215			return;
216		} else if (original.fromServer(account)) {
217			Pair<MessagePacket, Long> f;
218			f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
219			f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
220			packet = f != null ? f.first : original;
221			if (handleErrorMessage(account, packet)) {
222				return;
223			}
224			timestamp = f != null ? f.second : null;
225			isForwarded = f != null;
226		} else {
227			packet = original;
228			isForwarded = false;
229		}
230
231		if (timestamp == null) {
232			timestamp = AbstractParser.getTimestamp(packet, System.currentTimeMillis());
233		}
234		final String body = packet.getBody();
235		final String encrypted = packet.findChildContent("x", "jabber:x:encrypted");
236		final Element mucUserElement = packet.findChild("x","http://jabber.org/protocol/muc#user");
237		int status;
238		final Jid counterpart;
239		final Jid to = packet.getTo();
240		final Jid from = packet.getFrom();
241		final String remoteMsgId = packet.getId();
242		boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
243		boolean isProperlyAddressed = !to.isBareJid() || account.countPresences() == 1;
244		boolean isMucStatusMessage = from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
245		if (packet.fromAccount(account)) {
246			status = Message.STATUS_SEND;
247			counterpart = to;
248		} else {
249			status = Message.STATUS_RECEIVED;
250			counterpart = from;
251		}
252
253		if (from == null || to == null) {
254			Log.d(Config.LOGTAG,"no to or from in: "+packet.toString());
255			return;
256		}
257
258		Invite invite = extractInvite(packet);
259		if (invite != null && invite.execute(account)) {
260			return;
261		}
262
263		if (extractChatState(mXmppConnectionService.find(account,from), packet)) {
264			mXmppConnectionService.updateConversationUi();
265		}
266
267		if ((body != null || encrypted != null) && !isMucStatusMessage) {
268			Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat);
269			if (isTypeGroupChat) {
270				if (counterpart.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
271					status = Message.STATUS_SEND_RECEIVED;
272					if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status)) {
273						return;
274					} else {
275						Message message = conversation.findSentMessageWithBody(body);
276						if (message != null) {
277							message.setRemoteMsgId(remoteMsgId);
278							mXmppConnectionService.markMessage(message, status);
279							return;
280						}
281					}
282				} else {
283					status = Message.STATUS_RECEIVED;
284				}
285			}
286			Message message;
287			if (body != null && body.startsWith("?OTR")) {
288				if (!isForwarded && !isTypeGroupChat && isProperlyAddressed) {
289					message = parseOtrChat(body, from, remoteMsgId, conversation);
290					if (message == null) {
291						return;
292					}
293				} else {
294					message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
295				}
296			} else if (encrypted != null) {
297				message = new Message(conversation, encrypted, Message.ENCRYPTION_PGP, status);
298			} else {
299				message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
300			}
301			message.setCounterpart(counterpart);
302			message.setRemoteMsgId(remoteMsgId);
303			message.setServerMsgId(serverMsgId);
304			message.setTime(timestamp);
305			message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
306			if (conversation.getMode() == Conversation.MODE_MULTI) {
307				message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(counterpart.getResourcepart()));
308				if (!isTypeGroupChat) {
309					message.setType(Message.TYPE_PRIVATE);
310				}
311			}
312			updateLastseen(packet,account,true);
313			boolean checkForDuplicates = serverMsgId != null
314					|| (isTypeGroupChat && packet.hasChild("delay","urn:xmpp:delay"))
315					|| message.getType() == Message.TYPE_PRIVATE;
316			if (checkForDuplicates && conversation.hasDuplicateMessage(message)) {
317				Log.d(Config.LOGTAG,"skipping duplicate message from "+message.getCounterpart().toString()+" "+message.getBody());
318				return;
319			}
320			if (query != null) {
321				query.incrementMessageCount();
322			}
323			conversation.add(message);
324			if (serverMsgId == null) {
325				if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
326					mXmppConnectionService.markRead(conversation);
327					account.activateGracePeriod();
328				} else {
329					message.markUnread();
330				}
331				mXmppConnectionService.updateConversationUi();
332			}
333
334			if (mXmppConnectionService.confirmMessages() && remoteMsgId != null && !isForwarded) {
335				if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
336					MessagePacket receipt = mXmppConnectionService
337							.getMessageGenerator().received(account, packet, "urn:xmpp:chat-markers:0");
338					mXmppConnectionService.sendMessagePacket(account, receipt);
339				}
340				if (packet.hasChild("request", "urn:xmpp:receipts")) {
341					MessagePacket receipt = mXmppConnectionService
342							.getMessageGenerator().received(account, packet, "urn:xmpp:receipts");
343					mXmppConnectionService.sendMessagePacket(account, receipt);
344				}
345			}
346			if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
347				if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
348					mXmppConnectionService.updateConversation(conversation);
349				}
350			}
351
352			if (message.getStatus() == Message.STATUS_RECEIVED
353					&& conversation.getOtrSession() != null
354					&& !conversation.getOtrSession().getSessionID().getUserID()
355					.equals(message.getCounterpart().getResourcepart())) {
356				conversation.endOtrIfNeeded();
357			}
358
359			if (message.getEncryption() == Message.ENCRYPTION_NONE || mXmppConnectionService.saveEncryptedMessages()) {
360				mXmppConnectionService.databaseBackend.createMessage(message);
361			}
362			final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
363			if (message.trusted() && message.bodyContainsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
364				manager.createNewConnection(message);
365			} else if (!message.isRead()) {
366				mXmppConnectionService.getNotificationService().push(message);
367			}
368		} else { //no body
369			if (isTypeGroupChat) {
370				Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
371				if (packet.hasChild("subject")) {
372					if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
373						conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
374						conversation.getMucOptions().setSubject(packet.findChildContent("subject"));
375						mXmppConnectionService.updateConversationUi();
376						return;
377					}
378				}
379
380				if (conversation != null && isMucStatusMessage) {
381					for (Element child : mucUserElement.getChildren()) {
382						if (child.getName().equals("status")
383								&& MucOptions.STATUS_CODE_ROOM_CONFIG_CHANGED.equals(child.getAttribute("code"))) {
384							mXmppConnectionService.fetchConferenceConfiguration(conversation);
385						}
386					}
387				}
388			}
389		}
390
391		Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
392		if (received == null) {
393			received = packet.findChild("received", "urn:xmpp:receipts");
394		}
395		if (received != null && !packet.fromAccount(account)) {
396			mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
397		}
398		Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
399		if (displayed != null) {
400			if (packet.fromAccount(account)) {
401				Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
402				if (conversation != null) {
403					mXmppConnectionService.markRead(conversation);
404				}
405			} else {
406				updateLastseen(packet, account, true);
407				final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
408				Message message = displayedMessage == null ? null : displayedMessage.prev();
409				while (message != null
410						&& message.getStatus() == Message.STATUS_SEND_RECEIVED
411						&& message.getTimeSent() < displayedMessage.getTimeSent()) {
412					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
413					message = message.prev();
414				}
415			}
416		}
417
418		Element event = packet.findChild("event", "http://jabber.org/protocol/pubsub#event");
419		if (event != null) {
420			parseEvent(event, from, account);
421		}
422
423		String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
424		if (nick != null) {
425			Contact contact = account.getRoster().getContact(from);
426			contact.setPresenceName(nick);
427		}
428	}
429}