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 boolean saveInDb = addToConversation;
847 message.setStatus(Message.STATUS_WAITING);
848
849 if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
850 message.getConversation().endOtrIfNeeded();
851 message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
852 new Conversation.OnMessageFound() {
853 @Override
854 public void onMessageFound(Message message) {
855 markMessage(message, Message.STATUS_SEND_FAILED);
856 }
857 });
858 }
859
860 if (account.isOnlineAndConnected()) {
861 switch (message.getEncryption()) {
862 case Message.ENCRYPTION_NONE:
863 if (message.needsUploading()) {
864 if (account.httpUploadAvailable() || message.fixCounterpart()) {
865 this.sendFileMessage(message, delay);
866 } else {
867 break;
868 }
869 } else {
870 packet = mMessageGenerator.generateChat(message);
871 }
872 break;
873 case Message.ENCRYPTION_PGP:
874 case Message.ENCRYPTION_DECRYPTED:
875 if (message.needsUploading()) {
876 if (account.httpUploadAvailable() || message.fixCounterpart()) {
877 this.sendFileMessage(message, delay);
878 } else {
879 break;
880 }
881 } else {
882 packet = mMessageGenerator.generatePgpChat(message);
883 }
884 break;
885 case Message.ENCRYPTION_OTR:
886 SessionImpl otrSession = conversation.getOtrSession();
887 if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
888 try {
889 message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
890 } catch (InvalidJidException e) {
891 break;
892 }
893 if (message.needsUploading()) {
894 mJingleConnectionManager.createNewConnection(message);
895 } else {
896 packet = mMessageGenerator.generateOtrChat(message);
897 }
898 } else if (otrSession == null) {
899 if (message.fixCounterpart()) {
900 conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
901 } else {
902 break;
903 }
904 }
905 break;
906 case Message.ENCRYPTION_AXOLOTL:
907 message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
908 if (message.needsUploading()) {
909 if (account.httpUploadAvailable() || message.fixCounterpart()) {
910 this.sendFileMessage(message, delay);
911 } else {
912 break;
913 }
914 } else {
915 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
916 if (axolotlMessage == null) {
917 account.getAxolotlService().preparePayloadMessage(message, delay);
918 } else {
919 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
920 }
921 }
922 break;
923
924 }
925 if (packet != null) {
926 if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
927 message.setStatus(Message.STATUS_UNSEND);
928 } else {
929 message.setStatus(Message.STATUS_SEND);
930 }
931 }
932 } else {
933 switch (message.getEncryption()) {
934 case Message.ENCRYPTION_DECRYPTED:
935 if (!message.needsUploading()) {
936 String pgpBody = message.getEncryptedBody();
937 String decryptedBody = message.getBody();
938 message.setBody(pgpBody);
939 message.setEncryption(Message.ENCRYPTION_PGP);
940 databaseBackend.createMessage(message);
941 saveInDb = false;
942 message.setBody(decryptedBody);
943 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
944 }
945 break;
946 case Message.ENCRYPTION_OTR:
947 if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
948 conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
949 }
950 break;
951 case Message.ENCRYPTION_AXOLOTL:
952 message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint());
953 break;
954 }
955 }
956
957 if (resend) {
958 if (packet != null && addToConversation) {
959 if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) {
960 markMessage(message, Message.STATUS_UNSEND);
961 } else {
962 markMessage(message, Message.STATUS_SEND);
963 }
964 }
965 } else {
966 if (addToConversation) {
967 conversation.add(message);
968 }
969 if (saveInDb && (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages())) {
970 databaseBackend.createMessage(message);
971 }
972 updateConversationUi();
973 }
974 if (packet != null) {
975 if (delay) {
976 mMessageGenerator.addDelay(packet, message.getTimeSent());
977 }
978 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
979 if (this.sendChatStates()) {
980 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
981 }
982 }
983 sendMessagePacket(account, packet);
984 }
985 }
986
987 private void sendUnsentMessages(final Conversation conversation) {
988 conversation.findWaitingMessages(new Conversation.OnMessageFound() {
989
990 @Override
991 public void onMessageFound(Message message) {
992 resendMessage(message, true);
993 }
994 });
995 }
996
997 public void resendMessage(final Message message, final boolean delay) {
998 sendMessage(message, true, delay);
999 }
1000
1001 public void fetchRosterFromServer(final Account account) {
1002 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1003 if (!"".equals(account.getRosterVersion())) {
1004 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1005 + ": fetching roster version " + account.getRosterVersion());
1006 } else {
1007 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
1008 }
1009 iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
1010 sendIqPacket(account, iqPacket, mIqParser);
1011 }
1012
1013 public void fetchBookmarks(final Account account) {
1014 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1015 final Element query = iqPacket.query("jabber:iq:private");
1016 query.addChild("storage", "storage:bookmarks");
1017 final OnIqPacketReceived callback = new OnIqPacketReceived() {
1018
1019 @Override
1020 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1021 if (packet.getType() == IqPacket.TYPE.RESULT) {
1022 final Element query = packet.query();
1023 final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1024 final Element storage = query.findChild("storage", "storage:bookmarks");
1025 final boolean autojoin = respectAutojoin();
1026 if (storage != null) {
1027 for (final Element item : storage.getChildren()) {
1028 if (item.getName().equals("conference")) {
1029 final Bookmark bookmark = Bookmark.parse(item, account);
1030 Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1031 if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1032 bookmark.setBookmarkName(old.getBookmarkName());
1033 }
1034 Conversation conversation = find(bookmark);
1035 if (conversation != null) {
1036 conversation.setBookmark(bookmark);
1037 } else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1038 conversation = findOrCreateConversation(
1039 account, bookmark.getJid(), true);
1040 conversation.setBookmark(bookmark);
1041 joinMuc(conversation);
1042 }
1043 }
1044 }
1045 }
1046 account.setBookmarks(new ArrayList<>(bookmarks.values()));
1047 } else {
1048 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
1049 }
1050 }
1051 };
1052 sendIqPacket(account, iqPacket, callback);
1053 }
1054
1055 public void pushBookmarks(Account account) {
1056 Log.d(Config.LOGTAG, account.getJid().toBareJid()+": pushing bookmarks");
1057 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1058 Element query = iqPacket.query("jabber:iq:private");
1059 Element storage = query.addChild("storage", "storage:bookmarks");
1060 for (Bookmark bookmark : account.getBookmarks()) {
1061 storage.addChild(bookmark);
1062 }
1063 sendIqPacket(account, iqPacket, mDefaultIqHandler);
1064 }
1065
1066 public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
1067 if (mPhoneContactMergerThread != null) {
1068 mPhoneContactMergerThread.interrupt();
1069 }
1070 mPhoneContactMergerThread = new Thread(new Runnable() {
1071 @Override
1072 public void run() {
1073 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1074 for (Account account : accounts) {
1075 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1076 for (Bundle phoneContact : phoneContacts) {
1077 if (Thread.interrupted()) {
1078 Log.d(Config.LOGTAG, "interrupted merging phone contacts");
1079 return;
1080 }
1081 Jid jid;
1082 try {
1083 jid = Jid.fromString(phoneContact.getString("jid"));
1084 } catch (final InvalidJidException e) {
1085 continue;
1086 }
1087 final Contact contact = account.getRoster().getContact(jid);
1088 String systemAccount = phoneContact.getInt("phoneid")
1089 + "#"
1090 + phoneContact.getString("lookup");
1091 contact.setSystemAccount(systemAccount);
1092 if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
1093 getAvatarService().clear(contact);
1094 }
1095 contact.setSystemName(phoneContact.getString("displayname"));
1096 withSystemAccounts.remove(contact);
1097 }
1098 for (Contact contact : withSystemAccounts) {
1099 contact.setSystemAccount(null);
1100 contact.setSystemName(null);
1101 if (contact.setPhotoUri(null)) {
1102 getAvatarService().clear(contact);
1103 }
1104 }
1105 }
1106 Log.d(Config.LOGTAG, "finished merging phone contacts");
1107 updateAccountUi();
1108 }
1109 });
1110 mPhoneContactMergerThread.start();
1111 }
1112
1113 private void restoreFromDatabase() {
1114 synchronized (this.conversations) {
1115 final Map<String, Account> accountLookupTable = new Hashtable<>();
1116 for (Account account : this.accounts) {
1117 accountLookupTable.put(account.getUuid(), account);
1118 }
1119 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1120 for (Conversation conversation : this.conversations) {
1121 Account account = accountLookupTable.get(conversation.getAccountUuid());
1122 conversation.setAccount(account);
1123 }
1124 Runnable runnable = new Runnable() {
1125 @Override
1126 public void run() {
1127 Log.d(Config.LOGTAG, "restoring roster");
1128 for (Account account : accounts) {
1129 databaseBackend.readRoster(account.getRoster());
1130 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1131 }
1132 getBitmapCache().evictAll();
1133 Looper.prepare();
1134 loadPhoneContacts();
1135 Log.d(Config.LOGTAG, "restoring messages");
1136 for (Conversation conversation : conversations) {
1137 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1138 checkDeletedFiles(conversation);
1139 conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1140 @Override
1141 public void onMessageFound(Message message) {
1142 mNotificationService.pushFromBacklog(message);
1143 }
1144 });
1145 }
1146 mNotificationService.finishBacklog(false);
1147 mRestoredFromDatabase = true;
1148 Log.d(Config.LOGTAG, "restored all messages");
1149 updateConversationUi();
1150 }
1151 };
1152 mDatabaseExecutor.execute(runnable);
1153 }
1154 }
1155
1156 public void loadPhoneContacts() {
1157 PhoneHelper.loadPhoneContacts(getApplicationContext(),
1158 new CopyOnWriteArrayList<Bundle>(),
1159 XmppConnectionService.this);
1160 }
1161
1162 public List<Conversation> getConversations() {
1163 return this.conversations;
1164 }
1165
1166 private void checkDeletedFiles(Conversation conversation) {
1167 conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1168
1169 @Override
1170 public void onMessageFound(Message message) {
1171 if (!getFileBackend().isFileAvailable(message)) {
1172 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1173 final int s = message.getStatus();
1174 if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1175 markMessage(message, Message.STATUS_SEND_FAILED);
1176 }
1177 }
1178 }
1179 });
1180 }
1181
1182 private void markFileDeleted(String uuid) {
1183 for (Conversation conversation : getConversations()) {
1184 Message message = conversation.findMessageWithFileAndUuid(uuid);
1185 if (message != null) {
1186 if (!getFileBackend().isFileAvailable(message)) {
1187 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1188 final int s = message.getStatus();
1189 if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1190 markMessage(message, Message.STATUS_SEND_FAILED);
1191 } else {
1192 updateConversationUi();
1193 }
1194 }
1195 return;
1196 }
1197 }
1198 }
1199
1200 public void populateWithOrderedConversations(final List<Conversation> list) {
1201 populateWithOrderedConversations(list, true);
1202 }
1203
1204 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1205 list.clear();
1206 if (includeNoFileUpload) {
1207 list.addAll(getConversations());
1208 } else {
1209 for (Conversation conversation : getConversations()) {
1210 if (conversation.getMode() == Conversation.MODE_SINGLE
1211 || conversation.getAccount().httpUploadAvailable()) {
1212 list.add(conversation);
1213 }
1214 }
1215 }
1216 Collections.sort(list, new Comparator<Conversation>() {
1217 @Override
1218 public int compare(Conversation lhs, Conversation rhs) {
1219 Message left = lhs.getLatestMessage();
1220 Message right = rhs.getLatestMessage();
1221 if (left.getTimeSent() > right.getTimeSent()) {
1222 return -1;
1223 } else if (left.getTimeSent() < right.getTimeSent()) {
1224 return 1;
1225 } else {
1226 return 0;
1227 }
1228 }
1229 });
1230 }
1231
1232 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1233 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1234 return;
1235 } else if (timestamp == 0) {
1236 return;
1237 }
1238 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1239 Runnable runnable = new Runnable() {
1240 @Override
1241 public void run() {
1242 final Account account = conversation.getAccount();
1243 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1244 if (messages.size() > 0) {
1245 conversation.addAll(0, messages);
1246 checkDeletedFiles(conversation);
1247 callback.onMoreMessagesLoaded(messages.size(), conversation);
1248 } else if (conversation.hasMessagesLeftOnServer()
1249 && account.isOnlineAndConnected()
1250 && conversation.getLastClearHistory() == 0) {
1251 if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1252 || (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1253 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp);
1254 if (query != null) {
1255 query.setCallback(callback);
1256 }
1257 callback.informUser(R.string.fetching_history_from_server);
1258 }
1259 }
1260 }
1261 };
1262 mDatabaseExecutor.execute(runnable);
1263 }
1264
1265 public List<Account> getAccounts() {
1266 return this.accounts;
1267 }
1268
1269 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1270 for (final Conversation conversation : haystack) {
1271 if (conversation.getContact() == contact) {
1272 return conversation;
1273 }
1274 }
1275 return null;
1276 }
1277
1278 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1279 if (jid == null) {
1280 return null;
1281 }
1282 for (final Conversation conversation : haystack) {
1283 if ((account == null || conversation.getAccount() == account)
1284 && (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1285 return conversation;
1286 }
1287 }
1288 return null;
1289 }
1290
1291 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1292 return this.findOrCreateConversation(account, jid, muc, null);
1293 }
1294
1295 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1296 synchronized (this.conversations) {
1297 Conversation conversation = find(account, jid);
1298 if (conversation != null) {
1299 return conversation;
1300 }
1301 conversation = databaseBackend.findConversation(account, jid);
1302 if (conversation != null) {
1303 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1304 conversation.setAccount(account);
1305 if (muc) {
1306 conversation.setMode(Conversation.MODE_MULTI);
1307 conversation.setContactJid(jid);
1308 } else {
1309 conversation.setMode(Conversation.MODE_SINGLE);
1310 conversation.setContactJid(jid.toBareJid());
1311 }
1312 conversation.setNextEncryption(-1);
1313 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1314 this.databaseBackend.updateConversation(conversation);
1315 } else {
1316 String conversationName;
1317 Contact contact = account.getRoster().getContact(jid);
1318 if (contact != null) {
1319 conversationName = contact.getDisplayName();
1320 } else {
1321 conversationName = jid.getLocalpart();
1322 }
1323 if (muc) {
1324 conversation = new Conversation(conversationName, account, jid,
1325 Conversation.MODE_MULTI);
1326 } else {
1327 conversation = new Conversation(conversationName, account, jid.toBareJid(),
1328 Conversation.MODE_SINGLE);
1329 }
1330 this.databaseBackend.createConversation(conversation);
1331 }
1332 if (account.getXmppConnection() != null
1333 && account.getXmppConnection().getFeatures().mam()
1334 && !muc) {
1335 if (query == null) {
1336 this.mMessageArchiveService.query(conversation);
1337 } else {
1338 if (query.getConversation() == null) {
1339 this.mMessageArchiveService.query(conversation, query.getStart());
1340 }
1341 }
1342 }
1343 checkDeletedFiles(conversation);
1344 this.conversations.add(conversation);
1345 updateConversationUi();
1346 return conversation;
1347 }
1348 }
1349
1350 public void archiveConversation(Conversation conversation) {
1351 getNotificationService().clear(conversation);
1352 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1353 conversation.setNextEncryption(-1);
1354 synchronized (this.conversations) {
1355 if (conversation.getMode() == Conversation.MODE_MULTI) {
1356 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1357 Bookmark bookmark = conversation.getBookmark();
1358 if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1359 bookmark.setAutojoin(false);
1360 pushBookmarks(bookmark.getAccount());
1361 }
1362 }
1363 leaveMuc(conversation);
1364 } else {
1365 conversation.endOtrIfNeeded();
1366 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1367 Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1368 sendPresencePacket(
1369 conversation.getAccount(),
1370 mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1371 );
1372 }
1373 }
1374 this.databaseBackend.updateConversation(conversation);
1375 this.conversations.remove(conversation);
1376 updateConversationUi();
1377 }
1378 }
1379
1380 public void createAccount(final Account account) {
1381 account.initAccountServices(this);
1382 databaseBackend.createAccount(account);
1383 this.accounts.add(account);
1384 this.reconnectAccountInBackground(account);
1385 updateAccountUi();
1386 }
1387
1388 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1389 new Thread(new Runnable() {
1390 @Override
1391 public void run() {
1392 try {
1393 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1394 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1395 if (findAccountByJid(info.first) == null) {
1396 Account account = new Account(info.first, "");
1397 account.setPrivateKeyAlias(alias);
1398 account.setOption(Account.OPTION_DISABLED, true);
1399 account.setDisplayName(info.second);
1400 createAccount(account);
1401 callback.onAccountCreated(account);
1402 if (Config.X509_VERIFICATION) {
1403 try {
1404 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1405 } catch (CertificateException e) {
1406 callback.informUser(R.string.certificate_chain_is_not_trusted);
1407 }
1408 }
1409 } else {
1410 callback.informUser(R.string.account_already_exists);
1411 }
1412 } catch (Exception e) {
1413 e.printStackTrace();
1414 callback.informUser(R.string.unable_to_parse_certificate);
1415 }
1416 }
1417 }).start();
1418
1419 }
1420
1421 public void updateKeyInAccount(final Account account, final String alias) {
1422 Log.d(Config.LOGTAG, "update key in account " + alias);
1423 try {
1424 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1425 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1426 if (account.getJid().toBareJid().equals(info.first)) {
1427 account.setPrivateKeyAlias(alias);
1428 account.setDisplayName(info.second);
1429 databaseBackend.updateAccount(account);
1430 if (Config.X509_VERIFICATION) {
1431 try {
1432 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1433 } catch (CertificateException e) {
1434 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1435 }
1436 account.getAxolotlService().regenerateKeys(true);
1437 }
1438 } else {
1439 showErrorToastInUi(R.string.jid_does_not_match_certificate);
1440 }
1441 } catch (Exception e) {
1442 e.printStackTrace();
1443 }
1444 }
1445
1446 public void updateAccount(final Account account) {
1447 this.statusListener.onStatusChanged(account);
1448 databaseBackend.updateAccount(account);
1449 reconnectAccountInBackground(account);
1450 updateAccountUi();
1451 getNotificationService().updateErrorNotification();
1452 }
1453
1454 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1455 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1456 sendIqPacket(account, iq, new OnIqPacketReceived() {
1457 @Override
1458 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1459 if (packet.getType() == IqPacket.TYPE.RESULT) {
1460 account.setPassword(newPassword);
1461 databaseBackend.updateAccount(account);
1462 callback.onPasswordChangeSucceeded();
1463 } else {
1464 callback.onPasswordChangeFailed();
1465 }
1466 }
1467 });
1468 }
1469
1470 public void deleteAccount(final Account account) {
1471 synchronized (this.conversations) {
1472 for (final Conversation conversation : conversations) {
1473 if (conversation.getAccount() == account) {
1474 if (conversation.getMode() == Conversation.MODE_MULTI) {
1475 leaveMuc(conversation);
1476 } else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1477 conversation.endOtrIfNeeded();
1478 }
1479 conversations.remove(conversation);
1480 }
1481 }
1482 if (account.getXmppConnection() != null) {
1483 this.disconnect(account, true);
1484 }
1485 Runnable runnable = new Runnable() {
1486 @Override
1487 public void run() {
1488 databaseBackend.deleteAccount(account);
1489 }
1490 };
1491 mDatabaseExecutor.execute(runnable);
1492 this.accounts.remove(account);
1493 updateAccountUi();
1494 getNotificationService().updateErrorNotification();
1495 }
1496 }
1497
1498 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1499 synchronized (this) {
1500 if (checkListeners()) {
1501 switchToForeground();
1502 }
1503 this.mOnConversationUpdate = listener;
1504 this.mNotificationService.setIsInForeground(true);
1505 if (this.convChangedListenerCount < 2) {
1506 this.convChangedListenerCount++;
1507 }
1508 }
1509 }
1510
1511 public void removeOnConversationListChangedListener() {
1512 synchronized (this) {
1513 this.convChangedListenerCount--;
1514 if (this.convChangedListenerCount <= 0) {
1515 this.convChangedListenerCount = 0;
1516 this.mOnConversationUpdate = null;
1517 this.mNotificationService.setIsInForeground(false);
1518 if (checkListeners()) {
1519 switchToBackground();
1520 }
1521 }
1522 }
1523 }
1524
1525 public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1526 synchronized (this) {
1527 if (checkListeners()) {
1528 switchToForeground();
1529 }
1530 this.mOnShowErrorToast = onShowErrorToast;
1531 if (this.showErrorToastListenerCount < 2) {
1532 this.showErrorToastListenerCount++;
1533 }
1534 }
1535 this.mOnShowErrorToast = onShowErrorToast;
1536 }
1537
1538 public void removeOnShowErrorToastListener() {
1539 synchronized (this) {
1540 this.showErrorToastListenerCount--;
1541 if (this.showErrorToastListenerCount <= 0) {
1542 this.showErrorToastListenerCount = 0;
1543 this.mOnShowErrorToast = null;
1544 if (checkListeners()) {
1545 switchToBackground();
1546 }
1547 }
1548 }
1549 }
1550
1551 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1552 synchronized (this) {
1553 if (checkListeners()) {
1554 switchToForeground();
1555 }
1556 this.mOnAccountUpdate = listener;
1557 if (this.accountChangedListenerCount < 2) {
1558 this.accountChangedListenerCount++;
1559 }
1560 }
1561 }
1562
1563 public void removeOnAccountListChangedListener() {
1564 synchronized (this) {
1565 this.accountChangedListenerCount--;
1566 if (this.accountChangedListenerCount <= 0) {
1567 this.mOnAccountUpdate = null;
1568 this.accountChangedListenerCount = 0;
1569 if (checkListeners()) {
1570 switchToBackground();
1571 }
1572 }
1573 }
1574 }
1575
1576 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1577 synchronized (this) {
1578 if (checkListeners()) {
1579 switchToForeground();
1580 }
1581 this.mOnCaptchaRequested = listener;
1582 if (this.captchaRequestedListenerCount < 2) {
1583 this.captchaRequestedListenerCount++;
1584 }
1585 }
1586 }
1587
1588 public void removeOnCaptchaRequestedListener() {
1589 synchronized (this) {
1590 this.captchaRequestedListenerCount--;
1591 if (this.captchaRequestedListenerCount <= 0) {
1592 this.mOnCaptchaRequested = null;
1593 this.captchaRequestedListenerCount = 0;
1594 if (checkListeners()) {
1595 switchToBackground();
1596 }
1597 }
1598 }
1599 }
1600
1601 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1602 synchronized (this) {
1603 if (checkListeners()) {
1604 switchToForeground();
1605 }
1606 this.mOnRosterUpdate = listener;
1607 if (this.rosterChangedListenerCount < 2) {
1608 this.rosterChangedListenerCount++;
1609 }
1610 }
1611 }
1612
1613 public void removeOnRosterUpdateListener() {
1614 synchronized (this) {
1615 this.rosterChangedListenerCount--;
1616 if (this.rosterChangedListenerCount <= 0) {
1617 this.rosterChangedListenerCount = 0;
1618 this.mOnRosterUpdate = null;
1619 if (checkListeners()) {
1620 switchToBackground();
1621 }
1622 }
1623 }
1624 }
1625
1626 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1627 synchronized (this) {
1628 if (checkListeners()) {
1629 switchToForeground();
1630 }
1631 this.mOnUpdateBlocklist = listener;
1632 if (this.updateBlocklistListenerCount < 2) {
1633 this.updateBlocklistListenerCount++;
1634 }
1635 }
1636 }
1637
1638 public void removeOnUpdateBlocklistListener() {
1639 synchronized (this) {
1640 this.updateBlocklistListenerCount--;
1641 if (this.updateBlocklistListenerCount <= 0) {
1642 this.updateBlocklistListenerCount = 0;
1643 this.mOnUpdateBlocklist = null;
1644 if (checkListeners()) {
1645 switchToBackground();
1646 }
1647 }
1648 }
1649 }
1650
1651 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1652 synchronized (this) {
1653 if (checkListeners()) {
1654 switchToForeground();
1655 }
1656 this.mOnKeyStatusUpdated = listener;
1657 if (this.keyStatusUpdatedListenerCount < 2) {
1658 this.keyStatusUpdatedListenerCount++;
1659 }
1660 }
1661 }
1662
1663 public void removeOnNewKeysAvailableListener() {
1664 synchronized (this) {
1665 this.keyStatusUpdatedListenerCount--;
1666 if (this.keyStatusUpdatedListenerCount <= 0) {
1667 this.keyStatusUpdatedListenerCount = 0;
1668 this.mOnKeyStatusUpdated = null;
1669 if (checkListeners()) {
1670 switchToBackground();
1671 }
1672 }
1673 }
1674 }
1675
1676 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1677 synchronized (this) {
1678 if (checkListeners()) {
1679 switchToForeground();
1680 }
1681 this.mOnMucRosterUpdate = listener;
1682 if (this.mucRosterChangedListenerCount < 2) {
1683 this.mucRosterChangedListenerCount++;
1684 }
1685 }
1686 }
1687
1688 public void removeOnMucRosterUpdateListener() {
1689 synchronized (this) {
1690 this.mucRosterChangedListenerCount--;
1691 if (this.mucRosterChangedListenerCount <= 0) {
1692 this.mucRosterChangedListenerCount = 0;
1693 this.mOnMucRosterUpdate = null;
1694 if (checkListeners()) {
1695 switchToBackground();
1696 }
1697 }
1698 }
1699 }
1700
1701 private boolean checkListeners() {
1702 return (this.mOnAccountUpdate == null
1703 && this.mOnConversationUpdate == null
1704 && this.mOnRosterUpdate == null
1705 && this.mOnCaptchaRequested == null
1706 && this.mOnUpdateBlocklist == null
1707 && this.mOnShowErrorToast == null
1708 && this.mOnKeyStatusUpdated == null);
1709 }
1710
1711 private void switchToForeground() {
1712 for (Conversation conversation : getConversations()) {
1713 conversation.setIncomingChatState(ChatState.ACTIVE);
1714 }
1715 for (Account account : getAccounts()) {
1716 if (account.getStatus() == Account.State.ONLINE) {
1717 XmppConnection connection = account.getXmppConnection();
1718 if (connection != null && connection.getFeatures().csi()) {
1719 connection.sendActive();
1720 }
1721 }
1722 }
1723 Log.d(Config.LOGTAG, "app switched into foreground");
1724 }
1725
1726 private void switchToBackground() {
1727 for (Account account : getAccounts()) {
1728 if (account.getStatus() == Account.State.ONLINE) {
1729 XmppConnection connection = account.getXmppConnection();
1730 if (connection != null) {
1731 if (connection.getFeatures().csi()) {
1732 connection.sendInactive();
1733 }
1734 if (Config.CLOSE_TCP_WHEN_SWITCHING_TO_BACKGROUND && mPushManagementService.available(account)) {
1735 connection.waitForPush();
1736 cancelWakeUpCall(account.getUuid().hashCode());
1737 }
1738 }
1739 }
1740 }
1741 this.mNotificationService.setIsInForeground(false);
1742 Log.d(Config.LOGTAG, "app switched into background");
1743 }
1744
1745 private void connectMultiModeConversations(Account account) {
1746 List<Conversation> conversations = getConversations();
1747 for (Conversation conversation : conversations) {
1748 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
1749 joinMuc(conversation, true, null);
1750 }
1751 }
1752 }
1753
1754 public void joinMuc(Conversation conversation) {
1755 joinMuc(conversation, false, null);
1756 }
1757
1758 private void joinMuc(Conversation conversation, boolean now, final OnConferenceJoined onConferenceJoined) {
1759 Account account = conversation.getAccount();
1760 account.pendingConferenceJoins.remove(conversation);
1761 account.pendingConferenceLeaves.remove(conversation);
1762 if (account.getStatus() == Account.State.ONLINE || now) {
1763 conversation.resetMucOptions();
1764 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
1765
1766 private void join(Conversation conversation) {
1767 Account account = conversation.getAccount();
1768 final String nick = conversation.getMucOptions().getProposedNick();
1769 final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1770 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1771 PresencePacket packet = new PresencePacket();
1772 packet.setFrom(conversation.getAccount().getJid());
1773 packet.setTo(joinJid);
1774 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1775 if (conversation.getMucOptions().getPassword() != null) {
1776 x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1777 }
1778
1779 if (conversation.getMucOptions().mamSupport()) {
1780 // Use MAM instead of the limited muc history to get history
1781 x.addChild("history").setAttribute("maxchars", "0");
1782 } else {
1783 // Fallback to muc history
1784 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1785 }
1786 String sig = account.getPgpSignature();
1787 if (sig != null) {
1788 packet.addChild("x", "jabber:x:signed").setContent(sig);
1789 }
1790 sendPresencePacket(account, packet);
1791 if (onConferenceJoined != null) {
1792 onConferenceJoined.onConferenceJoined(conversation);
1793 }
1794 if (!joinJid.equals(conversation.getJid())) {
1795 conversation.setContactJid(joinJid);
1796 databaseBackend.updateConversation(conversation);
1797 }
1798 conversation.setHasMessagesLeftOnServer(false);
1799 if (conversation.getMucOptions().mamSupport()) {
1800 getMessageArchiveService().catchupMUC(conversation);
1801 }
1802 sendUnsentMessages(conversation);
1803 }
1804
1805 @Override
1806 public void onConferenceConfigurationFetched(Conversation conversation) {
1807 join(conversation);
1808 }
1809
1810 @Override
1811 public void onFetchFailed(final Conversation conversation, Element error) {
1812 join(conversation);
1813 fetchConferenceConfiguration(conversation);
1814 }
1815 });
1816
1817 } else {
1818 account.pendingConferenceJoins.add(conversation);
1819 }
1820 }
1821
1822 public void providePasswordForMuc(Conversation conversation, String password) {
1823 if (conversation.getMode() == Conversation.MODE_MULTI) {
1824 conversation.getMucOptions().setPassword(password);
1825 if (conversation.getBookmark() != null) {
1826 if (respectAutojoin()) {
1827 conversation.getBookmark().setAutojoin(true);
1828 }
1829 pushBookmarks(conversation.getAccount());
1830 }
1831 databaseBackend.updateConversation(conversation);
1832 joinMuc(conversation);
1833 }
1834 }
1835
1836 public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1837 final MucOptions options = conversation.getMucOptions();
1838 final Jid joinJid = options.createJoinJid(nick);
1839 if (options.online()) {
1840 Account account = conversation.getAccount();
1841 options.setOnRenameListener(new OnRenameListener() {
1842
1843 @Override
1844 public void onSuccess() {
1845 conversation.setContactJid(joinJid);
1846 databaseBackend.updateConversation(conversation);
1847 Bookmark bookmark = conversation.getBookmark();
1848 if (bookmark != null) {
1849 bookmark.setNick(nick);
1850 pushBookmarks(bookmark.getAccount());
1851 }
1852 callback.success(conversation);
1853 }
1854
1855 @Override
1856 public void onFailure() {
1857 callback.error(R.string.nick_in_use, conversation);
1858 }
1859 });
1860
1861 PresencePacket packet = new PresencePacket();
1862 packet.setTo(joinJid);
1863 packet.setFrom(conversation.getAccount().getJid());
1864
1865 String sig = account.getPgpSignature();
1866 if (sig != null) {
1867 packet.addChild("status").setContent("online");
1868 packet.addChild("x", "jabber:x:signed").setContent(sig);
1869 }
1870 sendPresencePacket(account, packet);
1871 } else {
1872 conversation.setContactJid(joinJid);
1873 databaseBackend.updateConversation(conversation);
1874 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1875 Bookmark bookmark = conversation.getBookmark();
1876 if (bookmark != null) {
1877 bookmark.setNick(nick);
1878 pushBookmarks(bookmark.getAccount());
1879 }
1880 joinMuc(conversation);
1881 }
1882 }
1883 }
1884
1885 public void leaveMuc(Conversation conversation) {
1886 leaveMuc(conversation, false);
1887 }
1888
1889 private void leaveMuc(Conversation conversation, boolean now) {
1890 Account account = conversation.getAccount();
1891 account.pendingConferenceJoins.remove(conversation);
1892 account.pendingConferenceLeaves.remove(conversation);
1893 if (account.getStatus() == Account.State.ONLINE || now) {
1894 PresencePacket packet = new PresencePacket();
1895 packet.setTo(conversation.getJid());
1896 packet.setFrom(conversation.getAccount().getJid());
1897 packet.setAttribute("type", "unavailable");
1898 sendPresencePacket(conversation.getAccount(), packet);
1899 conversation.getMucOptions().setOffline();
1900 conversation.deregisterWithBookmark();
1901 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1902 + ": leaving muc " + conversation.getJid());
1903 } else {
1904 account.pendingConferenceLeaves.add(conversation);
1905 }
1906 }
1907
1908 private String findConferenceServer(final Account account) {
1909 String server;
1910 if (account.getXmppConnection() != null) {
1911 server = account.getXmppConnection().getMucServer();
1912 if (server != null) {
1913 return server;
1914 }
1915 }
1916 for (Account other : getAccounts()) {
1917 if (other != account && other.getXmppConnection() != null) {
1918 server = other.getXmppConnection().getMucServer();
1919 if (server != null) {
1920 return server;
1921 }
1922 }
1923 }
1924 return null;
1925 }
1926
1927 public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1928 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1929 if (account.getStatus() == Account.State.ONLINE) {
1930 try {
1931 String server = findConferenceServer(account);
1932 if (server == null) {
1933 if (callback != null) {
1934 callback.error(R.string.no_conference_server_found, null);
1935 }
1936 return;
1937 }
1938 String name = new BigInteger(75, getRNG()).toString(32);
1939 Jid jid = Jid.fromParts(name, server, null);
1940 final Conversation conversation = findOrCreateConversation(account, jid, true);
1941 joinMuc(conversation, true, new OnConferenceJoined() {
1942 @Override
1943 public void onConferenceJoined(final Conversation conversation) {
1944 Bundle options = new Bundle();
1945 options.putString("muc#roomconfig_persistentroom", "1");
1946 options.putString("muc#roomconfig_membersonly", "1");
1947 options.putString("muc#roomconfig_publicroom", "0");
1948 options.putString("muc#roomconfig_whois", "anyone");
1949 pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1950 @Override
1951 public void onPushSucceeded() {
1952 for (Jid invite : jids) {
1953 invite(conversation, invite);
1954 }
1955 if (account.countPresences() > 1) {
1956 directInvite(conversation, account.getJid().toBareJid());
1957 }
1958 if (callback != null) {
1959 callback.success(conversation);
1960 }
1961 }
1962
1963 @Override
1964 public void onPushFailed() {
1965 if (callback != null) {
1966 callback.error(R.string.conference_creation_failed, conversation);
1967 }
1968 }
1969 });
1970 }
1971 });
1972 } catch (InvalidJidException e) {
1973 if (callback != null) {
1974 callback.error(R.string.conference_creation_failed, null);
1975 }
1976 }
1977 } else {
1978 if (callback != null) {
1979 callback.error(R.string.not_connected_try_again, null);
1980 }
1981 }
1982 }
1983
1984 public void fetchConferenceConfiguration(final Conversation conversation) {
1985 fetchConferenceConfiguration(conversation, null);
1986 }
1987
1988 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
1989 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1990 request.setTo(conversation.getJid().toBareJid());
1991 request.query("http://jabber.org/protocol/disco#info");
1992 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1993 @Override
1994 public void onIqPacketReceived(Account account, IqPacket packet) {
1995 if (packet.getType() == IqPacket.TYPE.RESULT) {
1996 ArrayList<String> features = new ArrayList<>();
1997 Element query = packet.query();
1998 for (Element child : query.getChildren()) {
1999 if (child != null && child.getName().equals("feature")) {
2000 String var = child.getAttribute("var");
2001 if (var != null) {
2002 features.add(var);
2003 }
2004 }
2005 }
2006 Element form = query.findChild("x", "jabber:x:data");
2007 if (form != null) {
2008 conversation.getMucOptions().updateFormData(Data.parse(form));
2009 }
2010 conversation.getMucOptions().updateFeatures(features);
2011 if (callback != null) {
2012 callback.onConferenceConfigurationFetched(conversation);
2013 }
2014 updateConversationUi();
2015 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2016 if (callback != null) {
2017 callback.onFetchFailed(conversation, packet.getError());
2018 }
2019 }
2020 }
2021 });
2022 }
2023
2024 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2025 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2026 request.setTo(conversation.getJid().toBareJid());
2027 request.query("http://jabber.org/protocol/muc#owner");
2028 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2029 @Override
2030 public void onIqPacketReceived(Account account, IqPacket packet) {
2031 if (packet.getType() == IqPacket.TYPE.RESULT) {
2032 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2033 for (Field field : data.getFields()) {
2034 if (options.containsKey(field.getFieldName())) {
2035 field.setValue(options.getString(field.getFieldName()));
2036 }
2037 }
2038 data.submit();
2039 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2040 set.setTo(conversation.getJid().toBareJid());
2041 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2042 sendIqPacket(account, set, new OnIqPacketReceived() {
2043 @Override
2044 public void onIqPacketReceived(Account account, IqPacket packet) {
2045 if (callback != null) {
2046 if (packet.getType() == IqPacket.TYPE.RESULT) {
2047 callback.onPushSucceeded();
2048 } else {
2049 callback.onPushFailed();
2050 }
2051 }
2052 }
2053 });
2054 } else {
2055 if (callback != null) {
2056 callback.onPushFailed();
2057 }
2058 }
2059 }
2060 });
2061 }
2062
2063 public void pushSubjectToConference(final Conversation conference, final String subject) {
2064 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2065 this.sendMessagePacket(conference.getAccount(), packet);
2066 final MucOptions mucOptions = conference.getMucOptions();
2067 final MucOptions.User self = mucOptions.getSelf();
2068 if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2069 Bundle options = new Bundle();
2070 options.putString("muc#roomconfig_persistentroom", "1");
2071 this.pushConferenceConfiguration(conference, options, null);
2072 }
2073 }
2074
2075 public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2076 final Jid jid = user.toBareJid();
2077 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2078 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2079 @Override
2080 public void onIqPacketReceived(Account account, IqPacket packet) {
2081 if (packet.getType() == IqPacket.TYPE.RESULT) {
2082 callback.onAffiliationChangedSuccessful(jid);
2083 } else {
2084 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2085 }
2086 }
2087 });
2088 }
2089
2090 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2091 List<Jid> jids = new ArrayList<>();
2092 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2093 if (user.getAffiliation() == before && user.getJid() != null) {
2094 jids.add(user.getJid());
2095 }
2096 }
2097 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2098 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2099 }
2100
2101 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2102 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2103 Log.d(Config.LOGTAG, request.toString());
2104 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2105 @Override
2106 public void onIqPacketReceived(Account account, IqPacket packet) {
2107 Log.d(Config.LOGTAG, packet.toString());
2108 if (packet.getType() == IqPacket.TYPE.RESULT) {
2109 callback.onRoleChangedSuccessful(nick);
2110 } else {
2111 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2112 }
2113 }
2114 });
2115 }
2116
2117 private void disconnect(Account account, boolean force) {
2118 if ((account.getStatus() == Account.State.ONLINE)
2119 || (account.getStatus() == Account.State.DISABLED)) {
2120 if (!force) {
2121 List<Conversation> conversations = getConversations();
2122 for (Conversation conversation : conversations) {
2123 if (conversation.getAccount() == account) {
2124 if (conversation.getMode() == Conversation.MODE_MULTI) {
2125 leaveMuc(conversation, true);
2126 } else {
2127 if (conversation.endOtrIfNeeded()) {
2128 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2129 + ": ended otr session with "
2130 + conversation.getJid());
2131 }
2132 }
2133 }
2134 }
2135 sendOfflinePresence(account);
2136 }
2137 account.getXmppConnection().disconnect(force);
2138 }
2139 }
2140
2141 @Override
2142 public IBinder onBind(Intent intent) {
2143 return mBinder;
2144 }
2145
2146 public void updateMessage(Message message) {
2147 databaseBackend.updateMessage(message);
2148 updateConversationUi();
2149 }
2150
2151 protected void syncDirtyContacts(Account account) {
2152 for (Contact contact : account.getRoster().getContacts()) {
2153 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2154 pushContactToServer(contact);
2155 }
2156 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2157 deleteContactOnServer(contact);
2158 }
2159 }
2160 }
2161
2162 public void createContact(Contact contact) {
2163 boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2164 if (autoGrant) {
2165 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2166 contact.setOption(Contact.Options.ASKING);
2167 }
2168 pushContactToServer(contact);
2169 }
2170
2171 public void onOtrSessionEstablished(Conversation conversation) {
2172 final Account account = conversation.getAccount();
2173 final Session otrSession = conversation.getOtrSession();
2174 Log.d(Config.LOGTAG,
2175 account.getJid().toBareJid() + " otr session established with "
2176 + conversation.getJid() + "/"
2177 + otrSession.getSessionID().getUserID());
2178 conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2179
2180 @Override
2181 public void onMessageFound(Message message) {
2182 SessionID id = otrSession.getSessionID();
2183 try {
2184 message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2185 } catch (InvalidJidException e) {
2186 return;
2187 }
2188 if (message.needsUploading()) {
2189 mJingleConnectionManager.createNewConnection(message);
2190 } else {
2191 MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2192 if (outPacket != null) {
2193 mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2194 message.setStatus(Message.STATUS_SEND);
2195 databaseBackend.updateMessage(message);
2196 sendMessagePacket(account, outPacket);
2197 }
2198 }
2199 updateConversationUi();
2200 }
2201 });
2202 }
2203
2204 public boolean renewSymmetricKey(Conversation conversation) {
2205 Account account = conversation.getAccount();
2206 byte[] symmetricKey = new byte[32];
2207 this.mRandom.nextBytes(symmetricKey);
2208 Session otrSession = conversation.getOtrSession();
2209 if (otrSession != null) {
2210 MessagePacket packet = new MessagePacket();
2211 packet.setType(MessagePacket.TYPE_CHAT);
2212 packet.setFrom(account.getJid());
2213 MessageGenerator.addMessageHints(packet);
2214 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2215 + otrSession.getSessionID().getUserID());
2216 try {
2217 packet.setBody(otrSession
2218 .transformSending(CryptoHelper.FILETRANSFER
2219 + CryptoHelper.bytesToHex(symmetricKey))[0]);
2220 sendMessagePacket(account, packet);
2221 conversation.setSymmetricKey(symmetricKey);
2222 return true;
2223 } catch (OtrException e) {
2224 return false;
2225 }
2226 }
2227 return false;
2228 }
2229
2230 public void pushContactToServer(final Contact contact) {
2231 contact.resetOption(Contact.Options.DIRTY_DELETE);
2232 contact.setOption(Contact.Options.DIRTY_PUSH);
2233 final Account account = contact.getAccount();
2234 if (account.getStatus() == Account.State.ONLINE) {
2235 final boolean ask = contact.getOption(Contact.Options.ASKING);
2236 final boolean sendUpdates = contact
2237 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2238 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2239 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2240 iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2241 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2242 if (sendUpdates) {
2243 sendPresencePacket(account,
2244 mPresenceGenerator.sendPresenceUpdatesTo(contact));
2245 }
2246 if (ask) {
2247 sendPresencePacket(account,
2248 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2249 }
2250 }
2251 }
2252
2253 public void publishAvatar(final Account account,
2254 final Uri image,
2255 final UiCallback<Avatar> callback) {
2256 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2257 final int size = Config.AVATAR_SIZE;
2258 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2259 if (avatar != null) {
2260 avatar.height = size;
2261 avatar.width = size;
2262 if (format.equals(Bitmap.CompressFormat.WEBP)) {
2263 avatar.type = "image/webp";
2264 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2265 avatar.type = "image/jpeg";
2266 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
2267 avatar.type = "image/png";
2268 }
2269 if (!getFileBackend().save(avatar)) {
2270 callback.error(R.string.error_saving_avatar, avatar);
2271 return;
2272 }
2273 final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2274 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2275
2276 @Override
2277 public void onIqPacketReceived(Account account, IqPacket result) {
2278 if (result.getType() == IqPacket.TYPE.RESULT) {
2279 final IqPacket packet = XmppConnectionService.this.mIqGenerator
2280 .publishAvatarMetadata(avatar);
2281 sendIqPacket(account, packet, new OnIqPacketReceived() {
2282 @Override
2283 public void onIqPacketReceived(Account account, IqPacket result) {
2284 if (result.getType() == IqPacket.TYPE.RESULT) {
2285 if (account.setAvatar(avatar.getFilename())) {
2286 getAvatarService().clear(account);
2287 databaseBackend.updateAccount(account);
2288 }
2289 callback.success(avatar);
2290 } else {
2291 callback.error(
2292 R.string.error_publish_avatar_server_reject,
2293 avatar);
2294 }
2295 }
2296 });
2297 } else {
2298 callback.error(
2299 R.string.error_publish_avatar_server_reject,
2300 avatar);
2301 }
2302 }
2303 });
2304 } else {
2305 callback.error(R.string.error_publish_avatar_converting, null);
2306 }
2307 }
2308
2309 public void fetchAvatar(Account account, Avatar avatar) {
2310 fetchAvatar(account, avatar, null);
2311 }
2312
2313 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2314 final String KEY = generateFetchKey(account, avatar);
2315 synchronized (this.mInProgressAvatarFetches) {
2316 if (this.mInProgressAvatarFetches.contains(KEY)) {
2317 return;
2318 } else {
2319 switch (avatar.origin) {
2320 case PEP:
2321 this.mInProgressAvatarFetches.add(KEY);
2322 fetchAvatarPep(account, avatar, callback);
2323 break;
2324 case VCARD:
2325 this.mInProgressAvatarFetches.add(KEY);
2326 fetchAvatarVcard(account, avatar, callback);
2327 break;
2328 }
2329 }
2330 }
2331 }
2332
2333 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2334 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2335 sendIqPacket(account, packet, new OnIqPacketReceived() {
2336
2337 @Override
2338 public void onIqPacketReceived(Account account, IqPacket result) {
2339 synchronized (mInProgressAvatarFetches) {
2340 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2341 }
2342 final String ERROR = account.getJid().toBareJid()
2343 + ": fetching avatar for " + avatar.owner + " failed ";
2344 if (result.getType() == IqPacket.TYPE.RESULT) {
2345 avatar.image = mIqParser.avatarData(result);
2346 if (avatar.image != null) {
2347 if (getFileBackend().save(avatar)) {
2348 if (account.getJid().toBareJid().equals(avatar.owner)) {
2349 if (account.setAvatar(avatar.getFilename())) {
2350 databaseBackend.updateAccount(account);
2351 }
2352 getAvatarService().clear(account);
2353 updateConversationUi();
2354 updateAccountUi();
2355 } else {
2356 Contact contact = account.getRoster()
2357 .getContact(avatar.owner);
2358 contact.setAvatar(avatar);
2359 getAvatarService().clear(contact);
2360 updateConversationUi();
2361 updateRosterUi();
2362 }
2363 if (callback != null) {
2364 callback.success(avatar);
2365 }
2366 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2367 + ": succesfuly fetched pep avatar for " + avatar.owner);
2368 return;
2369 }
2370 } else {
2371
2372 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2373 }
2374 } else {
2375 Element error = result.findChild("error");
2376 if (error == null) {
2377 Log.d(Config.LOGTAG, ERROR + "(server error)");
2378 } else {
2379 Log.d(Config.LOGTAG, ERROR + error.toString());
2380 }
2381 }
2382 if (callback != null) {
2383 callback.error(0, null);
2384 }
2385
2386 }
2387 });
2388 }
2389
2390 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2391 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2392 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2393 @Override
2394 public void onIqPacketReceived(Account account, IqPacket packet) {
2395 synchronized (mInProgressAvatarFetches) {
2396 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2397 }
2398 if (packet.getType() == IqPacket.TYPE.RESULT) {
2399 Element vCard = packet.findChild("vCard", "vcard-temp");
2400 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2401 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2402 if (image != null) {
2403 avatar.image = image;
2404 if (getFileBackend().save(avatar)) {
2405 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2406 + ": successfully fetched vCard avatar for " + avatar.owner);
2407 if (avatar.owner.isBareJid()) {
2408 Contact contact = account.getRoster()
2409 .getContact(avatar.owner);
2410 contact.setAvatar(avatar);
2411 getAvatarService().clear(contact);
2412 updateConversationUi();
2413 updateRosterUi();
2414 } else {
2415 Conversation conversation = find(account, avatar.owner.toBareJid());
2416 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2417 MucOptions.User user = conversation.getMucOptions().findUser(avatar.owner.getResourcepart());
2418 if (user != null) {
2419 if (user.setAvatar(avatar)) {
2420 getAvatarService().clear(user);
2421 updateConversationUi();
2422 updateMucRosterUi();
2423 }
2424 }
2425 }
2426 }
2427 }
2428 }
2429 }
2430 }
2431 });
2432 }
2433
2434 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2435 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2436 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2437
2438 @Override
2439 public void onIqPacketReceived(Account account, IqPacket packet) {
2440 if (packet.getType() == IqPacket.TYPE.RESULT) {
2441 Element pubsub = packet.findChild("pubsub",
2442 "http://jabber.org/protocol/pubsub");
2443 if (pubsub != null) {
2444 Element items = pubsub.findChild("items");
2445 if (items != null) {
2446 Avatar avatar = Avatar.parseMetadata(items);
2447 if (avatar != null) {
2448 avatar.owner = account.getJid().toBareJid();
2449 if (fileBackend.isAvatarCached(avatar)) {
2450 if (account.setAvatar(avatar.getFilename())) {
2451 databaseBackend.updateAccount(account);
2452 }
2453 getAvatarService().clear(account);
2454 callback.success(avatar);
2455 } else {
2456 fetchAvatarPep(account, avatar, callback);
2457 }
2458 return;
2459 }
2460 }
2461 }
2462 }
2463 callback.error(0, null);
2464 }
2465 });
2466 }
2467
2468 public void deleteContactOnServer(Contact contact) {
2469 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2470 contact.resetOption(Contact.Options.DIRTY_PUSH);
2471 contact.setOption(Contact.Options.DIRTY_DELETE);
2472 Account account = contact.getAccount();
2473 if (account.getStatus() == Account.State.ONLINE) {
2474 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2475 Element item = iq.query(Xmlns.ROSTER).addChild("item");
2476 item.setAttribute("jid", contact.getJid().toString());
2477 item.setAttribute("subscription", "remove");
2478 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2479 }
2480 }
2481
2482 public void updateConversation(Conversation conversation) {
2483 this.databaseBackend.updateConversation(conversation);
2484 }
2485
2486 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2487 synchronized (account) {
2488 XmppConnection connection = account.getXmppConnection();
2489 if (connection != null) {
2490 disconnect(account, force);
2491 } else {
2492 connection = createConnection(account);
2493 account.setXmppConnection(connection);
2494 }
2495 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2496 synchronized (this.mInProgressAvatarFetches) {
2497 for (Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
2498 final String KEY = iterator.next();
2499 if (KEY.startsWith(account.getJid().toBareJid() + "_")) {
2500 iterator.remove();
2501 }
2502 }
2503 }
2504 if (!force) {
2505 try {
2506 Log.d(Config.LOGTAG, "wait for disconnect");
2507 Thread.sleep(500); //sleep wait for disconnect
2508 } catch (InterruptedException e) {
2509 //ignored
2510 }
2511 }
2512 Thread thread = new Thread(connection);
2513 connection.setInteractive(interactive);
2514 thread.start();
2515 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2516 } else {
2517 account.getRoster().clearPresences();
2518 connection.resetEverything();
2519 }
2520 }
2521 }
2522
2523 public void reconnectAccountInBackground(final Account account) {
2524 new Thread(new Runnable() {
2525 @Override
2526 public void run() {
2527 reconnectAccount(account, false, true);
2528 }
2529 }).start();
2530 }
2531
2532 public void invite(Conversation conversation, Jid contact) {
2533 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2534 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2535 sendMessagePacket(conversation.getAccount(), packet);
2536 }
2537
2538 public void directInvite(Conversation conversation, Jid jid) {
2539 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2540 sendMessagePacket(conversation.getAccount(), packet);
2541 }
2542
2543 public void resetSendingToWaiting(Account account) {
2544 for (Conversation conversation : getConversations()) {
2545 if (conversation.getAccount() == account) {
2546 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2547
2548 @Override
2549 public void onMessageFound(Message message) {
2550 markMessage(message, Message.STATUS_WAITING);
2551 }
2552 });
2553 }
2554 }
2555 }
2556
2557 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2558 if (uuid == null) {
2559 return null;
2560 }
2561 for (Conversation conversation : getConversations()) {
2562 if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2563 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2564 if (message != null) {
2565 markMessage(message, status);
2566 }
2567 return message;
2568 }
2569 }
2570 return null;
2571 }
2572
2573 public boolean markMessage(Conversation conversation, String uuid, int status) {
2574 if (uuid == null) {
2575 return false;
2576 } else {
2577 Message message = conversation.findSentMessageWithUuid(uuid);
2578 if (message != null) {
2579 markMessage(message, status);
2580 return true;
2581 } else {
2582 return false;
2583 }
2584 }
2585 }
2586
2587 public void markMessage(Message message, int status) {
2588 if (status == Message.STATUS_SEND_FAILED
2589 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2590 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2591 return;
2592 }
2593 message.setStatus(status);
2594 databaseBackend.updateMessage(message);
2595 updateConversationUi();
2596 }
2597
2598 public SharedPreferences getPreferences() {
2599 return PreferenceManager
2600 .getDefaultSharedPreferences(getApplicationContext());
2601 }
2602
2603 public boolean confirmMessages() {
2604 return getPreferences().getBoolean("confirm_messages", true);
2605 }
2606
2607 public boolean sendChatStates() {
2608 return getPreferences().getBoolean("chat_states", false);
2609 }
2610
2611 public boolean saveEncryptedMessages() {
2612 return !getPreferences().getBoolean("dont_save_encrypted", false);
2613 }
2614
2615 private boolean respectAutojoin() {
2616 return getPreferences().getBoolean("autojoin", true);
2617 }
2618
2619 public boolean indicateReceived() {
2620 return getPreferences().getBoolean("indicate_received", false);
2621 }
2622
2623 public boolean useTorToConnect() {
2624 return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
2625 }
2626
2627 public boolean showExtendedConnectionOptions() {
2628 return getPreferences().getBoolean("show_connection_options", false);
2629 }
2630
2631 public int unreadCount() {
2632 int count = 0;
2633 for (Conversation conversation : getConversations()) {
2634 count += conversation.unreadCount();
2635 }
2636 return count;
2637 }
2638
2639
2640 public void showErrorToastInUi(int resId) {
2641 if (mOnShowErrorToast != null) {
2642 mOnShowErrorToast.onShowErrorToast(resId);
2643 }
2644 }
2645
2646 public void updateConversationUi() {
2647 if (mOnConversationUpdate != null) {
2648 mOnConversationUpdate.onConversationUpdate();
2649 }
2650 }
2651
2652 public void updateAccountUi() {
2653 if (mOnAccountUpdate != null) {
2654 mOnAccountUpdate.onAccountUpdate();
2655 }
2656 }
2657
2658 public void updateRosterUi() {
2659 if (mOnRosterUpdate != null) {
2660 mOnRosterUpdate.onRosterUpdate();
2661 }
2662 }
2663
2664 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2665 boolean rc = false;
2666 if (mOnCaptchaRequested != null) {
2667 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2668 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2669 (int) (captcha.getHeight() * metrics.scaledDensity), false);
2670
2671 mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2672 rc = true;
2673 }
2674
2675 return rc;
2676 }
2677
2678 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2679 if (mOnUpdateBlocklist != null) {
2680 mOnUpdateBlocklist.OnUpdateBlocklist(status);
2681 }
2682 }
2683
2684 public void updateMucRosterUi() {
2685 if (mOnMucRosterUpdate != null) {
2686 mOnMucRosterUpdate.onMucRosterUpdate();
2687 }
2688 }
2689
2690 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
2691 if (mOnKeyStatusUpdated != null) {
2692 mOnKeyStatusUpdated.onKeyStatusUpdated(report);
2693 }
2694 }
2695
2696 public Account findAccountByJid(final Jid accountJid) {
2697 for (Account account : this.accounts) {
2698 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2699 return account;
2700 }
2701 }
2702 return null;
2703 }
2704
2705 public Conversation findConversationByUuid(String uuid) {
2706 for (Conversation conversation : getConversations()) {
2707 if (conversation.getUuid().equals(uuid)) {
2708 return conversation;
2709 }
2710 }
2711 return null;
2712 }
2713
2714 public void markRead(final Conversation conversation) {
2715 mNotificationService.clear(conversation);
2716 final List<Message> readMessages = conversation.markRead();
2717 if (readMessages.size() > 0) {
2718 Runnable runnable = new Runnable() {
2719 @Override
2720 public void run() {
2721 for (Message message : readMessages) {
2722 databaseBackend.updateMessage(message);
2723 }
2724 }
2725 };
2726 mDatabaseExecutor.execute(runnable);
2727 }
2728 updateUnreadCountBadge();
2729 }
2730
2731 public synchronized void updateUnreadCountBadge() {
2732 int count = unreadCount();
2733 if (unreadCount != count) {
2734 Log.d(Config.LOGTAG, "update unread count to " + count);
2735 if (count > 0) {
2736 ShortcutBadger.with(getApplicationContext()).count(count);
2737 } else {
2738 ShortcutBadger.with(getApplicationContext()).remove();
2739 }
2740 unreadCount = count;
2741 }
2742 }
2743
2744 public void sendReadMarker(final Conversation conversation) {
2745 final Message markable = conversation.getLatestMarkableMessage();
2746 this.markRead(conversation);
2747 if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2748 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2749 Account account = conversation.getAccount();
2750 final Jid to = markable.getCounterpart();
2751 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2752 this.sendMessagePacket(conversation.getAccount(), packet);
2753 }
2754 updateConversationUi();
2755 }
2756
2757 public SecureRandom getRNG() {
2758 return this.mRandom;
2759 }
2760
2761 public MemorizingTrustManager getMemorizingTrustManager() {
2762 return this.mMemorizingTrustManager;
2763 }
2764
2765 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2766 this.mMemorizingTrustManager = trustManager;
2767 }
2768
2769 public void updateMemorizingTrustmanager() {
2770 final MemorizingTrustManager tm;
2771 final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2772 if (dontTrustSystemCAs) {
2773 tm = new MemorizingTrustManager(getApplicationContext(), null);
2774 } else {
2775 tm = new MemorizingTrustManager(getApplicationContext());
2776 }
2777 setMemorizingTrustManager(tm);
2778 }
2779
2780 public PowerManager getPowerManager() {
2781 return this.pm;
2782 }
2783
2784 public LruCache<String, Bitmap> getBitmapCache() {
2785 return this.mBitmapCache;
2786 }
2787
2788 public void syncRosterToDisk(final Account account) {
2789 Runnable runnable = new Runnable() {
2790
2791 @Override
2792 public void run() {
2793 databaseBackend.writeRoster(account.getRoster());
2794 }
2795 };
2796 mDatabaseExecutor.execute(runnable);
2797
2798 }
2799
2800 public List<String> getKnownHosts() {
2801 final List<String> hosts = new ArrayList<>();
2802 for (final Account account : getAccounts()) {
2803 if (!hosts.contains(account.getServer().toString())) {
2804 hosts.add(account.getServer().toString());
2805 }
2806 for (final Contact contact : account.getRoster().getContacts()) {
2807 if (contact.showInRoster()) {
2808 final String server = contact.getServer().toString();
2809 if (server != null && !hosts.contains(server)) {
2810 hosts.add(server);
2811 }
2812 }
2813 }
2814 }
2815 return hosts;
2816 }
2817
2818 public List<String> getKnownConferenceHosts() {
2819 final ArrayList<String> mucServers = new ArrayList<>();
2820 for (final Account account : accounts) {
2821 if (account.getXmppConnection() != null) {
2822 final String server = account.getXmppConnection().getMucServer();
2823 if (server != null && !mucServers.contains(server)) {
2824 mucServers.add(server);
2825 }
2826 }
2827 }
2828 return mucServers;
2829 }
2830
2831 public void sendMessagePacket(Account account, MessagePacket packet) {
2832 XmppConnection connection = account.getXmppConnection();
2833 if (connection != null) {
2834 connection.sendMessagePacket(packet);
2835 }
2836 }
2837
2838 public void sendPresencePacket(Account account, PresencePacket packet) {
2839 XmppConnection connection = account.getXmppConnection();
2840 if (connection != null) {
2841 connection.sendPresencePacket(packet);
2842 }
2843 }
2844
2845 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
2846 XmppConnection connection = account.getXmppConnection();
2847 if (connection != null) {
2848 connection.sendCaptchaRegistryRequest(id, data);
2849 }
2850 }
2851
2852 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2853 final XmppConnection connection = account.getXmppConnection();
2854 if (connection != null) {
2855 connection.sendIqPacket(packet, callback);
2856 }
2857 }
2858
2859 public void sendPresence(final Account account) {
2860 sendPresencePacket(account, mPresenceGenerator.selfPresence(account, getTargetPresence()));
2861 }
2862
2863 public void refreshAllPresences() {
2864 for (Account account : getAccounts()) {
2865 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2866 sendPresence(account);
2867 }
2868 }
2869 }
2870
2871 private void refreshAllGcmTokens() {
2872 for(Account account : getAccounts()) {
2873 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
2874 mPushManagementService.registerPushTokenOnServer(account);
2875 }
2876 }
2877 }
2878
2879 public void sendOfflinePresence(final Account account) {
2880 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2881 }
2882
2883 public MessageGenerator getMessageGenerator() {
2884 return this.mMessageGenerator;
2885 }
2886
2887 public PresenceGenerator getPresenceGenerator() {
2888 return this.mPresenceGenerator;
2889 }
2890
2891 public IqGenerator getIqGenerator() {
2892 return this.mIqGenerator;
2893 }
2894
2895 public IqParser getIqParser() {
2896 return this.mIqParser;
2897 }
2898
2899 public JingleConnectionManager getJingleConnectionManager() {
2900 return this.mJingleConnectionManager;
2901 }
2902
2903 public MessageArchiveService getMessageArchiveService() {
2904 return this.mMessageArchiveService;
2905 }
2906
2907 public List<Contact> findContacts(Jid jid) {
2908 ArrayList<Contact> contacts = new ArrayList<>();
2909 for (Account account : getAccounts()) {
2910 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2911 Contact contact = account.getRoster().getContactFromRoster(jid);
2912 if (contact != null) {
2913 contacts.add(contact);
2914 }
2915 }
2916 }
2917 return contacts;
2918 }
2919
2920 public NotificationService getNotificationService() {
2921 return this.mNotificationService;
2922 }
2923
2924 public HttpConnectionManager getHttpConnectionManager() {
2925 return this.mHttpConnectionManager;
2926 }
2927
2928 public void resendFailedMessages(final Message message) {
2929 final Collection<Message> messages = new ArrayList<>();
2930 Message current = message;
2931 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2932 messages.add(current);
2933 if (current.mergeable(current.next())) {
2934 current = current.next();
2935 } else {
2936 break;
2937 }
2938 }
2939 for (final Message msg : messages) {
2940 msg.setTime(System.currentTimeMillis());
2941 markMessage(msg, Message.STATUS_WAITING);
2942 this.resendMessage(msg, false);
2943 }
2944 }
2945
2946 public void clearConversationHistory(final Conversation conversation) {
2947 conversation.clearMessages();
2948 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2949 conversation.setLastClearHistory(System.currentTimeMillis());
2950 Runnable runnable = new Runnable() {
2951 @Override
2952 public void run() {
2953 databaseBackend.deleteMessagesInConversation(conversation);
2954 }
2955 };
2956 mDatabaseExecutor.execute(runnable);
2957 }
2958
2959 public void sendBlockRequest(final Blockable blockable) {
2960 if (blockable != null && blockable.getBlockedJid() != null) {
2961 final Jid jid = blockable.getBlockedJid();
2962 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2963
2964 @Override
2965 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2966 if (packet.getType() == IqPacket.TYPE.RESULT) {
2967 account.getBlocklist().add(jid);
2968 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2969 }
2970 }
2971 });
2972 }
2973 }
2974
2975 public void sendUnblockRequest(final Blockable blockable) {
2976 if (blockable != null && blockable.getJid() != null) {
2977 final Jid jid = blockable.getBlockedJid();
2978 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2979 @Override
2980 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2981 if (packet.getType() == IqPacket.TYPE.RESULT) {
2982 account.getBlocklist().remove(jid);
2983 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2984 }
2985 }
2986 });
2987 }
2988 }
2989
2990 public void publishDisplayName(Account account) {
2991 String displayName = account.getDisplayName();
2992 if (displayName != null && !displayName.isEmpty()) {
2993 IqPacket publish = mIqGenerator.publishNick(displayName);
2994 sendIqPacket(account, publish, new OnIqPacketReceived() {
2995 @Override
2996 public void onIqPacketReceived(Account account, IqPacket packet) {
2997 if (packet.getType() == IqPacket.TYPE.ERROR) {
2998 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
2999 }
3000 }
3001 });
3002 }
3003 }
3004
3005 private ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String,String> key) {
3006 ServiceDiscoveryResult result = discoCache.get(key);
3007 if (result != null) {
3008 return result;
3009 } else {
3010 result = databaseBackend.findDiscoveryResult(key.first, key.second);
3011 if (result != null) {
3012 discoCache.put(key, result);
3013 }
3014 return result;
3015 }
3016 }
3017
3018 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3019 final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3020 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3021 if (disco != null) {
3022 presence.setServiceDiscoveryResult(disco);
3023 } else {
3024 if (!account.inProgressDiscoFetches.contains(key)) {
3025 account.inProgressDiscoFetches.add(key);
3026 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3027 request.setTo(jid);
3028 request.query("http://jabber.org/protocol/disco#info");
3029 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3030 sendIqPacket(account, request, new OnIqPacketReceived() {
3031 @Override
3032 public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3033 if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3034 ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3035 if (presence.getVer().equals(disco.getVer())) {
3036 databaseBackend.insertDiscoveryResult(disco);
3037 injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3038 } else {
3039 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3040 }
3041 }
3042 account.inProgressDiscoFetches.remove(key);
3043 }
3044 });
3045 }
3046 }
3047 }
3048
3049 private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3050 for(Contact contact : roster.getContacts()) {
3051 for(Presence presence : contact.getPresences().getPresences().values()) {
3052 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3053 presence.setServiceDiscoveryResult(disco);
3054 }
3055 }
3056 }
3057 }
3058
3059 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3060 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3061 request.addChild("prefs","urn:xmpp:mam:0");
3062 sendIqPacket(account, request, new OnIqPacketReceived() {
3063 @Override
3064 public void onIqPacketReceived(Account account, IqPacket packet) {
3065 Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3066 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3067 callback.onPreferencesFetched(prefs);
3068 } else {
3069 callback.onPreferencesFetchFailed();
3070 }
3071 }
3072 });
3073 }
3074
3075 public PushManagementService getPushManagementService() {
3076 return mPushManagementService;
3077 }
3078
3079 public interface OnMamPreferencesFetched {
3080 void onPreferencesFetched(Element prefs);
3081 void onPreferencesFetchFailed();
3082 }
3083
3084 public void pushMamPreferences(Account account, Element prefs) {
3085 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3086 set.addChild(prefs);
3087 sendIqPacket(account, set, null);
3088 }
3089
3090 public interface OnAccountCreated {
3091 void onAccountCreated(Account account);
3092
3093 void informUser(int r);
3094 }
3095
3096 public interface OnMoreMessagesLoaded {
3097 void onMoreMessagesLoaded(int count, Conversation conversation);
3098
3099 void informUser(int r);
3100 }
3101
3102 public interface OnAccountPasswordChanged {
3103 void onPasswordChangeSucceeded();
3104
3105 void onPasswordChangeFailed();
3106 }
3107
3108 public interface OnAffiliationChanged {
3109 void onAffiliationChangedSuccessful(Jid jid);
3110
3111 void onAffiliationChangeFailed(Jid jid, int resId);
3112 }
3113
3114 public interface OnRoleChanged {
3115 void onRoleChangedSuccessful(String nick);
3116
3117 void onRoleChangeFailed(String nick, int resid);
3118 }
3119
3120 public interface OnConversationUpdate {
3121 void onConversationUpdate();
3122 }
3123
3124 public interface OnAccountUpdate {
3125 void onAccountUpdate();
3126 }
3127
3128 public interface OnCaptchaRequested {
3129 void onCaptchaRequested(Account account,
3130 String id,
3131 Data data,
3132 Bitmap captcha);
3133 }
3134
3135 public interface OnRosterUpdate {
3136 void onRosterUpdate();
3137 }
3138
3139 public interface OnMucRosterUpdate {
3140 void onMucRosterUpdate();
3141 }
3142
3143 public interface OnConferenceConfigurationFetched {
3144 void onConferenceConfigurationFetched(Conversation conversation);
3145
3146 void onFetchFailed(Conversation conversation, Element error);
3147 }
3148
3149 public interface OnConferenceJoined {
3150 void onConferenceJoined(Conversation conversation);
3151 }
3152
3153 public interface OnConferenceOptionsPushed {
3154 void onPushSucceeded();
3155
3156 void onPushFailed();
3157 }
3158
3159 public interface OnShowErrorToast {
3160 void onShowErrorToast(int resId);
3161 }
3162
3163 public class XmppConnectionBinder extends Binder {
3164 public XmppConnectionService getService() {
3165 return XmppConnectionService.this;
3166 }
3167 }
3168}