1package eu.siacs.conversations.parser;
2
3import android.util.Log;
4import android.util.Pair;
5
6import java.net.URL;
7import java.text.SimpleDateFormat;
8import java.util.ArrayList;
9import java.util.Arrays;
10import java.util.Collections;
11import java.util.Date;
12import java.util.List;
13import java.util.Locale;
14import java.util.Map;
15import java.util.Set;
16import java.util.UUID;
17
18import eu.siacs.conversations.Config;
19import eu.siacs.conversations.R;
20import eu.siacs.conversations.crypto.axolotl.AxolotlService;
21import eu.siacs.conversations.crypto.axolotl.BrokenSessionException;
22import eu.siacs.conversations.crypto.axolotl.NotEncryptedForThisDeviceException;
23import eu.siacs.conversations.crypto.axolotl.OutdatedSenderException;
24import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
25import eu.siacs.conversations.entities.Account;
26import eu.siacs.conversations.entities.Bookmark;
27import eu.siacs.conversations.entities.Contact;
28import eu.siacs.conversations.entities.Conversation;
29import eu.siacs.conversations.entities.Conversational;
30import eu.siacs.conversations.entities.Message;
31import eu.siacs.conversations.entities.MucOptions;
32import eu.siacs.conversations.entities.ReadByMarker;
33import eu.siacs.conversations.entities.ReceiptRequest;
34import eu.siacs.conversations.entities.RtpSessionStatus;
35import eu.siacs.conversations.http.HttpConnectionManager;
36import eu.siacs.conversations.http.P1S3UrlStreamHandler;
37import eu.siacs.conversations.services.MessageArchiveService;
38import eu.siacs.conversations.services.QuickConversationsService;
39import eu.siacs.conversations.services.XmppConnectionService;
40import eu.siacs.conversations.utils.CryptoHelper;
41import eu.siacs.conversations.xml.LocalizedContent;
42import eu.siacs.conversations.xml.Namespace;
43import eu.siacs.conversations.xml.Element;
44import eu.siacs.conversations.xmpp.InvalidJid;
45import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
46import eu.siacs.conversations.xmpp.chatstate.ChatState;
47import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
48import eu.siacs.conversations.xmpp.jingle.JingleRtpConnection;
49import eu.siacs.conversations.xmpp.pep.Avatar;
50import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
51import eu.siacs.conversations.xmpp.Jid;
52
53public class MessageParser extends AbstractParser implements OnMessagePacketReceived {
54
55 private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
56
57 private static final List<String> JINGLE_MESSAGE_ELEMENT_NAMES = Arrays.asList("accept", "propose", "proceed", "reject", "retract");
58
59 public MessageParser(XmppConnectionService service) {
60 super(service);
61 }
62
63 private static String extractStanzaId(Element packet, boolean isTypeGroupChat, Conversation conversation) {
64 final Jid by;
65 final boolean safeToExtract;
66 if (isTypeGroupChat) {
67 by = conversation.getJid().asBareJid();
68 safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
69 } else {
70 Account account = conversation.getAccount();
71 by = account.getJid().asBareJid();
72 safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
73 }
74 return safeToExtract ? extractStanzaId(packet, by) : null;
75 }
76
77 private static String extractStanzaId(Account account, Element packet) {
78 final boolean safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
79 return safeToExtract ? extractStanzaId(packet, account.getJid().asBareJid()) : null;
80 }
81
82 private static String extractStanzaId(Element packet, Jid by) {
83 for (Element child : packet.getChildren()) {
84 if (child.getName().equals("stanza-id")
85 && Namespace.STANZA_IDS.equals(child.getNamespace())
86 && by.equals(InvalidJid.getNullForInvalid(child.getAttributeAsJid("by")))) {
87 return child.getAttribute("id");
88 }
89 }
90 return null;
91 }
92
93 private static Jid getTrueCounterpart(Element mucUserElement, Jid fallback) {
94 final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
95 Jid result = item == null ? null : InvalidJid.getNullForInvalid(item.getAttributeAsJid("jid"));
96 return result != null ? result : fallback;
97 }
98
99 private boolean extractChatState(Conversation c, final boolean isTypeGroupChat, final MessagePacket packet) {
100 ChatState state = ChatState.parse(packet);
101 if (state != null && c != null) {
102 final Account account = c.getAccount();
103 Jid from = packet.getFrom();
104 if (from.asBareJid().equals(account.getJid().asBareJid())) {
105 c.setOutgoingChatState(state);
106 if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
107 mXmppConnectionService.markRead(c);
108 activateGracePeriod(account);
109 }
110 return false;
111 } else {
112 if (isTypeGroupChat) {
113 MucOptions.User user = c.getMucOptions().findUserByFullJid(from);
114 if (user != null) {
115 return user.setChatState(state);
116 } else {
117 return false;
118 }
119 } else {
120 return c.setIncomingChatState(state);
121 }
122 }
123 }
124 return false;
125 }
126
127 private Message parseAxolotlChat(Element axolotlMessage, Jid from, Conversation conversation, int status, final boolean checkedForDuplicates, boolean postpone) {
128 final AxolotlService service = conversation.getAccount().getAxolotlService();
129 final XmppAxolotlMessage xmppAxolotlMessage;
130 try {
131 xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.asBareJid());
132 } catch (Exception e) {
133 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": invalid omemo message received " + e.getMessage());
134 return null;
135 }
136 if (xmppAxolotlMessage.hasPayload()) {
137 final XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage;
138 try {
139 plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage, postpone);
140 } catch (BrokenSessionException e) {
141 if (checkedForDuplicates) {
142 if (service.trustedOrPreviouslyResponded(from.asBareJid())) {
143 service.reportBrokenSessionException(e, postpone);
144 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
145 } else {
146 Log.d(Config.LOGTAG, "ignoring broken session exception because contact was not trusted");
147 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
148 }
149 } else {
150 Log.d(Config.LOGTAG, "ignoring broken session exception because checkForDuplicates failed");
151 return null;
152 }
153 } catch (NotEncryptedForThisDeviceException e) {
154 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE, status);
155 } catch (OutdatedSenderException e) {
156 return new Message(conversation, "", Message.ENCRYPTION_AXOLOTL_FAILED, status);
157 }
158 if (plaintextMessage != null) {
159 Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
160 finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
161 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount()) + " Received Message with session fingerprint: " + plaintextMessage.getFingerprint());
162 return finishedMessage;
163 }
164 } else {
165 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": received OMEMO key transport message");
166 service.processReceivingKeyTransportMessage(xmppAxolotlMessage, postpone);
167 }
168 return null;
169 }
170
171 private Invite extractInvite(Element message) {
172 final Element mucUser = message.findChild("x", Namespace.MUC_USER);
173 if (mucUser != null) {
174 Element invite = mucUser.findChild("invite");
175 if (invite != null) {
176 String password = mucUser.findChildContent("password");
177 Jid from = InvalidJid.getNullForInvalid(invite.getAttributeAsJid("from"));
178 Jid room = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
179 if (room == null) {
180 return null;
181 }
182 return new Invite(room, password, false, from);
183 }
184 }
185 final Element conference = message.findChild("x", "jabber:x:conference");
186 if (conference != null) {
187 Jid from = InvalidJid.getNullForInvalid(message.getAttributeAsJid("from"));
188 Jid room = InvalidJid.getNullForInvalid(conference.getAttributeAsJid("jid"));
189 if (room == null) {
190 return null;
191 }
192 return new Invite(room, conference.getAttribute("password"), true, from);
193 }
194 return null;
195 }
196
197 private void parseEvent(final Element event, final Jid from, final Account account) {
198 Element items = event.findChild("items");
199 String node = items == null ? null : items.getAttribute("node");
200 if ("urn:xmpp:avatar:metadata".equals(node)) {
201 Avatar avatar = Avatar.parseMetadata(items);
202 if (avatar != null) {
203 avatar.owner = from.asBareJid();
204 if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
205 if (account.getJid().asBareJid().equals(from)) {
206 if (account.setAvatar(avatar.getFilename())) {
207 mXmppConnectionService.databaseBackend.updateAccount(account);
208 mXmppConnectionService.notifyAccountAvatarHasChanged(account);
209 }
210 mXmppConnectionService.getAvatarService().clear(account);
211 mXmppConnectionService.updateConversationUi();
212 mXmppConnectionService.updateAccountUi();
213 } else {
214 Contact contact = account.getRoster().getContact(from);
215 if (contact.setAvatar(avatar)) {
216 mXmppConnectionService.syncRoster(account);
217 mXmppConnectionService.getAvatarService().clear(contact);
218 mXmppConnectionService.updateConversationUi();
219 mXmppConnectionService.updateRosterUi();
220 }
221 }
222 } else if (mXmppConnectionService.isDataSaverDisabled()) {
223 mXmppConnectionService.fetchAvatar(account, avatar);
224 }
225 }
226 } else if (Namespace.NICK.equals(node)) {
227 final Element i = items.findChild("item");
228 final String nick = i == null ? null : i.findChildContent("nick", Namespace.NICK);
229 if (nick != null) {
230 setNick(account, from, nick);
231 }
232 } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
233 Element item = items.findChild("item");
234 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
235 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received PEP device list " + deviceIds + " update from " + from + ", processing... ");
236 AxolotlService axolotlService = account.getAxolotlService();
237 axolotlService.registerDevices(from, deviceIds);
238 } else if (Namespace.BOOKMARKS.equals(node) && account.getJid().asBareJid().equals(from)) {
239 if (account.getXmppConnection().getFeatures().bookmarksConversion()) {
240 final Element i = items.findChild("item");
241 final Element storage = i == null ? null : i.findChild("storage", Namespace.BOOKMARKS);
242 Map<Jid, Bookmark> bookmarks = Bookmark.parseFromStorage(storage, account);
243 mXmppConnectionService.processBookmarksInitial(account, bookmarks, true);
244 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": processing bookmark PEP event");
245 } else {
246 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring bookmark PEP event because bookmark conversion was not detected");
247 }
248 } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
249 final Element item = items.findChild("item");
250 final Element retract = items.findChild("retract");
251 if (item != null) {
252 final Bookmark bookmark = Bookmark.parseFromItem(item, account);
253 if (bookmark != null) {
254 account.putBookmark(bookmark);
255 mXmppConnectionService.processModifiedBookmark(bookmark);
256 mXmppConnectionService.updateConversationUi();
257 }
258 }
259 if (retract != null) {
260 final Jid id = InvalidJid.getNullForInvalid(retract.getAttributeAsJid("id"));
261 if (id != null) {
262 account.removeBookmark(id);
263 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmark for " + id);
264 mXmppConnectionService.processDeletedBookmark(account, id);
265 mXmppConnectionService.updateConversationUi();
266 }
267 }
268 } else {
269 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " received pubsub notification for node=" + node);
270 }
271 }
272
273 private void parseDeleteEvent(final Element event, final Jid from, final Account account) {
274 final Element delete = event.findChild("delete");
275 final String node = delete == null ? null : delete.getAttribute("node");
276 if (Namespace.NICK.equals(node)) {
277 Log.d(Config.LOGTAG, "parsing nick delete event from " + from);
278 setNick(account, from, null);
279 } else if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
280 account.setBookmarks(Collections.emptyMap());
281 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": deleted bookmarks node");
282 }
283 }
284
285 private void parsePurgeEvent(final Element event, final Jid from, final Account account) {
286 final Element purge = event.findChild("purge");
287 final String node = purge == null ? null : purge.getAttribute("node");
288 if (Namespace.BOOKMARKS2.equals(node) && account.getJid().asBareJid().equals(from)) {
289 account.setBookmarks(Collections.emptyMap());
290 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": purged bookmarks");
291 }
292 }
293
294 private void setNick(Account account, Jid user, String nick) {
295 if (user.asBareJid().equals(account.getJid().asBareJid())) {
296 account.setDisplayName(nick);
297 if (QuickConversationsService.isQuicksy()) {
298 mXmppConnectionService.getAvatarService().clear(account);
299 }
300 } else {
301 Contact contact = account.getRoster().getContact(user);
302 if (contact.setPresenceName(nick)) {
303 mXmppConnectionService.getAvatarService().clear(contact);
304 }
305 }
306 mXmppConnectionService.updateConversationUi();
307 mXmppConnectionService.updateAccountUi();
308 }
309
310 private boolean handleErrorMessage(Account account, MessagePacket packet) {
311 if (packet.getType() == MessagePacket.TYPE_ERROR) {
312 final Jid from = packet.getFrom();
313 final String id = packet.getId();
314 if (from != null && id != null) {
315 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
316 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
317 mXmppConnectionService.getJingleConnectionManager()
318 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.FAILED);
319 return true;
320 }
321 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX)) {
322 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROCEED_ID_PREFIX.length());
323 mXmppConnectionService.getJingleConnectionManager().failProceed(account, from, sessionId);
324 return true;
325 }
326 mXmppConnectionService.markMessage(account,
327 from.asBareJid(),
328 id,
329 Message.STATUS_SEND_FAILED,
330 extractErrorMessage(packet));
331 final Element error = packet.findChild("error");
332 final boolean pingWorthyError = error != null && (error.hasChild("not-acceptable") || error.hasChild("remote-server-timeout") || error.hasChild("remote-server-not-found"));
333 if (pingWorthyError) {
334 Conversation conversation = mXmppConnectionService.find(account, from);
335 if (conversation != null && conversation.getMode() == Conversational.MODE_MULTI) {
336 if (conversation.getMucOptions().online()) {
337 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received ping worthy error for seemingly online muc at " + from);
338 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
339 }
340 }
341 }
342 }
343 return true;
344 }
345 return false;
346 }
347
348 @Override
349 public void onMessagePacketReceived(Account account, MessagePacket original) {
350 if (handleErrorMessage(account, original)) {
351 return;
352 }
353 final MessagePacket packet;
354 Long timestamp = null;
355 boolean isCarbon = false;
356 String serverMsgId = null;
357 final Element fin = original.findChild("fin", MessageArchiveService.Version.MAM_0.namespace);
358 if (fin != null) {
359 mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin, original.getFrom());
360 return;
361 }
362 final Element result = MessageArchiveService.Version.findResult(original);
363 final MessageArchiveService.Query query = result == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
364 if (query != null && query.validFrom(original.getFrom())) {
365 Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", query.version.namespace);
366 if (f == null) {
367 return;
368 }
369 timestamp = f.second;
370 packet = f.first;
371 serverMsgId = result.getAttribute("id");
372 query.incrementMessageCount();
373 } else if (query != null) {
374 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received mam result from invalid sender");
375 return;
376 } else if (original.fromServer(account)) {
377 Pair<MessagePacket, Long> f;
378 f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
379 f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
380 packet = f != null ? f.first : original;
381 if (handleErrorMessage(account, packet)) {
382 return;
383 }
384 timestamp = f != null ? f.second : null;
385 isCarbon = f != null;
386 } else {
387 packet = original;
388 }
389
390 if (timestamp == null) {
391 timestamp = AbstractParser.parseTimestamp(original, AbstractParser.parseTimestamp(packet));
392 }
393 final LocalizedContent body = packet.getBody();
394 final Element mucUserElement = packet.findChild("x", Namespace.MUC_USER);
395 final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
396 final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
397 final Element oob = packet.findChild("x", Namespace.OOB);
398 final Element xP1S3 = packet.findChild("x", Namespace.P1_S3_FILE_TRANSFER);
399 final URL xP1S3url = xP1S3 == null ? null : P1S3UrlStreamHandler.of(xP1S3);
400 final String oobUrl = oob != null ? oob.findChildContent("url") : null;
401 final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
402 final Element axolotlEncrypted = packet.findChildEnsureSingle(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
403 int status;
404 final Jid counterpart;
405 final Jid to = packet.getTo();
406 final Jid from = packet.getFrom();
407 final Element originId = packet.findChild("origin-id", Namespace.STANZA_IDS);
408 final String remoteMsgId;
409 if (originId != null && originId.getAttribute("id") != null) {
410 remoteMsgId = originId.getAttribute("id");
411 } else {
412 remoteMsgId = packet.getId();
413 }
414 boolean notify = false;
415
416 if (from == null || !InvalidJid.isValid(from) || !InvalidJid.isValid(to)) {
417 Log.e(Config.LOGTAG, "encountered invalid message from='" + from + "' to='" + to + "'");
418 return;
419 }
420
421 boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
422 if (query != null && !query.muc() && isTypeGroupChat) {
423 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": received groupchat (" + from + ") message on regular MAM request. skipping");
424 return;
425 }
426 boolean isMucStatusMessage = InvalidJid.hasValidFrom(packet) && from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
427 boolean selfAddressed;
428 if (packet.fromAccount(account)) {
429 status = Message.STATUS_SEND;
430 selfAddressed = to == null || account.getJid().asBareJid().equals(to.asBareJid());
431 if (selfAddressed) {
432 counterpart = from;
433 } else {
434 counterpart = to != null ? to : account.getJid();
435 }
436 } else {
437 status = Message.STATUS_RECEIVED;
438 counterpart = from;
439 selfAddressed = false;
440 }
441
442 final Invite invite = extractInvite(packet);
443 if (invite != null) {
444 if (isTypeGroupChat) {
445 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring invite to " + invite.jid + " because type=groupchat");
446 } else if (invite.direct && (mucUserElement != null || invite.inviter == null || mXmppConnectionService.isMuc(account, invite.inviter))) {
447 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring direct invite to " + invite.jid + " because it was received in MUC");
448 } else {
449 invite.execute(account);
450 return;
451 }
452 }
453
454 if ((body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || oobUrl != null || xP1S3 != null) && !isMucStatusMessage) {
455 final boolean conversationIsProbablyMuc = isTypeGroupChat || mucUserElement != null || account.getXmppConnection().getMucServersWithholdAccount().contains(counterpart.getDomain().toEscapedString());
456 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), conversationIsProbablyMuc, false, query, false);
457 final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
458
459 if (serverMsgId == null) {
460 serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
461 }
462
463
464 if (selfAddressed) {
465 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, Message.STATUS_SEND_RECEIVED, serverMsgId)) {
466 return;
467 }
468 status = Message.STATUS_RECEIVED;
469 if (remoteMsgId != null && conversation.findMessageWithRemoteId(remoteMsgId, counterpart) != null) {
470 return;
471 }
472 }
473
474 if (isTypeGroupChat) {
475 if (conversation.getMucOptions().isSelf(counterpart)) {
476 status = Message.STATUS_SEND_RECEIVED;
477 isCarbon = true; //not really carbon but received from another resource
478 //TODO this would be the place to change the body after something like mod_pastebin
479 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId)) {
480 return;
481 } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
482 LocalizedContent localizedBody = packet.getBody();
483 if (localizedBody != null) {
484 Message message = conversation.findSentMessageWithBody(localizedBody.content);
485 if (message != null) {
486 mXmppConnectionService.markMessage(message, status);
487 return;
488 }
489 }
490 }
491 } else {
492 status = Message.STATUS_RECEIVED;
493 }
494 }
495 final Message message;
496 if (xP1S3url != null) {
497 message = new Message(conversation, xP1S3url.toString(), Message.ENCRYPTION_NONE, status);
498 message.setOob(true);
499 if (CryptoHelper.isPgpEncryptedUrl(xP1S3url.toString())) {
500 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
501 }
502 } else if (pgpEncrypted != null && Config.supportOpenPgp()) {
503 message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
504 } else if (axolotlEncrypted != null && Config.supportOmemo()) {
505 Jid origin;
506 Set<Jid> fallbacksBySourceId = Collections.emptySet();
507 if (conversationMultiMode) {
508 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
509 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
510 if (origin == null) {
511 try {
512 fallbacksBySourceId = account.getAxolotlService().findCounterpartsBySourceId(XmppAxolotlMessage.parseSourceId(axolotlEncrypted));
513 } catch (IllegalArgumentException e) {
514 //ignoring
515 }
516 }
517 if (origin == null && fallbacksBySourceId.size() == 0) {
518 Log.d(Config.LOGTAG, "axolotl message in anonymous conference received and no possible fallbacks");
519 return;
520 }
521 } else {
522 fallbacksBySourceId = Collections.emptySet();
523 origin = from;
524 }
525
526 final boolean liveMessage = query == null && !isTypeGroupChat && mucUserElement == null;
527 final boolean checkedForDuplicates = liveMessage || (serverMsgId != null && remoteMsgId != null && !conversation.possibleDuplicate(serverMsgId, remoteMsgId));
528
529 if (origin != null) {
530 message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status, checkedForDuplicates, query != null);
531 } else {
532 Message trial = null;
533 for (Jid fallback : fallbacksBySourceId) {
534 trial = parseAxolotlChat(axolotlEncrypted, fallback, conversation, status, checkedForDuplicates && fallbacksBySourceId.size() == 1, query != null);
535 if (trial != null) {
536 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": decoded muc message using fallback");
537 origin = fallback;
538 break;
539 }
540 }
541 message = trial;
542 }
543 if (message == null) {
544 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
545 mXmppConnectionService.updateConversationUi();
546 }
547 if (query != null && status == Message.STATUS_SEND && remoteMsgId != null) {
548 Message previouslySent = conversation.findSentMessageWithUuid(remoteMsgId);
549 if (previouslySent != null && previouslySent.getServerMsgId() == null && serverMsgId != null) {
550 previouslySent.setServerMsgId(serverMsgId);
551 mXmppConnectionService.databaseBackend.updateMessage(previouslySent, false);
552 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": encountered previously sent OMEMO message without serverId. updating...");
553 }
554 }
555 return;
556 }
557 if (conversationMultiMode) {
558 message.setTrueCounterpart(origin);
559 }
560 } else if (body == null && oobUrl != null) {
561 message = new Message(conversation, oobUrl, Message.ENCRYPTION_NONE, status);
562 message.setOob(true);
563 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
564 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
565 }
566 } else {
567 message = new Message(conversation, body.content, Message.ENCRYPTION_NONE, status);
568 if (body.count > 1) {
569 message.setBodyLanguage(body.language);
570 }
571 }
572
573 message.setCounterpart(counterpart);
574 message.setRemoteMsgId(remoteMsgId);
575 message.setServerMsgId(serverMsgId);
576 message.setCarbon(isCarbon);
577 message.setTime(timestamp);
578 if (body != null && body.content != null && body.content.equals(oobUrl)) {
579 message.setOob(true);
580 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
581 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
582 }
583 }
584 message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
585 if (conversationMultiMode) {
586 message.setMucUser(conversation.getMucOptions().findUserByFullJid(counterpart));
587 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
588 Jid trueCounterpart;
589 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
590 trueCounterpart = message.getTrueCounterpart();
591 } else if (query != null && query.safeToExtractTrueCounterpart()) {
592 trueCounterpart = getTrueCounterpart(mucUserElement, fallback);
593 } else {
594 trueCounterpart = fallback;
595 }
596 if (trueCounterpart != null && isTypeGroupChat) {
597 if (trueCounterpart.asBareJid().equals(account.getJid().asBareJid())) {
598 status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
599 } else {
600 status = Message.STATUS_RECEIVED;
601 message.setCarbon(false);
602 }
603 }
604 message.setStatus(status);
605 message.setTrueCounterpart(trueCounterpart);
606 if (!isTypeGroupChat) {
607 message.setType(Message.TYPE_PRIVATE);
608 }
609 } else {
610 updateLastseen(account, from);
611 }
612
613 if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
614 final Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
615 counterpart,
616 message.getStatus() == Message.STATUS_RECEIVED,
617 message.isCarbon());
618 if (replacedMessage != null) {
619 final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
620 || replacedMessage.getFingerprint().equals(message.getFingerprint());
621 final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
622 && message.getTrueCounterpart() != null
623 && replacedMessage.getTrueCounterpart().asBareJid().equals(message.getTrueCounterpart().asBareJid());
624 final boolean mucUserMatches = query == null && replacedMessage.sameMucUser(message); //can not be checked when using mam
625 final boolean duplicate = conversation.hasDuplicateMessage(message);
626 if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode || mucUserMatches) && !duplicate) {
627 Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
628 synchronized (replacedMessage) {
629 final String uuid = replacedMessage.getUuid();
630 replacedMessage.setUuid(UUID.randomUUID().toString());
631 replacedMessage.setBody(message.getBody());
632 replacedMessage.putEdited(replacedMessage.getRemoteMsgId(), replacedMessage.getServerMsgId());
633 replacedMessage.setRemoteMsgId(remoteMsgId);
634 if (replacedMessage.getServerMsgId() == null || message.getServerMsgId() != null) {
635 replacedMessage.setServerMsgId(message.getServerMsgId());
636 }
637 replacedMessage.setEncryption(message.getEncryption());
638 if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
639 replacedMessage.markUnread();
640 }
641 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
642 mXmppConnectionService.updateMessage(replacedMessage, uuid);
643 if (mXmppConnectionService.confirmMessages()
644 && replacedMessage.getStatus() == Message.STATUS_RECEIVED
645 && (replacedMessage.trusted() || replacedMessage.isPrivateMessage()) //TODO do we really want to send receipts for all PMs?
646 && remoteMsgId != null
647 && !selfAddressed
648 && !isTypeGroupChat) {
649 processMessageReceipts(account, packet, query);
650 }
651 if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
652 conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
653 conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
654 }
655 }
656 mXmppConnectionService.getNotificationService().updateNotification();
657 return;
658 } else {
659 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received message correction but verification didn't check out");
660 }
661 }
662 }
663
664 long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate();
665 if (deletionDate != 0 && message.getTimeSent() < deletionDate) {
666 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping message from " + message.getCounterpart().toString() + " because it was sent prior to our deletion date");
667 return;
668 }
669
670 boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay", "urn:xmpp:delay"))
671 || message.isPrivateMessage()
672 || message.getServerMsgId() != null
673 || (query == null && mXmppConnectionService.getMessageArchiveService().isCatchupInProgress(conversation));
674 if (checkForDuplicates) {
675 final Message duplicate = conversation.findDuplicateMessage(message);
676 if (duplicate != null) {
677 final boolean serverMsgIdUpdated;
678 if (duplicate.getStatus() != Message.STATUS_RECEIVED
679 && duplicate.getUuid().equals(message.getRemoteMsgId())
680 && duplicate.getServerMsgId() == null
681 && message.getServerMsgId() != null) {
682 duplicate.setServerMsgId(message.getServerMsgId());
683 if (mXmppConnectionService.databaseBackend.updateMessage(duplicate, false)) {
684 serverMsgIdUpdated = true;
685 } else {
686 serverMsgIdUpdated = false;
687 Log.e(Config.LOGTAG, "failed to update message");
688 }
689 } else {
690 serverMsgIdUpdated = false;
691 }
692 Log.d(Config.LOGTAG, "skipping duplicate message with " + message.getCounterpart() + ". serverMsgIdUpdated=" + serverMsgIdUpdated);
693 return;
694 }
695 }
696
697 if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
698 conversation.prepend(query.getActualInThisQuery(), message);
699 } else {
700 conversation.add(message);
701 }
702 if (query != null) {
703 query.incrementActualMessageCount();
704 }
705
706 if (query == null || query.isCatchup()) { //either no mam or catchup
707 if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
708 mXmppConnectionService.markRead(conversation);
709 if (query == null) {
710 activateGracePeriod(account);
711 }
712 } else {
713 message.markUnread();
714 notify = true;
715 }
716 }
717
718 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
719 notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
720 } else if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE || message.getEncryption() == Message.ENCRYPTION_AXOLOTL_FAILED) {
721 notify = false;
722 }
723
724 if (query == null) {
725 extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet);
726 mXmppConnectionService.updateConversationUi();
727 }
728
729 if (mXmppConnectionService.confirmMessages()
730 && message.getStatus() == Message.STATUS_RECEIVED
731 && (message.trusted() || message.isPrivateMessage())
732 && remoteMsgId != null
733 && !selfAddressed
734 && !isTypeGroupChat) {
735 processMessageReceipts(account, packet, query);
736 }
737
738 mXmppConnectionService.databaseBackend.createMessage(message);
739 final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
740 if (message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
741 manager.createNewDownloadConnection(message);
742 } else if (notify) {
743 if (query != null && query.isCatchup()) {
744 mXmppConnectionService.getNotificationService().pushFromBacklog(message);
745 } else {
746 mXmppConnectionService.getNotificationService().push(message);
747 }
748 }
749 } else if (!packet.hasChild("body")) { //no body
750
751 final Conversation conversation = mXmppConnectionService.find(account, from.asBareJid());
752 if (axolotlEncrypted != null) {
753 Jid origin;
754 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
755 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
756 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
757 if (origin == null) {
758 Log.d(Config.LOGTAG, "omemo key transport message in anonymous conference received");
759 return;
760 }
761 } else if (isTypeGroupChat) {
762 return;
763 } else {
764 origin = from;
765 }
766 try {
767 final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.asBareJid());
768 account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
769 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": omemo key transport message received from " + origin);
770 } catch (Exception e) {
771 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": invalid omemo key transport message received " + e.getMessage());
772 return;
773 }
774 }
775
776 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.asBareJid()), isTypeGroupChat, packet)) {
777 mXmppConnectionService.updateConversationUi();
778 }
779
780 if (isTypeGroupChat) {
781 if (packet.hasChild("subject")) { //TODO usually we would want to check for lack of body; however some servers do set a body :(
782 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
783 conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
784 final LocalizedContent subject = packet.findInternationalizedChildContentInDefaultNamespace("subject");
785 if (subject != null && conversation.getMucOptions().setSubject(subject.content)) {
786 mXmppConnectionService.updateConversation(conversation);
787 }
788 mXmppConnectionService.updateConversationUi();
789 return;
790 }
791 }
792 }
793 if (conversation != null && mucUserElement != null && InvalidJid.hasValidFrom(packet) && from.isBareJid()) {
794 for (Element child : mucUserElement.getChildren()) {
795 if ("status".equals(child.getName())) {
796 try {
797 int code = Integer.parseInt(child.getAttribute("code"));
798 if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
799 mXmppConnectionService.fetchConferenceConfiguration(conversation);
800 break;
801 }
802 } catch (Exception e) {
803 //ignored
804 }
805 } else if ("item".equals(child.getName())) {
806 MucOptions.User user = AbstractParser.parseItem(conversation, child);
807 Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for "
808 + user.getRealJid() + " to " + user.getAffiliation() + " in "
809 + conversation.getJid().asBareJid());
810 if (!user.realJidMatchesAccount()) {
811 boolean isNew = conversation.getMucOptions().updateUser(user);
812 mXmppConnectionService.getAvatarService().clear(conversation);
813 mXmppConnectionService.updateMucRosterUi();
814 mXmppConnectionService.updateConversationUi();
815 Contact contact = user.getContact();
816 if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
817 Jid jid = user.getRealJid();
818 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
819 if (cryptoTargets.remove(user.getRealJid())) {
820 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
821 conversation.setAcceptedCryptoTargets(cryptoTargets);
822 mXmppConnectionService.updateConversation(conversation);
823 }
824 } else if (isNew
825 && user.getRealJid() != null
826 && conversation.getMucOptions().isPrivateAndNonAnonymous()
827 && (contact == null || !contact.mutualPresenceSubscription())
828 && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
829 account.getAxolotlService().fetchDeviceIds(user.getRealJid());
830 }
831 }
832 }
833 }
834 }
835 if (!isTypeGroupChat) {
836 for (Element child : packet.getChildren()) {
837 if (Namespace.JINGLE_MESSAGE.equals(child.getNamespace()) && JINGLE_MESSAGE_ELEMENT_NAMES.contains(child.getName())) {
838 final String action = child.getName();
839 if (query == null) {
840 if (serverMsgId == null) {
841 serverMsgId = extractStanzaId(account, packet);
842 }
843 mXmppConnectionService.getJingleConnectionManager().deliverMessage(account, packet.getTo(), packet.getFrom(), child, remoteMsgId, serverMsgId, timestamp);
844 if (!account.getJid().asBareJid().equals(from.asBareJid())) {
845 processMessageReceipts(account, packet, query);
846 }
847 } else if (query.isCatchup()) {
848 final String sessionId = child.getAttribute("id");
849 if (sessionId == null) {
850 break;
851 }
852 if ("propose".equals(action)) {
853 final Element description = child.findChild("description");
854 final String namespace = description == null ? null : description.getNamespace();
855 if (Namespace.JINGLE_APPS_RTP.equals(namespace)) {
856 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
857 final Message preExistingMessage = c.findRtpSession(sessionId, status);
858 if (preExistingMessage != null) {
859 preExistingMessage.setServerMsgId(serverMsgId);
860 mXmppConnectionService.updateMessage(preExistingMessage);
861 break;
862 }
863 final Message message = new Message(
864 c,
865 status,
866 Message.TYPE_RTP_SESSION,
867 sessionId
868 );
869 message.setServerMsgId(serverMsgId);
870 message.setTime(timestamp);
871 message.setBody(new RtpSessionStatus(false, 0).toString());
872 c.add(message);
873 mXmppConnectionService.databaseBackend.createMessage(message);
874 }
875
876 } else if ("proceed".equals(action)) {
877 //status needs to be flipped to find the original propose
878 final Conversation c = mXmppConnectionService.findOrCreateConversation(account, counterpart.asBareJid(), false, false);
879 final int s = packet.fromAccount(account) ? Message.STATUS_RECEIVED : Message.STATUS_SEND;
880 final Message message = c.findRtpSession(sessionId, s);
881 if (message != null) {
882 message.setBody(new RtpSessionStatus(true, 0).toString());
883 if (serverMsgId != null) {
884 message.setServerMsgId(serverMsgId);
885 }
886 message.setTime(timestamp);
887 mXmppConnectionService.updateMessage(message, true);
888 } else {
889 Log.d(Config.LOGTAG, "unable to find original rtp session message for received propose");
890 }
891
892 }
893 }
894 break;
895 }
896 }
897 }
898 }
899
900 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
901 if (received == null) {
902 received = packet.findChild("received", "urn:xmpp:receipts");
903 }
904 if (received != null) {
905 String id = received.getAttribute("id");
906 if (packet.fromAccount(account)) {
907 if (query != null && id != null && packet.getTo() != null) {
908 query.removePendingReceiptRequest(new ReceiptRequest(packet.getTo(), id));
909 }
910 } else if (id != null) {
911 if (id.startsWith(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX)) {
912 final String sessionId = id.substring(JingleRtpConnection.JINGLE_MESSAGE_PROPOSE_ID_PREFIX.length());
913 mXmppConnectionService.getJingleConnectionManager()
914 .updateProposedSessionDiscovered(account, from, sessionId, JingleConnectionManager.DeviceDiscoveryState.DISCOVERED);
915 } else {
916 mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_RECEIVED);
917 }
918 }
919 }
920 Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
921 if (displayed != null) {
922 final String id = displayed.getAttribute("id");
923 final Jid sender = InvalidJid.getNullForInvalid(displayed.getAttributeAsJid("sender"));
924 if (packet.fromAccount(account) && !selfAddressed) {
925 dismissNotification(account, counterpart, query);
926 if (query == null) {
927 activateGracePeriod(account);
928 }
929 } else if (isTypeGroupChat) {
930 final Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
931 final Message message;
932 if (conversation != null && id != null) {
933 if (sender != null) {
934 message = conversation.findMessageWithRemoteId(id, sender);
935 } else {
936 message = conversation.findMessageWithServerMsgId(id);
937 }
938 } else {
939 message = null;
940 }
941 if (message != null) {
942 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
943 final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
944 final boolean trueJidMatchesAccount = account.getJid().asBareJid().equals(trueJid == null ? null : trueJid.asBareJid());
945 if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
946 if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
947 mXmppConnectionService.markRead(conversation);
948 }
949 } else if (!counterpart.isBareJid() && trueJid != null) {
950 final ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
951 if (message.addReadByMarker(readByMarker)) {
952 mXmppConnectionService.updateMessage(message, false);
953 }
954 }
955 }
956 } else {
957 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.asBareJid(), id, Message.STATUS_SEND_DISPLAYED);
958 Message message = displayedMessage == null ? null : displayedMessage.prev();
959 while (message != null
960 && message.getStatus() == Message.STATUS_SEND_RECEIVED
961 && message.getTimeSent() < displayedMessage.getTimeSent()) {
962 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
963 message = message.prev();
964 }
965 if (displayedMessage != null && selfAddressed) {
966 dismissNotification(account, counterpart, query);
967 }
968 }
969 }
970
971 final Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
972 if (event != null && InvalidJid.hasValidFrom(original)) {
973 if (event.hasChild("items")) {
974 parseEvent(event, original.getFrom(), account);
975 } else if (event.hasChild("delete")) {
976 parseDeleteEvent(event, original.getFrom(), account);
977 } else if (event.hasChild("purge")) {
978 parsePurgeEvent(event, original.getFrom(), account);
979 }
980 }
981
982 final String nick = packet.findChildContent("nick", Namespace.NICK);
983 if (nick != null && InvalidJid.hasValidFrom(original)) {
984 Contact contact = account.getRoster().getContact(from);
985 if (contact.setPresenceName(nick)) {
986 mXmppConnectionService.getAvatarService().clear(contact);
987 }
988 }
989 }
990
991 private void dismissNotification(Account account, Jid counterpart, MessageArchiveService.Query query) {
992 Conversation conversation = mXmppConnectionService.find(account, counterpart.asBareJid());
993 if (conversation != null && (query == null || query.isCatchup())) {
994 mXmppConnectionService.markRead(conversation); //TODO only mark messages read that are older than timestamp
995 }
996 }
997
998 private void processMessageReceipts(Account account, MessagePacket packet, MessageArchiveService.Query query) {
999 final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
1000 final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
1001 if (query == null) {
1002 final ArrayList<String> receiptsNamespaces = new ArrayList<>();
1003 if (markable) {
1004 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
1005 }
1006 if (request) {
1007 receiptsNamespaces.add("urn:xmpp:receipts");
1008 }
1009 if (receiptsNamespaces.size() > 0) {
1010 MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
1011 packet,
1012 receiptsNamespaces,
1013 packet.getType());
1014 mXmppConnectionService.sendMessagePacket(account, receipt);
1015 }
1016 } else if (query.isCatchup()) {
1017 if (request) {
1018 query.addPendingReceiptRequest(new ReceiptRequest(packet.getFrom(), packet.getId()));
1019 }
1020 }
1021 }
1022
1023 private void activateGracePeriod(Account account) {
1024 long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
1025 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
1026 account.activateGracePeriod(duration);
1027 }
1028
1029 private class Invite {
1030 final Jid jid;
1031 final String password;
1032 final boolean direct;
1033 final Jid inviter;
1034
1035 Invite(Jid jid, String password, boolean direct, Jid inviter) {
1036 this.jid = jid;
1037 this.password = password;
1038 this.direct = direct;
1039 this.inviter = inviter;
1040 }
1041
1042 public boolean execute(Account account) {
1043 if (jid != null) {
1044 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
1045 if (conversation.getMucOptions().online()) {
1046 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received invite to " + jid + " but muc is considered to be online");
1047 mXmppConnectionService.mucSelfPingAndRejoin(conversation);
1048 } else {
1049 conversation.getMucOptions().setPassword(password);
1050 mXmppConnectionService.databaseBackend.updateConversation(conversation);
1051 final Contact contact = inviter != null ? account.getRoster().getContactFromContactList(inviter) : null;
1052 mXmppConnectionService.joinMuc(conversation, contact != null && contact.mutualPresenceSubscription());
1053 mXmppConnectionService.updateConversationUi();
1054 }
1055 return true;
1056 }
1057 return false;
1058 }
1059 }
1060}