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