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