aboutsummaryrefslogtreecommitdiffstats
path: root/src/eu/siacs/conversations/parser/MessageParser.java
blob: b54f6b9898638b13b01bb2a790236bc5678581e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package eu.siacs.conversations.parser;

import android.os.SystemClock;
import android.util.Log;
import net.java.otr4j.session.Session;
import net.java.otr4j.session.SessionStatus;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
import eu.siacs.conversations.xmpp.pep.Avatar;
import eu.siacs.conversations.xmpp.stanzas.MessagePacket;

public class MessageParser extends AbstractParser implements
		OnMessagePacketReceived {

	private long lastCarbonMessageReceived = -XmppConnectionService.CARBON_GRACE_PERIOD;

	public MessageParser(XmppConnectionService service) {
		super(service);
	}

	private Message parseChat(MessagePacket packet, Account account) {
		String[] fromParts = packet.getFrom().split("/");
		Conversation conversation = mXmppConnectionService
				.findOrCreateConversation(account, fromParts[0], false);
		conversation.setLatestMarkableMessageId(getMarkableMessageId(packet));
		updateLastseen(packet, account, true);
		String pgpBody = getPgpBody(packet);
		Message finishedMessage;
		if (pgpBody != null) {
			finishedMessage = new Message(conversation, packet.getFrom(),
					pgpBody, Message.ENCRYPTION_PGP, Message.STATUS_RECIEVED);
		} else {
			finishedMessage = new Message(conversation, packet.getFrom(),
					packet.getBody(), Message.ENCRYPTION_NONE,
					Message.STATUS_RECIEVED);
		}
		finishedMessage.setTime(getTimestamp(packet));
		return finishedMessage;
	}

	private Message parseOtrChat(MessagePacket packet, Account account) {
		boolean properlyAddressed = (packet.getTo().split("/").length == 2)
				|| (account.countPresences() == 1);
		String[] fromParts = packet.getFrom().split("/");
		Conversation conversation = mXmppConnectionService
				.findOrCreateConversation(account, fromParts[0], false);
		updateLastseen(packet, account, true);
		String body = packet.getBody();
		if (!conversation.hasValidOtrSession()) {
			if (properlyAddressed) {
				conversation.startOtrSession(
						mXmppConnectionService.getApplicationContext(),
						fromParts[1], false);
			} else {
				return null;
			}
		} else {
			String foreignPresence = conversation.getOtrSession()
					.getSessionID().getUserID();
			if (!foreignPresence.equals(fromParts[1])) {
				conversation.endOtrIfNeeded();
				if (properlyAddressed) {
					conversation.startOtrSession(
							mXmppConnectionService.getApplicationContext(),
							fromParts[1], false);
				} else {
					return null;
				}
			}
		}
		try {
			Session otrSession = conversation.getOtrSession();
			SessionStatus before = otrSession.getSessionStatus();
			body = otrSession.transformReceiving(body);
			SessionStatus after = otrSession.getSessionStatus();
			if ((before != after) && (after == SessionStatus.ENCRYPTED)) {
				mXmppConnectionService.onOtrSessionEstablished(conversation);
			} else if ((before != after) && (after == SessionStatus.FINISHED)) {
				conversation.resetOtrSession();
				mXmppConnectionService.updateConversationUi();
			}
			if ((body == null) || (body.isEmpty())) {
				return null;
			}
			if (body.startsWith(CryptoHelper.FILETRANSFER)) {
				String key = body.substring(CryptoHelper.FILETRANSFER.length());
				conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
				return null;
			}
			conversation
					.setLatestMarkableMessageId(getMarkableMessageId(packet));
			Message finishedMessage = new Message(conversation,
					packet.getFrom(), body, Message.ENCRYPTION_OTR,
					Message.STATUS_RECIEVED);
			finishedMessage.setTime(getTimestamp(packet));
			return finishedMessage;
		} catch (Exception e) {
			String receivedId = packet.getId();
			if (receivedId != null) {
				mXmppConnectionService.replyWithNotAcceptable(account, packet);
			}
			conversation.endOtrIfNeeded();
			return null;
		}
	}

	private Message parseGroupchat(MessagePacket packet, Account account) {
		int status;
		String[] fromParts = packet.getFrom().split("/");
		if (mXmppConnectionService.find(account.pendingConferenceLeaves,account,fromParts[0]) != null) {
			return null;
		}
		Conversation conversation = mXmppConnectionService
				.findOrCreateConversation(account, fromParts[0], true);
		if (packet.hasChild("subject")) {
			conversation.getMucOptions().setSubject(
					packet.findChild("subject").getContent());
			mXmppConnectionService.updateConversationUi();
			return null;
		}
		if ((fromParts.length == 1)) {
			return null;
		}
		String counterPart = fromParts[1];
		if (counterPart.equals(conversation.getMucOptions().getActualNick())) {
			if (mXmppConnectionService.markMessage(conversation,
					packet.getId(), Message.STATUS_SEND)) {
				return null;
			} else {
				status = Message.STATUS_SEND;
			}
		} else {
			status = Message.STATUS_RECIEVED;
		}
		String pgpBody = getPgpBody(packet);
		conversation.setLatestMarkableMessageId(getMarkableMessageId(packet));
		Message finishedMessage;
		if (pgpBody == null) {
			finishedMessage = new Message(conversation, counterPart,
					packet.getBody(), Message.ENCRYPTION_NONE, status);
		} else {
			finishedMessage = new Message(conversation, counterPart, pgpBody,
					Message.ENCRYPTION_PGP, status);
		}
		finishedMessage.setTime(getTimestamp(packet));
		if (status == Message.STATUS_RECIEVED) {
			finishedMessage.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(counterPart));
		}
		return finishedMessage;
	}

	private Message parseCarbonMessage(MessagePacket packet, Account account) {
		int status;
		String fullJid;
		Element forwarded;
		if (packet.hasChild("received")) {
			forwarded = packet.findChild("received").findChild("forwarded");
			status = Message.STATUS_RECIEVED;
		} else if (packet.hasChild("sent")) {
			forwarded = packet.findChild("sent").findChild("forwarded");
			status = Message.STATUS_SEND;
		} else {
			return null;
		}
		if (forwarded == null) {
			return null;
		}
		Element message = forwarded.findChild("message");
		if ((message == null) || (!message.hasChild("body"))) {
			if (status == Message.STATUS_RECIEVED) {
				parseNormal(message, account);
			}
			return null;
		}
		if (status == Message.STATUS_RECIEVED) {
			fullJid = message.getAttribute("from");
			if (fullJid == null ) {
				return null;
			} else {
				updateLastseen(message, account, true);
			}
		} else {
			fullJid = message.getAttribute("to");
			if (fullJid == null) {
				return null;
			}
		}
		String[] parts = fullJid.split("/");
		Conversation conversation = mXmppConnectionService
				.findOrCreateConversation(account, parts[0], false);
		conversation.setLatestMarkableMessageId(getMarkableMessageId(packet));
		String pgpBody = getPgpBody(message);
		Message finishedMessage;
		if (pgpBody != null) {
			finishedMessage = new Message(conversation, fullJid, pgpBody,
					Message.ENCRYPTION_PGP, status);
		} else {
			String body = message.findChild("body").getContent();
			finishedMessage = new Message(conversation, fullJid, body,
					Message.ENCRYPTION_NONE, status);
		}
		finishedMessage.setTime(getTimestamp(message));
		return finishedMessage;
	}

	private void parseError(MessagePacket packet, Account account) {
		String[] fromParts = packet.getFrom().split("/");
		mXmppConnectionService.markMessage(account, fromParts[0],
				packet.getId(), Message.STATUS_SEND_FAILED);
	}

	private void parseNormal(Element packet, Account account) {
		if (packet.hasChild("event","http://jabber.org/protocol/pubsub#event")) {
			Element event = packet.findChild("event","http://jabber.org/protocol/pubsub#event");
			parseEvent(event,packet.getAttribute("from"),account);
		}
		if (packet.hasChild("displayed", "urn:xmpp:chat-markers:0")) {
			String id = packet
					.findChild("displayed", "urn:xmpp:chat-markers:0")
					.getAttribute("id");
			String[] fromParts = packet.getAttribute("from").split("/");
			updateLastseen(packet, account, true);
			mXmppConnectionService.markMessage(account, fromParts[0], id,
					Message.STATUS_SEND_DISPLAYED);
		} else if (packet.hasChild("received", "urn:xmpp:chat-markers:0")) {
			String id = packet.findChild("received", "urn:xmpp:chat-markers:0")
					.getAttribute("id");
			String[] fromParts = packet.getAttribute("from").split("/");
			updateLastseen(packet, account, false);
			mXmppConnectionService.markMessage(account, fromParts[0], id,
					Message.STATUS_SEND_RECEIVED);
		} else if (packet.hasChild("x","http://jabber.org/protocol/muc#user")) {
			Element x = packet.findChild("x","http://jabber.org/protocol/muc#user");
			if (x.hasChild("invite")) {
				Conversation conversation = mXmppConnectionService
						.findOrCreateConversation(account,
								packet.getAttribute("from"), true);
				if (!conversation.getMucOptions().online()) {
					mXmppConnectionService.joinMuc(conversation);
					mXmppConnectionService.updateConversationUi();
				}	
			}

		} else if (packet.hasChild("x", "jabber:x:conference")) {
			Element x = packet.findChild("x", "jabber:x:conference");
			String jid = x.getAttribute("jid");
			if (jid!=null) {
				Conversation conversation = mXmppConnectionService
						.findOrCreateConversation(account,jid, true);
				if (!conversation.getMucOptions().online()) {
					mXmppConnectionService.joinMuc(conversation);
					mXmppConnectionService.updateConversationUi();
				}
			}
		}
	}

	private void parseEvent(Element event, String from, Account account) {
		Element items = event.findChild("items");
		String node = items.getAttribute("node");
		if (node!=null) {
			if (node.equals("urn:xmpp:avatar:metadata")) {
				Avatar avatar = Avatar.parseMetadata(items);
				avatar.owner = from;
				if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
					if (account.getJid().equals(from)) {
						account.setAvatar(avatar.getFilename());
					} else {
						Contact contact = account.getRoster().getContact(from);
						contact.setAvatar(avatar.getFilename());
					}
				} else {
					mXmppConnectionService.fetchAvatar(account, avatar);
				}
			} else {
				Log.d("xmppService",account.getJid()+": "+node+" from "+from);
			}
		} else {
			Log.d("xmppService",event.toString());
		}
	}

	private String getPgpBody(Element message) {
		Element child = message.findChild("x", "jabber:x:encrypted");
		if (child == null) {
			return null;
		} else {
			return child.getContent();
		}
	}

	private String getMarkableMessageId(Element message) {
		if (message.hasChild("markable", "urn:xmpp:chat-markers:0")) {
			return message.getAttribute("id");
		} else {
			return null;
		}
	}

	@Override
	public void onMessagePacketReceived(Account account, MessagePacket packet) {
		Message message = null;
		boolean notify = true;
		if (mXmppConnectionService.getPreferences().getBoolean(
				"notification_grace_period_after_carbon_received", true)) {
			notify = (SystemClock.elapsedRealtime() - lastCarbonMessageReceived) > XmppConnectionService.CARBON_GRACE_PERIOD;
		}

		if ((packet.getType() == MessagePacket.TYPE_CHAT)) {
			if ((packet.getBody() != null)
					&& (packet.getBody().startsWith("?OTR"))) {
				message = this.parseOtrChat(packet, account);
				if (message != null) {
					message.markUnread();
				}
			} else if (packet.hasChild("body")) {
				message = this.parseChat(packet, account);
				message.markUnread();
			} else if (packet.hasChild("received") || (packet.hasChild("sent"))) {
				message = this.parseCarbonMessage(packet, account);
				if (message != null) {
					if (message.getStatus() == Message.STATUS_SEND) {
						lastCarbonMessageReceived = SystemClock
								.elapsedRealtime();
						notify = false;
						message.getConversation().markRead();
					} else {
						message.markUnread();
					}
				}
			} else {
				parseNormal(packet, account);
			}

		} else if (packet.getType() == MessagePacket.TYPE_GROUPCHAT) {
			message = this.parseGroupchat(packet, account);
			if (message != null) {
				if (message.getStatus() == Message.STATUS_RECIEVED) {
					message.markUnread();
				} else {
					message.getConversation().markRead();
					lastCarbonMessageReceived = SystemClock
							.elapsedRealtime();
					notify = false;
				}
			}
		} else if (packet.getType() == MessagePacket.TYPE_ERROR) {
			this.parseError(packet, account);
			return;
		} else if (packet.getType() == MessagePacket.TYPE_NORMAL) {
			this.parseNormal(packet, account);
			return;
		} else if (packet.getType() == MessagePacket.TYPE_HEADLINE) {
			this.parseHeadline(packet, account);
			return;
		}
		if ((message == null) || (message.getBody() == null)) {
			return;
		}
		if ((mXmppConnectionService.confirmMessages())
				&& ((packet.getId() != null))) {
			if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
				MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account, packet, "urn:xmpp:chat-markers:0");
				mXmppConnectionService.sendMessagePacket(account, receipt);
			}
			if (packet.hasChild("request", "urn:xmpp:receipts")) {
				MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account, packet, "urn:xmpp:receipts");
				mXmppConnectionService.sendMessagePacket(account, receipt);
			}
		}
		Conversation conversation = message.getConversation();
		conversation.getMessages().add(message);
		if (packet.getType() != MessagePacket.TYPE_ERROR) {
			mXmppConnectionService.databaseBackend.createMessage(message);
		}
		mXmppConnectionService.notifyUi(conversation, notify);
	}

	private void parseHeadline(MessagePacket packet, Account account) {
		if (packet.hasChild("event","http://jabber.org/protocol/pubsub#event")) {
			Element event = packet.findChild("event","http://jabber.org/protocol/pubsub#event");
			parseEvent(event,packet.getFrom(),account);
		}
	}
}