1package eu.siacs.conversations.services;
2
3import android.annotation.SuppressLint;
4import android.app.AlarmManager;
5import android.app.PendingIntent;
6import android.app.Service;
7import android.content.Context;
8import android.content.Intent;
9import android.content.IntentFilter;
10import android.content.SharedPreferences;
11import android.database.ContentObserver;
12import android.graphics.Bitmap;
13import android.media.AudioManager;
14import android.net.ConnectivityManager;
15import android.net.NetworkInfo;
16import android.net.Uri;
17import android.os.Binder;
18import android.os.Build;
19import android.os.Bundle;
20import android.os.FileObserver;
21import android.os.IBinder;
22import android.os.Looper;
23import android.os.PowerManager;
24import android.os.PowerManager.WakeLock;
25import android.os.SystemClock;
26import android.preference.PreferenceManager;
27import android.provider.ContactsContract;
28import android.security.KeyChain;
29import android.util.DisplayMetrics;
30import android.util.Log;
31import android.util.LruCache;
32import android.util.Pair;
33
34import net.java.otr4j.OtrException;
35import net.java.otr4j.session.Session;
36import net.java.otr4j.session.SessionID;
37import net.java.otr4j.session.SessionImpl;
38import net.java.otr4j.session.SessionStatus;
39
40import org.openintents.openpgp.IOpenPgpService2;
41import org.openintents.openpgp.util.OpenPgpApi;
42import org.openintents.openpgp.util.OpenPgpServiceConnection;
43
44import java.math.BigInteger;
45import java.security.SecureRandom;
46import java.security.cert.CertificateException;
47import java.security.cert.X509Certificate;
48import java.util.ArrayList;
49import java.util.Arrays;
50import java.util.Collection;
51import java.util.Collections;
52import java.util.Comparator;
53import java.util.HashMap;
54import java.util.HashSet;
55import java.util.Hashtable;
56import java.util.Iterator;
57import java.util.List;
58import java.util.Locale;
59import java.util.Map;
60import java.util.concurrent.CopyOnWriteArrayList;
61
62import de.duenndns.ssl.MemorizingTrustManager;
63import eu.siacs.conversations.Config;
64import eu.siacs.conversations.R;
65import eu.siacs.conversations.crypto.PgpEngine;
66import eu.siacs.conversations.crypto.axolotl.AxolotlService;
67import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
68import eu.siacs.conversations.entities.Account;
69import eu.siacs.conversations.entities.Blockable;
70import eu.siacs.conversations.entities.Bookmark;
71import eu.siacs.conversations.entities.Contact;
72import eu.siacs.conversations.entities.Conversation;
73import eu.siacs.conversations.entities.Message;
74import eu.siacs.conversations.entities.MucOptions;
75import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
76import eu.siacs.conversations.entities.Presence;
77import eu.siacs.conversations.entities.PresenceTemplate;
78import eu.siacs.conversations.entities.Roster;
79import eu.siacs.conversations.entities.ServiceDiscoveryResult;
80import eu.siacs.conversations.entities.Transferable;
81import eu.siacs.conversations.entities.TransferablePlaceholder;
82import eu.siacs.conversations.generator.IqGenerator;
83import eu.siacs.conversations.generator.MessageGenerator;
84import eu.siacs.conversations.generator.PresenceGenerator;
85import eu.siacs.conversations.http.HttpConnectionManager;
86import eu.siacs.conversations.parser.IqParser;
87import eu.siacs.conversations.parser.MessageParser;
88import eu.siacs.conversations.parser.PresenceParser;
89import eu.siacs.conversations.persistance.DatabaseBackend;
90import eu.siacs.conversations.persistance.FileBackend;
91import eu.siacs.conversations.ui.UiCallback;
92import eu.siacs.conversations.utils.CryptoHelper;
93import eu.siacs.conversations.utils.ExceptionHelper;
94import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
95import eu.siacs.conversations.utils.PRNGFixes;
96import eu.siacs.conversations.utils.PhoneHelper;
97import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
98import eu.siacs.conversations.utils.Xmlns;
99import eu.siacs.conversations.xml.Element;
100import eu.siacs.conversations.xmpp.OnBindListener;
101import eu.siacs.conversations.xmpp.OnContactStatusChanged;
102import eu.siacs.conversations.xmpp.OnIqPacketReceived;
103import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
104import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
105import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
106import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
107import eu.siacs.conversations.xmpp.OnStatusChanged;
108import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
109import eu.siacs.conversations.xmpp.XmppConnection;
110import eu.siacs.conversations.xmpp.chatstate.ChatState;
111import eu.siacs.conversations.xmpp.forms.Data;
112import eu.siacs.conversations.xmpp.forms.Field;
113import eu.siacs.conversations.xmpp.jid.InvalidJidException;
114import eu.siacs.conversations.xmpp.jid.Jid;
115import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
116import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
117import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
118import eu.siacs.conversations.xmpp.pep.Avatar;
119import eu.siacs.conversations.xmpp.stanzas.IqPacket;
120import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
121import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
122import me.leolin.shortcutbadger.ShortcutBadger;
123
124public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
125
126 public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
127 public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
128 public static final String ACTION_TRY_AGAIN = "try_again";
129 public static final String ACTION_DISABLE_ACCOUNT = "disable_account";
130 private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
131 public static final String ACTION_GCM_TOKEN_REFRESH = "gcm_token_refresh";
132 public static final String ACTION_GCM_MESSAGE_RECEIVED = "gcm_message_received";
133 private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
134 private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
135 private final IBinder mBinder = new XmppConnectionBinder();
136 private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
137 private final IqGenerator mIqGenerator = new IqGenerator(this);
138 private final List<String> mInProgressAvatarFetches = new ArrayList<>();
139 public DatabaseBackend databaseBackend;
140 private ContentObserver contactObserver = new ContentObserver(null) {
141 @Override
142 public void onChange(boolean selfChange) {
143 super.onChange(selfChange);
144 Intent intent = new Intent(getApplicationContext(),
145 XmppConnectionService.class);
146 intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
147 startService(intent);
148 }
149 };
150 private FileBackend fileBackend = new FileBackend(this);
151 private MemorizingTrustManager mMemorizingTrustManager;
152 private NotificationService mNotificationService = new NotificationService(
153 this);
154 private OnMessagePacketReceived mMessageParser = new MessageParser(this);
155 private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
156 private IqParser mIqParser = new IqParser(this);
157 private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
158 @Override
159 public void onIqPacketReceived(Account account, IqPacket packet) {
160 if (packet.getType() != IqPacket.TYPE.RESULT) {
161 Element error = packet.findChild("error");
162 String text = error != null ? error.findChildContent("text") : null;
163 if (text != null) {
164 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received iq error - " + text);
165 }
166 }
167 }
168 };
169 private MessageGenerator mMessageGenerator = new MessageGenerator(this);
170 private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
171 private List<Account> accounts;
172 private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
173 this);
174 public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
175
176 @Override
177 public void onContactStatusChanged(Contact contact, boolean online) {
178 Conversation conversation = find(getConversations(), contact);
179 if (conversation != null) {
180 if (online) {
181 conversation.endOtrIfNeeded();
182 if (contact.getPresences().size() == 1) {
183 sendUnsentMessages(conversation);
184 }
185 } else {
186 if (contact.getPresences().size() >= 1) {
187 if (conversation.hasValidOtrSession()) {
188 String otrResource = conversation.getOtrSession().getSessionID().getUserID();
189 if (!(Arrays.asList(contact.getPresences().asStringArray()).contains(otrResource))) {
190 conversation.endOtrIfNeeded();
191 }
192 }
193 } else {
194 conversation.endOtrIfNeeded();
195 }
196 }
197 }
198 }
199 };
200 private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
201 this);
202 private AvatarService mAvatarService = new AvatarService(this);
203 private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
204 private PushManagementService mPushManagementService = new PushManagementService(this);
205 private OnConversationUpdate mOnConversationUpdate = null;
206 private final FileObserver fileObserver = new FileObserver(
207 FileBackend.getConversationsImageDirectory()) {
208
209 @Override
210 public void onEvent(int event, String path) {
211 if (event == FileObserver.DELETE) {
212 markFileDeleted(path.split("\\.")[0]);
213 }
214 }
215 };
216 private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
217
218 @Override
219 public void onJinglePacketReceived(Account account, JinglePacket packet) {
220 mJingleConnectionManager.deliverPacket(account, packet);
221 }
222 };
223 private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
224
225 @Override
226 public void onMessageAcknowledged(Account account, String uuid) {
227 for (final Conversation conversation : getConversations()) {
228 if (conversation.getAccount() == account) {
229 Message message = conversation.findUnsentMessageWithUuid(uuid);
230 if (message != null) {
231 markMessage(message, Message.STATUS_SEND);
232 }
233 }
234 }
235 }
236 };
237 private int convChangedListenerCount = 0;
238 private OnShowErrorToast mOnShowErrorToast = null;
239 private int showErrorToastListenerCount = 0;
240 private int unreadCount = -1;
241 private OnAccountUpdate mOnAccountUpdate = null;
242 private OnCaptchaRequested mOnCaptchaRequested = null;
243 private int accountChangedListenerCount = 0;
244 private int captchaRequestedListenerCount = 0;
245 private OnRosterUpdate mOnRosterUpdate = null;
246 private OnUpdateBlocklist mOnUpdateBlocklist = null;
247 private int updateBlocklistListenerCount = 0;
248 private int rosterChangedListenerCount = 0;
249 private OnMucRosterUpdate mOnMucRosterUpdate = null;
250 private int mucRosterChangedListenerCount = 0;
251 private OnKeyStatusUpdated mOnKeyStatusUpdated = null;
252 private int keyStatusUpdatedListenerCount = 0;
253 private SecureRandom mRandom;
254 private LruCache<Pair<String,String>,ServiceDiscoveryResult> discoCache = new LruCache<>(20);
255 private final OnBindListener mOnBindListener = new OnBindListener() {
256
257 @Override
258 public void onBind(final Account account) {
259 synchronized (mInProgressAvatarFetches) {
260 for (Iterator<String> iterator = mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
261 final String KEY = iterator.next();
262 if (KEY.startsWith(account.getJid().toBareJid() + "_")) {
263 iterator.remove();
264 }
265 }
266 }
267 account.getRoster().clearPresences();
268 mJingleConnectionManager.cancelInTransmission();
269 fetchRosterFromServer(account);
270 fetchBookmarks(account);
271 sendPresence(account);
272 if (mPushManagementService.available(account)) {
273 mPushManagementService.registerPushTokenOnServer(account);
274 }
275 connectMultiModeConversations(account);
276 syncDirtyContacts(account);
277 }
278 };
279 private OnStatusChanged statusListener = new OnStatusChanged() {
280
281 @Override
282 public void onStatusChanged(final Account account) {
283 XmppConnection connection = account.getXmppConnection();
284 if (mOnAccountUpdate != null) {
285 mOnAccountUpdate.onAccountUpdate();
286 }
287 if (account.getStatus() == Account.State.ONLINE) {
288 mMessageArchiveService.executePendingQueries(account);
289 if (connection != null && connection.getFeatures().csi()) {
290 if (checkListeners()) {
291 Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//inactive");
292 connection.sendInactive();
293 } else {
294 Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//active");
295 connection.sendActive();
296 }
297 }
298 List<Conversation> conversations = getConversations();
299 for (Conversation conversation : conversations) {
300 if (conversation.getAccount() == account
301 && !account.pendingConferenceJoins.contains(conversation)) {
302 if (!conversation.startOtrIfNeeded()) {
303 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": couldn't start OTR with "+conversation.getContact().getJid()+" when needed");
304 }
305 sendUnsentMessages(conversation);
306 }
307 }
308 for (Conversation conversation : account.pendingConferenceLeaves) {
309 leaveMuc(conversation);
310 }
311 account.pendingConferenceLeaves.clear();
312 for (Conversation conversation : account.pendingConferenceJoins) {
313 joinMuc(conversation);
314 }
315 account.pendingConferenceJoins.clear();
316 scheduleWakeUpCall(Config.PING_MAX_INTERVAL, account.getUuid().hashCode());
317 } else if (account.getStatus() == Account.State.OFFLINE) {
318 resetSendingToWaiting(account);
319 final boolean disabled = account.isOptionSet(Account.OPTION_DISABLED);
320 final boolean pushMode = Config.CLOSE_TCP_WHEN_SWITCHING_TO_BACKGROUND
321 && mPushManagementService.available(account)
322 && checkListeners();
323 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": push mode "+Boolean.toString(pushMode));
324 if (!disabled && !pushMode) {
325 int timeToReconnect = mRandom.nextInt(20) + 10;
326 scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode());
327 }
328 } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
329 databaseBackend.updateAccount(account);
330 reconnectAccount(account, true, false);
331 } else if ((account.getStatus() != Account.State.CONNECTING)
332 && (account.getStatus() != Account.State.NO_INTERNET)) {
333 if (connection != null) {
334 int next = connection.getTimeToNextAttempt();
335 Log.d(Config.LOGTAG, account.getJid().toBareJid()
336 + ": error connecting account. try again in "
337 + next + "s for the "
338 + (connection.getAttempt() + 1) + " time");
339 scheduleWakeUpCall(next, account.getUuid().hashCode());
340 }
341 }
342 getNotificationService().updateErrorNotification();
343 }
344 };
345 private OpenPgpServiceConnection pgpServiceConnection;
346 private PgpEngine mPgpEngine = null;
347 private WakeLock wakeLock;
348 private PowerManager pm;
349 private LruCache<String, Bitmap> mBitmapCache;
350 private Thread mPhoneContactMergerThread;
351 private EventReceiver mEventReceiver = new EventReceiver();
352
353 private boolean mRestoredFromDatabase = false;
354
355 private static String generateFetchKey(Account account, final Avatar avatar) {
356 return account.getJid().toBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum;
357 }
358
359 public boolean areMessagesInitialized() {
360 return this.mRestoredFromDatabase;
361 }
362
363 public PgpEngine getPgpEngine() {
364 if (!Config.supportOpenPgp()) {
365 return null;
366 } else if (pgpServiceConnection != null && pgpServiceConnection.isBound()) {
367 if (this.mPgpEngine == null) {
368 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
369 getApplicationContext(),
370 pgpServiceConnection.getService()), this);
371 }
372 return mPgpEngine;
373 } else {
374 return null;
375 }
376
377 }
378
379 public FileBackend getFileBackend() {
380 return this.fileBackend;
381 }
382
383 public AvatarService getAvatarService() {
384 return this.mAvatarService;
385 }
386
387 public void attachLocationToConversation(final Conversation conversation,
388 final Uri uri,
389 final UiCallback<Message> callback) {
390 int encryption = conversation.getNextEncryption();
391 if (encryption == Message.ENCRYPTION_PGP) {
392 encryption = Message.ENCRYPTION_DECRYPTED;
393 }
394 Message message = new Message(conversation, uri.toString(), encryption);
395 if (conversation.getNextCounterpart() != null) {
396 message.setCounterpart(conversation.getNextCounterpart());
397 }
398 if (encryption == Message.ENCRYPTION_DECRYPTED) {
399 getPgpEngine().encrypt(message, callback);
400 } else {
401 callback.success(message);
402 }
403 }
404
405 public void attachFileToConversation(final Conversation conversation,
406 final Uri uri,
407 final UiCallback<Message> callback) {
408 if (FileBackend.weOwnFile(this, uri)) {
409 Log.d(Config.LOGTAG,"trying to attach file that belonged to us");
410 callback.error(R.string.security_error_invalid_file_access, null);
411 return;
412 }
413 final Message message;
414 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
415 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
416 } else {
417 message = new Message(conversation, "", conversation.getNextEncryption());
418 }
419 message.setCounterpart(conversation.getNextCounterpart());
420 message.setType(Message.TYPE_FILE);
421 String path = getFileBackend().getOriginalPath(uri);
422 if (path != null) {
423 message.setRelativeFilePath(path);
424 getFileBackend().updateFileParams(message);
425 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
426 getPgpEngine().encrypt(message, callback);
427 } else {
428 callback.success(message);
429 }
430 } else {
431 mFileAddingExecutor.execute(new Runnable() {
432 @Override
433 public void run() {
434 try {
435 getFileBackend().copyFileToPrivateStorage(message, uri);
436 getFileBackend().updateFileParams(message);
437 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
438 getPgpEngine().encrypt(message, callback);
439 } else {
440 callback.success(message);
441 }
442 } catch (FileBackend.FileCopyException e) {
443 callback.error(e.getResId(), message);
444 }
445 }
446 });
447 }
448 }
449
450 public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback<Message> callback) {
451 if (FileBackend.weOwnFile(this, uri)) {
452 Log.d(Config.LOGTAG,"trying to attach file that belonged to us");
453 callback.error(R.string.security_error_invalid_file_access, null);
454 return;
455 }
456 final String compressPictures = getCompressPicturesPreference();
457 if ("never".equals(compressPictures)
458 || ("auto".equals(compressPictures) && getFileBackend().useImageAsIs(uri))) {
459 Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+ ": not compressing picture. sending as file");
460 attachFileToConversation(conversation, uri, callback);
461 return;
462 }
463 final Message message;
464 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
465 message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED);
466 } else {
467 message = new Message(conversation, "", conversation.getNextEncryption());
468 }
469 message.setCounterpart(conversation.getNextCounterpart());
470 message.setType(Message.TYPE_IMAGE);
471 mFileAddingExecutor.execute(new Runnable() {
472
473 @Override
474 public void run() {
475 try {
476 getFileBackend().copyImageToPrivateStorage(message, uri);
477 if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) {
478 getPgpEngine().encrypt(message, callback);
479 } else {
480 callback.success(message);
481 }
482 } catch (final FileBackend.FileCopyException e) {
483 callback.error(e.getResId(), message);
484 }
485 }
486 });
487 }
488
489 public Conversation find(Bookmark bookmark) {
490 return find(bookmark.getAccount(), bookmark.getJid());
491 }
492
493 public Conversation find(final Account account, final Jid jid) {
494 return find(getConversations(), account, jid);
495 }
496
497 @Override
498 public int onStartCommand(Intent intent, int flags, int startId) {
499 final String action = intent == null ? null : intent.getAction();
500 boolean interactive = false;
501 if (action != null) {
502 switch (action) {
503 case ConnectivityManager.CONNECTIVITY_ACTION:
504 if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
505 resetAllAttemptCounts(true);
506 }
507 break;
508 case ACTION_MERGE_PHONE_CONTACTS:
509 if (mRestoredFromDatabase) {
510 loadPhoneContacts();
511 }
512 return START_STICKY;
513 case Intent.ACTION_SHUTDOWN:
514 logoutAndSave(true);
515 return START_NOT_STICKY;
516 case ACTION_CLEAR_NOTIFICATION:
517 mNotificationService.clear();
518 break;
519 case ACTION_DISABLE_FOREGROUND:
520 getPreferences().edit().putBoolean("keep_foreground_service", false).commit();
521 toggleForegroundService();
522 break;
523 case ACTION_TRY_AGAIN:
524 resetAllAttemptCounts(false);
525 interactive = true;
526 break;
527 case ACTION_DISABLE_ACCOUNT:
528 try {
529 String jid = intent.getStringExtra("account");
530 Account account = jid == null ? null : findAccountByJid(Jid.fromString(jid));
531 if (account != null) {
532 account.setOption(Account.OPTION_DISABLED, true);
533 updateAccount(account);
534 }
535 } catch (final InvalidJidException ignored) {
536 break;
537 }
538 break;
539 case AudioManager.RINGER_MODE_CHANGED_ACTION:
540 if (xaOnSilentMode()) {
541 refreshAllPresences();
542 }
543 break;
544 case Intent.ACTION_SCREEN_OFF:
545 case Intent.ACTION_SCREEN_ON:
546 if (awayWhenScreenOff()) {
547 refreshAllPresences();
548 }
549 break;
550 case ACTION_GCM_TOKEN_REFRESH:
551 refreshAllGcmTokens();
552 break;
553 case ACTION_GCM_MESSAGE_RECEIVED:
554 Log.d(Config.LOGTAG,"gcm push message arrived in service. extras="+intent.getExtras());
555 }
556 }
557 this.wakeLock.acquire();
558
559 boolean pingNow = false;
560 HashSet<Account> pingCandidates = new HashSet<>();
561
562 for (Account account : accounts) {
563 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
564 if (!hasInternetConnection()) {
565 account.setStatus(Account.State.NO_INTERNET);
566 if (statusListener != null) {
567 statusListener.onStatusChanged(account);
568 }
569 } else {
570 if (account.getStatus() == Account.State.NO_INTERNET) {
571 account.setStatus(Account.State.OFFLINE);
572 if (statusListener != null) {
573 statusListener.onStatusChanged(account);
574 }
575 }
576 if (account.getStatus() == Account.State.ONLINE) {
577 long lastReceived = account.getXmppConnection().getLastPacketReceived();
578 long lastSent = account.getXmppConnection().getLastPingSent();
579 long pingInterval = "ui".equals(action) ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
580 long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime();
581 long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime();
582 if (lastSent > lastReceived) {
583 if (pingTimeoutIn < 0) {
584 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
585 this.reconnectAccount(account, true, interactive);
586 } else {
587 int secs = (int) (pingTimeoutIn / 1000);
588 this.scheduleWakeUpCall(secs, account.getUuid().hashCode());
589 }
590 } else {
591 pingCandidates.add(account);
592 if (msToNextPing <= 0) {
593 pingNow = true;
594 } else {
595 this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
596 }
597 }
598 } else if (account.getStatus() == Account.State.OFFLINE) {
599 reconnectAccount(account, true, interactive);
600 } else if (account.getStatus() == Account.State.CONNECTING) {
601 long secondsSinceLastConnect = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000;
602 long secondsSinceLastDisco = (SystemClock.elapsedRealtime() - account.getXmppConnection().getLastDiscoStarted()) / 1000;
603 long discoTimeout = Config.CONNECT_DISCO_TIMEOUT - secondsSinceLastDisco;
604 long timeout = Config.CONNECT_TIMEOUT - secondsSinceLastConnect;
605 if (timeout < 0) {
606 Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting");
607 account.getXmppConnection().resetAttemptCount();
608 reconnectAccount(account, true, interactive);
609 } else if (discoTimeout < 0) {
610 account.getXmppConnection().sendDiscoTimeout();
611 scheduleWakeUpCall((int) Math.min(timeout,discoTimeout), account.getUuid().hashCode());
612 } else {
613 scheduleWakeUpCall((int) Math.min(timeout,discoTimeout), account.getUuid().hashCode());
614 }
615 } else {
616 if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
617 reconnectAccount(account, true, interactive);
618 }
619 }
620 }
621 if (mOnAccountUpdate != null) {
622 mOnAccountUpdate.onAccountUpdate();
623 }
624 }
625 }
626 if (pingNow) {
627 for (Account account : pingCandidates) {
628 account.getXmppConnection().sendPing();
629 Log.d(Config.LOGTAG, account.getJid().toBareJid() + " send ping");
630 this.scheduleWakeUpCall(Config.PING_TIMEOUT, account.getUuid().hashCode());
631 }
632 }
633 if (wakeLock.isHeld()) {
634 try {
635 wakeLock.release();
636 } catch (final RuntimeException ignored) {
637 }
638 }
639 return START_STICKY;
640 }
641
642 private boolean xaOnSilentMode() {
643 return getPreferences().getBoolean("xa_on_silent_mode", false);
644 }
645
646 private boolean manuallyChangePresence() {
647 return getPreferences().getBoolean("manually_change_presence", false);
648 }
649
650 private boolean treatVibrateAsSilent() {
651 return getPreferences().getBoolean("treat_vibrate_as_silent", false);
652 }
653
654 private boolean awayWhenScreenOff() {
655 return getPreferences().getBoolean("away_when_screen_off", false);
656 }
657
658 private String getCompressPicturesPreference() {
659 return getPreferences().getString("picture_compression", "auto");
660 }
661
662 private Presence.Status getTargetPresence() {
663 if (xaOnSilentMode() && isPhoneSilenced()) {
664 return Presence.Status.XA;
665 } else if (awayWhenScreenOff() && !isInteractive()) {
666 return Presence.Status.AWAY;
667 } else {
668 return Presence.Status.ONLINE;
669 }
670 }
671
672 @SuppressLint("NewApi")
673 @SuppressWarnings("deprecation")
674 public boolean isInteractive() {
675 final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
676
677 final boolean isScreenOn;
678 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
679 isScreenOn = pm.isScreenOn();
680 } else {
681 isScreenOn = pm.isInteractive();
682 }
683 return isScreenOn;
684 }
685
686 private boolean isPhoneSilenced() {
687 AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
688 if (treatVibrateAsSilent()) {
689 return audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL;
690 } else {
691 return audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
692 }
693 }
694
695 private void resetAllAttemptCounts(boolean reallyAll) {
696 Log.d(Config.LOGTAG, "resetting all attempt counts");
697 for (Account account : accounts) {
698 if (account.hasErrorStatus() || reallyAll) {
699 final XmppConnection connection = account.getXmppConnection();
700 if (connection != null) {
701 connection.resetAttemptCount();
702 }
703 }
704 }
705 }
706
707 public boolean hasInternetConnection() {
708 ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
709 .getSystemService(Context.CONNECTIVITY_SERVICE);
710 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
711 return activeNetwork != null && activeNetwork.isConnected();
712 }
713
714 @SuppressLint("TrulyRandom")
715 @Override
716 public void onCreate() {
717 ExceptionHelper.init(getApplicationContext());
718 PRNGFixes.apply();
719 this.mRandom = new SecureRandom();
720 updateMemorizingTrustmanager();
721 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
722 final int cacheSize = maxMemory / 8;
723 this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
724 @Override
725 protected int sizeOf(final String key, final Bitmap bitmap) {
726 return bitmap.getByteCount() / 1024;
727 }
728 };
729
730 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
731 this.accounts = databaseBackend.getAccounts();
732
733 restoreFromDatabase();
734
735 getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
736 this.fileObserver.startWatching();
737
738 if (Config.supportOpenPgp()) {
739 this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain", new OpenPgpServiceConnection.OnBound() {
740 @Override
741 public void onBound(IOpenPgpService2 service) {
742 for (Account account : accounts) {
743 if (account.getPgpDecryptionService() != null) {
744 account.getPgpDecryptionService().onOpenPgpServiceBound();
745 }
746 }
747 }
748
749 @Override
750 public void onError(Exception e) {
751 }
752 });
753 this.pgpServiceConnection.bindToService();
754 }
755
756 this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
757 this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XmppConnectionService");
758 toggleForegroundService();
759 updateUnreadCountBadge();
760 toggleScreenEventReceiver();
761 }
762
763 @Override
764 public void onTrimMemory(int level) {
765 super.onTrimMemory(level);
766 if (level >= TRIM_MEMORY_COMPLETE) {
767 Log.d(Config.LOGTAG, "clear cache due to low memory");
768 getBitmapCache().evictAll();
769 }
770 }
771
772 @Override
773 public void onDestroy() {
774 try {
775 unregisterReceiver(this.mEventReceiver);
776 } catch (IllegalArgumentException e) {
777 //ignored
778 }
779 super.onDestroy();
780 }
781
782 public void toggleScreenEventReceiver() {
783 if (awayWhenScreenOff() && !manuallyChangePresence()) {
784 final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
785 filter.addAction(Intent.ACTION_SCREEN_OFF);
786 registerReceiver(this.mEventReceiver, filter);
787 } else {
788 try {
789 unregisterReceiver(this.mEventReceiver);
790 } catch (IllegalArgumentException e) {
791 //ignored
792 }
793 }
794 }
795
796 public void toggleForegroundService() {
797 if (getPreferences().getBoolean("keep_foreground_service", false)) {
798 startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
799 } else {
800 stopForeground(true);
801 }
802 }
803
804 @Override
805 public void onTaskRemoved(final Intent rootIntent) {
806 super.onTaskRemoved(rootIntent);
807 if (!getPreferences().getBoolean("keep_foreground_service", false)) {
808 this.logoutAndSave(false);
809 }
810 }
811
812 private void logoutAndSave(boolean stop) {
813 int activeAccounts = 0;
814 for (final Account account : accounts) {
815 if (account.getStatus() != Account.State.DISABLED) {
816 activeAccounts++;
817 }
818 databaseBackend.writeRoster(account.getRoster());
819 if (account.getXmppConnection() != null) {
820 new Thread(new Runnable() {
821 @Override
822 public void run() {
823 disconnect(account, false);
824 }
825 }).start();
826 }
827 }
828 if (stop || activeAccounts == 0) {
829 Log.d(Config.LOGTAG, "good bye");
830 stopSelf();
831 }
832 }
833
834 private void cancelWakeUpCall(int requestCode) {
835 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
836 final Intent intent = new Intent(this, EventReceiver.class);
837 intent.setAction("ping");
838 alarmManager.cancel(PendingIntent.getBroadcast(this, requestCode, intent, 0));
839 }
840
841 public void scheduleWakeUpCall(int seconds, int requestCode) {
842 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
843
844 Context context = getApplicationContext();
845 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
846
847 Intent intent = new Intent(context, EventReceiver.class);
848 intent.setAction("ping");
849 PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
850 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
851 }
852
853 public XmppConnection createConnection(final Account account) {
854 final SharedPreferences sharedPref = getPreferences();
855 account.setResource(sharedPref.getString("resource", getString(R.string.default_resource))
856 .toLowerCase(Locale.getDefault()));
857 final XmppConnection connection = new XmppConnection(account, this);
858 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
859 connection.setOnStatusChangedListener(this.statusListener);
860 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
861 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
862 connection.setOnJinglePacketReceivedListener(this.jingleListener);
863 connection.setOnBindListener(this.mOnBindListener);
864 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
865 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
866 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
867 AxolotlService axolotlService = account.getAxolotlService();
868 if (axolotlService != null) {
869 connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
870 }
871 return connection;
872 }
873
874 public void sendChatState(Conversation conversation) {
875 if (sendChatStates()) {
876 MessagePacket packet = mMessageGenerator.generateChatState(conversation);
877 sendMessagePacket(conversation.getAccount(), packet);
878 }
879 }
880
881 private void sendFileMessage(final Message message, final boolean delay) {
882 Log.d(Config.LOGTAG, "send file message");
883 final Account account = message.getConversation().getAccount();
884 if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())) {
885 mHttpConnectionManager.createNewUploadConnection(message, delay);
886 } else {
887 mJingleConnectionManager.createNewConnection(message);
888 }
889 }
890
891 public void sendMessage(final Message message) {
892 sendMessage(message, false, false);
893 }
894
895 private void sendMessage(final Message message, final boolean resend, final boolean delay) {
896 final Account account = message.getConversation().getAccount();
897 final Conversation conversation = message.getConversation();
898 account.deactivateGracePeriod();
899 MessagePacket packet = null;
900 final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
901 || account.getServerIdentity() != XmppConnection.Identity.SLACK)
902 && !message.edited();
903 boolean saveInDb = addToConversation;
904 message.setStatus(Message.STATUS_WAITING);
905
906 if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
907 message.getConversation().endOtrIfNeeded();
908 message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
909 new Conversation.OnMessageFound() {
910 @Override
911 public void onMessageFound(Message message) {
912 markMessage(message, Message.STATUS_SEND_FAILED);
913 }
914 });
915 }
916
917 if (account.isOnlineAndConnected()) {
918 switch (message.getEncryption()) {
919 case Message.ENCRYPTION_NONE:
920 if (message.needsUploading()) {
921 if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
922 || message.fixCounterpart()) {
923 this.sendFileMessage(message, delay);
924 } else {
925 break;
926 }
927 } else {
928 packet = mMessageGenerator.generateChat(message);
929 }
930 break;
931 case Message.ENCRYPTION_PGP:
932 case Message.ENCRYPTION_DECRYPTED:
933 if (message.needsUploading()) {
934 if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
935 || message.fixCounterpart()) {
936 this.sendFileMessage(message, delay);
937 } else {
938 break;
939 }
940 } else {
941 packet = mMessageGenerator.generatePgpChat(message);
942 }
943 break;
944 case Message.ENCRYPTION_OTR:
945 SessionImpl otrSession = conversation.getOtrSession();
946 if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
947 try {
948 message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
949 } catch (InvalidJidException e) {
950 break;
951 }
952 if (message.needsUploading()) {
953 mJingleConnectionManager.createNewConnection(message);
954 } else {
955 packet = mMessageGenerator.generateOtrChat(message);
956 }
957 } else if (otrSession == null) {
958 if (message.fixCounterpart()) {
959 conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
960 } else {
961 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not fix counterpart for OTR message to contact "+message.getContact().getJid());
962 break;
963 }
964 } else {
965 Log.d(Config.LOGTAG,account.getJid().toBareJid()+" OTR session with "+message.getContact()+" is in wrong state: "+otrSession.getSessionStatus().toString());
966 }
967 break;
968 case Message.ENCRYPTION_AXOLOTL:
969 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
970 if (message.needsUploading()) {
971 if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
972 || message.fixCounterpart()) {
973 this.sendFileMessage(message, delay);
974 } else {
975 break;
976 }
977 } else {
978 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
979 if (axolotlMessage == null) {
980 account.getAxolotlService().preparePayloadMessage(message, delay);
981 } else {
982 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
983 }
984 }
985 break;
986
987 }
988 if (packet != null) {
989 if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
990 message.setStatus(Message.STATUS_UNSEND);
991 } else {
992 message.setStatus(Message.STATUS_SEND);
993 }
994 }
995 } else {
996 switch (message.getEncryption()) {
997 case Message.ENCRYPTION_DECRYPTED:
998 if (!message.needsUploading()) {
999 String pgpBody = message.getEncryptedBody();
1000 String decryptedBody = message.getBody();
1001 message.setBody(pgpBody);
1002 message.setEncryption(Message.ENCRYPTION_PGP);
1003 databaseBackend.createMessage(message);
1004 saveInDb = false;
1005 message.setBody(decryptedBody);
1006 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1007 }
1008 break;
1009 case Message.ENCRYPTION_OTR:
1010 if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
1011 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": create otr session without starting for "+message.getContact().getJid());
1012 conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
1013 }
1014 break;
1015 case Message.ENCRYPTION_AXOLOTL:
1016 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1017 break;
1018 }
1019 }
1020
1021 if (resend) {
1022 if (packet != null && addToConversation) {
1023 if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
1024 markMessage(message, Message.STATUS_UNSEND);
1025 } else {
1026 markMessage(message, Message.STATUS_SEND);
1027 }
1028 }
1029 } else {
1030 if (addToConversation) {
1031 conversation.add(message);
1032 }
1033 if (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages()) {
1034 if (saveInDb) {
1035 databaseBackend.createMessage(message);
1036 } else if (message.edited()) {
1037 databaseBackend.updateMessage(message, message.getEditedId());
1038 }
1039 }
1040 updateConversationUi();
1041 }
1042 if (packet != null) {
1043 if (delay) {
1044 mMessageGenerator.addDelay(packet, message.getTimeSent());
1045 }
1046 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1047 if (this.sendChatStates()) {
1048 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1049 }
1050 }
1051 sendMessagePacket(account, packet);
1052 }
1053 }
1054
1055 private void sendUnsentMessages(final Conversation conversation) {
1056 conversation.findWaitingMessages(new Conversation.OnMessageFound() {
1057
1058 @Override
1059 public void onMessageFound(Message message) {
1060 resendMessage(message, true);
1061 }
1062 });
1063 }
1064
1065 public void resendMessage(final Message message, final boolean delay) {
1066 sendMessage(message, true, delay);
1067 }
1068
1069 public void fetchRosterFromServer(final Account account) {
1070 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1071 if (!"".equals(account.getRosterVersion())) {
1072 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1073 + ": fetching roster version " + account.getRosterVersion());
1074 } else {
1075 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
1076 }
1077 iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
1078 sendIqPacket(account, iqPacket, mIqParser);
1079 }
1080
1081 public void fetchBookmarks(final Account account) {
1082 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1083 final Element query = iqPacket.query("jabber:iq:private");
1084 query.addChild("storage", "storage:bookmarks");
1085 final OnIqPacketReceived callback = new OnIqPacketReceived() {
1086
1087 @Override
1088 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1089 if (packet.getType() == IqPacket.TYPE.RESULT) {
1090 final Element query = packet.query();
1091 final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1092 final Element storage = query.findChild("storage", "storage:bookmarks");
1093 final boolean autojoin = respectAutojoin();
1094 if (storage != null) {
1095 for (final Element item : storage.getChildren()) {
1096 if (item.getName().equals("conference")) {
1097 final Bookmark bookmark = Bookmark.parse(item, account);
1098 Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1099 if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1100 bookmark.setBookmarkName(old.getBookmarkName());
1101 }
1102 Conversation conversation = find(bookmark);
1103 if (conversation != null) {
1104 conversation.setBookmark(bookmark);
1105 } else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1106 conversation = findOrCreateConversation(
1107 account, bookmark.getJid(), true);
1108 conversation.setBookmark(bookmark);
1109 joinMuc(conversation);
1110 }
1111 }
1112 }
1113 }
1114 account.setBookmarks(new ArrayList<>(bookmarks.values()));
1115 } else {
1116 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
1117 }
1118 }
1119 };
1120 sendIqPacket(account, iqPacket, callback);
1121 }
1122
1123 public void pushBookmarks(Account account) {
1124 Log.d(Config.LOGTAG, account.getJid().toBareJid()+": pushing bookmarks");
1125 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1126 Element query = iqPacket.query("jabber:iq:private");
1127 Element storage = query.addChild("storage", "storage:bookmarks");
1128 for (Bookmark bookmark : account.getBookmarks()) {
1129 storage.addChild(bookmark);
1130 }
1131 sendIqPacket(account, iqPacket, mDefaultIqHandler);
1132 }
1133
1134 public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
1135 if (mPhoneContactMergerThread != null) {
1136 mPhoneContactMergerThread.interrupt();
1137 }
1138 mPhoneContactMergerThread = new Thread(new Runnable() {
1139 @Override
1140 public void run() {
1141 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1142 for (Account account : accounts) {
1143 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1144 for (Bundle phoneContact : phoneContacts) {
1145 if (Thread.interrupted()) {
1146 Log.d(Config.LOGTAG, "interrupted merging phone contacts");
1147 return;
1148 }
1149 Jid jid;
1150 try {
1151 jid = Jid.fromString(phoneContact.getString("jid"));
1152 } catch (final InvalidJidException e) {
1153 continue;
1154 }
1155 final Contact contact = account.getRoster().getContact(jid);
1156 String systemAccount = phoneContact.getInt("phoneid")
1157 + "#"
1158 + phoneContact.getString("lookup");
1159 contact.setSystemAccount(systemAccount);
1160 if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
1161 getAvatarService().clear(contact);
1162 }
1163 contact.setSystemName(phoneContact.getString("displayname"));
1164 withSystemAccounts.remove(contact);
1165 }
1166 for (Contact contact : withSystemAccounts) {
1167 contact.setSystemAccount(null);
1168 contact.setSystemName(null);
1169 if (contact.setPhotoUri(null)) {
1170 getAvatarService().clear(contact);
1171 }
1172 }
1173 }
1174 Log.d(Config.LOGTAG, "finished merging phone contacts");
1175 updateAccountUi();
1176 }
1177 });
1178 mPhoneContactMergerThread.start();
1179 }
1180
1181 private void restoreFromDatabase() {
1182 synchronized (this.conversations) {
1183 final Map<String, Account> accountLookupTable = new Hashtable<>();
1184 for (Account account : this.accounts) {
1185 accountLookupTable.put(account.getUuid(), account);
1186 }
1187 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1188 for (Conversation conversation : this.conversations) {
1189 Account account = accountLookupTable.get(conversation.getAccountUuid());
1190 conversation.setAccount(account);
1191 }
1192 Runnable runnable = new Runnable() {
1193 @Override
1194 public void run() {
1195 Log.d(Config.LOGTAG, "restoring roster");
1196 for (Account account : accounts) {
1197 databaseBackend.readRoster(account.getRoster());
1198 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1199 }
1200 getBitmapCache().evictAll();
1201 Looper.prepare();
1202 loadPhoneContacts();
1203 Log.d(Config.LOGTAG, "restoring messages");
1204 for (Conversation conversation : conversations) {
1205 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1206 checkDeletedFiles(conversation);
1207 conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1208 @Override
1209 public void onMessageFound(Message message) {
1210 mNotificationService.pushFromBacklog(message);
1211 }
1212 });
1213 }
1214 mNotificationService.finishBacklog(false);
1215 mRestoredFromDatabase = true;
1216 Log.d(Config.LOGTAG, "restored all messages");
1217 updateConversationUi();
1218 }
1219 };
1220 mDatabaseExecutor.execute(runnable);
1221 }
1222 }
1223
1224 public void loadPhoneContacts() {
1225 PhoneHelper.loadPhoneContacts(getApplicationContext(),
1226 new CopyOnWriteArrayList<Bundle>(),
1227 XmppConnectionService.this);
1228 }
1229
1230 public List<Conversation> getConversations() {
1231 return this.conversations;
1232 }
1233
1234 private void checkDeletedFiles(Conversation conversation) {
1235 conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1236
1237 @Override
1238 public void onMessageFound(Message message) {
1239 if (!getFileBackend().isFileAvailable(message)) {
1240 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1241 final int s = message.getStatus();
1242 if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1243 markMessage(message, Message.STATUS_SEND_FAILED);
1244 }
1245 }
1246 }
1247 });
1248 }
1249
1250 private void markFileDeleted(String uuid) {
1251 for (Conversation conversation : getConversations()) {
1252 Message message = conversation.findMessageWithFileAndUuid(uuid);
1253 if (message != null) {
1254 if (!getFileBackend().isFileAvailable(message)) {
1255 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1256 final int s = message.getStatus();
1257 if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1258 markMessage(message, Message.STATUS_SEND_FAILED);
1259 } else {
1260 updateConversationUi();
1261 }
1262 }
1263 return;
1264 }
1265 }
1266 }
1267
1268 public void populateWithOrderedConversations(final List<Conversation> list) {
1269 populateWithOrderedConversations(list, true);
1270 }
1271
1272 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1273 list.clear();
1274 if (includeNoFileUpload) {
1275 list.addAll(getConversations());
1276 } else {
1277 for (Conversation conversation : getConversations()) {
1278 if (conversation.getMode() == Conversation.MODE_SINGLE
1279 || conversation.getAccount().httpUploadAvailable()) {
1280 list.add(conversation);
1281 }
1282 }
1283 }
1284 Collections.sort(list, new Comparator<Conversation>() {
1285 @Override
1286 public int compare(Conversation lhs, Conversation rhs) {
1287 Message left = lhs.getLatestMessage();
1288 Message right = rhs.getLatestMessage();
1289 if (left.getTimeSent() > right.getTimeSent()) {
1290 return -1;
1291 } else if (left.getTimeSent() < right.getTimeSent()) {
1292 return 1;
1293 } else {
1294 return 0;
1295 }
1296 }
1297 });
1298 }
1299
1300 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1301 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1302 return;
1303 } else if (timestamp == 0) {
1304 return;
1305 }
1306 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1307 Runnable runnable = new Runnable() {
1308 @Override
1309 public void run() {
1310 final Account account = conversation.getAccount();
1311 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1312 if (messages.size() > 0) {
1313 conversation.addAll(0, messages);
1314 checkDeletedFiles(conversation);
1315 callback.onMoreMessagesLoaded(messages.size(), conversation);
1316 } else if (conversation.hasMessagesLeftOnServer()
1317 && account.isOnlineAndConnected()
1318 && conversation.getLastClearHistory() == 0) {
1319 if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1320 || (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1321 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp);
1322 if (query != null) {
1323 query.setCallback(callback);
1324 }
1325 callback.informUser(R.string.fetching_history_from_server);
1326 }
1327 }
1328 }
1329 };
1330 mDatabaseExecutor.execute(runnable);
1331 }
1332
1333 public List<Account> getAccounts() {
1334 return this.accounts;
1335 }
1336
1337 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1338 for (final Conversation conversation : haystack) {
1339 if (conversation.getContact() == contact) {
1340 return conversation;
1341 }
1342 }
1343 return null;
1344 }
1345
1346 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1347 if (jid == null) {
1348 return null;
1349 }
1350 for (final Conversation conversation : haystack) {
1351 if ((account == null || conversation.getAccount() == account)
1352 && (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1353 return conversation;
1354 }
1355 }
1356 return null;
1357 }
1358
1359 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1360 return this.findOrCreateConversation(account, jid, muc, null);
1361 }
1362
1363 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1364 synchronized (this.conversations) {
1365 Conversation conversation = find(account, jid);
1366 if (conversation != null) {
1367 return conversation;
1368 }
1369 conversation = databaseBackend.findConversation(account, jid);
1370 if (conversation != null) {
1371 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1372 conversation.setAccount(account);
1373 if (muc) {
1374 conversation.setMode(Conversation.MODE_MULTI);
1375 conversation.setContactJid(jid);
1376 } else {
1377 conversation.setMode(Conversation.MODE_SINGLE);
1378 conversation.setContactJid(jid.toBareJid());
1379 }
1380 conversation.setNextEncryption(-1);
1381 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1382 this.databaseBackend.updateConversation(conversation);
1383 } else {
1384 String conversationName;
1385 Contact contact = account.getRoster().getContact(jid);
1386 if (contact != null) {
1387 conversationName = contact.getDisplayName();
1388 } else {
1389 conversationName = jid.getLocalpart();
1390 }
1391 if (muc) {
1392 conversation = new Conversation(conversationName, account, jid,
1393 Conversation.MODE_MULTI);
1394 } else {
1395 conversation = new Conversation(conversationName, account, jid.toBareJid(),
1396 Conversation.MODE_SINGLE);
1397 }
1398 this.databaseBackend.createConversation(conversation);
1399 }
1400 if (account.getXmppConnection() != null
1401 && account.getXmppConnection().getFeatures().mam()
1402 && !muc) {
1403 if (query == null) {
1404 this.mMessageArchiveService.query(conversation);
1405 } else {
1406 if (query.getConversation() == null) {
1407 this.mMessageArchiveService.query(conversation, query.getStart());
1408 }
1409 }
1410 }
1411 checkDeletedFiles(conversation);
1412 this.conversations.add(conversation);
1413 updateConversationUi();
1414 return conversation;
1415 }
1416 }
1417
1418 public void archiveConversation(Conversation conversation) {
1419 getNotificationService().clear(conversation);
1420 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1421 conversation.setNextEncryption(-1);
1422 synchronized (this.conversations) {
1423 if (conversation.getMode() == Conversation.MODE_MULTI) {
1424 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1425 Bookmark bookmark = conversation.getBookmark();
1426 if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1427 bookmark.setAutojoin(false);
1428 pushBookmarks(bookmark.getAccount());
1429 }
1430 }
1431 leaveMuc(conversation);
1432 } else {
1433 conversation.endOtrIfNeeded();
1434 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1435 Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1436 sendPresencePacket(
1437 conversation.getAccount(),
1438 mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1439 );
1440 }
1441 }
1442 this.databaseBackend.updateConversation(conversation);
1443 this.conversations.remove(conversation);
1444 updateConversationUi();
1445 }
1446 }
1447
1448 public void createAccount(final Account account) {
1449 account.initAccountServices(this);
1450 databaseBackend.createAccount(account);
1451 this.accounts.add(account);
1452 this.reconnectAccountInBackground(account);
1453 updateAccountUi();
1454 }
1455
1456 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1457 new Thread(new Runnable() {
1458 @Override
1459 public void run() {
1460 try {
1461 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1462 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1463 if (findAccountByJid(info.first) == null) {
1464 Account account = new Account(info.first, "");
1465 account.setPrivateKeyAlias(alias);
1466 account.setOption(Account.OPTION_DISABLED, true);
1467 account.setDisplayName(info.second);
1468 createAccount(account);
1469 callback.onAccountCreated(account);
1470 if (Config.X509_VERIFICATION) {
1471 try {
1472 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1473 } catch (CertificateException e) {
1474 callback.informUser(R.string.certificate_chain_is_not_trusted);
1475 }
1476 }
1477 } else {
1478 callback.informUser(R.string.account_already_exists);
1479 }
1480 } catch (Exception e) {
1481 e.printStackTrace();
1482 callback.informUser(R.string.unable_to_parse_certificate);
1483 }
1484 }
1485 }).start();
1486
1487 }
1488
1489 public void updateKeyInAccount(final Account account, final String alias) {
1490 Log.d(Config.LOGTAG, "update key in account " + alias);
1491 try {
1492 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1493 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1494 if (account.getJid().toBareJid().equals(info.first)) {
1495 account.setPrivateKeyAlias(alias);
1496 account.setDisplayName(info.second);
1497 databaseBackend.updateAccount(account);
1498 if (Config.X509_VERIFICATION) {
1499 try {
1500 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1501 } catch (CertificateException e) {
1502 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1503 }
1504 account.getAxolotlService().regenerateKeys(true);
1505 }
1506 } else {
1507 showErrorToastInUi(R.string.jid_does_not_match_certificate);
1508 }
1509 } catch (Exception e) {
1510 e.printStackTrace();
1511 }
1512 }
1513
1514 public void updateAccount(final Account account) {
1515 this.statusListener.onStatusChanged(account);
1516 databaseBackend.updateAccount(account);
1517 reconnectAccountInBackground(account);
1518 updateAccountUi();
1519 getNotificationService().updateErrorNotification();
1520 }
1521
1522 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1523 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1524 sendIqPacket(account, iq, new OnIqPacketReceived() {
1525 @Override
1526 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1527 if (packet.getType() == IqPacket.TYPE.RESULT) {
1528 account.setPassword(newPassword);
1529 account.setOption(Account.OPTION_MAGIC_CREATE, false);
1530 databaseBackend.updateAccount(account);
1531 callback.onPasswordChangeSucceeded();
1532 } else {
1533 callback.onPasswordChangeFailed();
1534 }
1535 }
1536 });
1537 }
1538
1539 public void deleteAccount(final Account account) {
1540 synchronized (this.conversations) {
1541 for (final Conversation conversation : conversations) {
1542 if (conversation.getAccount() == account) {
1543 if (conversation.getMode() == Conversation.MODE_MULTI) {
1544 leaveMuc(conversation);
1545 } else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1546 conversation.endOtrIfNeeded();
1547 }
1548 conversations.remove(conversation);
1549 }
1550 }
1551 if (account.getXmppConnection() != null) {
1552 this.disconnect(account, true);
1553 }
1554 Runnable runnable = new Runnable() {
1555 @Override
1556 public void run() {
1557 databaseBackend.deleteAccount(account);
1558 }
1559 };
1560 mDatabaseExecutor.execute(runnable);
1561 this.accounts.remove(account);
1562 updateAccountUi();
1563 getNotificationService().updateErrorNotification();
1564 }
1565 }
1566
1567 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1568 synchronized (this) {
1569 if (checkListeners()) {
1570 switchToForeground();
1571 }
1572 this.mOnConversationUpdate = listener;
1573 this.mNotificationService.setIsInForeground(true);
1574 if (this.convChangedListenerCount < 2) {
1575 this.convChangedListenerCount++;
1576 }
1577 }
1578 }
1579
1580 public void removeOnConversationListChangedListener() {
1581 synchronized (this) {
1582 this.convChangedListenerCount--;
1583 if (this.convChangedListenerCount <= 0) {
1584 this.convChangedListenerCount = 0;
1585 this.mOnConversationUpdate = null;
1586 this.mNotificationService.setIsInForeground(false);
1587 if (checkListeners()) {
1588 switchToBackground();
1589 }
1590 }
1591 }
1592 }
1593
1594 public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1595 synchronized (this) {
1596 if (checkListeners()) {
1597 switchToForeground();
1598 }
1599 this.mOnShowErrorToast = onShowErrorToast;
1600 if (this.showErrorToastListenerCount < 2) {
1601 this.showErrorToastListenerCount++;
1602 }
1603 }
1604 this.mOnShowErrorToast = onShowErrorToast;
1605 }
1606
1607 public void removeOnShowErrorToastListener() {
1608 synchronized (this) {
1609 this.showErrorToastListenerCount--;
1610 if (this.showErrorToastListenerCount <= 0) {
1611 this.showErrorToastListenerCount = 0;
1612 this.mOnShowErrorToast = null;
1613 if (checkListeners()) {
1614 switchToBackground();
1615 }
1616 }
1617 }
1618 }
1619
1620 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1621 synchronized (this) {
1622 if (checkListeners()) {
1623 switchToForeground();
1624 }
1625 this.mOnAccountUpdate = listener;
1626 if (this.accountChangedListenerCount < 2) {
1627 this.accountChangedListenerCount++;
1628 }
1629 }
1630 }
1631
1632 public void removeOnAccountListChangedListener() {
1633 synchronized (this) {
1634 this.accountChangedListenerCount--;
1635 if (this.accountChangedListenerCount <= 0) {
1636 this.mOnAccountUpdate = null;
1637 this.accountChangedListenerCount = 0;
1638 if (checkListeners()) {
1639 switchToBackground();
1640 }
1641 }
1642 }
1643 }
1644
1645 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1646 synchronized (this) {
1647 if (checkListeners()) {
1648 switchToForeground();
1649 }
1650 this.mOnCaptchaRequested = listener;
1651 if (this.captchaRequestedListenerCount < 2) {
1652 this.captchaRequestedListenerCount++;
1653 }
1654 }
1655 }
1656
1657 public void removeOnCaptchaRequestedListener() {
1658 synchronized (this) {
1659 this.captchaRequestedListenerCount--;
1660 if (this.captchaRequestedListenerCount <= 0) {
1661 this.mOnCaptchaRequested = null;
1662 this.captchaRequestedListenerCount = 0;
1663 if (checkListeners()) {
1664 switchToBackground();
1665 }
1666 }
1667 }
1668 }
1669
1670 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1671 synchronized (this) {
1672 if (checkListeners()) {
1673 switchToForeground();
1674 }
1675 this.mOnRosterUpdate = listener;
1676 if (this.rosterChangedListenerCount < 2) {
1677 this.rosterChangedListenerCount++;
1678 }
1679 }
1680 }
1681
1682 public void removeOnRosterUpdateListener() {
1683 synchronized (this) {
1684 this.rosterChangedListenerCount--;
1685 if (this.rosterChangedListenerCount <= 0) {
1686 this.rosterChangedListenerCount = 0;
1687 this.mOnRosterUpdate = null;
1688 if (checkListeners()) {
1689 switchToBackground();
1690 }
1691 }
1692 }
1693 }
1694
1695 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1696 synchronized (this) {
1697 if (checkListeners()) {
1698 switchToForeground();
1699 }
1700 this.mOnUpdateBlocklist = listener;
1701 if (this.updateBlocklistListenerCount < 2) {
1702 this.updateBlocklistListenerCount++;
1703 }
1704 }
1705 }
1706
1707 public void removeOnUpdateBlocklistListener() {
1708 synchronized (this) {
1709 this.updateBlocklistListenerCount--;
1710 if (this.updateBlocklistListenerCount <= 0) {
1711 this.updateBlocklistListenerCount = 0;
1712 this.mOnUpdateBlocklist = null;
1713 if (checkListeners()) {
1714 switchToBackground();
1715 }
1716 }
1717 }
1718 }
1719
1720 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1721 synchronized (this) {
1722 if (checkListeners()) {
1723 switchToForeground();
1724 }
1725 this.mOnKeyStatusUpdated = listener;
1726 if (this.keyStatusUpdatedListenerCount < 2) {
1727 this.keyStatusUpdatedListenerCount++;
1728 }
1729 }
1730 }
1731
1732 public void removeOnNewKeysAvailableListener() {
1733 synchronized (this) {
1734 this.keyStatusUpdatedListenerCount--;
1735 if (this.keyStatusUpdatedListenerCount <= 0) {
1736 this.keyStatusUpdatedListenerCount = 0;
1737 this.mOnKeyStatusUpdated = null;
1738 if (checkListeners()) {
1739 switchToBackground();
1740 }
1741 }
1742 }
1743 }
1744
1745 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1746 synchronized (this) {
1747 if (checkListeners()) {
1748 switchToForeground();
1749 }
1750 this.mOnMucRosterUpdate = listener;
1751 if (this.mucRosterChangedListenerCount < 2) {
1752 this.mucRosterChangedListenerCount++;
1753 }
1754 }
1755 }
1756
1757 public void removeOnMucRosterUpdateListener() {
1758 synchronized (this) {
1759 this.mucRosterChangedListenerCount--;
1760 if (this.mucRosterChangedListenerCount <= 0) {
1761 this.mucRosterChangedListenerCount = 0;
1762 this.mOnMucRosterUpdate = null;
1763 if (checkListeners()) {
1764 switchToBackground();
1765 }
1766 }
1767 }
1768 }
1769
1770 private boolean checkListeners() {
1771 return (this.mOnAccountUpdate == null
1772 && this.mOnConversationUpdate == null
1773 && this.mOnRosterUpdate == null
1774 && this.mOnCaptchaRequested == null
1775 && this.mOnUpdateBlocklist == null
1776 && this.mOnShowErrorToast == null
1777 && this.mOnKeyStatusUpdated == null);
1778 }
1779
1780 private void switchToForeground() {
1781 for (Conversation conversation : getConversations()) {
1782 conversation.setIncomingChatState(ChatState.ACTIVE);
1783 }
1784 for (Account account : getAccounts()) {
1785 if (account.getStatus() == Account.State.ONLINE) {
1786 XmppConnection connection = account.getXmppConnection();
1787 if (connection != null && connection.getFeatures().csi()) {
1788 connection.sendActive();
1789 }
1790 }
1791 }
1792 Log.d(Config.LOGTAG, "app switched into foreground");
1793 }
1794
1795 private void switchToBackground() {
1796 for (Account account : getAccounts()) {
1797 if (account.getStatus() == Account.State.ONLINE) {
1798 XmppConnection connection = account.getXmppConnection();
1799 if (connection != null) {
1800 if (connection.getFeatures().csi()) {
1801 connection.sendInactive();
1802 }
1803 if (Config.CLOSE_TCP_WHEN_SWITCHING_TO_BACKGROUND && mPushManagementService.available(account)) {
1804 connection.waitForPush();
1805 cancelWakeUpCall(account.getUuid().hashCode());
1806 }
1807 }
1808 }
1809 }
1810 this.mNotificationService.setIsInForeground(false);
1811 Log.d(Config.LOGTAG, "app switched into background");
1812 }
1813
1814 private void connectMultiModeConversations(Account account) {
1815 List<Conversation> conversations = getConversations();
1816 for (Conversation conversation : conversations) {
1817 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1818 joinMuc(conversation);
1819 }
1820 }
1821 }
1822
1823 public void joinMuc(Conversation conversation) {
1824 joinMuc(conversation, null);
1825 }
1826
1827 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
1828 Account account = conversation.getAccount();
1829 account.pendingConferenceJoins.remove(conversation);
1830 account.pendingConferenceLeaves.remove(conversation);
1831 if (account.getStatus() == Account.State.ONLINE) {
1832 conversation.resetMucOptions();
1833 conversation.setHasMessagesLeftOnServer(false);
1834 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1835
1836 private void join(Conversation conversation) {
1837 Account account = conversation.getAccount();
1838 final MucOptions mucOptions = conversation.getMucOptions();
1839 final Jid joinJid = mucOptions.getSelf().getFullJid();
1840 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1841 PresencePacket packet = new PresencePacket();
1842 packet.setFrom(conversation.getAccount().getJid());
1843 packet.setTo(joinJid);
1844 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1845 if (conversation.getMucOptions().getPassword() != null) {
1846 x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1847 }
1848
1849 if (mucOptions.mamSupport()) {
1850 // Use MAM instead of the limited muc history to get history
1851 x.addChild("history").setAttribute("maxchars", "0");
1852 } else {
1853 // Fallback to muc history
1854 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1855 }
1856 String sig = account.getPgpSignature();
1857 if (sig != null) {
1858 packet.addChild("x", "jabber:x:signed").setContent(sig);
1859 }
1860 sendPresencePacket(account, packet);
1861 if (onConferenceJoined != null) {
1862 onConferenceJoined.onConferenceJoined(conversation);
1863 }
1864 if (!joinJid.equals(conversation.getJid())) {
1865 conversation.setContactJid(joinJid);
1866 databaseBackend.updateConversation(conversation);
1867 }
1868
1869 if (mucOptions.mamSupport()) {
1870 getMessageArchiveService().catchupMUC(conversation);
1871 }
1872 if (mucOptions.membersOnly() && mucOptions.nonanonymous()) {
1873 fetchConferenceMembers(conversation);
1874 }
1875 sendUnsentMessages(conversation);
1876 }
1877
1878 @Override
1879 public void onConferenceConfigurationFetched(Conversation conversation) {
1880 join(conversation);
1881 }
1882
1883 @Override
1884 public void onFetchFailed(final Conversation conversation, Element error) {
1885 join(conversation);
1886 fetchConferenceConfiguration(conversation);
1887 }
1888 });
1889 updateConversationUi();
1890 } else {
1891 account.pendingConferenceJoins.add(conversation);
1892 conversation.resetMucOptions();
1893 conversation.setHasMessagesLeftOnServer(false);
1894 updateConversationUi();
1895 }
1896 }
1897
1898 private void fetchConferenceMembers(final Conversation conversation) {
1899 final Account account = conversation.getAccount();
1900 final String[] affiliations = {"member","admin","owner"};
1901 OnIqPacketReceived callback = new OnIqPacketReceived() {
1902
1903 private int i = 0;
1904
1905 @Override
1906 public void onIqPacketReceived(Account account, IqPacket packet) {
1907 Element query = packet.query("http://jabber.org/protocol/muc#admin");
1908 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
1909 for(Element child : query.getChildren()) {
1910 if ("item".equals(child.getName())) {
1911 conversation.getMucOptions().putMember(child.getAttributeAsJid("jid"));
1912 }
1913 }
1914 } else {
1915 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not request affiliation "+affiliations[i]+" in "+conversation.getJid().toBareJid());
1916 }
1917 ++i;
1918 if (i >= affiliations.length) {
1919 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved members for "+conversation.getJid().toBareJid()+": "+conversation.getMucOptions().getMembers());
1920 }
1921 }
1922 };
1923 for(String affiliation : affiliations) {
1924 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
1925 }
1926 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetching members for "+conversation.getName());
1927 }
1928
1929 public void providePasswordForMuc(Conversation conversation, String password) {
1930 if (conversation.getMode() == Conversation.MODE_MULTI) {
1931 conversation.getMucOptions().setPassword(password);
1932 if (conversation.getBookmark() != null) {
1933 if (respectAutojoin()) {
1934 conversation.getBookmark().setAutojoin(true);
1935 }
1936 pushBookmarks(conversation.getAccount());
1937 }
1938 databaseBackend.updateConversation(conversation);
1939 joinMuc(conversation);
1940 }
1941 }
1942
1943 public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1944 final MucOptions options = conversation.getMucOptions();
1945 final Jid joinJid = options.createJoinJid(nick);
1946 if (options.online()) {
1947 Account account = conversation.getAccount();
1948 options.setOnRenameListener(new OnRenameListener() {
1949
1950 @Override
1951 public void onSuccess() {
1952 conversation.setContactJid(joinJid);
1953 databaseBackend.updateConversation(conversation);
1954 Bookmark bookmark = conversation.getBookmark();
1955 if (bookmark != null) {
1956 bookmark.setNick(nick);
1957 pushBookmarks(bookmark.getAccount());
1958 }
1959 callback.success(conversation);
1960 }
1961
1962 @Override
1963 public void onFailure() {
1964 callback.error(R.string.nick_in_use, conversation);
1965 }
1966 });
1967
1968 PresencePacket packet = new PresencePacket();
1969 packet.setTo(joinJid);
1970 packet.setFrom(conversation.getAccount().getJid());
1971
1972 String sig = account.getPgpSignature();
1973 if (sig != null) {
1974 packet.addChild("status").setContent("online");
1975 packet.addChild("x", "jabber:x:signed").setContent(sig);
1976 }
1977 sendPresencePacket(account, packet);
1978 } else {
1979 conversation.setContactJid(joinJid);
1980 databaseBackend.updateConversation(conversation);
1981 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1982 Bookmark bookmark = conversation.getBookmark();
1983 if (bookmark != null) {
1984 bookmark.setNick(nick);
1985 pushBookmarks(bookmark.getAccount());
1986 }
1987 joinMuc(conversation);
1988 }
1989 }
1990 }
1991
1992 public void leaveMuc(Conversation conversation) {
1993 leaveMuc(conversation, false);
1994 }
1995
1996 private void leaveMuc(Conversation conversation, boolean now) {
1997 Account account = conversation.getAccount();
1998 account.pendingConferenceJoins.remove(conversation);
1999 account.pendingConferenceLeaves.remove(conversation);
2000 if (account.getStatus() == Account.State.ONLINE || now) {
2001 PresencePacket packet = new PresencePacket();
2002 packet.setTo(conversation.getMucOptions().getSelf().getFullJid());
2003 packet.setFrom(conversation.getAccount().getJid());
2004 packet.setAttribute("type", "unavailable");
2005 sendPresencePacket(conversation.getAccount(), packet);
2006 conversation.getMucOptions().setOffline();
2007 conversation.deregisterWithBookmark();
2008 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
2009 + ": leaving muc " + conversation.getJid());
2010 } else {
2011 account.pendingConferenceLeaves.add(conversation);
2012 }
2013 }
2014
2015 private String findConferenceServer(final Account account) {
2016 String server;
2017 if (account.getXmppConnection() != null) {
2018 server = account.getXmppConnection().getMucServer();
2019 if (server != null) {
2020 return server;
2021 }
2022 }
2023 for (Account other : getAccounts()) {
2024 if (other != account && other.getXmppConnection() != null) {
2025 server = other.getXmppConnection().getMucServer();
2026 if (server != null) {
2027 return server;
2028 }
2029 }
2030 }
2031 return null;
2032 }
2033
2034 public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
2035 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2036 if (account.getStatus() == Account.State.ONLINE) {
2037 try {
2038 String server = findConferenceServer(account);
2039 if (server == null) {
2040 if (callback != null) {
2041 callback.error(R.string.no_conference_server_found, null);
2042 }
2043 return;
2044 }
2045 String name = new BigInteger(75, getRNG()).toString(32);
2046 Jid jid = Jid.fromParts(name, server, null);
2047 final Conversation conversation = findOrCreateConversation(account, jid, true);
2048 joinMuc(conversation, new OnConferenceJoined() {
2049 @Override
2050 public void onConferenceJoined(final Conversation conversation) {
2051 Bundle options = new Bundle();
2052 options.putString("muc#roomconfig_persistentroom", "1");
2053 options.putString("muc#roomconfig_membersonly", "1");
2054 options.putString("muc#roomconfig_publicroom", "0");
2055 options.putString("muc#roomconfig_whois", "anyone");
2056 pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
2057 @Override
2058 public void onPushSucceeded() {
2059 for (Jid invite : jids) {
2060 invite(conversation, invite);
2061 }
2062 if (account.countPresences() > 1) {
2063 directInvite(conversation, account.getJid().toBareJid());
2064 }
2065 if (callback != null) {
2066 callback.success(conversation);
2067 }
2068 }
2069
2070 @Override
2071 public void onPushFailed() {
2072 if (callback != null) {
2073 callback.error(R.string.conference_creation_failed, conversation);
2074 }
2075 }
2076 });
2077 }
2078 });
2079 } catch (InvalidJidException e) {
2080 if (callback != null) {
2081 callback.error(R.string.conference_creation_failed, null);
2082 }
2083 }
2084 } else {
2085 if (callback != null) {
2086 callback.error(R.string.not_connected_try_again, null);
2087 }
2088 }
2089 }
2090
2091 public void fetchConferenceConfiguration(final Conversation conversation) {
2092 fetchConferenceConfiguration(conversation, null);
2093 }
2094
2095 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2096 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2097 request.setTo(conversation.getJid().toBareJid());
2098 request.query("http://jabber.org/protocol/disco#info");
2099 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2100 @Override
2101 public void onIqPacketReceived(Account account, IqPacket packet) {
2102 Element query = packet.findChild("query","http://jabber.org/protocol/disco#info");
2103 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2104 ArrayList<String> features = new ArrayList<>();
2105 for (Element child : query.getChildren()) {
2106 if (child != null && child.getName().equals("feature")) {
2107 String var = child.getAttribute("var");
2108 if (var != null) {
2109 features.add(var);
2110 }
2111 }
2112 }
2113 Element form = query.findChild("x", "jabber:x:data");
2114 if (form != null) {
2115 conversation.getMucOptions().updateFormData(Data.parse(form));
2116 }
2117 conversation.getMucOptions().updateFeatures(features);
2118 if (callback != null) {
2119 callback.onConferenceConfigurationFetched(conversation);
2120 }
2121 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetched muc configuration for "+conversation.getJid().toBareJid()+" - "+features.toString());
2122 updateConversationUi();
2123 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2124 if (callback != null) {
2125 callback.onFetchFailed(conversation, packet.getError());
2126 }
2127 }
2128 }
2129 });
2130 }
2131
2132 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2133 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2134 request.setTo(conversation.getJid().toBareJid());
2135 request.query("http://jabber.org/protocol/muc#owner");
2136 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2137 @Override
2138 public void onIqPacketReceived(Account account, IqPacket packet) {
2139 if (packet.getType() == IqPacket.TYPE.RESULT) {
2140 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2141 for (Field field : data.getFields()) {
2142 if (options.containsKey(field.getFieldName())) {
2143 field.setValue(options.getString(field.getFieldName()));
2144 }
2145 }
2146 data.submit();
2147 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2148 set.setTo(conversation.getJid().toBareJid());
2149 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2150 sendIqPacket(account, set, new OnIqPacketReceived() {
2151 @Override
2152 public void onIqPacketReceived(Account account, IqPacket packet) {
2153 if (callback != null) {
2154 if (packet.getType() == IqPacket.TYPE.RESULT) {
2155 callback.onPushSucceeded();
2156 } else {
2157 callback.onPushFailed();
2158 }
2159 }
2160 }
2161 });
2162 } else {
2163 if (callback != null) {
2164 callback.onPushFailed();
2165 }
2166 }
2167 }
2168 });
2169 }
2170
2171 public void pushSubjectToConference(final Conversation conference, final String subject) {
2172 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2173 this.sendMessagePacket(conference.getAccount(), packet);
2174 final MucOptions mucOptions = conference.getMucOptions();
2175 final MucOptions.User self = mucOptions.getSelf();
2176 if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2177 Bundle options = new Bundle();
2178 options.putString("muc#roomconfig_persistentroom", "1");
2179 this.pushConferenceConfiguration(conference, options, null);
2180 }
2181 }
2182
2183 public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2184 final Jid jid = user.toBareJid();
2185 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2186 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2187 @Override
2188 public void onIqPacketReceived(Account account, IqPacket packet) {
2189 if (packet.getType() == IqPacket.TYPE.RESULT) {
2190 callback.onAffiliationChangedSuccessful(jid);
2191 } else {
2192 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2193 }
2194 }
2195 });
2196 }
2197
2198 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2199 List<Jid> jids = new ArrayList<>();
2200 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2201 if (user.getAffiliation() == before && user.getJid() != null) {
2202 jids.add(user.getJid());
2203 }
2204 }
2205 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2206 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2207 }
2208
2209 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2210 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2211 Log.d(Config.LOGTAG, request.toString());
2212 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2213 @Override
2214 public void onIqPacketReceived(Account account, IqPacket packet) {
2215 Log.d(Config.LOGTAG, packet.toString());
2216 if (packet.getType() == IqPacket.TYPE.RESULT) {
2217 callback.onRoleChangedSuccessful(nick);
2218 } else {
2219 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2220 }
2221 }
2222 });
2223 }
2224
2225 private void disconnect(Account account, boolean force) {
2226 if ((account.getStatus() == Account.State.ONLINE)
2227 || (account.getStatus() == Account.State.DISABLED)) {
2228 if (!force) {
2229 List<Conversation> conversations = getConversations();
2230 for (Conversation conversation : conversations) {
2231 if (conversation.getAccount() == account) {
2232 if (conversation.getMode() == Conversation.MODE_MULTI) {
2233 leaveMuc(conversation, true);
2234 } else {
2235 if (conversation.endOtrIfNeeded()) {
2236 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2237 + ": ended otr session with "
2238 + conversation.getJid());
2239 }
2240 }
2241 }
2242 }
2243 sendOfflinePresence(account);
2244 }
2245 account.getXmppConnection().disconnect(force);
2246 }
2247 }
2248
2249 @Override
2250 public IBinder onBind(Intent intent) {
2251 return mBinder;
2252 }
2253
2254 public void updateMessage(Message message) {
2255 databaseBackend.updateMessage(message);
2256 updateConversationUi();
2257 }
2258
2259 public void updateMessage(Message message, String uuid) {
2260 databaseBackend.updateMessage(message, uuid);
2261 updateConversationUi();
2262 }
2263
2264 protected void syncDirtyContacts(Account account) {
2265 for (Contact contact : account.getRoster().getContacts()) {
2266 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2267 pushContactToServer(contact);
2268 }
2269 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2270 deleteContactOnServer(contact);
2271 }
2272 }
2273 }
2274
2275 public void createContact(Contact contact) {
2276 boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2277 if (autoGrant) {
2278 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2279 contact.setOption(Contact.Options.ASKING);
2280 }
2281 pushContactToServer(contact);
2282 }
2283
2284 public void onOtrSessionEstablished(Conversation conversation) {
2285 final Account account = conversation.getAccount();
2286 final Session otrSession = conversation.getOtrSession();
2287 Log.d(Config.LOGTAG,
2288 account.getJid().toBareJid() + " otr session established with "
2289 + conversation.getJid() + "/"
2290 + otrSession.getSessionID().getUserID());
2291 conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2292
2293 @Override
2294 public void onMessageFound(Message message) {
2295 SessionID id = otrSession.getSessionID();
2296 try {
2297 message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2298 } catch (InvalidJidException e) {
2299 return;
2300 }
2301 if (message.needsUploading()) {
2302 mJingleConnectionManager.createNewConnection(message);
2303 } else {
2304 MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2305 if (outPacket != null) {
2306 mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2307 message.setStatus(Message.STATUS_SEND);
2308 databaseBackend.updateMessage(message);
2309 sendMessagePacket(account, outPacket);
2310 }
2311 }
2312 updateConversationUi();
2313 }
2314 });
2315 }
2316
2317 public boolean renewSymmetricKey(Conversation conversation) {
2318 Account account = conversation.getAccount();
2319 byte[] symmetricKey = new byte[32];
2320 this.mRandom.nextBytes(symmetricKey);
2321 Session otrSession = conversation.getOtrSession();
2322 if (otrSession != null) {
2323 MessagePacket packet = new MessagePacket();
2324 packet.setType(MessagePacket.TYPE_CHAT);
2325 packet.setFrom(account.getJid());
2326 MessageGenerator.addMessageHints(packet);
2327 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2328 + otrSession.getSessionID().getUserID());
2329 try {
2330 packet.setBody(otrSession
2331 .transformSending(CryptoHelper.FILETRANSFER
2332 + CryptoHelper.bytesToHex(symmetricKey))[0]);
2333 sendMessagePacket(account, packet);
2334 conversation.setSymmetricKey(symmetricKey);
2335 return true;
2336 } catch (OtrException e) {
2337 return false;
2338 }
2339 }
2340 return false;
2341 }
2342
2343 public void pushContactToServer(final Contact contact) {
2344 contact.resetOption(Contact.Options.DIRTY_DELETE);
2345 contact.setOption(Contact.Options.DIRTY_PUSH);
2346 final Account account = contact.getAccount();
2347 if (account.getStatus() == Account.State.ONLINE) {
2348 final boolean ask = contact.getOption(Contact.Options.ASKING);
2349 final boolean sendUpdates = contact
2350 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2351 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2352 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2353 iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2354 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2355 if (sendUpdates) {
2356 sendPresencePacket(account,
2357 mPresenceGenerator.sendPresenceUpdatesTo(contact));
2358 }
2359 if (ask) {
2360 sendPresencePacket(account,
2361 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2362 }
2363 }
2364 }
2365
2366 public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2367 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2368 final int size = Config.AVATAR_SIZE;
2369 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2370 if (avatar != null) {
2371 avatar.height = size;
2372 avatar.width = size;
2373 if (format.equals(Bitmap.CompressFormat.WEBP)) {
2374 avatar.type = "image/webp";
2375 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2376 avatar.type = "image/jpeg";
2377 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
2378 avatar.type = "image/png";
2379 }
2380 if (!getFileBackend().save(avatar)) {
2381 callback.error(R.string.error_saving_avatar, avatar);
2382 return;
2383 }
2384 publishAvatar(account, avatar, callback);
2385 } else {
2386 callback.error(R.string.error_publish_avatar_converting, null);
2387 }
2388 }
2389
2390 public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2391 final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2392 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2393
2394 @Override
2395 public void onIqPacketReceived(Account account, IqPacket result) {
2396 if (result.getType() == IqPacket.TYPE.RESULT) {
2397 final IqPacket packet = XmppConnectionService.this.mIqGenerator
2398 .publishAvatarMetadata(avatar);
2399 sendIqPacket(account, packet, new OnIqPacketReceived() {
2400 @Override
2401 public void onIqPacketReceived(Account account, IqPacket result) {
2402 if (result.getType() == IqPacket.TYPE.RESULT) {
2403 if (account.setAvatar(avatar.getFilename())) {
2404 getAvatarService().clear(account);
2405 databaseBackend.updateAccount(account);
2406 }
2407 if (callback != null) {
2408 callback.success(avatar);
2409 } else {
2410 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar");
2411 }
2412 } else {
2413 if (callback != null) {
2414 callback.error(
2415 R.string.error_publish_avatar_server_reject,
2416 avatar);
2417 }
2418 }
2419 }
2420 });
2421 } else {
2422 if (callback != null) {
2423 callback.error(
2424 R.string.error_publish_avatar_server_reject,
2425 avatar);
2426 }
2427 }
2428 }
2429 });
2430 }
2431
2432 public void republishAvatarIfNeeded(Account account) {
2433 if (account.getAxolotlService().isPepBroken()) {
2434 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
2435 return;
2436 }
2437 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2438 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2439
2440 private Avatar parseAvatar(IqPacket packet) {
2441 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2442 if (pubsub != null) {
2443 Element items = pubsub.findChild("items");
2444 if (items != null) {
2445 return Avatar.parseMetadata(items);
2446 }
2447 }
2448 return null;
2449 }
2450
2451 private boolean errorIsItemNotFound(IqPacket packet) {
2452 Element error = packet.findChild("error");
2453 return packet.getType() == IqPacket.TYPE.ERROR
2454 && error != null
2455 && error.hasChild("item-not-found");
2456 }
2457
2458 @Override
2459 public void onIqPacketReceived(Account account, IqPacket packet) {
2460 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2461 Avatar serverAvatar = parseAvatar(packet);
2462 if (serverAvatar == null && account.getAvatar() != null) {
2463 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2464 if (avatar != null) {
2465 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
2466 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2467 } else {
2468 Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
2469 }
2470 }
2471 }
2472 }
2473 });
2474 }
2475
2476 public void fetchAvatar(Account account, Avatar avatar) {
2477 fetchAvatar(account, avatar, null);
2478 }
2479
2480 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2481 final String KEY = generateFetchKey(account, avatar);
2482 synchronized (this.mInProgressAvatarFetches) {
2483 if (!this.mInProgressAvatarFetches.contains(KEY)) {
2484 switch (avatar.origin) {
2485 case PEP:
2486 this.mInProgressAvatarFetches.add(KEY);
2487 fetchAvatarPep(account, avatar, callback);
2488 break;
2489 case VCARD:
2490 this.mInProgressAvatarFetches.add(KEY);
2491 fetchAvatarVcard(account, avatar, callback);
2492 break;
2493 }
2494 }
2495 }
2496 }
2497
2498 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2499 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2500 sendIqPacket(account, packet, new OnIqPacketReceived() {
2501
2502 @Override
2503 public void onIqPacketReceived(Account account, IqPacket result) {
2504 synchronized (mInProgressAvatarFetches) {
2505 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2506 }
2507 final String ERROR = account.getJid().toBareJid()
2508 + ": fetching avatar for " + avatar.owner + " failed ";
2509 if (result.getType() == IqPacket.TYPE.RESULT) {
2510 avatar.image = mIqParser.avatarData(result);
2511 if (avatar.image != null) {
2512 if (getFileBackend().save(avatar)) {
2513 if (account.getJid().toBareJid().equals(avatar.owner)) {
2514 if (account.setAvatar(avatar.getFilename())) {
2515 databaseBackend.updateAccount(account);
2516 }
2517 getAvatarService().clear(account);
2518 updateConversationUi();
2519 updateAccountUi();
2520 } else {
2521 Contact contact = account.getRoster()
2522 .getContact(avatar.owner);
2523 contact.setAvatar(avatar);
2524 getAvatarService().clear(contact);
2525 updateConversationUi();
2526 updateRosterUi();
2527 }
2528 if (callback != null) {
2529 callback.success(avatar);
2530 }
2531 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2532 + ": successfully fetched pep avatar for " + avatar.owner);
2533 return;
2534 }
2535 } else {
2536
2537 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2538 }
2539 } else {
2540 Element error = result.findChild("error");
2541 if (error == null) {
2542 Log.d(Config.LOGTAG, ERROR + "(server error)");
2543 } else {
2544 Log.d(Config.LOGTAG, ERROR + error.toString());
2545 }
2546 }
2547 if (callback != null) {
2548 callback.error(0, null);
2549 }
2550
2551 }
2552 });
2553 }
2554
2555 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2556 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2557 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2558 @Override
2559 public void onIqPacketReceived(Account account, IqPacket packet) {
2560 synchronized (mInProgressAvatarFetches) {
2561 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2562 }
2563 if (packet.getType() == IqPacket.TYPE.RESULT) {
2564 Element vCard = packet.findChild("vCard", "vcard-temp");
2565 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2566 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2567 if (image != null) {
2568 avatar.image = image;
2569 if (getFileBackend().save(avatar)) {
2570 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2571 + ": successfully fetched vCard avatar for " + avatar.owner);
2572 if (avatar.owner.isBareJid()) {
2573 Contact contact = account.getRoster()
2574 .getContact(avatar.owner);
2575 contact.setAvatar(avatar);
2576 getAvatarService().clear(contact);
2577 updateConversationUi();
2578 updateRosterUi();
2579 } else {
2580 Conversation conversation = find(account, avatar.owner.toBareJid());
2581 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2582 MucOptions.User user = conversation.getMucOptions().findUser(avatar.owner.getResourcepart());
2583 if (user != null) {
2584 if (user.setAvatar(avatar)) {
2585 getAvatarService().clear(user);
2586 updateConversationUi();
2587 updateMucRosterUi();
2588 }
2589 }
2590 }
2591 }
2592 }
2593 }
2594 }
2595 }
2596 });
2597 }
2598
2599 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2600 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2601 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2602
2603 @Override
2604 public void onIqPacketReceived(Account account, IqPacket packet) {
2605 if (packet.getType() == IqPacket.TYPE.RESULT) {
2606 Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
2607 if (pubsub != null) {
2608 Element items = pubsub.findChild("items");
2609 if (items != null) {
2610 Avatar avatar = Avatar.parseMetadata(items);
2611 if (avatar != null) {
2612 avatar.owner = account.getJid().toBareJid();
2613 if (fileBackend.isAvatarCached(avatar)) {
2614 if (account.setAvatar(avatar.getFilename())) {
2615 databaseBackend.updateAccount(account);
2616 }
2617 getAvatarService().clear(account);
2618 callback.success(avatar);
2619 } else {
2620 fetchAvatarPep(account, avatar, callback);
2621 }
2622 return;
2623 }
2624 }
2625 }
2626 }
2627 callback.error(0, null);
2628 }
2629 });
2630 }
2631
2632 public void deleteContactOnServer(Contact contact) {
2633 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2634 contact.resetOption(Contact.Options.DIRTY_PUSH);
2635 contact.setOption(Contact.Options.DIRTY_DELETE);
2636 Account account = contact.getAccount();
2637 if (account.getStatus() == Account.State.ONLINE) {
2638 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2639 Element item = iq.query(Xmlns.ROSTER).addChild("item");
2640 item.setAttribute("jid", contact.getJid().toString());
2641 item.setAttribute("subscription", "remove");
2642 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2643 }
2644 }
2645
2646 public void updateConversation(Conversation conversation) {
2647 this.databaseBackend.updateConversation(conversation);
2648 }
2649
2650 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2651 synchronized (account) {
2652 XmppConnection connection = account.getXmppConnection();
2653 if (connection == null) {
2654 connection = createConnection(account);
2655 account.setXmppConnection(connection);
2656 } else {
2657 connection.interrupt();
2658 }
2659 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2660 if (!force) {
2661 disconnect(account, false);
2662 }
2663 Thread thread = new Thread(connection);
2664 connection.setInteractive(interactive);
2665 connection.prepareNewConnection();
2666 thread.start();
2667 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2668 } else {
2669 disconnect(account, force);
2670 account.getRoster().clearPresences();
2671 connection.resetEverything();
2672 account.getAxolotlService().resetBrokenness();
2673 }
2674 }
2675 }
2676
2677 public void reconnectAccountInBackground(final Account account) {
2678 new Thread(new Runnable() {
2679 @Override
2680 public void run() {
2681 reconnectAccount(account, false, true);
2682 }
2683 }).start();
2684 }
2685
2686 public void invite(Conversation conversation, Jid contact) {
2687 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2688 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2689 sendMessagePacket(conversation.getAccount(), packet);
2690 }
2691
2692 public void directInvite(Conversation conversation, Jid jid) {
2693 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2694 sendMessagePacket(conversation.getAccount(), packet);
2695 }
2696
2697 public void resetSendingToWaiting(Account account) {
2698 for (Conversation conversation : getConversations()) {
2699 if (conversation.getAccount() == account) {
2700 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2701
2702 @Override
2703 public void onMessageFound(Message message) {
2704 markMessage(message, Message.STATUS_WAITING);
2705 }
2706 });
2707 }
2708 }
2709 }
2710
2711 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2712 if (uuid == null) {
2713 return null;
2714 }
2715 for (Conversation conversation : getConversations()) {
2716 if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2717 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2718 if (message != null) {
2719 markMessage(message, status);
2720 }
2721 return message;
2722 }
2723 }
2724 return null;
2725 }
2726
2727 public boolean markMessage(Conversation conversation, String uuid, int status) {
2728 if (uuid == null) {
2729 return false;
2730 } else {
2731 Message message = conversation.findSentMessageWithUuid(uuid);
2732 if (message != null) {
2733 markMessage(message, status);
2734 return true;
2735 } else {
2736 return false;
2737 }
2738 }
2739 }
2740
2741 public void markMessage(Message message, int status) {
2742 if (status == Message.STATUS_SEND_FAILED
2743 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2744 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2745 return;
2746 }
2747 message.setStatus(status);
2748 databaseBackend.updateMessage(message);
2749 updateConversationUi();
2750 }
2751
2752 public SharedPreferences getPreferences() {
2753 return PreferenceManager
2754 .getDefaultSharedPreferences(getApplicationContext());
2755 }
2756
2757 public boolean confirmMessages() {
2758 return getPreferences().getBoolean("confirm_messages", true);
2759 }
2760
2761 public boolean allowMessageCorrection() {
2762 return getPreferences().getBoolean("allow_message_correction", false);
2763 }
2764
2765 public boolean sendChatStates() {
2766 return getPreferences().getBoolean("chat_states", false);
2767 }
2768
2769 public boolean saveEncryptedMessages() {
2770 return !getPreferences().getBoolean("dont_save_encrypted", false);
2771 }
2772
2773 private boolean respectAutojoin() {
2774 return getPreferences().getBoolean("autojoin", true);
2775 }
2776
2777 public boolean indicateReceived() {
2778 return getPreferences().getBoolean("indicate_received", false);
2779 }
2780
2781 public boolean useTorToConnect() {
2782 return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
2783 }
2784
2785 public boolean showExtendedConnectionOptions() {
2786 return getPreferences().getBoolean("show_connection_options", false);
2787 }
2788
2789 public int unreadCount() {
2790 int count = 0;
2791 for (Conversation conversation : getConversations()) {
2792 count += conversation.unreadCount();
2793 }
2794 return count;
2795 }
2796
2797
2798 public void showErrorToastInUi(int resId) {
2799 if (mOnShowErrorToast != null) {
2800 mOnShowErrorToast.onShowErrorToast(resId);
2801 }
2802 }
2803
2804 public void updateConversationUi() {
2805 if (mOnConversationUpdate != null) {
2806 mOnConversationUpdate.onConversationUpdate();
2807 }
2808 }
2809
2810 public void updateAccountUi() {
2811 if (mOnAccountUpdate != null) {
2812 mOnAccountUpdate.onAccountUpdate();
2813 }
2814 }
2815
2816 public void updateRosterUi() {
2817 if (mOnRosterUpdate != null) {
2818 mOnRosterUpdate.onRosterUpdate();
2819 }
2820 }
2821
2822 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2823 if (mOnCaptchaRequested != null) {
2824 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2825 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2826 (int) (captcha.getHeight() * metrics.scaledDensity), false);
2827
2828 mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2829 return true;
2830 }
2831 return false;
2832 }
2833
2834 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2835 if (mOnUpdateBlocklist != null) {
2836 mOnUpdateBlocklist.OnUpdateBlocklist(status);
2837 }
2838 }
2839
2840 public void updateMucRosterUi() {
2841 if (mOnMucRosterUpdate != null) {
2842 mOnMucRosterUpdate.onMucRosterUpdate();
2843 }
2844 }
2845
2846 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
2847 if (mOnKeyStatusUpdated != null) {
2848 mOnKeyStatusUpdated.onKeyStatusUpdated(report);
2849 }
2850 }
2851
2852 public Account findAccountByJid(final Jid accountJid) {
2853 for (Account account : this.accounts) {
2854 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2855 return account;
2856 }
2857 }
2858 return null;
2859 }
2860
2861 public Conversation findConversationByUuid(String uuid) {
2862 for (Conversation conversation : getConversations()) {
2863 if (conversation.getUuid().equals(uuid)) {
2864 return conversation;
2865 }
2866 }
2867 return null;
2868 }
2869
2870 public boolean markRead(final Conversation conversation) {
2871 mNotificationService.clear(conversation);
2872 final List<Message> readMessages = conversation.markRead();
2873 if (readMessages.size() > 0) {
2874 Runnable runnable = new Runnable() {
2875 @Override
2876 public void run() {
2877 for (Message message : readMessages) {
2878 databaseBackend.updateMessage(message);
2879 }
2880 }
2881 };
2882 mDatabaseExecutor.execute(runnable);
2883 updateUnreadCountBadge();
2884 return true;
2885 } else {
2886 return false;
2887 }
2888 }
2889
2890 public synchronized void updateUnreadCountBadge() {
2891 int count = unreadCount();
2892 if (unreadCount != count) {
2893 Log.d(Config.LOGTAG, "update unread count to " + count);
2894 if (count > 0) {
2895 ShortcutBadger.applyCount(getApplicationContext(), count);
2896 } else {
2897 ShortcutBadger.removeCount(getApplicationContext());
2898 }
2899 unreadCount = count;
2900 }
2901 }
2902
2903 public void sendReadMarker(final Conversation conversation) {
2904 final Message markable = conversation.getLatestMarkableMessage();
2905 if (this.markRead(conversation)) {
2906 updateConversationUi();
2907 }
2908 if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2909 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2910 Account account = conversation.getAccount();
2911 final Jid to = markable.getCounterpart();
2912 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2913 this.sendMessagePacket(conversation.getAccount(), packet);
2914 }
2915 }
2916
2917 public SecureRandom getRNG() {
2918 return this.mRandom;
2919 }
2920
2921 public MemorizingTrustManager getMemorizingTrustManager() {
2922 return this.mMemorizingTrustManager;
2923 }
2924
2925 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2926 this.mMemorizingTrustManager = trustManager;
2927 }
2928
2929 public void updateMemorizingTrustmanager() {
2930 final MemorizingTrustManager tm;
2931 final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2932 if (dontTrustSystemCAs) {
2933 tm = new MemorizingTrustManager(getApplicationContext(), null);
2934 } else {
2935 tm = new MemorizingTrustManager(getApplicationContext());
2936 }
2937 setMemorizingTrustManager(tm);
2938 }
2939
2940 public PowerManager getPowerManager() {
2941 return this.pm;
2942 }
2943
2944 public LruCache<String, Bitmap> getBitmapCache() {
2945 return this.mBitmapCache;
2946 }
2947
2948 public void syncRosterToDisk(final Account account) {
2949 Runnable runnable = new Runnable() {
2950
2951 @Override
2952 public void run() {
2953 databaseBackend.writeRoster(account.getRoster());
2954 }
2955 };
2956 mDatabaseExecutor.execute(runnable);
2957
2958 }
2959
2960 public List<String> getKnownHosts() {
2961 final List<String> hosts = new ArrayList<>();
2962 for (final Account account : getAccounts()) {
2963 if (!hosts.contains(account.getServer().toString())) {
2964 hosts.add(account.getServer().toString());
2965 }
2966 for (final Contact contact : account.getRoster().getContacts()) {
2967 if (contact.showInRoster()) {
2968 final String server = contact.getServer().toString();
2969 if (server != null && !hosts.contains(server)) {
2970 hosts.add(server);
2971 }
2972 }
2973 }
2974 }
2975 if(Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
2976 hosts.add(Config.DOMAIN_LOCK);
2977 }
2978 if(Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
2979 hosts.add(Config.MAGIC_CREATE_DOMAIN);
2980 }
2981 return hosts;
2982 }
2983
2984 public List<String> getKnownConferenceHosts() {
2985 final ArrayList<String> mucServers = new ArrayList<>();
2986 for (final Account account : accounts) {
2987 if (account.getXmppConnection() != null) {
2988 final String server = account.getXmppConnection().getMucServer();
2989 if (server != null && !mucServers.contains(server)) {
2990 mucServers.add(server);
2991 }
2992 }
2993 }
2994 return mucServers;
2995 }
2996
2997 public void sendMessagePacket(Account account, MessagePacket packet) {
2998 XmppConnection connection = account.getXmppConnection();
2999 if (connection != null) {
3000 connection.sendMessagePacket(packet);
3001 }
3002 }
3003
3004 public void sendPresencePacket(Account account, PresencePacket packet) {
3005 XmppConnection connection = account.getXmppConnection();
3006 if (connection != null) {
3007 connection.sendPresencePacket(packet);
3008 }
3009 }
3010
3011 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3012 final XmppConnection connection = account.getXmppConnection();
3013 if (connection != null) {
3014 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3015 sendIqPacket(account, request, connection.registrationResponseListener);
3016 }
3017 }
3018
3019 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3020 final XmppConnection connection = account.getXmppConnection();
3021 if (connection != null) {
3022 connection.sendIqPacket(packet, callback);
3023 }
3024 }
3025
3026 public void sendPresence(final Account account) {
3027 PresencePacket packet;
3028 if (manuallyChangePresence()) {
3029 packet = mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3030 String message = account.getPresenceStatusMessage();
3031 if (message != null && !message.isEmpty()) {
3032 packet.addChild(new Element("status").setContent(message));
3033 }
3034 } else {
3035 packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3036 }
3037 sendPresencePacket(account, packet);
3038 }
3039
3040 public void refreshAllPresences() {
3041 for (Account account : getAccounts()) {
3042 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3043 sendPresence(account);
3044 }
3045 }
3046 }
3047
3048 private void refreshAllGcmTokens() {
3049 for(Account account : getAccounts()) {
3050 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3051 mPushManagementService.registerPushTokenOnServer(account);
3052 }
3053 }
3054 }
3055
3056 public void sendOfflinePresence(final Account account) {
3057 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3058 }
3059
3060 public MessageGenerator getMessageGenerator() {
3061 return this.mMessageGenerator;
3062 }
3063
3064 public PresenceGenerator getPresenceGenerator() {
3065 return this.mPresenceGenerator;
3066 }
3067
3068 public IqGenerator getIqGenerator() {
3069 return this.mIqGenerator;
3070 }
3071
3072 public IqParser getIqParser() {
3073 return this.mIqParser;
3074 }
3075
3076 public JingleConnectionManager getJingleConnectionManager() {
3077 return this.mJingleConnectionManager;
3078 }
3079
3080 public MessageArchiveService getMessageArchiveService() {
3081 return this.mMessageArchiveService;
3082 }
3083
3084 public List<Contact> findContacts(Jid jid) {
3085 ArrayList<Contact> contacts = new ArrayList<>();
3086 for (Account account : getAccounts()) {
3087 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3088 Contact contact = account.getRoster().getContactFromRoster(jid);
3089 if (contact != null) {
3090 contacts.add(contact);
3091 }
3092 }
3093 }
3094 return contacts;
3095 }
3096
3097 public NotificationService getNotificationService() {
3098 return this.mNotificationService;
3099 }
3100
3101 public HttpConnectionManager getHttpConnectionManager() {
3102 return this.mHttpConnectionManager;
3103 }
3104
3105 public void resendFailedMessages(final Message message) {
3106 final Collection<Message> messages = new ArrayList<>();
3107 Message current = message;
3108 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3109 messages.add(current);
3110 if (current.mergeable(current.next())) {
3111 current = current.next();
3112 } else {
3113 break;
3114 }
3115 }
3116 for (final Message msg : messages) {
3117 msg.setTime(System.currentTimeMillis());
3118 markMessage(msg, Message.STATUS_WAITING);
3119 this.resendMessage(msg, false);
3120 }
3121 }
3122
3123 public void clearConversationHistory(final Conversation conversation) {
3124 conversation.clearMessages();
3125 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3126 conversation.setLastClearHistory(System.currentTimeMillis());
3127 Runnable runnable = new Runnable() {
3128 @Override
3129 public void run() {
3130 databaseBackend.deleteMessagesInConversation(conversation);
3131 }
3132 };
3133 mDatabaseExecutor.execute(runnable);
3134 }
3135
3136 public void sendBlockRequest(final Blockable blockable) {
3137 if (blockable != null && blockable.getBlockedJid() != null) {
3138 final Jid jid = blockable.getBlockedJid();
3139 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
3140
3141 @Override
3142 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3143 if (packet.getType() == IqPacket.TYPE.RESULT) {
3144 account.getBlocklist().add(jid);
3145 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3146 }
3147 }
3148 });
3149 }
3150 }
3151
3152 public void sendUnblockRequest(final Blockable blockable) {
3153 if (blockable != null && blockable.getJid() != null) {
3154 final Jid jid = blockable.getBlockedJid();
3155 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3156 @Override
3157 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3158 if (packet.getType() == IqPacket.TYPE.RESULT) {
3159 account.getBlocklist().remove(jid);
3160 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3161 }
3162 }
3163 });
3164 }
3165 }
3166
3167 public void publishDisplayName(Account account) {
3168 String displayName = account.getDisplayName();
3169 if (displayName != null && !displayName.isEmpty()) {
3170 IqPacket publish = mIqGenerator.publishNick(displayName);
3171 sendIqPacket(account, publish, new OnIqPacketReceived() {
3172 @Override
3173 public void onIqPacketReceived(Account account, IqPacket packet) {
3174 if (packet.getType() == IqPacket.TYPE.ERROR) {
3175 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3176 }
3177 }
3178 });
3179 }
3180 }
3181
3182 private ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String,String> key) {
3183 ServiceDiscoveryResult result = discoCache.get(key);
3184 if (result != null) {
3185 return result;
3186 } else {
3187 result = databaseBackend.findDiscoveryResult(key.first, key.second);
3188 if (result != null) {
3189 discoCache.put(key, result);
3190 }
3191 return result;
3192 }
3193 }
3194
3195 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3196 final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3197 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3198 if (disco != null) {
3199 presence.setServiceDiscoveryResult(disco);
3200 } else {
3201 if (!account.inProgressDiscoFetches.contains(key)) {
3202 account.inProgressDiscoFetches.add(key);
3203 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3204 request.setTo(jid);
3205 request.query("http://jabber.org/protocol/disco#info");
3206 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3207 sendIqPacket(account, request, new OnIqPacketReceived() {
3208 @Override
3209 public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3210 if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3211 ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3212 if (presence.getVer().equals(disco.getVer())) {
3213 databaseBackend.insertDiscoveryResult(disco);
3214 injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3215 } else {
3216 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3217 }
3218 }
3219 account.inProgressDiscoFetches.remove(key);
3220 }
3221 });
3222 }
3223 }
3224 }
3225
3226 private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3227 for(Contact contact : roster.getContacts()) {
3228 for(Presence presence : contact.getPresences().getPresences().values()) {
3229 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3230 presence.setServiceDiscoveryResult(disco);
3231 }
3232 }
3233 }
3234 }
3235
3236 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3237 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3238 request.addChild("prefs","urn:xmpp:mam:0");
3239 sendIqPacket(account, request, new OnIqPacketReceived() {
3240 @Override
3241 public void onIqPacketReceived(Account account, IqPacket packet) {
3242 Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3243 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3244 callback.onPreferencesFetched(prefs);
3245 } else {
3246 callback.onPreferencesFetchFailed();
3247 }
3248 }
3249 });
3250 }
3251
3252 public PushManagementService getPushManagementService() {
3253 return mPushManagementService;
3254 }
3255
3256 public Account getPendingAccount() {
3257 Account pending = null;
3258 for(Account account : getAccounts()) {
3259 if (account.isOptionSet(Account.OPTION_REGISTER)) {
3260 pending = account;
3261 } else {
3262 return null;
3263 }
3264 }
3265 return pending;
3266 }
3267
3268 public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3269 if (!statusMessage.isEmpty()) {
3270 databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3271 }
3272 changeStatusReal(account, status, statusMessage, send);
3273 }
3274
3275 private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3276 account.setPresenceStatus(status);
3277 account.setPresenceStatusMessage(statusMessage);
3278 databaseBackend.updateAccount(account);
3279 if (!account.isOptionSet(Account.OPTION_DISABLED) && send) {
3280 sendPresence(account);
3281 }
3282 }
3283
3284 public void changeStatus(Presence.Status status, String statusMessage) {
3285 if (!statusMessage.isEmpty()) {
3286 databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3287 }
3288 for(Account account : getAccounts()) {
3289 changeStatusReal(account, status, statusMessage, true);
3290 }
3291 }
3292
3293 public List<PresenceTemplate> getPresenceTemplates(Account account) {
3294 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3295 for(PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3296 if (!templates.contains(template)) {
3297 templates.add(0, template);
3298 }
3299 }
3300 return templates;
3301 }
3302
3303 public interface OnMamPreferencesFetched {
3304 void onPreferencesFetched(Element prefs);
3305 void onPreferencesFetchFailed();
3306 }
3307
3308 public void pushMamPreferences(Account account, Element prefs) {
3309 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3310 set.addChild(prefs);
3311 sendIqPacket(account, set, null);
3312 }
3313
3314 public interface OnAccountCreated {
3315 void onAccountCreated(Account account);
3316
3317 void informUser(int r);
3318 }
3319
3320 public interface OnMoreMessagesLoaded {
3321 void onMoreMessagesLoaded(int count, Conversation conversation);
3322
3323 void informUser(int r);
3324 }
3325
3326 public interface OnAccountPasswordChanged {
3327 void onPasswordChangeSucceeded();
3328
3329 void onPasswordChangeFailed();
3330 }
3331
3332 public interface OnAffiliationChanged {
3333 void onAffiliationChangedSuccessful(Jid jid);
3334
3335 void onAffiliationChangeFailed(Jid jid, int resId);
3336 }
3337
3338 public interface OnRoleChanged {
3339 void onRoleChangedSuccessful(String nick);
3340
3341 void onRoleChangeFailed(String nick, int resid);
3342 }
3343
3344 public interface OnConversationUpdate {
3345 void onConversationUpdate();
3346 }
3347
3348 public interface OnAccountUpdate {
3349 void onAccountUpdate();
3350 }
3351
3352 public interface OnCaptchaRequested {
3353 void onCaptchaRequested(Account account,
3354 String id,
3355 Data data,
3356 Bitmap captcha);
3357 }
3358
3359 public interface OnRosterUpdate {
3360 void onRosterUpdate();
3361 }
3362
3363 public interface OnMucRosterUpdate {
3364 void onMucRosterUpdate();
3365 }
3366
3367 public interface OnConferenceConfigurationFetched {
3368 void onConferenceConfigurationFetched(Conversation conversation);
3369
3370 void onFetchFailed(Conversation conversation, Element error);
3371 }
3372
3373 public interface OnConferenceJoined {
3374 void onConferenceJoined(Conversation conversation);
3375 }
3376
3377 public interface OnConferenceOptionsPushed {
3378 void onPushSucceeded();
3379
3380 void onPushFailed();
3381 }
3382
3383 public interface OnShowErrorToast {
3384 void onShowErrorToast(int resId);
3385 }
3386
3387 public class XmppConnectionBinder extends Binder {
3388 public XmppConnectionService getService() {
3389 return XmppConnectionService.this;
3390 }
3391 }
3392}