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.HttpConnectionManager;
 12import eu.siacs.conversations.services.MessageArchiveService;
 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.Jid;
 18import eu.siacs.conversations.xmpp.pep.Avatar;
 19import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 20
 21public class MessageParser extends AbstractParser implements
 22		OnMessagePacketReceived {
 23	public MessageParser(XmppConnectionService service) {
 24		super(service);
 25	}
 26
 27	private Message parseChat(MessagePacket packet, Account account) {
 28        final Jid jid = packet.getFrom();
 29		if (jid == null) {
 30			return null;
 31		}
 32		Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid.toBareJid(), false);
 33		updateLastseen(packet, account, true);
 34		String pgpBody = getPgpBody(packet);
 35		Message finishedMessage;
 36		if (pgpBody != null) {
 37			finishedMessage = new Message(conversation,
 38					pgpBody, Message.ENCRYPTION_PGP, Message.STATUS_RECEIVED);
 39		} else {
 40			finishedMessage = new Message(conversation,
 41					packet.getBody(), Message.ENCRYPTION_NONE,
 42					Message.STATUS_RECEIVED);
 43		}
 44		finishedMessage.setRemoteMsgId(packet.getId());
 45		finishedMessage.markable = isMarkable(packet);
 46		if (conversation.getMode() == Conversation.MODE_MULTI
 47				&& !jid.isBareJid()) {
 48			finishedMessage.setType(Message.TYPE_PRIVATE);
 49			finishedMessage.setTrueCounterpart(conversation.getMucOptions()
 50					.getTrueCounterpart(jid.getResourcepart()));
 51			if (conversation.hasDuplicateMessage(finishedMessage)) {
 52				return null;
 53			}
 54
 55		}
 56		finishedMessage.setCounterpart(jid);
 57		finishedMessage.setTime(getTimestamp(packet));
 58		return finishedMessage;
 59	}
 60
 61	private Message parseOtrChat(MessagePacket packet, Account account) {
 62		final Jid to = packet.getTo();
 63		final Jid from = packet.getFrom();
 64		if (to == null || from == null) {
 65			return null;
 66		}
 67		boolean properlyAddressed = !to.isBareJid() || account.countPresences() == 1;
 68		Conversation conversation = mXmppConnectionService
 69				.findOrCreateConversation(account, from.toBareJid(), false);
 70		String presence;
 71		if (from.isBareJid()) {
 72            presence = "";
 73		} else {
 74			presence = from.getResourcepart();
 75		}
 76		updateLastseen(packet, account, true);
 77		String body = packet.getBody();
 78		if (body.matches("^\\?OTRv\\d{1,2}\\?.*")) {
 79			conversation.endOtrIfNeeded();
 80		}
 81		if (!conversation.hasValidOtrSession()) {
 82			if (properlyAddressed) {
 83				conversation.startOtrSession(presence,false);
 84			} else {
 85				return null;
 86			}
 87		} else {
 88			String foreignPresence = conversation.getOtrSession()
 89					.getSessionID().getUserID();
 90			if (!foreignPresence.equals(presence)) {
 91				conversation.endOtrIfNeeded();
 92				if (properlyAddressed) {
 93					conversation.startOtrSession(presence, false);
 94				} else {
 95					return null;
 96				}
 97			}
 98		}
 99		try {
100			Session otrSession = conversation.getOtrSession();
101			SessionStatus before = otrSession.getSessionStatus();
102			body = otrSession.transformReceiving(body);
103			SessionStatus after = otrSession.getSessionStatus();
104			if ((before != after) && (after == SessionStatus.ENCRYPTED)) {
105				conversation.setNextEncryption(Message.ENCRYPTION_OTR);
106				mXmppConnectionService.onOtrSessionEstablished(conversation);
107			} else if ((before != after) && (after == SessionStatus.FINISHED)) {
108				conversation.setNextEncryption(Message.ENCRYPTION_NONE);
109				conversation.resetOtrSession();
110				mXmppConnectionService.updateConversationUi();
111			}
112			if ((body == null) || (body.isEmpty())) {
113				return null;
114			}
115			if (body.startsWith(CryptoHelper.FILETRANSFER)) {
116				String key = body.substring(CryptoHelper.FILETRANSFER.length());
117				conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
118				return null;
119			}
120			Message finishedMessage = new Message(conversation, body, Message.ENCRYPTION_OTR,
121					Message.STATUS_RECEIVED);
122			finishedMessage.setTime(getTimestamp(packet));
123			finishedMessage.setRemoteMsgId(packet.getId());
124			finishedMessage.markable = isMarkable(packet);
125			finishedMessage.setCounterpart(from);
126			return finishedMessage;
127		} catch (Exception e) {
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 (from == null) {
137			return null;
138		}
139		if (mXmppConnectionService.find(account.pendingConferenceLeaves,
140				account, from.toBareJid()) != null) {
141			return null;
142		}
143		Conversation conversation = mXmppConnectionService
144				.findOrCreateConversation(account, from.toBareJid(), true);
145		if (packet.hasChild("subject")) {
146			conversation.setHasMessagesLeftOnServer(true);
147			conversation.getMucOptions().setSubject(packet.findChild("subject").getContent());
148			mXmppConnectionService.updateConversationUi();
149			return null;
150		}
151
152		final Element x = packet.findChild("x", "http://jabber.org/protocol/muc#user");
153		if (from.isBareJid() && (x == null || !x.hasChild("status"))) {
154			return null;
155		} else if (from.isBareJid() && x.hasChild("status")) {
156			for(Element child : x.getChildren()) {
157				if (child.getName().equals("status")) {
158					String code = child.getAttribute("code");
159					if (code.contains(MucOptions.STATUS_CODE_ROOM_CONFIG_CHANGED)) {
160						mXmppConnectionService.fetchConferenceConfiguration(conversation);
161					}
162				}
163			}
164		}
165
166		if (from.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
167			if (mXmppConnectionService.markMessage(conversation,
168					packet.getId(), Message.STATUS_SEND)) {
169				return null;
170			} else if (packet.getId() == null) {
171				Message message = conversation.findSentMessageWithBody(packet.getBody());
172				if (message != null) {
173					mXmppConnectionService.markMessage(message,Message.STATUS_SEND_RECEIVED);
174					return null;
175				} else {
176					status = Message.STATUS_SEND;
177				}
178			} else {
179				status = Message.STATUS_SEND;
180			}
181		} else {
182			status = Message.STATUS_RECEIVED;
183		}
184		String pgpBody = getPgpBody(packet);
185		Message finishedMessage;
186		if (pgpBody == null) {
187			finishedMessage = new Message(conversation,
188					packet.getBody(), Message.ENCRYPTION_NONE, status);
189		} else {
190			finishedMessage = new Message(conversation, pgpBody,
191					Message.ENCRYPTION_PGP, status);
192		}
193		finishedMessage.setRemoteMsgId(packet.getId());
194		finishedMessage.markable = isMarkable(packet);
195		finishedMessage.setCounterpart(from);
196		if (status == Message.STATUS_RECEIVED) {
197			finishedMessage.setTrueCounterpart(conversation.getMucOptions()
198					.getTrueCounterpart(from.getResourcepart()));
199		}
200		if (packet.hasChild("delay")
201				&& conversation.hasDuplicateMessage(finishedMessage)) {
202			return null;
203		}
204		finishedMessage.setTime(getTimestamp(packet));
205		return finishedMessage;
206	}
207
208	private Message parseCarbonMessage(final MessagePacket packet, final Account account) {
209		int status;
210		final Jid fullJid;
211		Element forwarded;
212		if (packet.hasChild("received", "urn:xmpp:carbons:2")) {
213			forwarded = packet.findChild("received", "urn:xmpp:carbons:2")
214					.findChild("forwarded", "urn:xmpp:forward:0");
215			status = Message.STATUS_RECEIVED;
216		} else if (packet.hasChild("sent", "urn:xmpp:carbons:2")) {
217			forwarded = packet.findChild("sent", "urn:xmpp:carbons:2")
218					.findChild("forwarded", "urn:xmpp:forward:0");
219			status = Message.STATUS_SEND;
220		} else {
221			return null;
222		}
223		if (forwarded == null) {
224			return null;
225		}
226		Element message = forwarded.findChild("message");
227		if (message == null) {
228			return null;
229		}
230		if (!message.hasChild("body")) {
231			if (status == Message.STATUS_RECEIVED
232					&& message.getAttribute("from") != null) {
233				parseNonMessage(message, account);
234			} else if (status == Message.STATUS_SEND
235					&& message.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
236				final Jid to = message.getAttributeAsJid("to");
237				if (to != null) {
238					final Conversation conversation = mXmppConnectionService.find(
239							mXmppConnectionService.getConversations(), account,
240							to.toBareJid());
241					if (conversation != null) {
242						mXmppConnectionService.markRead(conversation);
243					}
244				}
245			}
246			return null;
247		}
248		if (status == Message.STATUS_RECEIVED) {
249			fullJid = message.getAttributeAsJid("from");
250			if (fullJid == null) {
251				return null;
252			} else {
253				updateLastseen(message, account, true);
254			}
255		} else {
256			fullJid = message.getAttributeAsJid("to");
257			if (fullJid == null) {
258				return null;
259			}
260		}
261		if (message.hasChild("x","http://jabber.org/protocol/muc#user")
262				&& "chat".equals(message.getAttribute("type"))) {
263			return null;
264		}
265		Conversation conversation = mXmppConnectionService
266				.findOrCreateConversation(account, fullJid.toBareJid(), false);
267		String pgpBody = getPgpBody(message);
268		Message finishedMessage;
269		if (pgpBody != null) {
270			finishedMessage = new Message(conversation, pgpBody,
271					Message.ENCRYPTION_PGP, status);
272		} else {
273			String body = message.findChild("body").getContent();
274			finishedMessage = new Message(conversation, body,
275					Message.ENCRYPTION_NONE, status);
276		}
277		finishedMessage.setTime(getTimestamp(message));
278		finishedMessage.setRemoteMsgId(message.getAttribute("id"));
279		finishedMessage.markable = isMarkable(message);
280		finishedMessage.setCounterpart(fullJid);
281		if (conversation.getMode() == Conversation.MODE_MULTI
282				&& !fullJid.isBareJid()) {
283			finishedMessage.setType(Message.TYPE_PRIVATE);
284			finishedMessage.setTrueCounterpart(conversation.getMucOptions()
285					.getTrueCounterpart(fullJid.getResourcepart()));
286			if (conversation.hasDuplicateMessage(finishedMessage)) {
287				return null;
288			}
289		}
290		return finishedMessage;
291	}
292
293	private Message parseMamMessage(MessagePacket packet, final Account account) {
294		final Element result = packet.findChild("result","urn:xmpp:mam:0");
295		if (result == null ) {
296			return null;
297		}
298		final MessageArchiveService.Query query = this.mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
299		if (query!=null) {
300			query.incrementTotalCount();
301		}
302		final Element forwarded = result.findChild("forwarded","urn:xmpp:forward:0");
303		if (forwarded == null) {
304			return null;
305		}
306		final Element message = forwarded.findChild("message");
307		if (message == null) {
308			return null;
309		}
310		final Element body = message.findChild("body");
311		if (body == null || message.hasChild("private","urn:xmpp:carbons:2") || message.hasChild("no-copy","urn:xmpp:hints")) {
312			return null;
313		}
314		int encryption;
315		String content = getPgpBody(message);
316		if (content != null) {
317			encryption = Message.ENCRYPTION_PGP;
318		} else {
319			encryption = Message.ENCRYPTION_NONE;
320			content = body.getContent();
321		}
322		if (content == null) {
323			return null;
324		}
325		final long timestamp = getTimestamp(forwarded);
326		final Jid to = message.getAttributeAsJid("to");
327		final Jid from = message.getAttributeAsJid("from");
328		Jid counterpart;
329		int status;
330		Conversation conversation;
331		if (from!=null && to != null && from.toBareJid().equals(account.getJid().toBareJid())) {
332			status = Message.STATUS_SEND;
333			conversation = this.mXmppConnectionService.findOrCreateConversation(account,to.toBareJid(),false,query);
334			counterpart = to;
335		} else if (from !=null && to != null) {
336			status = Message.STATUS_RECEIVED;
337			conversation = this.mXmppConnectionService.findOrCreateConversation(account,from.toBareJid(),false,query);
338			counterpart = from;
339		} else {
340			return null;
341		}
342		Message finishedMessage = new Message(conversation,content,encryption,status);
343		finishedMessage.setTime(timestamp);
344		finishedMessage.setCounterpart(counterpart);
345		finishedMessage.setRemoteMsgId(message.getAttribute("id"));
346		finishedMessage.setServerMsgId(result.getAttribute("id"));
347		if (conversation.hasDuplicateMessage(finishedMessage)) {
348			return null;
349		}
350		if (query!=null) {
351			query.incrementMessageCount();
352		}
353		return finishedMessage;
354	}
355
356	private void parseError(final MessagePacket packet, final Account account) {
357		final Jid from = packet.getFrom();
358		mXmppConnectionService.markMessage(account, from.toBareJid(),
359				packet.getId(), Message.STATUS_SEND_FAILED);
360	}
361
362	private void parseNonMessage(Element packet, Account account) {
363		final Jid from = packet.getAttributeAsJid("from");
364		Element invite = extractInvite(packet);
365		if (invite != null) {
366			Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, from, true);
367			if (!conversation.getMucOptions().online()) {
368				Element password = invite.findChild("password");
369				conversation.getMucOptions().setPassword(password == null ? null : password.getContent());
370				mXmppConnectionService.databaseBackend.updateConversation(conversation);
371				mXmppConnectionService.joinMuc(conversation);
372				mXmppConnectionService.updateConversationUi();
373			}
374		}
375		if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
376			Element event = packet.findChild("event",
377					"http://jabber.org/protocol/pubsub#event");
378			parseEvent(event, from, account);
379		} else if (from != null
380				&& packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
381			String id = packet
382					.findChild("displayed", "urn:xmpp:chat-markers:0")
383					.getAttribute("id");
384			updateLastseen(packet, account, true);
385			mXmppConnectionService.markMessage(account, from.toBareJid(),
386					id, Message.STATUS_SEND_DISPLAYED);
387		} else if (from != null
388				&& packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
389			String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
390					.getAttribute("id");
391			updateLastseen(packet, account, false);
392			mXmppConnectionService.markMessage(account, from.toBareJid(),
393					id, Message.STATUS_SEND_RECEIVED);
394		} else if (from != null
395				&& packet.hasChild("received", "urn:xmpp:receipts")) {
396			String id = packet.findChild("received", "urn:xmpp:receipts")
397					.getAttribute("id");
398			updateLastseen(packet, account, false);
399			mXmppConnectionService.markMessage(account, from.toBareJid(),
400					id, Message.STATUS_SEND_RECEIVED);
401		}
402	}
403
404	private Element extractInvite(Element message) {
405		Element x = message.findChild("x","http://jabber.org/protocol/muc#user");
406		if (x == null) {
407			x = message.findChild("x","jabber:x:conference");
408		}
409		if (x != null && x.hasChild("invite")) {
410			return x;
411		} else {
412			return null;
413		}
414	}
415
416	private void parseEvent(final Element event, final Jid from, final Account account) {
417		Element items = event.findChild("items");
418		if (items == null) {
419			return;
420		}
421		String node = items.getAttribute("node");
422		if (node == null) {
423			return;
424		}
425		if (node.equals("urn:xmpp:avatar:metadata")) {
426			Avatar avatar = Avatar.parseMetadata(items);
427			if (avatar != null) {
428				avatar.owner = from;
429				if (mXmppConnectionService.getFileBackend().isAvatarCached(
430						avatar)) {
431					if (account.getJid().toBareJid().equals(from)) {
432						if (account.setAvatar(avatar.getFilename())) {
433							mXmppConnectionService.databaseBackend
434									.updateAccount(account);
435						}
436						mXmppConnectionService.getAvatarService().clear(
437								account);
438						mXmppConnectionService.updateConversationUi();
439						mXmppConnectionService.updateAccountUi();
440					} else {
441						Contact contact = account.getRoster().getContact(
442								from);
443						contact.setAvatar(avatar.getFilename());
444						mXmppConnectionService.getAvatarService().clear(
445								contact);
446						mXmppConnectionService.updateConversationUi();
447						mXmppConnectionService.updateRosterUi();
448					}
449				} else {
450					mXmppConnectionService.fetchAvatar(account, avatar);
451				}
452			}
453		} else if (node.equals("http://jabber.org/protocol/nick")) {
454			Element item = items.findChild("item");
455			if (item != null) {
456				Element nick = item.findChild("nick",
457						"http://jabber.org/protocol/nick");
458				if (nick != null) {
459					if (from != null) {
460						Contact contact = account.getRoster().getContact(
461								from);
462						contact.setPresenceName(nick.getContent());
463						mXmppConnectionService.getAvatarService().clear(account);
464						mXmppConnectionService.updateConversationUi();
465						mXmppConnectionService.updateAccountUi();
466					}
467				}
468			}
469		}
470	}
471
472	private String getPgpBody(Element message) {
473		Element child = message.findChild("x", "jabber:x:encrypted");
474		if (child == null) {
475			return null;
476		} else {
477			return child.getContent();
478		}
479	}
480
481	private boolean isMarkable(Element message) {
482		return message.hasChild("markable", "urn:xmpp:chat-markers:0");
483	}
484
485	@Override
486	public void onMessagePacketReceived(Account account, MessagePacket packet) {
487		Message message = null;
488		this.parseNick(packet, account);
489		if ((packet.getType() == MessagePacket.TYPE_CHAT || packet.getType() == MessagePacket.TYPE_NORMAL)) {
490			if ((packet.getBody() != null)
491					&& (packet.getBody().startsWith("?OTR"))) {
492				message = this.parseOtrChat(packet, account);
493				if (message != null) {
494					message.markUnread();
495				}
496			} else if (packet.hasChild("body") && extractInvite(packet) == null) {
497				message = this.parseChat(packet, account);
498				if (message != null) {
499					message.markUnread();
500				}
501			} else if (packet.hasChild("received", "urn:xmpp:carbons:2")
502					|| (packet.hasChild("sent", "urn:xmpp:carbons:2"))) {
503				message = this.parseCarbonMessage(packet, account);
504				if (message != null) {
505					if (message.getStatus() == Message.STATUS_SEND) {
506						account.activateGracePeriod();
507						mXmppConnectionService.markRead(message.getConversation());
508					} else {
509						message.markUnread();
510					}
511				}
512			} else if (packet.hasChild("result","urn:xmpp:mam:0")) {
513				message = parseMamMessage(packet, account);
514				if (message != null) {
515					Conversation conversation = message.getConversation();
516					conversation.add(message);
517					mXmppConnectionService.databaseBackend.createMessage(message);
518				}
519				return;
520			} else if (packet.hasChild("fin","urn:xmpp:mam:0")) {
521				Element fin = packet.findChild("fin","urn:xmpp:mam:0");
522				mXmppConnectionService.getMessageArchiveService().processFin(fin);
523			} else {
524				parseNonMessage(packet, account);
525			}
526		} else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
527			message = this.parseGroupchat(packet, account);
528			if (message != null) {
529				if (message.getStatus() == Message.STATUS_RECEIVED) {
530					message.markUnread();
531				} else {
532					mXmppConnectionService.markRead(message.getConversation());
533					account.activateGracePeriod();
534				}
535			}
536		} else if (packet.getType() == MessagePacket.TYPE_ERROR) {
537			this.parseError(packet, account);
538			return;
539		} else if (packet.getType() == MessagePacket.TYPE_HEADLINE) {
540			this.parseHeadline(packet, account);
541			return;
542		}
543		if ((message == null) || (message.getBody() == null)) {
544			return;
545		}
546		if ((mXmppConnectionService.confirmMessages())
547				&& ((packet.getId() != null))) {
548			if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
549				MessagePacket receipt = mXmppConnectionService
550						.getMessageGenerator().received(account, packet,
551								"urn:xmpp:chat-markers:0");
552				mXmppConnectionService.sendMessagePacket(account, receipt);
553			}
554			if (packet.hasChild("request", "urn:xmpp:receipts")) {
555				MessagePacket receipt = mXmppConnectionService
556						.getMessageGenerator().received(account, packet,
557								"urn:xmpp:receipts");
558				mXmppConnectionService.sendMessagePacket(account, receipt);
559			}
560		}
561		Conversation conversation = message.getConversation();
562		conversation.add(message);
563		if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
564			if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
565				mXmppConnectionService.updateConversation(conversation);
566			}
567		}
568
569		if (message.getStatus() == Message.STATUS_RECEIVED
570				&& conversation.getOtrSession() != null
571				&& !conversation.getOtrSession().getSessionID().getUserID()
572				.equals(message.getCounterpart().getResourcepart())) {
573			conversation.endOtrIfNeeded();
574		}
575
576		if (packet.getType() != MessagePacket.TYPE_ERROR) {
577			if (message.getEncryption() == Message.ENCRYPTION_NONE
578					|| mXmppConnectionService.saveEncryptedMessages()) {
579				mXmppConnectionService.databaseBackend.createMessage(message);
580			}
581		}
582		final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
583		if (message.trusted() && message.bodyContainsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
584			manager.createNewConnection(message);
585		} else if (!message.isRead()) {
586			mXmppConnectionService.getNotificationService().push(message);
587		}
588		mXmppConnectionService.updateConversationUi();
589	}
590
591	private void parseHeadline(MessagePacket packet, Account account) {
592		if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
593			Element event = packet.findChild("event",
594					"http://jabber.org/protocol/pubsub#event");
595			parseEvent(event, packet.getFrom(), account);
596		}
597	}
598
599	private void parseNick(MessagePacket packet, Account account) {
600		Element nick = packet.findChild("nick",
601				"http://jabber.org/protocol/nick");
602		if (nick != null) {
603			if (packet.getFrom() != null) {
604				Contact contact = account.getRoster().getContact(
605						packet.getFrom());
606				contact.setPresenceName(nick.getContent());
607			}
608		}
609	}
610}