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(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			Message finishedMessage = new Message(conversation, body, Message.ENCRYPTION_OTR,
117					Message.STATUS_RECEIVED);
118			finishedMessage.setTime(getTimestamp(packet));
119			finishedMessage.setRemoteMsgId(packet.getId());
120			finishedMessage.markable = isMarkable(packet);
121			finishedMessage.setCounterpart(from);
122			return finishedMessage;
123		} catch (Exception e) {
124			String receivedId = packet.getId();
125			if (receivedId != null) {
126				mXmppConnectionService.replyWithNotAcceptable(account, packet);
127			}
128			conversation.resetOtrSession();
129			return null;
130		}
131	}
132
133	private Message parseGroupchat(MessagePacket packet, Account account) {
134		int status;
135        final Jid from = packet.getFrom();
136		if (mXmppConnectionService.find(account.pendingConferenceLeaves,
137				account, from.toBareJid()) != null) {
138			return null;
139		}
140		Conversation conversation = mXmppConnectionService
141				.findOrCreateConversation(account, from.toBareJid(), true);
142		if (packet.hasChild("subject")) {
143			conversation.getMucOptions().setSubject(
144					packet.findChild("subject").getContent());
145			mXmppConnectionService.updateConversationUi();
146			return null;
147		}
148		if (from.isBareJid()) {
149			return null;
150		}
151		if (from.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
152			if (mXmppConnectionService.markMessage(conversation,
153					packet.getId(), Message.STATUS_SEND)) {
154				return null;
155			} else {
156				status = Message.STATUS_SEND;
157			}
158		} else {
159			status = Message.STATUS_RECEIVED;
160		}
161		String pgpBody = getPgpBody(packet);
162		Message finishedMessage;
163		if (pgpBody == null) {
164			finishedMessage = new Message(conversation,
165					packet.getBody(), Message.ENCRYPTION_NONE, status);
166		} else {
167			finishedMessage = new Message(conversation, pgpBody,
168					Message.ENCRYPTION_PGP, status);
169		}
170		finishedMessage.setRemoteMsgId(packet.getId());
171		finishedMessage.markable = isMarkable(packet);
172		finishedMessage.setCounterpart(from);
173		if (status == Message.STATUS_RECEIVED) {
174			finishedMessage.setTrueCounterpart(conversation.getMucOptions()
175					.getTrueCounterpart(from.getResourcepart()));
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(final MessagePacket packet, final Account account) {
186		int status;
187		final Jid fullJid;
188		Element forwarded;
189		if (packet.hasChild("received", "urn:xmpp:carbons:2")) {
190			forwarded = packet.findChild("received", "urn:xmpp:carbons:2")
191					.findChild("forwarded", "urn:xmpp:forward:0");
192			status = Message.STATUS_RECEIVED;
193		} else if (packet.hasChild("sent", "urn:xmpp:carbons:2")) {
194			forwarded = packet.findChild("sent", "urn:xmpp:carbons:2")
195					.findChild("forwarded", "urn:xmpp:forward:0");
196			status = Message.STATUS_SEND;
197		} else {
198			return null;
199		}
200		if (forwarded == null) {
201			return null;
202		}
203		Element message = forwarded.findChild("message");
204		if (message == null) {
205			return null;
206		}
207		if (!message.hasChild("body")) {
208			if (status == Message.STATUS_RECEIVED
209					&& message.getAttribute("from") != null) {
210				parseNonMessage(message, account);
211			} else if (status == Message.STATUS_SEND
212					&& message.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
213				final Jid to = message.getAttributeAsJid("to");
214				if (to != null) {
215					final Conversation conversation = mXmppConnectionService.find(
216							mXmppConnectionService.getConversations(), account,
217							to.toBareJid());
218					if (conversation != null) {
219						mXmppConnectionService.markRead(conversation, false);
220					}
221				}
222			}
223			return null;
224		}
225		if (status == Message.STATUS_RECEIVED) {
226			fullJid = message.getAttributeAsJid("from");
227			if (fullJid == null) {
228				return null;
229			} else {
230				updateLastseen(message, account, true);
231			}
232		} else {
233			fullJid = message.getAttributeAsJid("to");
234			if (fullJid == null) {
235				return null;
236			}
237		}
238		Conversation conversation = mXmppConnectionService
239				.findOrCreateConversation(account, fullJid.toBareJid(), false);
240		String pgpBody = getPgpBody(message);
241		Message finishedMessage;
242		if (pgpBody != null) {
243			finishedMessage = new Message(conversation, pgpBody,
244					Message.ENCRYPTION_PGP, status);
245		} else {
246			String body = message.findChild("body").getContent();
247			finishedMessage = new Message(conversation, body,
248					Message.ENCRYPTION_NONE, status);
249		}
250		finishedMessage.setTime(getTimestamp(message));
251		finishedMessage.setRemoteMsgId(message.getAttribute("id"));
252		finishedMessage.markable = isMarkable(message);
253		finishedMessage.setCounterpart(fullJid);
254		if (conversation.getMode() == Conversation.MODE_MULTI
255				&& !fullJid.isBareJid()) {
256			finishedMessage.setType(Message.TYPE_PRIVATE);
257			finishedMessage.setTrueCounterpart(conversation.getMucOptions()
258					.getTrueCounterpart(fullJid.getResourcepart()));
259			if (conversation.hasDuplicateMessage(finishedMessage)) {
260				return null;
261			}
262		}
263		return finishedMessage;
264	}
265
266	private void parseError(final MessagePacket packet, final Account account) {
267		final Jid from = packet.getFrom();
268		mXmppConnectionService.markMessage(account, from.toBareJid(),
269				packet.getId(), Message.STATUS_SEND_FAILED);
270	}
271
272	private void parseNonMessage(Element packet, Account account) {
273		final Jid from = packet.getAttributeAsJid("from");
274		if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
275			Element event = packet.findChild("event",
276					"http://jabber.org/protocol/pubsub#event");
277			parseEvent(event, from, account);
278		} else if (from != null
279				&& packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
280			String id = packet
281					.findChild("displayed", "urn:xmpp:chat-markers:0")
282					.getAttribute("id");
283			updateLastseen(packet, account, true);
284			mXmppConnectionService.markMessage(account, from.toBareJid(),
285					id, Message.STATUS_SEND_DISPLAYED);
286		} else if (from != null
287				&& packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
288			String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
289					.getAttribute("id");
290			updateLastseen(packet, account, false);
291			mXmppConnectionService.markMessage(account, from.toBareJid(),
292					id, Message.STATUS_SEND_RECEIVED);
293		} else if (from != null
294				&& packet.hasChild("received", "urn:xmpp:receipts")) {
295			String id = packet.findChild("received", "urn:xmpp:receipts")
296					.getAttribute("id");
297			updateLastseen(packet, account, false);
298			mXmppConnectionService.markMessage(account, from.toBareJid(),
299					id, Message.STATUS_SEND_RECEIVED);
300		} else if (packet.hasChild("x", "http://jabber.org/protocol/muc#user")) {
301			Element x = packet.findChild("x",
302					"http://jabber.org/protocol/muc#user");
303			if (x.hasChild("invite")) {
304				Conversation conversation = mXmppConnectionService
305						.findOrCreateConversation(account,
306								packet.getAttributeAsJid("from"), true);
307				if (!conversation.getMucOptions().online()) {
308					if (x.hasChild("password")) {
309						Element password = x.findChild("password");
310						conversation.getMucOptions().setPassword(
311								password.getContent());
312						mXmppConnectionService.databaseBackend
313								.updateConversation(conversation);
314					}
315					mXmppConnectionService.joinMuc(conversation);
316					mXmppConnectionService.updateConversationUi();
317				}
318			}
319		} else if (packet.hasChild("x", "jabber:x:conference")) {
320			Element x = packet.findChild("x", "jabber:x:conference");
321            Jid jid;
322            try {
323                jid = Jid.fromString(x.getAttribute("jid"));
324            } catch (InvalidJidException e) {
325                jid = null;
326            }
327            String password = x.getAttribute("password");
328			if (jid != null) {
329				Conversation conversation = mXmppConnectionService
330						.findOrCreateConversation(account, jid, true);
331				if (!conversation.getMucOptions().online()) {
332					if (password != null) {
333						conversation.getMucOptions().setPassword(password);
334						mXmppConnectionService.databaseBackend
335								.updateConversation(conversation);
336					}
337					mXmppConnectionService.joinMuc(conversation);
338					mXmppConnectionService.updateConversationUi();
339				}
340			}
341		}
342	}
343
344	private void parseEvent(final Element event, final Jid from, final Account account) {
345		Element items = event.findChild("items");
346		String node = items.getAttribute("node");
347		if (node != null) {
348			if (node.equals("urn:xmpp:avatar:metadata")) {
349				Avatar avatar = Avatar.parseMetadata(items);
350				if (avatar != null) {
351					avatar.owner = from;
352					if (mXmppConnectionService.getFileBackend().isAvatarCached(
353							avatar)) {
354						if (account.getJid().toBareJid().equals(from)) {
355							if (account.setAvatar(avatar.getFilename())) {
356								mXmppConnectionService.databaseBackend
357										.updateAccount(account);
358							}
359							mXmppConnectionService.getAvatarService().clear(
360									account);
361							mXmppConnectionService.updateConversationUi();
362							mXmppConnectionService.updateAccountUi();
363						} else {
364							Contact contact = account.getRoster().getContact(
365									from);
366							contact.setAvatar(avatar.getFilename());
367							mXmppConnectionService.getAvatarService().clear(
368									contact);
369							mXmppConnectionService.updateConversationUi();
370							mXmppConnectionService.updateRosterUi();
371						}
372					} else {
373						mXmppConnectionService.fetchAvatar(account, avatar);
374					}
375				}
376			} else if (node.equals("http://jabber.org/protocol/nick")) {
377				Element item = items.findChild("item");
378				if (item != null) {
379					Element nick = item.findChild("nick",
380							"http://jabber.org/protocol/nick");
381					if (nick != null) {
382						if (from != null) {
383							Contact contact = account.getRoster().getContact(
384									from);
385							contact.setPresenceName(nick.getContent());
386							mXmppConnectionService.getAvatarService().clear(account);
387							mXmppConnectionService.updateConversationUi();
388							mXmppConnectionService.updateAccountUi();
389						}
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}