MessageParser.java

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