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