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 = x.getAttributeAsJid("jid");
323            String password = x.getAttribute("password");
324			if (jid != null) {
325				Conversation conversation = mXmppConnectionService
326						.findOrCreateConversation(account, jid, true);
327				if (!conversation.getMucOptions().online()) {
328					if (password != null) {
329						conversation.getMucOptions().setPassword(password);
330						mXmppConnectionService.databaseBackend
331								.updateConversation(conversation);
332					}
333					mXmppConnectionService.joinMuc(conversation);
334					mXmppConnectionService.updateConversationUi();
335				}
336			}
337		}
338	}
339
340	private void parseEvent(final Element event, final Jid from, final Account account) {
341		Element items = event.findChild("items");
342		if (items == null) {
343			return;
344		}
345		String node = items.getAttribute("node");
346		if (node == null) {
347			return;
348		}
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	private String getPgpBody(Element message) {
397		Element child = message.findChild("x", "jabber:x:encrypted");
398		if (child == null) {
399			return null;
400		} else {
401			return child.getContent();
402		}
403	}
404
405	private boolean isMarkable(Element message) {
406		return message.hasChild("markable", "urn:xmpp:chat-markers:0");
407	}
408
409	@Override
410	public void onMessagePacketReceived(Account account, MessagePacket packet) {
411		Message message = null;
412		this.parseNick(packet, account);
413
414		if ((packet.getType() == MessagePacket.TYPE_CHAT || packet.getType() == MessagePacket.TYPE_NORMAL)) {
415			if ((packet.getBody() != null)
416					&& (packet.getBody().startsWith("?OTR"))) {
417				message = this.parseOtrChat(packet, account);
418				if (message != null) {
419					message.markUnread();
420				}
421			} else if (packet.hasChild("body")
422					&& !(packet.hasChild("x",
423					"http://jabber.org/protocol/muc#user"))) {
424				message = this.parseChat(packet, account);
425				if (message != null) {
426					message.markUnread();
427				}
428			} else if (packet.hasChild("received", "urn:xmpp:carbons:2")
429					|| (packet.hasChild("sent", "urn:xmpp:carbons:2"))) {
430				message = this.parseCarbonMessage(packet, account);
431				if (message != null) {
432					if (message.getStatus() == Message.STATUS_SEND) {
433						account.activateGracePeriod();
434						mXmppConnectionService.markRead(
435								message.getConversation(), false);
436					} else {
437						message.markUnread();
438					}
439				}
440			} else {
441				parseNonMessage(packet, account);
442			}
443		} else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
444			message = this.parseGroupchat(packet, account);
445			if (message != null) {
446				if (message.getStatus() == Message.STATUS_RECEIVED) {
447					message.markUnread();
448				} else {
449					mXmppConnectionService.markRead(message.getConversation(),
450							false);
451					account.activateGracePeriod();
452				}
453			}
454		} else if (packet.getType() == MessagePacket.TYPE_ERROR) {
455			this.parseError(packet, account);
456			return;
457		} else if (packet.getType() == MessagePacket.TYPE_HEADLINE) {
458			this.parseHeadline(packet, account);
459			return;
460		}
461		if ((message == null) || (message.getBody() == null)) {
462			return;
463		}
464		if ((mXmppConnectionService.confirmMessages())
465				&& ((packet.getId() != null))) {
466			if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
467				MessagePacket receipt = mXmppConnectionService
468						.getMessageGenerator().received(account, packet,
469								"urn:xmpp:chat-markers:0");
470				mXmppConnectionService.sendMessagePacket(account, receipt);
471			}
472			if (packet.hasChild("request", "urn:xmpp:receipts")) {
473				MessagePacket receipt = mXmppConnectionService
474						.getMessageGenerator().received(account, packet,
475								"urn:xmpp:receipts");
476				mXmppConnectionService.sendMessagePacket(account, receipt);
477			}
478		}
479		Conversation conversation = message.getConversation();
480		conversation.add(message);
481
482		if (message.getStatus() == Message.STATUS_RECEIVED
483				&& conversation.getOtrSession() != null
484				&& !conversation.getOtrSession().getSessionID().getUserID()
485				.equals(message.getCounterpart().getResourcepart())) {
486			Log.d(Config.LOGTAG, "ending because of reasons");
487			conversation.endOtrIfNeeded();
488		}
489
490		if (packet.getType() != MessagePacket.TYPE_ERROR) {
491			if (message.getEncryption() == Message.ENCRYPTION_NONE
492					|| mXmppConnectionService.saveEncryptedMessages()) {
493				mXmppConnectionService.databaseBackend.createMessage(message);
494			}
495		}
496		if (message.trusted() && message.bodyContainsDownloadable()) {
497			this.mXmppConnectionService.getHttpConnectionManager()
498					.createNewConnection(message);
499		} else {
500			mXmppConnectionService.getNotificationService().push(message);
501		}
502		mXmppConnectionService.updateConversationUi();
503	}
504
505	private void parseHeadline(MessagePacket packet, Account account) {
506		if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
507			Element event = packet.findChild("event",
508					"http://jabber.org/protocol/pubsub#event");
509			parseEvent(event, packet.getFrom(), account);
510		}
511	}
512
513	private void parseNick(MessagePacket packet, Account account) {
514		Element nick = packet.findChild("nick",
515				"http://jabber.org/protocol/nick");
516		if (nick != null) {
517			if (packet.getFrom() != null) {
518				Contact contact = account.getRoster().getContact(
519						packet.getFrom());
520				contact.setPresenceName(nick.getContent());
521			}
522		}
523	}
524}