MessageParser.java

  1package eu.siacs.conversations.parser;
  2
  3import android.os.SystemClock;
  4import net.java.otr4j.session.Session;
  5import net.java.otr4j.session.SessionStatus;
  6import eu.siacs.conversations.entities.Account;
  7import eu.siacs.conversations.entities.Conversation;
  8import eu.siacs.conversations.entities.Message;
  9import eu.siacs.conversations.services.XmppConnectionService;
 10import eu.siacs.conversations.utils.CryptoHelper;
 11import eu.siacs.conversations.xml.Element;
 12import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 13import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 14
 15public class MessageParser extends AbstractParser implements
 16		OnMessagePacketReceived {
 17
 18	private long lastCarbonMessageReceived = -XmppConnectionService.CARBON_GRACE_PERIOD;
 19
 20	public MessageParser(XmppConnectionService service) {
 21		super(service);
 22	}
 23
 24	private Message parseChat(MessagePacket packet, Account account) {
 25		String[] fromParts = packet.getFrom().split("/");
 26		Conversation conversation = mXmppConnectionService
 27				.findOrCreateConversation(account, fromParts[0], false);
 28		conversation.setLatestMarkableMessageId(getMarkableMessageId(packet));
 29		updateLastseen(packet, account, true);
 30		String pgpBody = getPgpBody(packet);
 31		Message finishedMessage;
 32		if (pgpBody != null) {
 33			finishedMessage = new Message(conversation, packet.getFrom(),
 34					pgpBody, Message.ENCRYPTION_PGP, Message.STATUS_RECIEVED);
 35		} else {
 36			finishedMessage = new Message(conversation, packet.getFrom(),
 37					packet.getBody(), Message.ENCRYPTION_NONE,
 38					Message.STATUS_RECIEVED);
 39		}
 40		finishedMessage.setTime(getTimestamp(packet));
 41		return finishedMessage;
 42	}
 43
 44	private Message parseOtrChat(MessagePacket packet, Account account) {
 45		boolean properlyAddressed = (packet.getTo().split("/").length == 2)
 46				|| (account.countPresences() == 1);
 47		String[] fromParts = packet.getFrom().split("/");
 48		Conversation conversation = mXmppConnectionService
 49				.findOrCreateConversation(account, fromParts[0], false);
 50		updateLastseen(packet, account, true);
 51		String body = packet.getBody();
 52		if (!conversation.hasValidOtrSession()) {
 53			if (properlyAddressed) {
 54				conversation.startOtrSession(
 55						mXmppConnectionService.getApplicationContext(),
 56						fromParts[1], false);
 57			} else {
 58				return null;
 59			}
 60		} else {
 61			String foreignPresence = conversation.getOtrSession()
 62					.getSessionID().getUserID();
 63			if (!foreignPresence.equals(fromParts[1])) {
 64				conversation.endOtrIfNeeded();
 65				if (properlyAddressed) {
 66					conversation.startOtrSession(
 67							mXmppConnectionService.getApplicationContext(),
 68							fromParts[1], false);
 69				} else {
 70					return null;
 71				}
 72			}
 73		}
 74		try {
 75			Session otrSession = conversation.getOtrSession();
 76			SessionStatus before = otrSession.getSessionStatus();
 77			body = otrSession.transformReceiving(body);
 78			SessionStatus after = otrSession.getSessionStatus();
 79			if ((before != after) && (after == SessionStatus.ENCRYPTED)) {
 80				mXmppConnectionService.onOtrSessionEstablished(conversation);
 81			} else if ((before != after) && (after == SessionStatus.FINISHED)) {
 82				conversation.resetOtrSession();
 83				mXmppConnectionService.updateConversationUi();
 84			}
 85			if ((body == null) || (body.isEmpty())) {
 86				return null;
 87			}
 88			if (body.startsWith(CryptoHelper.FILETRANSFER)) {
 89				String key = body.substring(CryptoHelper.FILETRANSFER.length());
 90				conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
 91				return null;
 92			}
 93			conversation
 94					.setLatestMarkableMessageId(getMarkableMessageId(packet));
 95			Message finishedMessage = new Message(conversation,
 96					packet.getFrom(), body, Message.ENCRYPTION_OTR,
 97					Message.STATUS_RECIEVED);
 98			finishedMessage.setTime(getTimestamp(packet));
 99			return finishedMessage;
100		} catch (Exception e) {
101			String receivedId = packet.getId();
102			if (receivedId != null) {
103				mXmppConnectionService.replyWithNotAcceptable(account, packet);
104			}
105			conversation.endOtrIfNeeded();
106			return null;
107		}
108	}
109
110	private Message parseGroupchat(MessagePacket packet, Account account) {
111		int status;
112		String[] fromParts = packet.getFrom().split("/");
113		if (mXmppConnectionService.find(account.pendingConferenceLeaves,account,fromParts[0]) != null) {
114			return null;
115		}
116		Conversation conversation = mXmppConnectionService
117				.findOrCreateConversation(account, fromParts[0], true);
118		if (packet.hasChild("subject")) {
119			conversation.getMucOptions().setSubject(
120					packet.findChild("subject").getContent());
121			mXmppConnectionService.updateConversationUi();
122			return null;
123		}
124		if ((fromParts.length == 1)) {
125			return null;
126		}
127		String counterPart = fromParts[1];
128		if (counterPart.equals(conversation.getMucOptions().getActualNick())) {
129			if (mXmppConnectionService.markMessage(conversation,
130					packet.getId(), Message.STATUS_SEND)) {
131				return null;
132			} else {
133				status = Message.STATUS_SEND;
134			}
135		} else {
136			status = Message.STATUS_RECIEVED;
137		}
138		String pgpBody = getPgpBody(packet);
139		conversation.setLatestMarkableMessageId(getMarkableMessageId(packet));
140		Message finishedMessage;
141		if (pgpBody == null) {
142			finishedMessage = new Message(conversation, counterPart,
143					packet.getBody(), Message.ENCRYPTION_NONE, status);
144		} else {
145			finishedMessage = new Message(conversation, counterPart, pgpBody,
146					Message.ENCRYPTION_PGP, status);
147		}
148		finishedMessage.setTime(getTimestamp(packet));
149		return finishedMessage;
150	}
151
152	private Message parseCarbonMessage(MessagePacket packet, Account account) {
153		int status;
154		String fullJid;
155		Element forwarded;
156		if (packet.hasChild("received")) {
157			forwarded = packet.findChild("received").findChild("forwarded");
158			status = Message.STATUS_RECIEVED;
159		} else if (packet.hasChild("sent")) {
160			forwarded = packet.findChild("sent").findChild("forwarded");
161			status = Message.STATUS_SEND;
162		} else {
163			return null;
164		}
165		if (forwarded == null) {
166			return null;
167		}
168		Element message = forwarded.findChild("message");
169		if ((message == null) || (!message.hasChild("body"))) {
170			if (status == Message.STATUS_RECIEVED) {
171				parseNormal(message, account);
172			}
173			return null;
174		}
175		if (status == Message.STATUS_RECIEVED) {
176			fullJid = message.getAttribute("from");
177			if (fullJid == null ) {
178				return null;
179			} else {
180				updateLastseen(message, account, true);
181			}
182		} else {
183			fullJid = message.getAttribute("to");
184			if (fullJid == null) {
185				return null;
186			}
187		}
188		String[] parts = fullJid.split("/");
189		Conversation conversation = mXmppConnectionService
190				.findOrCreateConversation(account, parts[0], false);
191		conversation.setLatestMarkableMessageId(getMarkableMessageId(packet));
192		String pgpBody = getPgpBody(message);
193		Message finishedMessage;
194		if (pgpBody != null) {
195			finishedMessage = new Message(conversation, fullJid, pgpBody,
196					Message.ENCRYPTION_PGP, status);
197		} else {
198			String body = message.findChild("body").getContent();
199			finishedMessage = new Message(conversation, fullJid, body,
200					Message.ENCRYPTION_NONE, status);
201		}
202		finishedMessage.setTime(getTimestamp(message));
203		return finishedMessage;
204	}
205
206	private void parseError(MessagePacket packet, Account account) {
207		String[] fromParts = packet.getFrom().split("/");
208		mXmppConnectionService.markMessage(account, fromParts[0],
209				packet.getId(), Message.STATUS_SEND_FAILED);
210	}
211
212	private void parseNormal(Element packet, Account account) {
213		if (packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
214			String id = packet
215					.findChild("displayed", "urn:xmpp:chat-markers:0")
216					.getAttribute("id");
217			String[] fromParts = packet.getAttribute("from").split("/");
218			updateLastseen(packet, account, true);
219			mXmppConnectionService.markMessage(account, fromParts[0], id,
220					Message.STATUS_SEND_DISPLAYED);
221		} else if (packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
222			String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
223					.getAttribute("id");
224			String[] fromParts = packet.getAttribute("from").split("/");
225			updateLastseen(packet, account, false);
226			mXmppConnectionService.markMessage(account, fromParts[0], id,
227					Message.STATUS_SEND_RECEIVED);
228		} else if (packet.hasChild("x","http://jabber.org/protocol/muc#user")) {
229			Element x = packet.findChild("x","http://jabber.org/protocol/muc#user");
230			if (x.hasChild("invite")) {
231				Conversation conversation = mXmppConnectionService
232						.findOrCreateConversation(account,
233								packet.getAttribute("from"), true);
234				if (!conversation.getMucOptions().online()) {
235					mXmppConnectionService.joinMuc(conversation);
236					mXmppConnectionService.updateConversationUi();
237				}	
238			}
239
240		} else if (packet.hasChild("x", "jabber:x:conference")) {
241			Element x = packet.findChild("x", "jabber:x:conference");
242			String jid = x.getAttribute("jid");
243			if (jid!=null) {
244				Conversation conversation = mXmppConnectionService
245						.findOrCreateConversation(account,jid, true);
246				if (!conversation.getMucOptions().online()) {
247					mXmppConnectionService.joinMuc(conversation);
248					mXmppConnectionService.updateConversationUi();
249				}
250			}
251		}
252	}
253
254	private String getPgpBody(Element message) {
255		Element child = message.findChild("x", "jabber:x:encrypted");
256		if (child == null) {
257			return null;
258		} else {
259			return child.getContent();
260		}
261	}
262
263	private String getMarkableMessageId(Element message) {
264		if (message.hasChild("markable", "urn:xmpp:chat-markers:0")) {
265			return message.getAttribute("id");
266		} else {
267			return null;
268		}
269	}
270
271	@Override
272	public void onMessagePacketReceived(Account account, MessagePacket packet) {
273		Message message = null;
274		boolean notify = true;
275		if (mXmppConnectionService.getPreferences().getBoolean(
276				"notification_grace_period_after_carbon_received", true)) {
277			notify = (SystemClock.elapsedRealtime() - lastCarbonMessageReceived) > XmppConnectionService.CARBON_GRACE_PERIOD;
278		}
279
280		if ((packet.getType() == MessagePacket.TYPE_CHAT)) {
281			if ((packet.getBody() != null)
282					&& (packet.getBody().startsWith("?OTR"))) {
283				message = this.parseOtrChat(packet, account);
284				if (message != null) {
285					message.markUnread();
286				}
287			} else if (packet.hasChild("body")) {
288				message = this.parseChat(packet, account);
289				message.markUnread();
290			} else if (packet.hasChild("received") || (packet.hasChild("sent"))) {
291				message = this.parseCarbonMessage(packet, account);
292				if (message != null) {
293					if (message.getStatus() == Message.STATUS_SEND) {
294						lastCarbonMessageReceived = SystemClock
295								.elapsedRealtime();
296						notify = false;
297						message.getConversation().markRead();
298					} else {
299						message.markUnread();
300					}
301				}
302			} else {
303				parseNormal(packet, account);
304			}
305
306		} else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
307			message = this.parseGroupchat(packet, account);
308			if (message != null) {
309				if (message.getStatus() == Message.STATUS_RECIEVED) {
310					message.markUnread();
311				} else {
312					message.getConversation().markRead();
313					lastCarbonMessageReceived = SystemClock
314							.elapsedRealtime();
315					notify = false;
316				}
317			}
318		} else if (packet.getType() == MessagePacket.TYPE_ERROR) {
319			this.parseError(packet, account);
320			return;
321		} else if (packet.getType() == MessagePacket.TYPE_NORMAL) {
322			this.parseNormal(packet, account);
323			return;
324		}
325		if ((message == null) || (message.getBody() == null)) {
326			return;
327		}
328		if ((mXmppConnectionService.confirmMessages())
329				&& ((packet.getId() != null))) {
330			if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
331				MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account, packet, "urn:xmpp:chat-markers:0");
332				mXmppConnectionService.sendMessagePacket(account, receipt);
333			}
334			if (packet.hasChild("request", "urn:xmpp:receipts")) {
335				MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account, packet, "urn:xmpp:receipts");
336				mXmppConnectionService.sendMessagePacket(account, receipt);
337			}
338		}
339		Conversation conversation = message.getConversation();
340		conversation.getMessages().add(message);
341		if (packet.getType() != MessagePacket.TYPE_ERROR) {
342			mXmppConnectionService.databaseBackend.createMessage(message);
343		}
344		mXmppConnectionService.notifyUi(conversation, notify);
345	}
346}