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