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