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