1package eu.siacs.conversations.parser;
2
3import android.os.SystemClock;
4import android.util.Log;
5import net.java.otr4j.session.Session;
6import net.java.otr4j.session.SessionStatus;
7import eu.siacs.conversations.entities.Account;
8import eu.siacs.conversations.entities.Contact;
9import eu.siacs.conversations.entities.Conversation;
10import eu.siacs.conversations.entities.Message;
11import eu.siacs.conversations.services.XmppConnectionService;
12import eu.siacs.conversations.utils.CryptoHelper;
13import eu.siacs.conversations.xml.Element;
14import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
15import eu.siacs.conversations.xmpp.pep.Avatar;
16import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
17
18public class MessageParser extends AbstractParser implements
19 OnMessagePacketReceived {
20
21 private long lastCarbonMessageReceived = -XmppConnectionService.CARBON_GRACE_PERIOD;
22
23 public MessageParser(XmppConnectionService service) {
24 super(service);
25 }
26
27 private Message parseChat(MessagePacket packet, Account account) {
28 String[] fromParts = packet.getFrom().split("/");
29 Conversation conversation = mXmppConnectionService
30 .findOrCreateConversation(account, fromParts[0], false);
31 conversation.setLatestMarkableMessageId(getMarkableMessageId(packet));
32 updateLastseen(packet, account, true);
33 String pgpBody = getPgpBody(packet);
34 Message finishedMessage;
35 if (pgpBody != null) {
36 finishedMessage = new Message(conversation, packet.getFrom(),
37 pgpBody, Message.ENCRYPTION_PGP, Message.STATUS_RECIEVED);
38 } else {
39 finishedMessage = new Message(conversation, packet.getFrom(),
40 packet.getBody(), Message.ENCRYPTION_NONE,
41 Message.STATUS_RECIEVED);
42 }
43 if (conversation.getMode() == Conversation.MODE_MULTI
44 && fromParts.length >= 2) {
45 finishedMessage.setType(Message.TYPE_PRIVATE);
46 finishedMessage.setPresence(fromParts[1]);
47 finishedMessage.setTrueCounterpart(conversation.getMucOptions()
48 .getTrueCounterpart(fromParts[1]));
49
50 }
51 finishedMessage.setTime(getTimestamp(packet));
52 return finishedMessage;
53 }
54
55 private Message parseOtrChat(MessagePacket packet, Account account) {
56 boolean properlyAddressed = (packet.getTo().split("/").length == 2)
57 || (account.countPresences() == 1);
58 String[] fromParts = packet.getFrom().split("/");
59 Conversation conversation = mXmppConnectionService
60 .findOrCreateConversation(account, fromParts[0], false);
61 updateLastseen(packet, account, true);
62 String body = packet.getBody();
63 if (!conversation.hasValidOtrSession()) {
64 if (properlyAddressed) {
65 conversation.startOtrSession(
66 mXmppConnectionService.getApplicationContext(),
67 fromParts[1], false);
68 } else {
69 return null;
70 }
71 } else {
72 String foreignPresence = conversation.getOtrSession()
73 .getSessionID().getUserID();
74 if (!foreignPresence.equals(fromParts[1])) {
75 conversation.endOtrIfNeeded();
76 if (properlyAddressed) {
77 conversation.startOtrSession(
78 mXmppConnectionService.getApplicationContext(),
79 fromParts[1], false);
80 } else {
81 return null;
82 }
83 }
84 }
85 try {
86 Session otrSession = conversation.getOtrSession();
87 SessionStatus before = otrSession.getSessionStatus();
88 body = otrSession.transformReceiving(body);
89 SessionStatus after = otrSession.getSessionStatus();
90 if ((before != after) && (after == SessionStatus.ENCRYPTED)) {
91 mXmppConnectionService.onOtrSessionEstablished(conversation);
92 } else if ((before != after) && (after == SessionStatus.FINISHED)) {
93 conversation.resetOtrSession();
94 mXmppConnectionService.updateConversationUi();
95 }
96 if ((body == null) || (body.isEmpty())) {
97 return null;
98 }
99 if (body.startsWith(CryptoHelper.FILETRANSFER)) {
100 String key = body.substring(CryptoHelper.FILETRANSFER.length());
101 conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
102 return null;
103 }
104 conversation
105 .setLatestMarkableMessageId(getMarkableMessageId(packet));
106 Message finishedMessage = new Message(conversation,
107 packet.getFrom(), body, Message.ENCRYPTION_OTR,
108 Message.STATUS_RECIEVED);
109 finishedMessage.setTime(getTimestamp(packet));
110 return finishedMessage;
111 } catch (Exception e) {
112 String receivedId = packet.getId();
113 if (receivedId != null) {
114 mXmppConnectionService.replyWithNotAcceptable(account, packet);
115 }
116 conversation.endOtrIfNeeded();
117 return null;
118 }
119 }
120
121 private Message parseGroupchat(MessagePacket packet, Account account) {
122 int status;
123 String[] fromParts = packet.getFrom().split("/");
124 if (mXmppConnectionService.find(account.pendingConferenceLeaves,
125 account, fromParts[0]) != null) {
126 return null;
127 }
128 Conversation conversation = mXmppConnectionService
129 .findOrCreateConversation(account, fromParts[0], true);
130 if (packet.hasChild("subject")) {
131 conversation.getMucOptions().setSubject(
132 packet.findChild("subject").getContent());
133 mXmppConnectionService.updateConversationUi();
134 return null;
135 }
136 if ((fromParts.length == 1)) {
137 return null;
138 }
139 String counterPart = fromParts[1];
140 if (counterPart.equals(conversation.getMucOptions().getActualNick())) {
141 if (mXmppConnectionService.markMessage(conversation,
142 packet.getId(), Message.STATUS_SEND)) {
143 return null;
144 } else {
145 status = Message.STATUS_SEND;
146 }
147 } else {
148 status = Message.STATUS_RECIEVED;
149 }
150 String pgpBody = getPgpBody(packet);
151 conversation.setLatestMarkableMessageId(getMarkableMessageId(packet));
152 Message finishedMessage;
153 if (pgpBody == null) {
154 finishedMessage = new Message(conversation, counterPart,
155 packet.getBody(), Message.ENCRYPTION_NONE, status);
156 } else {
157 finishedMessage = new Message(conversation, counterPart, pgpBody,
158 Message.ENCRYPTION_PGP, status);
159 }
160 finishedMessage.setTime(getTimestamp(packet));
161 if (status == Message.STATUS_RECIEVED) {
162 finishedMessage.setTrueCounterpart(conversation.getMucOptions()
163 .getTrueCounterpart(counterPart));
164 }
165 return finishedMessage;
166 }
167
168 private Message parseCarbonMessage(MessagePacket packet, Account account) {
169 int status;
170 String fullJid;
171 Element forwarded;
172 if (packet.hasChild("received")) {
173 forwarded = packet.findChild("received").findChild("forwarded");
174 status = Message.STATUS_RECIEVED;
175 } else if (packet.hasChild("sent")) {
176 forwarded = packet.findChild("sent").findChild("forwarded");
177 status = Message.STATUS_SEND;
178 } else {
179 return null;
180 }
181 if (forwarded == null) {
182 return null;
183 }
184 Element message = forwarded.findChild("message");
185 if ((message == null) || (!message.hasChild("body"))) {
186 if (status == Message.STATUS_RECIEVED) {
187 parseNormal(message, account);
188 }
189 return null;
190 }
191 if (status == Message.STATUS_RECIEVED) {
192 fullJid = message.getAttribute("from");
193 if (fullJid == null) {
194 return null;
195 } else {
196 updateLastseen(message, account, true);
197 }
198 } else {
199 fullJid = message.getAttribute("to");
200 if (fullJid == null) {
201 return null;
202 }
203 }
204 String[] parts = fullJid.split("/");
205 Conversation conversation = mXmppConnectionService
206 .findOrCreateConversation(account, parts[0], false);
207 conversation.setLatestMarkableMessageId(getMarkableMessageId(packet));
208
209 String pgpBody = getPgpBody(message);
210 Message finishedMessage;
211 if (pgpBody != null) {
212 finishedMessage = new Message(conversation, fullJid, pgpBody,
213 Message.ENCRYPTION_PGP, status);
214 } else {
215 String body = message.findChild("body").getContent();
216 finishedMessage = new Message(conversation, fullJid, body,
217 Message.ENCRYPTION_NONE, status);
218 }
219 finishedMessage.setTime(getTimestamp(message));
220
221 if (conversation.getMode() == Conversation.MODE_MULTI
222 && parts.length >= 2) {
223 finishedMessage.setType(Message.TYPE_PRIVATE);
224 finishedMessage.setPresence(parts[1]);
225 finishedMessage.setTrueCounterpart(conversation.getMucOptions()
226 .getTrueCounterpart(parts[1]));
227
228 }
229
230 return finishedMessage;
231 }
232
233 private void parseError(MessagePacket packet, Account account) {
234 String[] fromParts = packet.getFrom().split("/");
235 mXmppConnectionService.markMessage(account, fromParts[0],
236 packet.getId(), Message.STATUS_SEND_FAILED);
237 }
238
239 private void parseNormal(Element packet, Account account) {
240 if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
241 Element event = packet.findChild("event",
242 "http://jabber.org/protocol/pubsub#event");
243 parseEvent(event, packet.getAttribute("from"), account);
244 }
245 if (packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
246 String id = packet
247 .findChild("displayed", "urn:xmpp:chat-markers:0")
248 .getAttribute("id");
249 String[] fromParts = packet.getAttribute("from").split("/");
250 updateLastseen(packet, account, true);
251 mXmppConnectionService.markMessage(account, fromParts[0], id,
252 Message.STATUS_SEND_DISPLAYED);
253 } else if (packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
254 String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
255 .getAttribute("id");
256 String[] fromParts = packet.getAttribute("from").split("/");
257 updateLastseen(packet, account, false);
258 mXmppConnectionService.markMessage(account, fromParts[0], id,
259 Message.STATUS_SEND_RECEIVED);
260 } else if (packet.hasChild("x", "http://jabber.org/protocol/muc#user")) {
261 Element x = packet.findChild("x",
262 "http://jabber.org/protocol/muc#user");
263 if (x.hasChild("invite")) {
264 Conversation conversation = mXmppConnectionService
265 .findOrCreateConversation(account,
266 packet.getAttribute("from"), true);
267 if (!conversation.getMucOptions().online()) {
268 mXmppConnectionService.joinMuc(conversation);
269 mXmppConnectionService.updateConversationUi();
270 }
271 }
272
273 } else if (packet.hasChild("x", "jabber:x:conference")) {
274 Element x = packet.findChild("x", "jabber:x:conference");
275 String jid = x.getAttribute("jid");
276 if (jid != null) {
277 Conversation conversation = mXmppConnectionService
278 .findOrCreateConversation(account, jid, true);
279 if (!conversation.getMucOptions().online()) {
280 mXmppConnectionService.joinMuc(conversation);
281 mXmppConnectionService.updateConversationUi();
282 }
283 }
284 }
285 }
286
287 private void parseEvent(Element event, String from, Account account) {
288 Element items = event.findChild("items");
289 String node = items.getAttribute("node");
290 if (node != null) {
291 if (node.equals("urn:xmpp:avatar:metadata")) {
292 Avatar avatar = Avatar.parseMetadata(items);
293 avatar.owner = from;
294 if (mXmppConnectionService.getFileBackend().isAvatarCached(
295 avatar)) {
296 if (account.getJid().equals(from)) {
297 account.setAvatar(avatar.getFilename());
298 } else {
299 Contact contact = account.getRoster().getContact(from);
300 contact.setAvatar(avatar.getFilename());
301 }
302 } else {
303 mXmppConnectionService.fetchAvatar(account, avatar);
304 }
305 } else {
306 Log.d("xmppService", account.getJid() + ": " + node + " from "
307 + from);
308 }
309 } else {
310 Log.d("xmppService", event.toString());
311 }
312 }
313
314 private String getPgpBody(Element message) {
315 Element child = message.findChild("x", "jabber:x:encrypted");
316 if (child == null) {
317 return null;
318 } else {
319 return child.getContent();
320 }
321 }
322
323 private String getMarkableMessageId(Element message) {
324 if (message.hasChild("markable", "urn:xmpp:chat-markers:0")) {
325 return message.getAttribute("id");
326 } else {
327 return null;
328 }
329 }
330
331 @Override
332 public void onMessagePacketReceived(Account account, MessagePacket packet) {
333 Message message = null;
334 boolean notify = true;
335 if (mXmppConnectionService.getPreferences().getBoolean(
336 "notification_grace_period_after_carbon_received", true)) {
337 notify = (SystemClock.elapsedRealtime() - lastCarbonMessageReceived) > XmppConnectionService.CARBON_GRACE_PERIOD;
338 }
339
340 if ((packet.getType() == MessagePacket.TYPE_CHAT)) {
341 if ((packet.getBody() != null)
342 && (packet.getBody().startsWith("?OTR"))) {
343 message = this.parseOtrChat(packet, account);
344 if (message != null) {
345 message.markUnread();
346 }
347 } else if (packet.hasChild("body")) {
348 message = this.parseChat(packet, account);
349 message.markUnread();
350 } else if (packet.hasChild("received") || (packet.hasChild("sent"))) {
351 message = this.parseCarbonMessage(packet, account);
352 if (message != null) {
353 if (message.getStatus() == Message.STATUS_SEND) {
354 lastCarbonMessageReceived = SystemClock
355 .elapsedRealtime();
356 notify = false;
357 message.getConversation().markRead();
358 } else {
359 message.markUnread();
360 }
361 }
362 } else {
363 parseNormal(packet, account);
364 }
365
366 } else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
367 message = this.parseGroupchat(packet, account);
368 if (message != null) {
369 if (message.getStatus() == Message.STATUS_RECIEVED) {
370 message.markUnread();
371 } else {
372 message.getConversation().markRead();
373 lastCarbonMessageReceived = SystemClock.elapsedRealtime();
374 notify = false;
375 }
376 }
377 } else if (packet.getType() == MessagePacket.TYPE_ERROR) {
378 this.parseError(packet, account);
379 return;
380 } else if (packet.getType() == MessagePacket.TYPE_NORMAL) {
381 this.parseNormal(packet, account);
382 return;
383 } else if (packet.getType() == MessagePacket.TYPE_HEADLINE) {
384 this.parseHeadline(packet, account);
385 return;
386 }
387 if ((message == null) || (message.getBody() == null)) {
388 return;
389 }
390 if ((mXmppConnectionService.confirmMessages())
391 && ((packet.getId() != null))) {
392 if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
393 MessagePacket receipt = mXmppConnectionService
394 .getMessageGenerator().received(account, packet,
395 "urn:xmpp:chat-markers:0");
396 mXmppConnectionService.sendMessagePacket(account, receipt);
397 }
398 if (packet.hasChild("request", "urn:xmpp:receipts")) {
399 MessagePacket receipt = mXmppConnectionService
400 .getMessageGenerator().received(account, packet,
401 "urn:xmpp:receipts");
402 mXmppConnectionService.sendMessagePacket(account, receipt);
403 }
404 }
405 Conversation conversation = message.getConversation();
406 conversation.getMessages().add(message);
407 if (packet.getType() != MessagePacket.TYPE_ERROR) {
408 mXmppConnectionService.databaseBackend.createMessage(message);
409 }
410 mXmppConnectionService.notifyUi(conversation, notify);
411 }
412
413 private void parseHeadline(MessagePacket packet, Account account) {
414 if (packet.hasChild("event", "http://jabber.org/protocol/pubsub#event")) {
415 Element event = packet.findChild("event",
416 "http://jabber.org/protocol/pubsub#event");
417 parseEvent(event, packet.getFrom(), account);
418 }
419 }
420}