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