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