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