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
106	private Invite extractInvite(Element message) {
107		Element x = message.findChild("x", "http://jabber.org/protocol/muc#user");
108		if (x != null) {
109			Element invite = x.findChild("invite");
110			if (invite != null) {
111				Element pw = x.findChild("password");
112				return new Invite(message.getAttributeAsJid("from"), pw != null ? pw.getContent(): null);
113			}
114		} else {
115			x = message.findChild("x","jabber:x:conference");
116			if (x != null) {
117				return new Invite(x.getAttributeAsJid("jid"),x.getAttribute("password"));
118			}
119		}
120		return null;
121	}
122
123	private void parseEvent(final Element event, final Jid from, final Account account) {
124		Element items = event.findChild("items");
125		if (items == null) {
126			return;
127		}
128		String node = items.getAttribute("node");
129		if (node == null) {
130			return;
131		}
132		if (node.equals("urn:xmpp:avatar:metadata")) {
133			Avatar avatar = Avatar.parseMetadata(items);
134			if (avatar != null) {
135				avatar.owner = from;
136				if (mXmppConnectionService.getFileBackend().isAvatarCached(
137						avatar)) {
138					if (account.getJid().toBareJid().equals(from)) {
139						if (account.setAvatar(avatar.getFilename())) {
140							mXmppConnectionService.databaseBackend
141									.updateAccount(account);
142						}
143						mXmppConnectionService.getAvatarService().clear(
144								account);
145						mXmppConnectionService.updateConversationUi();
146						mXmppConnectionService.updateAccountUi();
147					} else {
148						Contact contact = account.getRoster().getContact(
149								from);
150						contact.setAvatar(avatar);
151						mXmppConnectionService.getAvatarService().clear(
152								contact);
153						mXmppConnectionService.updateConversationUi();
154						mXmppConnectionService.updateRosterUi();
155					}
156				} else {
157					mXmppConnectionService.fetchAvatar(account, avatar);
158				}
159			}
160		} else if (node.equals("http://jabber.org/protocol/nick")) {
161			Element item = items.findChild("item");
162			if (item != null) {
163				Element nick = item.findChild("nick",
164						"http://jabber.org/protocol/nick");
165				if (nick != null) {
166					if (from != null) {
167						Contact contact = account.getRoster().getContact(
168								from);
169						contact.setPresenceName(nick.getContent());
170						mXmppConnectionService.getAvatarService().clear(account);
171						mXmppConnectionService.updateConversationUi();
172						mXmppConnectionService.updateAccountUi();
173					}
174				}
175			}
176		}
177	}
178
179	@Override
180	public void onMessagePacketReceived(Account account, MessagePacket original) {
181		final MessagePacket packet;
182		Long timestamp = null;
183		final boolean isForwarded;
184		boolean carbon = false; //live carbons or mam-sub
185		if (original.fromServer(account)) {
186			Pair<MessagePacket, Long> f;
187			f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
188			f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
189			f = f == null ? original.getForwardedMessagePacket("result", "urn:xmpp:mam:0") : f;
190			packet = f != null ? f.first : original;
191			timestamp = f != null ? f.second : null;
192			isForwarded = f != null;
193			carbon = original.hasChild("received", "urn:xmpp:carbons:2") || original.hasChild("received", "urn:xmpp:carbons:2");
194
195			Element fin = packet.findChild("fin", "urn:xmpp:mam:0");
196			if (fin != null) {
197				mXmppConnectionService.getMessageArchiveService().processFin(fin);
198				return;
199			}
200
201		} else {
202			packet = original;
203			isForwarded = false;
204		}
205		if (timestamp == null) {
206			timestamp = AbstractParser.getTimestamp(packet, System.currentTimeMillis());
207		}
208		final String body = packet.getBody();
209		final String encrypted = packet.findChildContent("x", "jabber:x:encrypted");
210		int status;
211		final Jid to = packet.getTo();
212		final Jid from = packet.getFrom();
213		final Jid counterpart;
214		final String id = packet.getId();
215		boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
216		boolean properlyAddressed = !to.isBareJid() || account.countPresences() == 1;
217		if (packet.fromAccount(account)) {
218			status = Message.STATUS_SEND;
219			counterpart = to;
220		} else {
221			status = Message.STATUS_RECEIVED;
222			counterpart = from;
223		}
224
225		if (from == null || to == null) {
226			Log.d(Config.LOGTAG,"no to or from in: "+packet.toString());
227			return;
228		}
229
230		Invite invite = extractInvite(packet);
231		if (invite != null && invite.jid != null) {
232			Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, invite.jid, true);
233			if (!conversation.getMucOptions().online()) {
234				conversation.getMucOptions().setPassword(invite.password);
235				mXmppConnectionService.databaseBackend.updateConversation(conversation);
236				mXmppConnectionService.joinMuc(conversation);
237				mXmppConnectionService.updateConversationUi();
238			}
239			return;
240		}
241
242		if (extractChatState(mXmppConnectionService.find(account,from), packet)) {
243			mXmppConnectionService.updateConversationUi();
244		}
245
246		if (body != null || encrypted != null) {
247			Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat);
248			if (isTypeGroupChat) {
249				if (counterpart.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
250					status = Message.STATUS_SEND;
251					if (mXmppConnectionService.markMessage(conversation, id, Message.STATUS_SEND_RECEIVED)) {
252						return;
253					} else if (id == null) {
254						Message message = conversation.findSentMessageWithBody(packet.getBody());
255						if (message != null) {
256							mXmppConnectionService.markMessage(message, Message.STATUS_SEND_RECEIVED);
257							return;
258						}
259					}
260				} else {
261					status = Message.STATUS_RECEIVED;
262				}
263			}
264			Message message;
265			if (body != null && body.startsWith("?OTR")) {
266				if (!isForwarded && !isTypeGroupChat && properlyAddressed) {
267					message = parseOtrChat(body, from, id, conversation);
268					if (message == null) {
269						return;
270					}
271				} else {
272					message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
273				}
274			} else if (encrypted != null) {
275				message = new Message(conversation, encrypted, Message.ENCRYPTION_PGP, status);
276			} else {
277				message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
278			}
279			message.setCounterpart(counterpart);
280			message.setRemoteMsgId(id);
281			message.setTime(timestamp);
282			message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
283			if (conversation.getMode() == Conversation.MODE_MULTI) {
284				message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(counterpart.getResourcepart()));
285				if (!isTypeGroupChat) {
286					message.setType(Message.TYPE_PRIVATE);
287				}
288			}
289			updateLastseen(packet,account,true);
290			conversation.add(message);
291			if (carbon || status == Message.STATUS_RECEIVED) {
292				mXmppConnectionService.markRead(conversation);
293				account.activateGracePeriod();
294			} else if (!isForwarded) {
295				message.markUnread();
296			}
297
298
299			if (mXmppConnectionService.confirmMessages() && id != null && !packet.fromAccount(account)) {
300				if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
301					MessagePacket receipt = mXmppConnectionService
302							.getMessageGenerator().received(account, packet, "urn:xmpp:chat-markers:0");
303					mXmppConnectionService.sendMessagePacket(account, receipt);
304				}
305				if (packet.hasChild("request", "urn:xmpp:receipts")) {
306					MessagePacket receipt = mXmppConnectionService
307							.getMessageGenerator().received(account, packet, "urn:xmpp:receipts");
308					mXmppConnectionService.sendMessagePacket(account, receipt);
309				}
310			}
311			if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
312				if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
313					mXmppConnectionService.updateConversation(conversation);
314				}
315			}
316
317			if (message.getStatus() == Message.STATUS_RECEIVED
318					&& conversation.getOtrSession() != null
319					&& !conversation.getOtrSession().getSessionID().getUserID()
320					.equals(message.getCounterpart().getResourcepart())) {
321				conversation.endOtrIfNeeded();
322			}
323
324			if (message.getEncryption() == Message.ENCRYPTION_NONE
325					|| mXmppConnectionService.saveEncryptedMessages()) {
326				mXmppConnectionService.databaseBackend.createMessage(message);
327			}
328			final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
329			if (message.trusted() && message.bodyContainsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
330				manager.createNewConnection(message);
331			} else if (!message.isRead()) {
332				mXmppConnectionService.getNotificationService().push(message);
333			}
334			mXmppConnectionService.updateConversationUi();
335		} else {
336			if (packet.hasChild("subject") && isTypeGroupChat) {
337				Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
338				if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
339					conversation.setHasMessagesLeftOnServer(true);
340					conversation.getMucOptions().setSubject(packet.findChildContent("subject"));
341					mXmppConnectionService.updateConversationUi();
342					return;
343				}
344			}
345		}
346
347		Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
348		if (received == null) {
349			received = packet.findChild("received", "urn:xmpp:receipts");
350		}
351		if (received != null && !packet.fromAccount(account)) {
352			mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
353		}
354		Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
355		if (displayed != null) {
356			if (packet.fromAccount(account)) {
357				Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
358				mXmppConnectionService.markRead(conversation);
359			} else {
360				updateLastseen(packet, account, true);
361				final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
362				Message message = displayedMessage == null ? null : displayedMessage.prev();
363				while (message != null
364						&& message.getStatus() == Message.STATUS_SEND_RECEIVED
365						&& message.getTimeSent() < displayedMessage.getTimeSent()) {
366					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
367					message = message.prev();
368				}
369			}
370		}
371
372		Element event = packet.findChild("event", "http://jabber.org/protocol/pubsub#event");
373		if (event != null) {
374			parseEvent(event, from, account);
375		}
376
377		String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
378		if (nick != null) {
379			Contact contact = account.getRoster().getContact(from);
380			contact.setPresenceName(nick);
381		}
382	}
383}