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