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