MessageParser.java

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