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		int status;
237		final Jid counterpart;
238		final Jid to = packet.getTo();
239		final Jid from = packet.getFrom();
240		final String remoteMsgId = packet.getId();
241		boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
242		boolean properlyAddressed = !to.isBareJid() || account.countPresences() == 1;
243		if (packet.fromAccount(account)) {
244			status = Message.STATUS_SEND;
245			counterpart = to;
246		} else {
247			status = Message.STATUS_RECEIVED;
248			counterpart = from;
249		}
250
251		if (from == null || to == null) {
252			Log.d(Config.LOGTAG,"no to or from in: "+packet.toString());
253			return;
254		}
255
256		Invite invite = extractInvite(packet);
257		if (invite != null && invite.execute(account)) {
258			return;
259		}
260
261		if (extractChatState(mXmppConnectionService.find(account,from), packet)) {
262			mXmppConnectionService.updateConversationUi();
263		}
264
265		if (body != null || encrypted != null) {
266			Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat);
267			if (isTypeGroupChat) {
268				if (counterpart.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
269					status = Message.STATUS_SEND_RECEIVED;
270					if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status)) {
271						return;
272					} else {
273						Message message = conversation.findSentMessageWithBody(body);
274						if (message != null) {
275							message.setRemoteMsgId(remoteMsgId);
276							mXmppConnectionService.markMessage(message, status);
277							return;
278						}
279					}
280				} else {
281					status = Message.STATUS_RECEIVED;
282				}
283			}
284			Message message;
285			if (body != null && body.startsWith("?OTR")) {
286				if (!isForwarded && !isTypeGroupChat && properlyAddressed) {
287					message = parseOtrChat(body, from, remoteMsgId, conversation);
288					if (message == null) {
289						return;
290					}
291				} else {
292					message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
293				}
294			} else if (encrypted != null) {
295				message = new Message(conversation, encrypted, Message.ENCRYPTION_PGP, status);
296			} else {
297				message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
298			}
299			message.setCounterpart(counterpart);
300			message.setRemoteMsgId(remoteMsgId);
301			message.setServerMsgId(serverMsgId);
302			message.setTime(timestamp);
303			message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
304			if (conversation.getMode() == Conversation.MODE_MULTI) {
305				message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(counterpart.getResourcepart()));
306				if (!isTypeGroupChat) {
307					message.setType(Message.TYPE_PRIVATE);
308				}
309			}
310			updateLastseen(packet,account,true);
311			boolean checkForDuplicates = serverMsgId != null
312					|| (isTypeGroupChat && packet.hasChild("delay","urn:xmpp:delay"))
313					|| message.getType() == Message.TYPE_PRIVATE;
314			if (checkForDuplicates && conversation.hasDuplicateMessage(message)) {
315				Log.d(Config.LOGTAG,"skipping duplicate message from "+message.getCounterpart().toString()+" "+message.getBody());
316				return;
317			}
318			if (query != null) {
319				query.incrementMessageCount();
320			}
321			conversation.add(message);
322			if (serverMsgId == null) {
323				if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
324					mXmppConnectionService.markRead(conversation);
325					account.activateGracePeriod();
326				} else {
327					message.markUnread();
328				}
329				mXmppConnectionService.updateConversationUi();
330			}
331
332			if (mXmppConnectionService.confirmMessages() && remoteMsgId != null && !isForwarded) {
333				if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
334					MessagePacket receipt = mXmppConnectionService
335							.getMessageGenerator().received(account, packet, "urn:xmpp:chat-markers:0");
336					mXmppConnectionService.sendMessagePacket(account, receipt);
337				}
338				if (packet.hasChild("request", "urn:xmpp:receipts")) {
339					MessagePacket receipt = mXmppConnectionService
340							.getMessageGenerator().received(account, packet, "urn:xmpp:receipts");
341					mXmppConnectionService.sendMessagePacket(account, receipt);
342				}
343			}
344			if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
345				if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
346					mXmppConnectionService.updateConversation(conversation);
347				}
348			}
349
350			if (message.getStatus() == Message.STATUS_RECEIVED
351					&& conversation.getOtrSession() != null
352					&& !conversation.getOtrSession().getSessionID().getUserID()
353					.equals(message.getCounterpart().getResourcepart())) {
354				conversation.endOtrIfNeeded();
355			}
356
357			if (message.getEncryption() == Message.ENCRYPTION_NONE || mXmppConnectionService.saveEncryptedMessages()) {
358				mXmppConnectionService.databaseBackend.createMessage(message);
359			}
360			final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
361			if (message.trusted() && message.bodyContainsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
362				manager.createNewConnection(message);
363			} else if (!message.isRead()) {
364				mXmppConnectionService.getNotificationService().push(message);
365			}
366		} else { //no body
367			if (isTypeGroupChat) {
368				Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
369				if (packet.hasChild("subject")) {
370					if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
371						conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
372						conversation.getMucOptions().setSubject(packet.findChildContent("subject"));
373						mXmppConnectionService.updateConversationUi();
374						return;
375					}
376				}
377
378				final Element x = packet.findChild("x", "http://jabber.org/protocol/muc#user");
379				if (conversation != null && x != null && from.isBareJid()) {
380					for (Element child : x.getChildren()) {
381						if (child.getName().equals("status")
382								&& MucOptions.STATUS_CODE_ROOM_CONFIG_CHANGED.equals(child.getAttribute("code"))) {
383							mXmppConnectionService.fetchConferenceConfiguration(conversation);
384						}
385					}
386				}
387			}
388		}
389
390		Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
391		if (received == null) {
392			received = packet.findChild("received", "urn:xmpp:receipts");
393		}
394		if (received != null && !packet.fromAccount(account)) {
395			mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
396		}
397		Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
398		if (displayed != null) {
399			if (packet.fromAccount(account)) {
400				Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
401				if (conversation != null) {
402					mXmppConnectionService.markRead(conversation);
403				}
404			} else {
405				updateLastseen(packet, account, true);
406				final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
407				Message message = displayedMessage == null ? null : displayedMessage.prev();
408				while (message != null
409						&& message.getStatus() == Message.STATUS_SEND_RECEIVED
410						&& message.getTimeSent() < displayedMessage.getTimeSent()) {
411					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
412					message = message.prev();
413				}
414			}
415		}
416
417		Element event = packet.findChild("event", "http://jabber.org/protocol/pubsub#event");
418		if (event != null) {
419			parseEvent(event, from, account);
420		}
421
422		String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
423		if (nick != null) {
424			Contact contact = account.getRoster().getContact(from);
425			contact.setPresenceName(nick);
426		}
427	}
428}