MessageParser.java

  1package eu.siacs.conversations.parser;
  2
  3import net.java.otr4j.session.Session;
  4import net.java.otr4j.session.SessionStatus;
  5
  6import eu.siacs.conversations.entities.Account;
  7import eu.siacs.conversations.entities.Contact;
  8import eu.siacs.conversations.entities.Conversation;
  9import eu.siacs.conversations.entities.Message;
 10import eu.siacs.conversations.entities.MucOptions;
 11import eu.siacs.conversations.http.HttpConnection;
 12import eu.siacs.conversations.http.HttpConnectionManager;
 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		final Jid to = packet.getTo();
 64		final Jid from = packet.getFrom();
 65		if (to == null || from == null) {
 66			return null;
 67		}
 68		boolean properlyAddressed = !to.isBareJid() || account.countPresences() == 1;
 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(packet.findChild("subject").getContent());
146			mXmppConnectionService.updateConversationUi();
147			return null;
148		}
149
150		final Element x = packet.findChild("x", "http://jabber.org/protocol/muc#user");
151		if (from.isBareJid() && (x == null || !x.hasChild("status"))) {
152			return null;
153		} else if (from.isBareJid() && x.hasChild("status")) {
154			for(Element child : x.getChildren()) {
155				if (child.getName().equals("status")) {
156					String code = child.getAttribute("code");
157					if (code.contains(MucOptions.STATUS_CODE_ROOM_CONFIG_CHANGED)) {
158						mXmppConnectionService.fetchConferenceConfiguration(conversation);
159					}
160				}
161			}
162		}
163
164		if (from.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
165			if (mXmppConnectionService.markMessage(conversation,
166					packet.getId(), Message.STATUS_SEND)) {
167				return null;
168			} else if (packet.getId() == null) {
169				Message message = conversation.findSentMessageWithBody(packet.getBody());
170				if (message != null) {
171					mXmppConnectionService.markMessage(message,Message.STATUS_SEND_RECEIVED);
172					return null;
173				} else {
174					status = Message.STATUS_SEND;
175				}
176			} else {
177				status = Message.STATUS_SEND;
178			}
179		} else {
180			status = Message.STATUS_RECEIVED;
181		}
182		String pgpBody = getPgpBody(packet);
183		Message finishedMessage;
184		if (pgpBody == null) {
185			finishedMessage = new Message(conversation,
186					packet.getBody(), Message.ENCRYPTION_NONE, status);
187		} else {
188			finishedMessage = new Message(conversation, pgpBody,
189					Message.ENCRYPTION_PGP, status);
190		}
191		finishedMessage.setRemoteMsgId(packet.getId());
192		finishedMessage.markable = isMarkable(packet);
193		finishedMessage.setCounterpart(from);
194		if (status == Message.STATUS_RECEIVED) {
195			finishedMessage.setTrueCounterpart(conversation.getMucOptions()
196					.getTrueCounterpart(from.getResourcepart()));
197		}
198		if (packet.hasChild("delay")
199				&& conversation.hasDuplicateMessage(finishedMessage)) {
200			return null;
201		}
202		finishedMessage.setTime(getTimestamp(packet));
203		return finishedMessage;
204	}
205
206	private Message parseCarbonMessage(final MessagePacket packet, final Account account) {
207		int status;
208		final Jid fullJid;
209		Element forwarded;
210		if (packet.hasChild("received", "urn:xmpp:carbons:2")) {
211			forwarded = packet.findChild("received", "urn:xmpp:carbons:2")
212					.findChild("forwarded", "urn:xmpp:forward:0");
213			status = Message.STATUS_RECEIVED;
214		} else if (packet.hasChild("sent", "urn:xmpp:carbons:2")) {
215			forwarded = packet.findChild("sent", "urn:xmpp:carbons:2")
216					.findChild("forwarded", "urn:xmpp:forward:0");
217			status = Message.STATUS_SEND;
218		} else {
219			return null;
220		}
221		if (forwarded == null) {
222			return null;
223		}
224		Element message = forwarded.findChild("message");
225		if (message == null) {
226			return null;
227		}
228		if (!message.hasChild("body")) {
229			if (status == Message.STATUS_RECEIVED
230					&& message.getAttribute("from") != null) {
231				parseNonMessage(message, account);
232			} else if (status == Message.STATUS_SEND
233					&& message.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
234				final Jid to = message.getAttributeAsJid("to");
235				if (to != null) {
236					final Conversation conversation = mXmppConnectionService.find(
237							mXmppConnectionService.getConversations(), account,
238							to.toBareJid());
239					if (conversation != null) {
240						mXmppConnectionService.markRead(conversation);
241					}
242				}
243			}
244			return null;
245		}
246		if (status == Message.STATUS_RECEIVED) {
247			fullJid = message.getAttributeAsJid("from");
248			if (fullJid == null) {
249				return null;
250			} else {
251				updateLastseen(message, account, true);
252			}
253		} else {
254			fullJid = message.getAttributeAsJid("to");
255			if (fullJid == null) {
256				return null;
257			}
258		}
259		if (message.hasChild("x","http://jabber.org/protocol/muc#user")
260				&& "chat".equals(message.getAttribute("type"))) {
261			return null;
262		}
263		Conversation conversation = mXmppConnectionService
264				.findOrCreateConversation(account, fullJid.toBareJid(), false);
265		String pgpBody = getPgpBody(message);
266		Message finishedMessage;
267		if (pgpBody != null) {
268			finishedMessage = new Message(conversation, pgpBody,
269					Message.ENCRYPTION_PGP, status);
270		} else {
271			String body = message.findChild("body").getContent();
272			finishedMessage = new Message(conversation, body,
273					Message.ENCRYPTION_NONE, status);
274		}
275		finishedMessage.setTime(getTimestamp(message));
276		finishedMessage.setRemoteMsgId(message.getAttribute("id"));
277		finishedMessage.markable = isMarkable(message);
278		finishedMessage.setCounterpart(fullJid);
279		if (conversation.getMode() == Conversation.MODE_MULTI
280				&& !fullJid.isBareJid()) {
281			finishedMessage.setType(Message.TYPE_PRIVATE);
282			finishedMessage.setTrueCounterpart(conversation.getMucOptions()
283					.getTrueCounterpart(fullJid.getResourcepart()));
284			if (conversation.hasDuplicateMessage(finishedMessage)) {
285				return null;
286			}
287		}
288		return finishedMessage;
289	}
290
291	private Message parseMamMessage(MessagePacket packet, final Account account) {
292		final Element result = packet.findChild("result","urn:xmpp:mam:0");
293		if (result == null ) {
294			return null;
295		}
296		final MessageArchiveService.Query query = this.mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
297		if (query!=null) {
298			query.incrementTotalCount();
299		}
300		final Element forwarded = result.findChild("forwarded","urn:xmpp:forward:0");
301		if (forwarded == null) {
302			return null;
303		}
304		final Element message = forwarded.findChild("message");
305		if (message == null) {
306			return null;
307		}
308		final Element body = message.findChild("body");
309		if (body == null || message.hasChild("private","urn:xmpp:carbons:2") || message.hasChild("no-copy","urn:xmpp:hints")) {
310			return null;
311		}
312		int encryption;
313		String content = getPgpBody(message);
314		if (content != null) {
315			encryption = Message.ENCRYPTION_PGP;
316		} else {
317			encryption = Message.ENCRYPTION_NONE;
318			content = body.getContent();
319		}
320		if (content == null) {
321			return null;
322		}
323		final long timestamp = getTimestamp(forwarded);
324		final Jid to = message.getAttributeAsJid("to");
325		final Jid from = message.getAttributeAsJid("from");
326		Jid counterpart;
327		int status;
328		Conversation conversation;
329		if (from!=null && to != null && from.toBareJid().equals(account.getJid().toBareJid())) {
330			status = Message.STATUS_SEND;
331			conversation = this.mXmppConnectionService.findOrCreateConversation(account,to.toBareJid(),false,query);
332			counterpart = to;
333		} else if (from !=null && to != null) {
334			status = Message.STATUS_RECEIVED;
335			conversation = this.mXmppConnectionService.findOrCreateConversation(account,from.toBareJid(),false,query);
336			counterpart = from;
337		} else {
338			return null;
339		}
340		Message finishedMessage = new Message(conversation,content,encryption,status);
341		finishedMessage.setTime(timestamp);
342		finishedMessage.setCounterpart(counterpart);
343		finishedMessage.setRemoteMsgId(message.getAttribute("id"));
344		finishedMessage.setServerMsgId(result.getAttribute("id"));
345		if (conversation.hasDuplicateMessage(finishedMessage)) {
346			return null;
347		}
348		if (query!=null) {
349			query.incrementMessageCount();
350		}
351		return finishedMessage;
352	}
353
354	private void parseError(final MessagePacket packet, final Account account) {
355		final Jid from = packet.getFrom();
356		mXmppConnectionService.markMessage(account, from.toBareJid(),
357				packet.getId(), Message.STATUS_SEND_FAILED);
358	}
359
360	private void parseNonMessage(Element packet, Account account) {
361		final Jid from = packet.getAttributeAsJid("from");
362		Element invite = extractInvite(packet);
363		if (invite != null) {
364			Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, from, true);
365			if (!conversation.getMucOptions().online()) {
366				Element password = invite.findChild("password");
367				conversation.getMucOptions().setPassword(password == null ? null : password.getContent());
368				mXmppConnectionService.databaseBackend.updateConversation(conversation);
369				mXmppConnectionService.joinMuc(conversation);
370				mXmppConnectionService.updateConversationUi();
371			}
372		}
373		if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
374			Element event = packet.findChild("event",
375					"http://jabber.org/protocol/pubsub#event");
376			parseEvent(event, from, account);
377		} else if (from != null
378				&& packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
379			String id = packet
380					.findChild("displayed", "urn:xmpp:chat-markers:0")
381					.getAttribute("id");
382			updateLastseen(packet, account, true);
383			mXmppConnectionService.markMessage(account, from.toBareJid(),
384					id, Message.STATUS_SEND_DISPLAYED);
385		} else if (from != null
386				&& packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
387			String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
388					.getAttribute("id");
389			updateLastseen(packet, account, false);
390			mXmppConnectionService.markMessage(account, from.toBareJid(),
391					id, Message.STATUS_SEND_RECEIVED);
392		} else if (from != null
393				&& packet.hasChild("received", "urn:xmpp:receipts")) {
394			String id = packet.findChild("received", "urn:xmpp:receipts")
395					.getAttribute("id");
396			updateLastseen(packet, account, false);
397			mXmppConnectionService.markMessage(account, from.toBareJid(),
398					id, Message.STATUS_SEND_RECEIVED);
399		}
400	}
401
402	private Element extractInvite(Element message) {
403		Element x = message.findChild("x","http://jabber.org/protocol/muc#user");
404		if (x == null) {
405			x = message.findChild("x","jabber:x:conference");
406		}
407		if (x != null && x.hasChild("invite")) {
408			return x;
409		} else {
410			return null;
411		}
412	}
413
414	private void parseEvent(final Element event, final Jid from, final Account account) {
415		Element items = event.findChild("items");
416		if (items == null) {
417			return;
418		}
419		String node = items.getAttribute("node");
420		if (node == null) {
421			return;
422		}
423		if (node.equals("urn:xmpp:avatar:metadata")) {
424			Avatar avatar = Avatar.parseMetadata(items);
425			if (avatar != null) {
426				avatar.owner = from;
427				if (mXmppConnectionService.getFileBackend().isAvatarCached(
428						avatar)) {
429					if (account.getJid().toBareJid().equals(from)) {
430						if (account.setAvatar(avatar.getFilename())) {
431							mXmppConnectionService.databaseBackend
432									.updateAccount(account);
433						}
434						mXmppConnectionService.getAvatarService().clear(
435								account);
436						mXmppConnectionService.updateConversationUi();
437						mXmppConnectionService.updateAccountUi();
438					} else {
439						Contact contact = account.getRoster().getContact(
440								from);
441						contact.setAvatar(avatar.getFilename());
442						mXmppConnectionService.getAvatarService().clear(
443								contact);
444						mXmppConnectionService.updateConversationUi();
445						mXmppConnectionService.updateRosterUi();
446					}
447				} else {
448					mXmppConnectionService.fetchAvatar(account, avatar);
449				}
450			}
451		} else if (node.equals("http://jabber.org/protocol/nick")) {
452			Element item = items.findChild("item");
453			if (item != null) {
454				Element nick = item.findChild("nick",
455						"http://jabber.org/protocol/nick");
456				if (nick != null) {
457					if (from != null) {
458						Contact contact = account.getRoster().getContact(
459								from);
460						contact.setPresenceName(nick.getContent());
461						mXmppConnectionService.getAvatarService().clear(account);
462						mXmppConnectionService.updateConversationUi();
463						mXmppConnectionService.updateAccountUi();
464					}
465				}
466			}
467		}
468	}
469
470	private String getPgpBody(Element message) {
471		Element child = message.findChild("x", "jabber:x:encrypted");
472		if (child == null) {
473			return null;
474		} else {
475			return child.getContent();
476		}
477	}
478
479	private boolean isMarkable(Element message) {
480		return message.hasChild("markable", "urn:xmpp:chat-markers:0");
481	}
482
483	@Override
484	public void onMessagePacketReceived(Account account, MessagePacket packet) {
485		Message message = null;
486		this.parseNick(packet, account);
487		if ((packet.getType() == MessagePacket.TYPE_CHAT || packet.getType() == MessagePacket.TYPE_NORMAL)) {
488			if ((packet.getBody() != null)
489					&& (packet.getBody().startsWith("?OTR"))) {
490				message = this.parseOtrChat(packet, account);
491				if (message != null) {
492					message.markUnread();
493				}
494			} else if (packet.hasChild("body") && extractInvite(packet) == null) {
495				message = this.parseChat(packet, account);
496				if (message != null) {
497					message.markUnread();
498				}
499			} else if (packet.hasChild("received", "urn:xmpp:carbons:2")
500					|| (packet.hasChild("sent", "urn:xmpp:carbons:2"))) {
501				message = this.parseCarbonMessage(packet, account);
502				if (message != null) {
503					if (message.getStatus() == Message.STATUS_SEND) {
504						account.activateGracePeriod();
505						mXmppConnectionService.markRead(message.getConversation());
506					} else {
507						message.markUnread();
508					}
509				}
510			} else if (packet.hasChild("result","urn:xmpp:mam:0")) {
511				message = parseMamMessage(packet, account);
512				if (message != null) {
513					Conversation conversation = message.getConversation();
514					conversation.add(message);
515					mXmppConnectionService.databaseBackend.createMessage(message);
516				}
517				return;
518			} else if (packet.hasChild("fin","urn:xmpp:mam:0")) {
519				Element fin = packet.findChild("fin","urn:xmpp:mam:0");
520				mXmppConnectionService.getMessageArchiveService().processFin(fin);
521			} else {
522				parseNonMessage(packet, account);
523			}
524		} else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
525			message = this.parseGroupchat(packet, account);
526			if (message != null) {
527				if (message.getStatus() == Message.STATUS_RECEIVED) {
528					message.markUnread();
529				} else {
530					mXmppConnectionService.markRead(message.getConversation());
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		final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
581		if (message.trusted() && message.bodyContainsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
582			manager.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}