MessageParser.java

  1package eu.siacs.conversations.parser;
  2
  3import android.util.Log;
  4
  5import net.java.otr4j.session.Session;
  6import net.java.otr4j.session.SessionStatus;
  7
  8import eu.siacs.conversations.Config;
  9import eu.siacs.conversations.entities.Account;
 10import eu.siacs.conversations.entities.Contact;
 11import eu.siacs.conversations.entities.Conversation;
 12import eu.siacs.conversations.entities.Message;
 13import eu.siacs.conversations.services.MessageArchiveService;
 14import eu.siacs.conversations.services.XmppConnectionService;
 15import eu.siacs.conversations.utils.CryptoHelper;
 16import eu.siacs.conversations.xml.Element;
 17import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 18import eu.siacs.conversations.xmpp.jid.Jid;
 19import eu.siacs.conversations.xmpp.pep.Avatar;
 20import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 21
 22public class MessageParser extends AbstractParser implements
 23		OnMessagePacketReceived {
 24	public MessageParser(XmppConnectionService service) {
 25		super(service);
 26	}
 27
 28	private Message parseChat(MessagePacket packet, Account account) {
 29        final Jid jid = packet.getFrom();
 30		if (jid == null) {
 31			return null;
 32		}
 33		Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid.toBareJid(), false);
 34		updateLastseen(packet, account, true);
 35		String pgpBody = getPgpBody(packet);
 36		Message finishedMessage;
 37		if (pgpBody != null) {
 38			finishedMessage = new Message(conversation,
 39					pgpBody, Message.ENCRYPTION_PGP, Message.STATUS_RECEIVED);
 40		} else {
 41			finishedMessage = new Message(conversation,
 42					packet.getBody(), Message.ENCRYPTION_NONE,
 43					Message.STATUS_RECEIVED);
 44		}
 45		finishedMessage.setRemoteMsgId(packet.getId());
 46		finishedMessage.markable = isMarkable(packet);
 47		if (conversation.getMode() == Conversation.MODE_MULTI
 48				&& !jid.isBareJid()) {
 49			finishedMessage.setType(Message.TYPE_PRIVATE);
 50			finishedMessage.setTrueCounterpart(conversation.getMucOptions()
 51					.getTrueCounterpart(jid.getResourcepart()));
 52			if (conversation.hasDuplicateMessage(finishedMessage)) {
 53				return null;
 54			}
 55
 56		}
 57		finishedMessage.setCounterpart(jid);
 58		finishedMessage.setTime(getTimestamp(packet));
 59		return finishedMessage;
 60	}
 61
 62	private Message parseOtrChat(MessagePacket packet, Account account) {
 63		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(
146					packet.findChild("subject").getContent());
147			mXmppConnectionService.updateConversationUi();
148			return null;
149		}
150		if (from.isBareJid()) {
151			return null;
152		}
153		if (from.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
154			if (mXmppConnectionService.markMessage(conversation,
155					packet.getId(), Message.STATUS_SEND)) {
156				return null;
157			} else if (packet.getId() == null) {
158				Message message = conversation.findSentMessageWithBody(packet.getBody());
159				if (message != null) {
160					mXmppConnectionService.markMessage(message,Message.STATUS_SEND_RECEIVED);
161					return null;
162				} else {
163					status = Message.STATUS_SEND;
164				}
165			} else {
166				status = Message.STATUS_SEND;
167			}
168		} else {
169			status = Message.STATUS_RECEIVED;
170		}
171		String pgpBody = getPgpBody(packet);
172		Message finishedMessage;
173		if (pgpBody == null) {
174			finishedMessage = new Message(conversation,
175					packet.getBody(), Message.ENCRYPTION_NONE, status);
176		} else {
177			finishedMessage = new Message(conversation, pgpBody,
178					Message.ENCRYPTION_PGP, status);
179		}
180		finishedMessage.setRemoteMsgId(packet.getId());
181		finishedMessage.markable = isMarkable(packet);
182		finishedMessage.setCounterpart(from);
183		if (status == Message.STATUS_RECEIVED) {
184			finishedMessage.setTrueCounterpart(conversation.getMucOptions()
185					.getTrueCounterpart(from.getResourcepart()));
186		}
187		if (packet.hasChild("delay")
188				&& conversation.hasDuplicateMessage(finishedMessage)) {
189			return null;
190		}
191		finishedMessage.setTime(getTimestamp(packet));
192		return finishedMessage;
193	}
194
195	private Message parseCarbonMessage(final MessagePacket packet, final Account account) {
196		int status;
197		final Jid fullJid;
198		Element forwarded;
199		if (packet.hasChild("received", "urn:xmpp:carbons:2")) {
200			forwarded = packet.findChild("received", "urn:xmpp:carbons:2")
201					.findChild("forwarded", "urn:xmpp:forward:0");
202			status = Message.STATUS_RECEIVED;
203		} else if (packet.hasChild("sent", "urn:xmpp:carbons:2")) {
204			forwarded = packet.findChild("sent", "urn:xmpp:carbons:2")
205					.findChild("forwarded", "urn:xmpp:forward:0");
206			status = Message.STATUS_SEND;
207		} else {
208			return null;
209		}
210		if (forwarded == null) {
211			return null;
212		}
213		Element message = forwarded.findChild("message");
214		if (message == null) {
215			return null;
216		}
217		if (!message.hasChild("body")) {
218			if (status == Message.STATUS_RECEIVED
219					&& message.getAttribute("from") != null) {
220				parseNonMessage(message, account);
221			} else if (status == Message.STATUS_SEND
222					&& message.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
223				final Jid to = message.getAttributeAsJid("to");
224				if (to != null) {
225					final Conversation conversation = mXmppConnectionService.find(
226							mXmppConnectionService.getConversations(), account,
227							to.toBareJid());
228					if (conversation != null) {
229						mXmppConnectionService.markRead(conversation);
230					}
231				}
232			}
233			return null;
234		}
235		if (status == Message.STATUS_RECEIVED) {
236			fullJid = message.getAttributeAsJid("from");
237			if (fullJid == null) {
238				return null;
239			} else {
240				updateLastseen(message, account, true);
241			}
242		} else {
243			fullJid = message.getAttributeAsJid("to");
244			if (fullJid == null) {
245				return null;
246			}
247		}
248		Conversation conversation = mXmppConnectionService
249				.findOrCreateConversation(account, fullJid.toBareJid(), false);
250		String pgpBody = getPgpBody(message);
251		Message finishedMessage;
252		if (pgpBody != null) {
253			finishedMessage = new Message(conversation, pgpBody,
254					Message.ENCRYPTION_PGP, status);
255		} else {
256			String body = message.findChild("body").getContent();
257			finishedMessage = new Message(conversation, body,
258					Message.ENCRYPTION_NONE, status);
259		}
260		finishedMessage.setTime(getTimestamp(message));
261		finishedMessage.setRemoteMsgId(message.getAttribute("id"));
262		finishedMessage.markable = isMarkable(message);
263		finishedMessage.setCounterpart(fullJid);
264		if (conversation.getMode() == Conversation.MODE_MULTI
265				&& !fullJid.isBareJid()) {
266			finishedMessage.setType(Message.TYPE_PRIVATE);
267			finishedMessage.setTrueCounterpart(conversation.getMucOptions()
268					.getTrueCounterpart(fullJid.getResourcepart()));
269			if (conversation.hasDuplicateMessage(finishedMessage)) {
270				return null;
271			}
272		}
273		return finishedMessage;
274	}
275
276	private Message parseMamMessage(MessagePacket packet, final Account account) {
277		final Element result = packet.findChild("result","urn:xmpp:mam:0");
278		if (result == null ) {
279			return null;
280		}
281		final MessageArchiveService.Query query = this.mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
282		if (query!=null) {
283			query.incrementTotalCount();
284		}
285		final Element forwarded = result.findChild("forwarded","urn:xmpp:forward:0");
286		if (forwarded == null) {
287			return null;
288		}
289		final Element message = forwarded.findChild("message");
290		if (message == null) {
291			return null;
292		}
293		final Element body = message.findChild("body");
294		if (body == null || message.hasChild("private","urn:xmpp:carbons:2") || message.hasChild("no-copy","urn:xmpp:hints")) {
295			return null;
296		}
297		int encryption;
298		String content = getPgpBody(message);
299		if (content != null) {
300			encryption = Message.ENCRYPTION_PGP;
301		} else {
302			encryption = Message.ENCRYPTION_NONE;
303			content = body.getContent();
304		}
305		if (content == null) {
306			return null;
307		}
308		final long timestamp = getTimestamp(forwarded);
309		final Jid to = message.getAttributeAsJid("to");
310		final Jid from = message.getAttributeAsJid("from");
311		Jid counterpart;
312		int status;
313		Conversation conversation;
314		if (from!=null && to != null && from.toBareJid().equals(account.getJid().toBareJid())) {
315			status = Message.STATUS_SEND;
316			conversation = this.mXmppConnectionService.findOrCreateConversation(account,to.toBareJid(),false,query);
317			counterpart = to;
318		} else if (from !=null && to != null) {
319			status = Message.STATUS_RECEIVED;
320			conversation = this.mXmppConnectionService.findOrCreateConversation(account,from.toBareJid(),false,query);
321			counterpart = from;
322		} else {
323			return null;
324		}
325		Message finishedMessage = new Message(conversation,content,encryption,status);
326		finishedMessage.setTime(timestamp);
327		finishedMessage.setCounterpart(counterpart);
328		finishedMessage.setRemoteMsgId(message.getAttribute("id"));
329		finishedMessage.setServerMsgId(result.getAttribute("id"));
330		if (conversation.hasDuplicateMessage(finishedMessage)) {
331			return null;
332		}
333		if (query!=null) {
334			query.incrementMessageCount();
335		}
336		return finishedMessage;
337	}
338
339	private void parseError(final MessagePacket packet, final Account account) {
340		final Jid from = packet.getFrom();
341		mXmppConnectionService.markMessage(account, from.toBareJid(),
342				packet.getId(), Message.STATUS_SEND_FAILED);
343	}
344
345	private void parseNonMessage(Element packet, Account account) {
346		final Jid from = packet.getAttributeAsJid("from");
347		if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
348			Element event = packet.findChild("event",
349					"http://jabber.org/protocol/pubsub#event");
350			parseEvent(event, from, account);
351		} else if (from != null
352				&& packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
353			String id = packet
354					.findChild("displayed", "urn:xmpp:chat-markers:0")
355					.getAttribute("id");
356			updateLastseen(packet, account, true);
357			mXmppConnectionService.markMessage(account, from.toBareJid(),
358					id, Message.STATUS_SEND_DISPLAYED);
359		} else if (from != null
360				&& packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
361			String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
362					.getAttribute("id");
363			updateLastseen(packet, account, false);
364			mXmppConnectionService.markMessage(account, from.toBareJid(),
365					id, Message.STATUS_SEND_RECEIVED);
366		} else if (from != null
367				&& packet.hasChild("received", "urn:xmpp:receipts")) {
368			String id = packet.findChild("received", "urn:xmpp:receipts")
369					.getAttribute("id");
370			updateLastseen(packet, account, false);
371			mXmppConnectionService.markMessage(account, from.toBareJid(),
372					id, Message.STATUS_SEND_RECEIVED);
373		} else if (packet.hasChild("x", "http://jabber.org/protocol/muc#user")) {
374			Element x = packet.findChild("x",
375					"http://jabber.org/protocol/muc#user");
376			if (x.hasChild("invite")) {
377				Conversation conversation = mXmppConnectionService
378						.findOrCreateConversation(account,
379								packet.getAttributeAsJid("from"), true);
380				if (!conversation.getMucOptions().online()) {
381					if (x.hasChild("password")) {
382						Element password = x.findChild("password");
383						conversation.getMucOptions().setPassword(
384								password.getContent());
385						mXmppConnectionService.databaseBackend
386								.updateConversation(conversation);
387					}
388					mXmppConnectionService.joinMuc(conversation);
389					mXmppConnectionService.updateConversationUi();
390				}
391			}
392		} else if (packet.hasChild("x", "jabber:x:conference")) {
393			Element x = packet.findChild("x", "jabber:x:conference");
394            Jid jid = x.getAttributeAsJid("jid");
395            String password = x.getAttribute("password");
396			if (jid != null) {
397				Conversation conversation = mXmppConnectionService
398						.findOrCreateConversation(account, jid, true);
399				if (!conversation.getMucOptions().online()) {
400					if (password != null) {
401						conversation.getMucOptions().setPassword(password);
402						mXmppConnectionService.databaseBackend
403								.updateConversation(conversation);
404					}
405					mXmppConnectionService.joinMuc(conversation);
406					mXmppConnectionService.updateConversationUi();
407				}
408			}
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
486		if ((packet.getType() == MessagePacket.TYPE_CHAT || packet.getType() == MessagePacket.TYPE_NORMAL)) {
487			if ((packet.getBody() != null)
488					&& (packet.getBody().startsWith("?OTR"))) {
489				message = this.parseOtrChat(packet, account);
490				if (message != null) {
491					message.markUnread();
492				}
493			} else if (packet.hasChild("body")
494					&& !(packet.hasChild("x",
495					"http://jabber.org/protocol/muc#user"))) {
496				message = this.parseChat(packet, account);
497				if (message != null) {
498					message.markUnread();
499				}
500			} else if (packet.hasChild("received", "urn:xmpp:carbons:2")
501					|| (packet.hasChild("sent", "urn:xmpp:carbons:2"))) {
502				message = this.parseCarbonMessage(packet, account);
503				if (message != null) {
504					if (message.getStatus() == Message.STATUS_SEND) {
505						account.activateGracePeriod();
506						mXmppConnectionService.markRead(message.getConversation());
507					} else {
508						message.markUnread();
509					}
510				}
511			} else if (packet.hasChild("result","urn:xmpp:mam:0")) {
512				message = parseMamMessage(packet, account);
513				if (message != null) {
514					Conversation conversation = message.getConversation();
515					conversation.add(message);
516					mXmppConnectionService.databaseBackend.createMessage(message);
517				}
518				return;
519			} else if (packet.hasChild("fin","urn:xmpp:mam:0")) {
520				Element fin = packet.findChild("fin","urn:xmpp:mam:0");
521				mXmppConnectionService.getMessageArchiveService().processFin(fin);
522			} else {
523				parseNonMessage(packet, account);
524			}
525		} else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
526			message = this.parseGroupchat(packet, account);
527			if (message != null) {
528				if (message.getStatus() == Message.STATUS_RECEIVED) {
529					message.markUnread();
530				} else {
531					mXmppConnectionService.markRead(message.getConversation());
532					account.activateGracePeriod();
533				}
534			}
535		} else if (packet.getType() == MessagePacket.TYPE_ERROR) {
536			this.parseError(packet, account);
537			return;
538		} else if (packet.getType() == MessagePacket.TYPE_HEADLINE) {
539			this.parseHeadline(packet, account);
540			return;
541		}
542		if ((message == null) || (message.getBody() == null)) {
543			return;
544		}
545		if ((mXmppConnectionService.confirmMessages())
546				&& ((packet.getId() != null))) {
547			if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
548				MessagePacket receipt = mXmppConnectionService
549						.getMessageGenerator().received(account, packet,
550								"urn:xmpp:chat-markers:0");
551				mXmppConnectionService.sendMessagePacket(account, receipt);
552			}
553			if (packet.hasChild("request", "urn:xmpp:receipts")) {
554				MessagePacket receipt = mXmppConnectionService
555						.getMessageGenerator().received(account, packet,
556								"urn:xmpp:receipts");
557				mXmppConnectionService.sendMessagePacket(account, receipt);
558			}
559		}
560		Conversation conversation = message.getConversation();
561		conversation.add(message);
562		if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
563			if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
564				mXmppConnectionService.updateConversation(conversation);
565			}
566		}
567
568		if (message.getStatus() == Message.STATUS_RECEIVED
569				&& conversation.getOtrSession() != null
570				&& !conversation.getOtrSession().getSessionID().getUserID()
571				.equals(message.getCounterpart().getResourcepart())) {
572			conversation.endOtrIfNeeded();
573		}
574
575		if (packet.getType() != MessagePacket.TYPE_ERROR) {
576			if (message.getEncryption() == Message.ENCRYPTION_NONE
577					|| mXmppConnectionService.saveEncryptedMessages()) {
578				mXmppConnectionService.databaseBackend.createMessage(message);
579			}
580		}
581		if (message.trusted() && message.bodyContainsDownloadable()) {
582			this.mXmppConnectionService.getHttpConnectionManager()
583					.createNewConnection(message);
584		} else if (!message.isRead()) {
585			mXmppConnectionService.getNotificationService().push(message);
586		}
587		mXmppConnectionService.updateConversationUi();
588	}
589
590	private void parseHeadline(MessagePacket packet, Account account) {
591		if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
592			Element event = packet.findChild("event",
593					"http://jabber.org/protocol/pubsub#event");
594			parseEvent(event, packet.getFrom(), account);
595		}
596	}
597
598	private void parseNick(MessagePacket packet, Account account) {
599		Element nick = packet.findChild("nick",
600				"http://jabber.org/protocol/nick");
601		if (nick != null) {
602			if (packet.getFrom() != null) {
603				Contact contact = account.getRoster().getContact(
604						packet.getFrom());
605				contact.setPresenceName(nick.getContent());
606			}
607		}
608	}
609}