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 == null ? null : 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 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully changed node configuration for node "+node);
2487 callback.onPushSucceeded();
2488 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2489 callback.onPushFailed();
2490 }
2491 }
2492 });
2493 } else if (callback != null) {
2494 callback.onPushFailed();
2495 }
2496 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2497 callback.onPushFailed();
2498 }
2499 }
2500 });
2501 }
2502
2503 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2504 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2505 request.setTo(conversation.getJid().asBareJid());
2506 request.query("http://jabber.org/protocol/muc#owner");
2507 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2508 @Override
2509 public void onIqPacketReceived(Account account, IqPacket packet) {
2510 if (packet.getType() == IqPacket.TYPE.RESULT) {
2511 Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
2512 data.submit(options);
2513 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2514 set.setTo(conversation.getJid().asBareJid());
2515 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2516 sendIqPacket(account, set, new OnIqPacketReceived() {
2517 @Override
2518 public void onIqPacketReceived(Account account, IqPacket packet) {
2519 if (callback != null) {
2520 if (packet.getType() == IqPacket.TYPE.RESULT) {
2521 callback.onPushSucceeded();
2522 } else {
2523 callback.onPushFailed();
2524 }
2525 }
2526 }
2527 });
2528 } else {
2529 if (callback != null) {
2530 callback.onPushFailed();
2531 }
2532 }
2533 }
2534 });
2535 }
2536
2537 public void pushSubjectToConference(final Conversation conference, final String subject) {
2538 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2539 this.sendMessagePacket(conference.getAccount(), packet);
2540 final MucOptions mucOptions = conference.getMucOptions();
2541 final MucOptions.User self = mucOptions.getSelf();
2542 if (self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2543 Bundle options = new Bundle();
2544 options.putString("muc#roomconfig_persistentroom", "1");
2545 options.putString("muc#roomconfig_roomname", subject);
2546 this.pushConferenceConfiguration(conference, options, null);
2547 }
2548 }
2549
2550 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2551 final Jid jid = user.asBareJid();
2552 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2553 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2554 @Override
2555 public void onIqPacketReceived(Account account, IqPacket packet) {
2556 if (packet.getType() == IqPacket.TYPE.RESULT) {
2557 conference.getMucOptions().changeAffiliation(jid, affiliation);
2558 getAvatarService().clear(conference);
2559 callback.onAffiliationChangedSuccessful(jid);
2560 } else {
2561 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2562 }
2563 }
2564 });
2565 }
2566
2567 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2568 List<Jid> jids = new ArrayList<>();
2569 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2570 if (user.getAffiliation() == before && user.getRealJid() != null) {
2571 jids.add(user.getRealJid());
2572 }
2573 }
2574 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2575 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2576 }
2577
2578 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2579 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2580 Log.d(Config.LOGTAG, request.toString());
2581 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2582 @Override
2583 public void onIqPacketReceived(Account account, IqPacket packet) {
2584 Log.d(Config.LOGTAG, packet.toString());
2585 if (packet.getType() == IqPacket.TYPE.RESULT) {
2586 callback.onRoleChangedSuccessful(nick);
2587 } else {
2588 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2589 }
2590 }
2591 });
2592 }
2593
2594 private void disconnect(Account account, boolean force) {
2595 if ((account.getStatus() == Account.State.ONLINE)
2596 || (account.getStatus() == Account.State.DISABLED)) {
2597 final XmppConnection connection = account.getXmppConnection();
2598 if (!force) {
2599 List<Conversation> conversations = getConversations();
2600 for (Conversation conversation : conversations) {
2601 if (conversation.getAccount() == account) {
2602 if (conversation.getMode() == Conversation.MODE_MULTI) {
2603 leaveMuc(conversation, true);
2604 }
2605 }
2606 }
2607 sendOfflinePresence(account);
2608 }
2609 connection.disconnect(force);
2610 }
2611 }
2612
2613 @Override
2614 public IBinder onBind(Intent intent) {
2615 return mBinder;
2616 }
2617
2618 public void updateMessage(Message message) {
2619 updateMessage(message, true);
2620 }
2621
2622 public void updateMessage(Message message, boolean includeBody) {
2623 databaseBackend.updateMessage(message, includeBody);
2624 updateConversationUi();
2625 }
2626
2627 public void updateMessage(Message message, String uuid) {
2628 databaseBackend.updateMessage(message, uuid);
2629 updateConversationUi();
2630 }
2631
2632 protected void syncDirtyContacts(Account account) {
2633 for (Contact contact : account.getRoster().getContacts()) {
2634 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2635 pushContactToServer(contact);
2636 }
2637 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2638 deleteContactOnServer(contact);
2639 }
2640 }
2641 }
2642
2643 public void createContact(Contact contact, boolean autoGrant) {
2644 if (autoGrant) {
2645 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2646 contact.setOption(Contact.Options.ASKING);
2647 }
2648 pushContactToServer(contact);
2649 }
2650
2651 public void pushContactToServer(final Contact contact) {
2652 contact.resetOption(Contact.Options.DIRTY_DELETE);
2653 contact.setOption(Contact.Options.DIRTY_PUSH);
2654 final Account account = contact.getAccount();
2655 if (account.getStatus() == Account.State.ONLINE) {
2656 final boolean ask = contact.getOption(Contact.Options.ASKING);
2657 final boolean sendUpdates = contact
2658 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2659 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2660 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2661 iq.query(Namespace.ROSTER).addChild(contact.asElement());
2662 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2663 if (sendUpdates) {
2664 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
2665 }
2666 if (ask) {
2667 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2668 }
2669 } else {
2670 syncRoster(contact.getAccount());
2671 }
2672 }
2673
2674 public void publishAvatar(final Account account, final Uri image, final UiCallback<Avatar> callback) {
2675 new Thread(() -> {
2676 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2677 final int size = Config.AVATAR_SIZE;
2678 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2679 if (avatar != null) {
2680 if (!getFileBackend().save(avatar)) {
2681 callback.error(R.string.error_saving_avatar, avatar);
2682 return;
2683 }
2684 publishAvatar(account, avatar, callback);
2685 } else {
2686 callback.error(R.string.error_publish_avatar_converting, null);
2687 }
2688 }).start();
2689
2690 }
2691
2692 public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2693 IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2694 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2695
2696 @Override
2697 public void onIqPacketReceived(Account account, IqPacket result) {
2698 if (result.getType() == IqPacket.TYPE.RESULT) {
2699 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2700 sendIqPacket(account, packet, new OnIqPacketReceived() {
2701 @Override
2702 public void onIqPacketReceived(Account account, IqPacket result) {
2703 if (result.getType() == IqPacket.TYPE.RESULT) {
2704 if (account.setAvatar(avatar.getFilename())) {
2705 getAvatarService().clear(account);
2706 databaseBackend.updateAccount(account);
2707 }
2708 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
2709 if (callback != null) {
2710 callback.success(avatar);
2711 }
2712 } else {
2713 if (callback != null) {
2714 callback.error(R.string.error_publish_avatar_server_reject, avatar);
2715 }
2716 }
2717 }
2718 });
2719 } else {
2720 Element error = result.findChild("error");
2721 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
2722 if (callback != null) {
2723 callback.error(R.string.error_publish_avatar_server_reject, avatar);
2724 }
2725 }
2726 }
2727 });
2728 }
2729
2730 public void republishAvatarIfNeeded(Account account) {
2731 if (account.getAxolotlService().isPepBroken()) {
2732 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
2733 return;
2734 }
2735 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2736 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2737
2738 private Avatar parseAvatar(IqPacket packet) {
2739 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2740 if (pubsub != null) {
2741 Element items = pubsub.findChild("items");
2742 if (items != null) {
2743 return Avatar.parseMetadata(items);
2744 }
2745 }
2746 return null;
2747 }
2748
2749 private boolean errorIsItemNotFound(IqPacket packet) {
2750 Element error = packet.findChild("error");
2751 return packet.getType() == IqPacket.TYPE.ERROR
2752 && error != null
2753 && error.hasChild("item-not-found");
2754 }
2755
2756 @Override
2757 public void onIqPacketReceived(Account account, IqPacket packet) {
2758 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2759 Avatar serverAvatar = parseAvatar(packet);
2760 if (serverAvatar == null && account.getAvatar() != null) {
2761 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2762 if (avatar != null) {
2763 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
2764 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2765 } else {
2766 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
2767 }
2768 }
2769 }
2770 }
2771 });
2772 }
2773
2774 public void fetchAvatar(Account account, Avatar avatar) {
2775 fetchAvatar(account, avatar, null);
2776 }
2777
2778 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2779 final String KEY = generateFetchKey(account, avatar);
2780 synchronized (this.mInProgressAvatarFetches) {
2781 if (!this.mInProgressAvatarFetches.contains(KEY)) {
2782 switch (avatar.origin) {
2783 case PEP:
2784 this.mInProgressAvatarFetches.add(KEY);
2785 fetchAvatarPep(account, avatar, callback);
2786 break;
2787 case VCARD:
2788 this.mInProgressAvatarFetches.add(KEY);
2789 fetchAvatarVcard(account, avatar, callback);
2790 break;
2791 }
2792 }
2793 }
2794 }
2795
2796 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2797 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2798 sendIqPacket(account, packet, (a, result) -> {
2799 synchronized (mInProgressAvatarFetches) {
2800 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
2801 }
2802 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
2803 if (result.getType() == IqPacket.TYPE.RESULT) {
2804 avatar.image = mIqParser.avatarData(result);
2805 if (avatar.image != null) {
2806 if (getFileBackend().save(avatar)) {
2807 if (a.getJid().asBareJid().equals(avatar.owner)) {
2808 if (a.setAvatar(avatar.getFilename())) {
2809 databaseBackend.updateAccount(a);
2810 }
2811 getAvatarService().clear(a);
2812 updateConversationUi();
2813 updateAccountUi();
2814 } else {
2815 Contact contact = a.getRoster().getContact(avatar.owner);
2816 contact.setAvatar(avatar);
2817 getAvatarService().clear(contact);
2818 updateConversationUi();
2819 updateRosterUi();
2820 }
2821 if (callback != null) {
2822 callback.success(avatar);
2823 }
2824 Log.d(Config.LOGTAG, a.getJid().asBareJid()
2825 + ": successfully fetched pep avatar for " + avatar.owner);
2826 return;
2827 }
2828 } else {
2829
2830 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2831 }
2832 } else {
2833 Element error = result.findChild("error");
2834 if (error == null) {
2835 Log.d(Config.LOGTAG, ERROR + "(server error)");
2836 } else {
2837 Log.d(Config.LOGTAG, ERROR + error.toString());
2838 }
2839 }
2840 if (callback != null) {
2841 callback.error(0, null);
2842 }
2843
2844 });
2845 }
2846
2847 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2848 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2849 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2850 @Override
2851 public void onIqPacketReceived(Account account, IqPacket packet) {
2852 synchronized (mInProgressAvatarFetches) {
2853 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2854 }
2855 if (packet.getType() == IqPacket.TYPE.RESULT) {
2856 Element vCard = packet.findChild("vCard", "vcard-temp");
2857 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2858 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2859 if (image != null) {
2860 avatar.image = image;
2861 if (getFileBackend().save(avatar)) {
2862 Log.d(Config.LOGTAG, account.getJid().asBareJid()
2863 + ": successfully fetched vCard avatar for " + avatar.owner);
2864 if (avatar.owner.isBareJid()) {
2865 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
2866 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
2867 account.setAvatar(avatar.getFilename());
2868 databaseBackend.updateAccount(account);
2869 getAvatarService().clear(account);
2870 updateAccountUi();
2871 } else {
2872 Contact contact = account.getRoster().getContact(avatar.owner);
2873 contact.setAvatar(avatar);
2874 getAvatarService().clear(contact);
2875 updateRosterUi();
2876 }
2877 updateConversationUi();
2878 } else {
2879 Conversation conversation = find(account, avatar.owner.asBareJid());
2880 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2881 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2882 if (user != null) {
2883 if (user.setAvatar(avatar)) {
2884 getAvatarService().clear(user);
2885 updateConversationUi();
2886 updateMucRosterUi();
2887 }
2888 }
2889 }
2890 }
2891 }
2892 }
2893 }
2894 }
2895 });
2896 }
2897
2898 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2899 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2900 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2901
2902 @Override
2903 public void onIqPacketReceived(Account account, IqPacket packet) {
2904 if (packet.getType() == IqPacket.TYPE.RESULT) {
2905 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2906 if (pubsub != null) {
2907 Element items = pubsub.findChild("items");
2908 if (items != null) {
2909 Avatar avatar = Avatar.parseMetadata(items);
2910 if (avatar != null) {
2911 avatar.owner = account.getJid().asBareJid();
2912 if (fileBackend.isAvatarCached(avatar)) {
2913 if (account.setAvatar(avatar.getFilename())) {
2914 databaseBackend.updateAccount(account);
2915 }
2916 getAvatarService().clear(account);
2917 callback.success(avatar);
2918 } else {
2919 fetchAvatarPep(account, avatar, callback);
2920 }
2921 return;
2922 }
2923 }
2924 }
2925 }
2926 callback.error(0, null);
2927 }
2928 });
2929 }
2930
2931 public void deleteContactOnServer(Contact contact) {
2932 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2933 contact.resetOption(Contact.Options.DIRTY_PUSH);
2934 contact.setOption(Contact.Options.DIRTY_DELETE);
2935 Account account = contact.getAccount();
2936 if (account.getStatus() == Account.State.ONLINE) {
2937 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2938 Element item = iq.query(Namespace.ROSTER).addChild("item");
2939 item.setAttribute("jid", contact.getJid().toString());
2940 item.setAttribute("subscription", "remove");
2941 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2942 }
2943 }
2944
2945 public void updateConversation(final Conversation conversation) {
2946 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
2947 }
2948
2949 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2950 synchronized (account) {
2951 XmppConnection connection = account.getXmppConnection();
2952 if (connection == null) {
2953 connection = createConnection(account);
2954 account.setXmppConnection(connection);
2955 }
2956 boolean hasInternet = hasInternetConnection();
2957 if (account.isEnabled() && hasInternet) {
2958 if (!force) {
2959 disconnect(account, false);
2960 }
2961 Thread thread = new Thread(connection);
2962 connection.setInteractive(interactive);
2963 connection.prepareNewConnection();
2964 connection.interrupt();
2965 thread.start();
2966 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2967 } else {
2968 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
2969 account.getRoster().clearPresences();
2970 connection.resetEverything();
2971 final AxolotlService axolotlService = account.getAxolotlService();
2972 if (axolotlService != null) {
2973 axolotlService.resetBrokenness();
2974 }
2975 if (!hasInternet) {
2976 account.setStatus(Account.State.NO_INTERNET);
2977 }
2978 }
2979 }
2980 }
2981
2982 public void reconnectAccountInBackground(final Account account) {
2983 new Thread(() -> reconnectAccount(account, false, true)).start();
2984 }
2985
2986 public void invite(Conversation conversation, Jid contact) {
2987 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
2988 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2989 sendMessagePacket(conversation.getAccount(), packet);
2990 }
2991
2992 public void directInvite(Conversation conversation, Jid jid) {
2993 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2994 sendMessagePacket(conversation.getAccount(), packet);
2995 }
2996
2997 public void resetSendingToWaiting(Account account) {
2998 for (Conversation conversation : getConversations()) {
2999 if (conversation.getAccount() == account) {
3000 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
3001
3002 @Override
3003 public void onMessageFound(Message message) {
3004 markMessage(message, Message.STATUS_WAITING);
3005 }
3006 });
3007 }
3008 }
3009 }
3010
3011 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3012 return markMessage(account, recipient, uuid, status, null);
3013 }
3014
3015 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3016 if (uuid == null) {
3017 return null;
3018 }
3019 for (Conversation conversation : getConversations()) {
3020 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3021 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3022 if (message != null) {
3023 markMessage(message, status, errorMessage);
3024 }
3025 return message;
3026 }
3027 }
3028 return null;
3029 }
3030
3031 public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3032 if (uuid == null) {
3033 return false;
3034 } else {
3035 Message message = conversation.findSentMessageWithUuid(uuid);
3036 if (message != null) {
3037 if (message.getServerMsgId() == null) {
3038 message.setServerMsgId(serverMessageId);
3039 }
3040 markMessage(message, status);
3041 return true;
3042 } else {
3043 return false;
3044 }
3045 }
3046 }
3047
3048 public void markMessage(Message message, int status) {
3049 markMessage(message, status, null);
3050 }
3051
3052
3053 public void markMessage(Message message, int status, String errorMessage) {
3054 final int c = message.getStatus();
3055 if (status == Message.STATUS_SEND_FAILED && (c == Message.STATUS_SEND_RECEIVED || c == Message.STATUS_SEND_DISPLAYED)) {
3056 return;
3057 }
3058 if (status == Message.STATUS_SEND_RECEIVED && c == Message.STATUS_SEND_DISPLAYED) {
3059 return;
3060 }
3061 message.setErrorMessage(errorMessage);
3062 message.setStatus(status);
3063 databaseBackend.updateMessage(message, false);
3064 updateConversationUi();
3065 }
3066
3067 private SharedPreferences getPreferences() {
3068 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3069 }
3070
3071 public long getAutomaticMessageDeletionDate() {
3072 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3073 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3074 }
3075
3076 public long getLongPreference(String name, @IntegerRes int res) {
3077 long defaultValue = getResources().getInteger(res);
3078 try {
3079 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3080 } catch (NumberFormatException e) {
3081 return defaultValue;
3082 }
3083 }
3084
3085 public boolean getBooleanPreference(String name, @BoolRes int res) {
3086 return getPreferences().getBoolean(name, getResources().getBoolean(res));
3087 }
3088
3089 public boolean confirmMessages() {
3090 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3091 }
3092
3093 public boolean allowMessageCorrection() {
3094 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3095 }
3096
3097 public boolean sendChatStates() {
3098 return getBooleanPreference("chat_states", R.bool.chat_states);
3099 }
3100
3101 private boolean respectAutojoin() {
3102 return getBooleanPreference("autojoin", R.bool.autojoin);
3103 }
3104
3105 public boolean indicateReceived() {
3106 return getBooleanPreference("indicate_received", R.bool.indicate_received);
3107 }
3108
3109 public boolean useTorToConnect() {
3110 return Config.FORCE_ORBOT || getBooleanPreference("use_tor", R.bool.use_tor);
3111 }
3112
3113 public boolean showExtendedConnectionOptions() {
3114 return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3115 }
3116
3117 public boolean broadcastLastActivity() {
3118 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3119 }
3120
3121 public int unreadCount() {
3122 int count = 0;
3123 for (Conversation conversation : getConversations()) {
3124 count += conversation.unreadCount();
3125 }
3126 return count;
3127 }
3128
3129
3130 public void showErrorToastInUi(int resId) {
3131 for(OnShowErrorToast listener : this.mOnShowErrorToasts) {
3132 listener.onShowErrorToast(resId);
3133 }
3134 }
3135
3136 public void updateConversationUi() {
3137 for(OnConversationUpdate listener : this.mOnConversationUpdates) {
3138 listener.onConversationUpdate();
3139 }
3140 }
3141
3142 public void updateAccountUi() {
3143 for(OnAccountUpdate listener : this.mOnAccountUpdates) {
3144 listener.onAccountUpdate();
3145 }
3146 }
3147
3148 public void updateRosterUi() {
3149 for(OnRosterUpdate listener : this.mOnRosterUpdates) {
3150 listener.onRosterUpdate();
3151 }
3152 }
3153
3154 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3155 if (mOnCaptchaRequested.size() > 0) {
3156 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3157 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3158 (int) (captcha.getHeight() * metrics.scaledDensity), false);
3159 for(OnCaptchaRequested listener : this.mOnCaptchaRequested) {
3160 listener.onCaptchaRequested(account, id, data, scaled);
3161 }
3162 return true;
3163 }
3164 return false;
3165 }
3166
3167 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3168 for(OnUpdateBlocklist listener : this.mOnUpdateBlocklist) {
3169 listener.OnUpdateBlocklist(status);
3170 }
3171 }
3172
3173 public void updateMucRosterUi() {
3174 for(OnMucRosterUpdate listener : this.mOnMucRosterUpdate) {
3175 listener.onMucRosterUpdate();
3176 }
3177 }
3178
3179 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3180 for(OnKeyStatusUpdated listener : this.mOnKeyStatusUpdated) {
3181 listener.onKeyStatusUpdated(report);
3182 }
3183 }
3184
3185 public Account findAccountByJid(final Jid accountJid) {
3186 for (Account account : this.accounts) {
3187 if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3188 return account;
3189 }
3190 }
3191 return null;
3192 }
3193
3194 public Account findAccountByUuid(final String uuid) {
3195 for(Account account : this.accounts) {
3196 if (account.getUuid().equals(uuid)) {
3197 return account;
3198 }
3199 }
3200 return null;
3201 }
3202
3203 public Conversation findConversationByUuid(String uuid) {
3204 for (Conversation conversation : getConversations()) {
3205 if (conversation.getUuid().equals(uuid)) {
3206 return conversation;
3207 }
3208 }
3209 return null;
3210 }
3211
3212 public boolean markRead(final Conversation conversation, boolean dismiss) {
3213 return markRead(conversation, null, dismiss).size() > 0;
3214 }
3215
3216 public void markRead(final Conversation conversation) {
3217 markRead(conversation, null, true);
3218 }
3219
3220 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
3221 if (dismiss) {
3222 mNotificationService.clear(conversation);
3223 }
3224 final List<Message> readMessages = conversation.markRead(upToUuid);
3225 if (readMessages.size() > 0) {
3226 Runnable runnable = () -> {
3227 for (Message message : readMessages) {
3228 databaseBackend.updateMessage(message, false);
3229 }
3230 };
3231 mDatabaseWriterExecutor.execute(runnable);
3232 updateUnreadCountBadge();
3233 return readMessages;
3234 } else {
3235 return readMessages;
3236 }
3237 }
3238
3239 public synchronized void updateUnreadCountBadge() {
3240 int count = unreadCount();
3241 if (unreadCount != count) {
3242 Log.d(Config.LOGTAG, "update unread count to " + count);
3243 if (count > 0) {
3244 ShortcutBadger.applyCount(getApplicationContext(), count);
3245 } else {
3246 ShortcutBadger.removeCount(getApplicationContext());
3247 }
3248 unreadCount = count;
3249 }
3250 }
3251
3252 public void sendReadMarker(final Conversation conversation, String upToUuid) {
3253 final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
3254 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
3255 if (readMessages.size() > 0) {
3256 updateConversationUi();
3257 }
3258 final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
3259 if (confirmMessages()
3260 && markable != null
3261 && (markable.trusted() || isPrivateAndNonAnonymousMuc)
3262 && markable.getRemoteMsgId() != null) {
3263 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3264 Account account = conversation.getAccount();
3265 final Jid to = markable.getCounterpart();
3266 final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3267 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3268 this.sendMessagePacket(conversation.getAccount(), packet);
3269 }
3270 }
3271
3272 public SecureRandom getRNG() {
3273 return this.mRandom;
3274 }
3275
3276 public MemorizingTrustManager getMemorizingTrustManager() {
3277 return this.mMemorizingTrustManager;
3278 }
3279
3280 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3281 this.mMemorizingTrustManager = trustManager;
3282 }
3283
3284 public void updateMemorizingTrustmanager() {
3285 final MemorizingTrustManager tm;
3286 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3287 if (dontTrustSystemCAs) {
3288 tm = new MemorizingTrustManager(getApplicationContext(), null);
3289 } else {
3290 tm = new MemorizingTrustManager(getApplicationContext());
3291 }
3292 setMemorizingTrustManager(tm);
3293 }
3294
3295 public LruCache<String, Bitmap> getBitmapCache() {
3296 return this.mBitmapCache;
3297 }
3298
3299 public Collection<String> getKnownHosts() {
3300 final Set<String> hosts = new HashSet<>();
3301 for (final Account account : getAccounts()) {
3302 hosts.add(account.getServer());
3303 for (final Contact contact : account.getRoster().getContacts()) {
3304 if (contact.showInRoster()) {
3305 final String server = contact.getServer();
3306 if (server != null && !hosts.contains(server)) {
3307 hosts.add(server);
3308 }
3309 }
3310 }
3311 }
3312 if (Config.DOMAIN_LOCK != null) {
3313 hosts.add(Config.DOMAIN_LOCK);
3314 }
3315 if (Config.MAGIC_CREATE_DOMAIN != null) {
3316 hosts.add(Config.MAGIC_CREATE_DOMAIN);
3317 }
3318 return hosts;
3319 }
3320
3321 public Collection<String> getKnownConferenceHosts() {
3322 final Set<String> mucServers = new HashSet<>();
3323 for (final Account account : accounts) {
3324 if (account.getXmppConnection() != null) {
3325 mucServers.addAll(account.getXmppConnection().getMucServers());
3326 for (Bookmark bookmark : account.getBookmarks()) {
3327 final Jid jid = bookmark.getJid();
3328 final String s = jid == null ? null : jid.getDomain();
3329 if (s != null) {
3330 mucServers.add(s);
3331 }
3332 }
3333 }
3334 }
3335 return mucServers;
3336 }
3337
3338 public void sendMessagePacket(Account account, MessagePacket packet) {
3339 XmppConnection connection = account.getXmppConnection();
3340 if (connection != null) {
3341 connection.sendMessagePacket(packet);
3342 }
3343 }
3344
3345 public void sendPresencePacket(Account account, PresencePacket packet) {
3346 XmppConnection connection = account.getXmppConnection();
3347 if (connection != null) {
3348 connection.sendPresencePacket(packet);
3349 }
3350 }
3351
3352 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3353 final XmppConnection connection = account.getXmppConnection();
3354 if (connection != null) {
3355 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3356 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
3357 }
3358 }
3359
3360 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3361 final XmppConnection connection = account.getXmppConnection();
3362 if (connection != null) {
3363 connection.sendIqPacket(packet, callback);
3364 }
3365 }
3366
3367 public void sendPresence(final Account account) {
3368 sendPresence(account, checkListeners() && broadcastLastActivity());
3369 }
3370
3371 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3372 Presence.Status status;
3373 if (manuallyChangePresence()) {
3374 status = account.getPresenceStatus();
3375 } else {
3376 status = getTargetPresence();
3377 }
3378 PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
3379 String message = account.getPresenceStatusMessage();
3380 if (message != null && !message.isEmpty()) {
3381 packet.addChild(new Element("status").setContent(message));
3382 }
3383 if (mLastActivity > 0 && includeIdleTimestamp) {
3384 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3385 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3386 }
3387 sendPresencePacket(account, packet);
3388 }
3389
3390 private void deactivateGracePeriod() {
3391 for (Account account : getAccounts()) {
3392 account.deactivateGracePeriod();
3393 }
3394 }
3395
3396 public void refreshAllPresences() {
3397 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3398 for (Account account : getAccounts()) {
3399 if (account.isEnabled()) {
3400 sendPresence(account, includeIdleTimestamp);
3401 }
3402 }
3403 }
3404
3405 private void refreshAllGcmTokens() {
3406 for (Account account : getAccounts()) {
3407 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3408 mPushManagementService.registerPushTokenOnServer(account);
3409 }
3410 }
3411 }
3412
3413 private void sendOfflinePresence(final Account account) {
3414 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
3415 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3416 }
3417
3418 public MessageGenerator getMessageGenerator() {
3419 return this.mMessageGenerator;
3420 }
3421
3422 public PresenceGenerator getPresenceGenerator() {
3423 return this.mPresenceGenerator;
3424 }
3425
3426 public IqGenerator getIqGenerator() {
3427 return this.mIqGenerator;
3428 }
3429
3430 public IqParser getIqParser() {
3431 return this.mIqParser;
3432 }
3433
3434 public JingleConnectionManager getJingleConnectionManager() {
3435 return this.mJingleConnectionManager;
3436 }
3437
3438 public MessageArchiveService getMessageArchiveService() {
3439 return this.mMessageArchiveService;
3440 }
3441
3442 public List<Contact> findContacts(Jid jid, String accountJid) {
3443 ArrayList<Contact> contacts = new ArrayList<>();
3444 for (Account account : getAccounts()) {
3445 if ((account.isEnabled() || accountJid != null)
3446 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
3447 Contact contact = account.getRoster().getContactFromRoster(jid);
3448 if (contact != null) {
3449 contacts.add(contact);
3450 }
3451 }
3452 }
3453 return contacts;
3454 }
3455
3456 public Conversation findFirstMuc(Jid jid) {
3457 for (Conversation conversation : getConversations()) {
3458 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
3459 return conversation;
3460 }
3461 }
3462 return null;
3463 }
3464
3465 public NotificationService getNotificationService() {
3466 return this.mNotificationService;
3467 }
3468
3469 public HttpConnectionManager getHttpConnectionManager() {
3470 return this.mHttpConnectionManager;
3471 }
3472
3473 public void resendFailedMessages(final Message message) {
3474 final Collection<Message> messages = new ArrayList<>();
3475 Message current = message;
3476 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3477 messages.add(current);
3478 if (current.mergeable(current.next())) {
3479 current = current.next();
3480 } else {
3481 break;
3482 }
3483 }
3484 for (final Message msg : messages) {
3485 msg.setTime(System.currentTimeMillis());
3486 markMessage(msg, Message.STATUS_WAITING);
3487 this.resendMessage(msg, false);
3488 }
3489 if (message.getConversation() instanceof Conversation) {
3490 ((Conversation) message.getConversation()).sort();
3491 }
3492 updateConversationUi();
3493 }
3494
3495 public void clearConversationHistory(final Conversation conversation) {
3496 final long clearDate;
3497 final String reference;
3498 if (conversation.countMessages() > 0) {
3499 Message latestMessage = conversation.getLatestMessage();
3500 clearDate = latestMessage.getTimeSent() + 1000;
3501 reference = latestMessage.getServerMsgId();
3502 } else {
3503 clearDate = System.currentTimeMillis();
3504 reference = null;
3505 }
3506 conversation.clearMessages();
3507 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3508 conversation.setLastClearHistory(clearDate, reference);
3509 Runnable runnable = () -> {
3510 databaseBackend.deleteMessagesInConversation(conversation);
3511 databaseBackend.updateConversation(conversation);
3512 };
3513 mDatabaseWriterExecutor.execute(runnable);
3514 }
3515
3516 public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3517 if (blockable != null && blockable.getBlockedJid() != null) {
3518 final Jid jid = blockable.getBlockedJid();
3519 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3520
3521 @Override
3522 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3523 if (packet.getType() == IqPacket.TYPE.RESULT) {
3524 account.getBlocklist().add(jid);
3525 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3526 }
3527 }
3528 });
3529 if (removeBlockedConversations(blockable.getAccount(), jid)) {
3530 updateConversationUi();
3531 return true;
3532 } else {
3533 return false;
3534 }
3535 } else {
3536 return false;
3537 }
3538 }
3539
3540 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3541 boolean removed = false;
3542 synchronized (this.conversations) {
3543 boolean domainJid = blockedJid.getLocal() == null;
3544 for (Conversation conversation : this.conversations) {
3545 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
3546 || blockedJid.equals(conversation.getJid().asBareJid());
3547 if (conversation.getAccount() == account
3548 && conversation.getMode() == Conversation.MODE_SINGLE
3549 && jidMatches) {
3550 this.conversations.remove(conversation);
3551 markRead(conversation);
3552 conversation.setStatus(Conversation.STATUS_ARCHIVED);
3553 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
3554 updateConversation(conversation);
3555 removed = true;
3556 }
3557 }
3558 }
3559 return removed;
3560 }
3561
3562 public void sendUnblockRequest(final Blockable blockable) {
3563 if (blockable != null && blockable.getJid() != null) {
3564 final Jid jid = blockable.getBlockedJid();
3565 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3566 @Override
3567 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3568 if (packet.getType() == IqPacket.TYPE.RESULT) {
3569 account.getBlocklist().remove(jid);
3570 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3571 }
3572 }
3573 });
3574 }
3575 }
3576
3577 public void publishDisplayName(Account account) {
3578 String displayName = account.getDisplayName();
3579 if (displayName != null && !displayName.isEmpty()) {
3580 IqPacket publish = mIqGenerator.publishNick(displayName);
3581 sendIqPacket(account, publish, (account1, packet) -> {
3582 if (packet.getType() == IqPacket.TYPE.ERROR) {
3583 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": could not publish nick");
3584 }
3585 });
3586 }
3587 }
3588
3589 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3590 ServiceDiscoveryResult result = discoCache.get(key);
3591 if (result != null) {
3592 return result;
3593 } else {
3594 result = databaseBackend.findDiscoveryResult(key.first, key.second);
3595 if (result != null) {
3596 discoCache.put(key, result);
3597 }
3598 return result;
3599 }
3600 }
3601
3602 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3603 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
3604 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3605 if (disco != null) {
3606 presence.setServiceDiscoveryResult(disco);
3607 } else {
3608 if (!account.inProgressDiscoFetches.contains(key)) {
3609 account.inProgressDiscoFetches.add(key);
3610 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3611 request.setTo(jid);
3612 final String node = presence.getNode();
3613 final String ver = presence.getVer();
3614 final Element query = request.query("http://jabber.org/protocol/disco#info");
3615 if (node != null && ver != null) {
3616 query.setAttribute("node",node+"#"+ver);
3617 }
3618 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
3619 sendIqPacket(account, request, (a, response) -> {
3620 if (response.getType() == IqPacket.TYPE.RESULT) {
3621 ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
3622 if (presence.getVer().equals(discoveryResult.getVer())) {
3623 databaseBackend.insertDiscoveryResult(discoveryResult);
3624 injectServiceDiscorveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
3625 } else {
3626 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
3627 }
3628 }
3629 a.inProgressDiscoFetches.remove(key);
3630 });
3631 }
3632 }
3633 }
3634
3635 private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3636 for (Contact contact : roster.getContacts()) {
3637 for (Presence presence : contact.getPresences().getPresences().values()) {
3638 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3639 presence.setServiceDiscoveryResult(disco);
3640 }
3641 }
3642 }
3643 }
3644
3645 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3646 final boolean legacy = account.getXmppConnection().getFeatures().mamLegacy();
3647 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3648 request.addChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3649 sendIqPacket(account, request, (account1, packet) -> {
3650 Element prefs = packet.findChild("prefs", legacy ? Namespace.MAM_LEGACY : Namespace.MAM);
3651 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3652 callback.onPreferencesFetched(prefs);
3653 } else {
3654 callback.onPreferencesFetchFailed();
3655 }
3656 });
3657 }
3658
3659 public PushManagementService getPushManagementService() {
3660 return mPushManagementService;
3661 }
3662
3663 public Account getPendingAccount() {
3664 Account pending = null;
3665 for (Account account : getAccounts()) {
3666 if (!account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY)) {
3667 pending = account;
3668 } else {
3669 return null;
3670 }
3671 }
3672 return pending;
3673 }
3674
3675 public void changeStatus(Account account, PresenceTemplate template, String signature) {
3676 if (!template.getStatusMessage().isEmpty()) {
3677 databaseBackend.insertPresenceTemplate(template);
3678 }
3679 account.setPgpSignature(signature);
3680 account.setPresenceStatus(template.getStatus());
3681 account.setPresenceStatusMessage(template.getStatusMessage());
3682 databaseBackend.updateAccount(account);
3683 sendPresence(account);
3684 }
3685
3686 public List<PresenceTemplate> getPresenceTemplates(Account account) {
3687 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3688 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3689 if (!templates.contains(template)) {
3690 templates.add(0, template);
3691 }
3692 }
3693 return templates;
3694 }
3695
3696 public void saveConversationAsBookmark(Conversation conversation, String name) {
3697 Account account = conversation.getAccount();
3698 Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
3699 if (!conversation.getJid().isBareJid()) {
3700 bookmark.setNick(conversation.getJid().getResource());
3701 }
3702 if (name != null && !name.trim().isEmpty()) {
3703 bookmark.setBookmarkName(name.trim());
3704 }
3705 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
3706 account.getBookmarks().add(bookmark);
3707 pushBookmarks(account);
3708 bookmark.setConversation(conversation);
3709 }
3710
3711 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3712 boolean performedVerification = false;
3713 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3714 for (XmppUri.Fingerprint fp : fingerprints) {
3715 if (fp.type == XmppUri.FingerprintType.OMEMO) {
3716 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3717 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3718 if (fingerprintStatus != null) {
3719 if (!fingerprintStatus.isVerified()) {
3720 performedVerification = true;
3721 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3722 }
3723 } else {
3724 axolotlService.preVerifyFingerprint(contact, fingerprint);
3725 }
3726 }
3727 }
3728 return performedVerification;
3729 }
3730
3731 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3732 final AxolotlService axolotlService = account.getAxolotlService();
3733 boolean verifiedSomething = false;
3734 for (XmppUri.Fingerprint fp : fingerprints) {
3735 if (fp.type == XmppUri.FingerprintType.OMEMO) {
3736 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3737 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
3738 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3739 if (fingerprintStatus != null) {
3740 if (!fingerprintStatus.isVerified()) {
3741 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3742 verifiedSomething = true;
3743 }
3744 } else {
3745 axolotlService.preVerifyFingerprint(account, fingerprint);
3746 verifiedSomething = true;
3747 }
3748 }
3749 }
3750 return verifiedSomething;
3751 }
3752
3753 public boolean blindTrustBeforeVerification() {
3754 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
3755 }
3756
3757 public ShortcutService getShortcutService() {
3758 return mShortcutService;
3759 }
3760
3761 public void pushMamPreferences(Account account, Element prefs) {
3762 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3763 set.addChild(prefs);
3764 sendIqPacket(account, set, null);
3765 }
3766
3767 public interface OnMamPreferencesFetched {
3768 void onPreferencesFetched(Element prefs);
3769
3770 void onPreferencesFetchFailed();
3771 }
3772
3773 public interface OnAccountCreated {
3774 void onAccountCreated(Account account);
3775
3776 void informUser(int r);
3777 }
3778
3779 public interface OnMoreMessagesLoaded {
3780 void onMoreMessagesLoaded(int count, Conversation conversation);
3781
3782 void informUser(int r);
3783 }
3784
3785 public interface OnAccountPasswordChanged {
3786 void onPasswordChangeSucceeded();
3787
3788 void onPasswordChangeFailed();
3789 }
3790
3791 public interface OnAffiliationChanged {
3792 void onAffiliationChangedSuccessful(Jid jid);
3793
3794 void onAffiliationChangeFailed(Jid jid, int resId);
3795 }
3796
3797 public interface OnRoleChanged {
3798 void onRoleChangedSuccessful(String nick);
3799
3800 void onRoleChangeFailed(String nick, int resid);
3801 }
3802
3803 public interface OnConversationUpdate {
3804 void onConversationUpdate();
3805 }
3806
3807 public interface OnAccountUpdate {
3808 void onAccountUpdate();
3809 }
3810
3811 public interface OnCaptchaRequested {
3812 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
3813 }
3814
3815 public interface OnRosterUpdate {
3816 void onRosterUpdate();
3817 }
3818
3819 public interface OnMucRosterUpdate {
3820 void onMucRosterUpdate();
3821 }
3822
3823 public interface OnConferenceConfigurationFetched {
3824 void onConferenceConfigurationFetched(Conversation conversation);
3825
3826 void onFetchFailed(Conversation conversation, Element error);
3827 }
3828
3829 public interface OnConferenceJoined {
3830 void onConferenceJoined(Conversation conversation);
3831 }
3832
3833 public interface OnConfigurationPushed {
3834 void onPushSucceeded();
3835
3836 void onPushFailed();
3837 }
3838
3839 public interface OnShowErrorToast {
3840 void onShowErrorToast(int resId);
3841 }
3842
3843 public class XmppConnectionBinder extends Binder {
3844 public XmppConnectionService getService() {
3845 return XmppConnectionService.this;
3846 }
3847 }
3848}