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