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.MessageArchiveService;
 14import eu.siacs.conversations.services.XmppConnectionService;
 15import eu.siacs.conversations.utils.CryptoHelper;
 16import eu.siacs.conversations.xml.Element;
 17import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 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			conversation.resetOtrSession();
128			return null;
129		}
130	}
131
132	private Message parseGroupchat(MessagePacket packet, Account account) {
133		int status;
134        final Jid from = packet.getFrom();
135		if (from == null) {
136			return null;
137		}
138		if (mXmppConnectionService.find(account.pendingConferenceLeaves,
139				account, from.toBareJid()) != null) {
140			return null;
141		}
142		Conversation conversation = mXmppConnectionService
143				.findOrCreateConversation(account, from.toBareJid(), true);
144		if (packet.hasChild("subject")) {
145			conversation.getMucOptions().setSubject(
146					packet.findChild("subject").getContent());
147			mXmppConnectionService.updateConversationUi();
148			return null;
149		}
150		if (from.isBareJid()) {
151			return null;
152		}
153		if (from.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
154			if (mXmppConnectionService.markMessage(conversation,
155					packet.getId(), Message.STATUS_SEND)) {
156				return null;
157			} else if (packet.getId() == null) {
158				Message message = conversation.findSentMessageWithBody(packet.getBody());
159				if (message != null) {
160					mXmppConnectionService.markMessage(message,Message.STATUS_SEND_RECEIVED);
161					return null;
162				} else {
163					status = Message.STATUS_SEND;
164				}
165			} else {
166				status = Message.STATUS_SEND;
167			}
168		} else {
169			status = Message.STATUS_RECEIVED;
170		}
171		String pgpBody = getPgpBody(packet);
172		Message finishedMessage;
173		if (pgpBody == null) {
174			finishedMessage = new Message(conversation,
175					packet.getBody(), Message.ENCRYPTION_NONE, status);
176		} else {
177			finishedMessage = new Message(conversation, pgpBody,
178					Message.ENCRYPTION_PGP, status);
179		}
180		finishedMessage.setRemoteMsgId(packet.getId());
181		finishedMessage.markable = isMarkable(packet);
182		finishedMessage.setCounterpart(from);
183		if (status == Message.STATUS_RECEIVED) {
184			finishedMessage.setTrueCounterpart(conversation.getMucOptions()
185					.getTrueCounterpart(from.getResourcepart()));
186		}
187		if (packet.hasChild("delay")
188				&& conversation.hasDuplicateMessage(finishedMessage)) {
189			return null;
190		}
191		finishedMessage.setTime(getTimestamp(packet));
192		return finishedMessage;
193	}
194
195	private Message parseCarbonMessage(final MessagePacket packet, final Account account) {
196		int status;
197		final Jid fullJid;
198		Element forwarded;
199		if (packet.hasChild("received", "urn:xmpp:carbons:2")) {
200			forwarded = packet.findChild("received", "urn:xmpp:carbons:2")
201					.findChild("forwarded", "urn:xmpp:forward:0");
202			status = Message.STATUS_RECEIVED;
203		} else if (packet.hasChild("sent", "urn:xmpp:carbons:2")) {
204			forwarded = packet.findChild("sent", "urn:xmpp:carbons:2")
205					.findChild("forwarded", "urn:xmpp:forward:0");
206			status = Message.STATUS_SEND;
207		} else {
208			return null;
209		}
210		if (forwarded == null) {
211			return null;
212		}
213		Element message = forwarded.findChild("message");
214		if (message == null) {
215			return null;
216		}
217		if (!message.hasChild("body")) {
218			if (status == Message.STATUS_RECEIVED
219					&& message.getAttribute("from") != null) {
220				parseNonMessage(message, account);
221			} else if (status == Message.STATUS_SEND
222					&& message.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
223				final Jid to = message.getAttributeAsJid("to");
224				if (to != null) {
225					final Conversation conversation = mXmppConnectionService.find(
226							mXmppConnectionService.getConversations(), account,
227							to.toBareJid());
228					if (conversation != null) {
229						mXmppConnectionService.markRead(conversation, false);
230					}
231				}
232			}
233			return null;
234		}
235		if (status == Message.STATUS_RECEIVED) {
236			fullJid = message.getAttributeAsJid("from");
237			if (fullJid == null) {
238				return null;
239			} else {
240				updateLastseen(message, account, true);
241			}
242		} else {
243			fullJid = message.getAttributeAsJid("to");
244			if (fullJid == null) {
245				return null;
246			}
247		}
248		Conversation conversation = mXmppConnectionService
249				.findOrCreateConversation(account, fullJid.toBareJid(), false);
250		String pgpBody = getPgpBody(message);
251		Message finishedMessage;
252		if (pgpBody != null) {
253			finishedMessage = new Message(conversation, pgpBody,
254					Message.ENCRYPTION_PGP, status);
255		} else {
256			String body = message.findChild("body").getContent();
257			finishedMessage = new Message(conversation, body,
258					Message.ENCRYPTION_NONE, status);
259		}
260		finishedMessage.setTime(getTimestamp(message));
261		finishedMessage.setRemoteMsgId(message.getAttribute("id"));
262		finishedMessage.markable = isMarkable(message);
263		finishedMessage.setCounterpart(fullJid);
264		if (conversation.getMode() == Conversation.MODE_MULTI
265				&& !fullJid.isBareJid()) {
266			finishedMessage.setType(Message.TYPE_PRIVATE);
267			finishedMessage.setTrueCounterpart(conversation.getMucOptions()
268					.getTrueCounterpart(fullJid.getResourcepart()));
269			if (conversation.hasDuplicateMessage(finishedMessage)) {
270				return null;
271			}
272		}
273		return finishedMessage;
274	}
275
276	private Message parseMamMessage(MessagePacket packet, final Account account) {
277		final Element result = packet.findChild("result","urn:xmpp:mam:0");
278		if (result == null ) {
279			return null;
280		}
281		final Element forwarded = result.findChild("forwarded","urn:xmpp:forward:0");
282		if (forwarded == null) {
283			return null;
284		}
285		final Element message = forwarded.findChild("message");
286		if (message == null) {
287			return null;
288		}
289		final Element body = message.findChild("body");
290		if (body == null || message.hasChild("private","urn:xmpp:carbons:2") || message.hasChild("no-copy","urn:xmpp:hints")) {
291			return null;
292		}
293		int encryption;
294		String content = getPgpBody(message);
295		if (content != null) {
296			encryption = Message.ENCRYPTION_PGP;
297		} else {
298			encryption = Message.ENCRYPTION_NONE;
299			content = body.getContent();
300		}
301		if (content == null) {
302			return null;
303		}
304		final long timestamp = getTimestamp(forwarded);
305		final Jid to = message.getAttributeAsJid("to");
306		final Jid from = message.getAttributeAsJid("from");
307		final MessageArchiveService.Query query = this.mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
308		Jid counterpart;
309		int status;
310		Conversation conversation;
311		if (from!=null && to != null && from.toBareJid().equals(account.getJid().toBareJid())) {
312			status = Message.STATUS_SEND;
313			conversation = this.mXmppConnectionService.findOrCreateConversation(account,to.toBareJid(),false,query);
314			counterpart = to;
315		} else if (from !=null && to != null) {
316			status = Message.STATUS_RECEIVED;
317			conversation = this.mXmppConnectionService.findOrCreateConversation(account,from.toBareJid(),false,query);
318			counterpart = from;
319		} else {
320			return null;
321		}
322		Message finishedMessage = new Message(conversation,content,encryption,status);
323		finishedMessage.setTime(timestamp);
324		finishedMessage.setCounterpart(counterpart);
325		finishedMessage.setRemoteMsgId(message.getAttribute("id"));
326		finishedMessage.setServerMsgId(result.getAttribute("id"));
327		if (conversation.hasDuplicateMessage(finishedMessage)) {
328			Log.d(Config.LOGTAG, "received mam message " + content+ " (duplicate)");
329			return null;
330		} else {
331			Log.d(Config.LOGTAG, "received mam message " + content);
332		}
333		return finishedMessage;
334	}
335
336	private void parseError(final MessagePacket packet, final Account account) {
337		final Jid from = packet.getFrom();
338		mXmppConnectionService.markMessage(account, from.toBareJid(),
339				packet.getId(), Message.STATUS_SEND_FAILED);
340	}
341
342	private void parseNonMessage(Element packet, Account account) {
343		final Jid from = packet.getAttributeAsJid("from");
344		if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
345			Element event = packet.findChild("event",
346					"http://jabber.org/protocol/pubsub#event");
347			parseEvent(event, from, account);
348		} else if (from != null
349				&& packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
350			String id = packet
351					.findChild("displayed", "urn:xmpp:chat-markers:0")
352					.getAttribute("id");
353			updateLastseen(packet, account, true);
354			mXmppConnectionService.markMessage(account, from.toBareJid(),
355					id, Message.STATUS_SEND_DISPLAYED);
356		} else if (from != null
357				&& packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
358			String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
359					.getAttribute("id");
360			updateLastseen(packet, account, false);
361			mXmppConnectionService.markMessage(account, from.toBareJid(),
362					id, Message.STATUS_SEND_RECEIVED);
363		} else if (from != null
364				&& packet.hasChild("received", "urn:xmpp:receipts")) {
365			String id = packet.findChild("received", "urn:xmpp:receipts")
366					.getAttribute("id");
367			updateLastseen(packet, account, false);
368			mXmppConnectionService.markMessage(account, from.toBareJid(),
369					id, Message.STATUS_SEND_RECEIVED);
370		} else if (packet.hasChild("x", "http://jabber.org/protocol/muc#user")) {
371			Element x = packet.findChild("x",
372					"http://jabber.org/protocol/muc#user");
373			if (x.hasChild("invite")) {
374				Conversation conversation = mXmppConnectionService
375						.findOrCreateConversation(account,
376								packet.getAttributeAsJid("from"), true);
377				if (!conversation.getMucOptions().online()) {
378					if (x.hasChild("password")) {
379						Element password = x.findChild("password");
380						conversation.getMucOptions().setPassword(
381								password.getContent());
382						mXmppConnectionService.databaseBackend
383								.updateConversation(conversation);
384					}
385					mXmppConnectionService.joinMuc(conversation);
386					mXmppConnectionService.updateConversationUi();
387				}
388			}
389		} else if (packet.hasChild("x", "jabber:x:conference")) {
390			Element x = packet.findChild("x", "jabber:x:conference");
391            Jid jid = x.getAttributeAsJid("jid");
392            String password = x.getAttribute("password");
393			if (jid != null) {
394				Conversation conversation = mXmppConnectionService
395						.findOrCreateConversation(account, jid, true);
396				if (!conversation.getMucOptions().online()) {
397					if (password != null) {
398						conversation.getMucOptions().setPassword(password);
399						mXmppConnectionService.databaseBackend
400								.updateConversation(conversation);
401					}
402					mXmppConnectionService.joinMuc(conversation);
403					mXmppConnectionService.updateConversationUi();
404				}
405			}
406		}
407	}
408
409	private void parseEvent(final Element event, final Jid from, final Account account) {
410		Element items = event.findChild("items");
411		if (items == null) {
412			return;
413		}
414		String node = items.getAttribute("node");
415		if (node == null) {
416			return;
417		}
418		if (node.equals("urn:xmpp:avatar:metadata")) {
419			Avatar avatar = Avatar.parseMetadata(items);
420			if (avatar != null) {
421				avatar.owner = from;
422				if (mXmppConnectionService.getFileBackend().isAvatarCached(
423						avatar)) {
424					if (account.getJid().toBareJid().equals(from)) {
425						if (account.setAvatar(avatar.getFilename())) {
426							mXmppConnectionService.databaseBackend
427									.updateAccount(account);
428						}
429						mXmppConnectionService.getAvatarService().clear(
430								account);
431						mXmppConnectionService.updateConversationUi();
432						mXmppConnectionService.updateAccountUi();
433					} else {
434						Contact contact = account.getRoster().getContact(
435								from);
436						contact.setAvatar(avatar.getFilename());
437						mXmppConnectionService.getAvatarService().clear(
438								contact);
439						mXmppConnectionService.updateConversationUi();
440						mXmppConnectionService.updateRosterUi();
441					}
442				} else {
443					mXmppConnectionService.fetchAvatar(account, avatar);
444				}
445			}
446		} else if (node.equals("http://jabber.org/protocol/nick")) {
447			Element item = items.findChild("item");
448			if (item != null) {
449				Element nick = item.findChild("nick",
450						"http://jabber.org/protocol/nick");
451				if (nick != null) {
452					if (from != null) {
453						Contact contact = account.getRoster().getContact(
454								from);
455						contact.setPresenceName(nick.getContent());
456						mXmppConnectionService.getAvatarService().clear(account);
457						mXmppConnectionService.updateConversationUi();
458						mXmppConnectionService.updateAccountUi();
459					}
460				}
461			}
462		}
463	}
464
465	private String getPgpBody(Element message) {
466		Element child = message.findChild("x", "jabber:x:encrypted");
467		if (child == null) {
468			return null;
469		} else {
470			return child.getContent();
471		}
472	}
473
474	private boolean isMarkable(Element message) {
475		return message.hasChild("markable", "urn:xmpp:chat-markers:0");
476	}
477
478	@Override
479	public void onMessagePacketReceived(Account account, MessagePacket packet) {
480		Message message = null;
481		this.parseNick(packet, account);
482
483		if ((packet.getType() == MessagePacket.TYPE_CHAT || packet.getType() == MessagePacket.TYPE_NORMAL)) {
484			if ((packet.getBody() != null)
485					&& (packet.getBody().startsWith("?OTR"))) {
486				message = this.parseOtrChat(packet, account);
487				if (message != null) {
488					message.markUnread();
489				}
490			} else if (packet.hasChild("body")
491					&& !(packet.hasChild("x",
492					"http://jabber.org/protocol/muc#user"))) {
493				message = this.parseChat(packet, account);
494				if (message != null) {
495					message.markUnread();
496				}
497			} else if (packet.hasChild("received", "urn:xmpp:carbons:2")
498					|| (packet.hasChild("sent", "urn:xmpp:carbons:2"))) {
499				message = this.parseCarbonMessage(packet, account);
500				if (message != null) {
501					if (message.getStatus() == Message.STATUS_SEND) {
502						account.activateGracePeriod();
503						mXmppConnectionService.markRead(
504								message.getConversation(), false);
505					} else {
506						message.markUnread();
507					}
508				}
509			} else if (packet.hasChild("result","urn:xmpp:mam:0")) {
510				message = parseMamMessage(packet, account);
511				if (message != null) {
512					Conversation conversation = message.getConversation();
513					conversation.add(message);
514					mXmppConnectionService.databaseBackend.createMessage(message);
515				}
516				return;
517			} else if (packet.hasChild("fin","urn:xmpp:mam:0")) {
518				Element fin = packet.findChild("fin","urn:xmpp:mam:0");
519				mXmppConnectionService.getMessageArchiveService().processFin(fin);
520			} else {
521				parseNonMessage(packet, account);
522			}
523		} else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
524			message = this.parseGroupchat(packet, account);
525			if (message != null) {
526				if (message.getStatus() == Message.STATUS_RECEIVED) {
527					message.markUnread();
528				} else {
529					mXmppConnectionService.markRead(message.getConversation(),
530							false);
531					account.activateGracePeriod();
532				}
533			}
534		} else if (packet.getType() == MessagePacket.TYPE_ERROR) {
535			this.parseError(packet, account);
536			return;
537		} else if (packet.getType() == MessagePacket.TYPE_HEADLINE) {
538			this.parseHeadline(packet, account);
539			return;
540		}
541		if ((message == null) || (message.getBody() == null)) {
542			return;
543		}
544		if ((mXmppConnectionService.confirmMessages())
545				&& ((packet.getId() != null))) {
546			if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
547				MessagePacket receipt = mXmppConnectionService
548						.getMessageGenerator().received(account, packet,
549								"urn:xmpp:chat-markers:0");
550				mXmppConnectionService.sendMessagePacket(account, receipt);
551			}
552			if (packet.hasChild("request", "urn:xmpp:receipts")) {
553				MessagePacket receipt = mXmppConnectionService
554						.getMessageGenerator().received(account, packet,
555								"urn:xmpp:receipts");
556				mXmppConnectionService.sendMessagePacket(account, receipt);
557			}
558		}
559		Conversation conversation = message.getConversation();
560		conversation.add(message);
561		if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
562			if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
563				mXmppConnectionService.updateConversation(conversation);
564			}
565		}
566
567		if (message.getStatus() == Message.STATUS_RECEIVED
568				&& conversation.getOtrSession() != null
569				&& !conversation.getOtrSession().getSessionID().getUserID()
570				.equals(message.getCounterpart().getResourcepart())) {
571			conversation.endOtrIfNeeded();
572		}
573
574		if (packet.getType() != MessagePacket.TYPE_ERROR) {
575			if (message.getEncryption() == Message.ENCRYPTION_NONE
576					|| mXmppConnectionService.saveEncryptedMessages()) {
577				mXmppConnectionService.databaseBackend.createMessage(message);
578			}
579		}
580		if (message.trusted() && message.bodyContainsDownloadable()) {
581			this.mXmppConnectionService.getHttpConnectionManager()
582					.createNewConnection(message);
583		} else if (!message.isRead()) {
584			mXmppConnectionService.getNotificationService().push(message);
585		}
586		mXmppConnectionService.updateConversationUi();
587	}
588
589	private void parseHeadline(MessagePacket packet, Account account) {
590		if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
591			Element event = packet.findChild("event",
592					"http://jabber.org/protocol/pubsub#event");
593			parseEvent(event, packet.getFrom(), account);
594		}
595	}
596
597	private void parseNick(MessagePacket packet, Account account) {
598		Element nick = packet.findChild("nick",
599				"http://jabber.org/protocol/nick");
600		if (nick != null) {
601			if (packet.getFrom() != null) {
602				Contact contact = account.getRoster().getContact(
603						packet.getFrom());
604				contact.setPresenceName(nick.getContent());
605			}
606		}
607	}
608}