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