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 return;
2428 }
2429
2430 final Jid joinJid = mucOptions.getSelf().getFullJid();
2431 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2432 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2433 packet.setTo(joinJid);
2434 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2435 if (conversation.getMucOptions().getPassword() != null) {
2436 x.addChild("password").setContent(mucOptions.getPassword());
2437 }
2438
2439 if (mucOptions.mamSupport()) {
2440 // Use MAM instead of the limited muc history to get history
2441 x.addChild("history").setAttribute("maxchars", "0");
2442 } else {
2443 // Fallback to muc history
2444 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2445 }
2446 sendPresencePacket(account, packet);
2447 if (onConferenceJoined != null) {
2448 onConferenceJoined.onConferenceJoined(conversation);
2449 }
2450 if (!joinJid.equals(conversation.getJid())) {
2451 conversation.setContactJid(joinJid);
2452 databaseBackend.updateConversation(conversation);
2453 }
2454
2455 if (mucOptions.mamSupport()) {
2456 getMessageArchiveService().catchupMUC(conversation);
2457 }
2458 if (mucOptions.isPrivateAndNonAnonymous()) {
2459 fetchConferenceMembers(conversation);
2460 if (followedInvite && conversation.getBookmark() == null) {
2461 saveConversationAsBookmark(conversation, null);
2462 }
2463 }
2464 sendUnsentMessages(conversation);
2465 }
2466
2467 @Override
2468 public void onConferenceConfigurationFetched(Conversation conversation) {
2469 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2470 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": conversation ("+conversation.getJid()+") got archived before IQ result");
2471 return;
2472 }
2473 join(conversation);
2474 }
2475
2476 @Override
2477 public void onFetchFailed(final Conversation conversation, Element error) {
2478 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2479 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": conversation ("+conversation.getJid()+") got archived before IQ result");
2480 return;
2481 }
2482 if (error != null && "remote-server-not-found".equals(error.getName())) {
2483 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2484 updateConversationUi();
2485 } else {
2486 join(conversation);
2487 fetchConferenceConfiguration(conversation);
2488 }
2489 }
2490 });
2491 updateConversationUi();
2492 } else {
2493 account.pendingConferenceJoins.add(conversation);
2494 conversation.resetMucOptions();
2495 conversation.setHasMessagesLeftOnServer(false);
2496 updateConversationUi();
2497 }
2498 }
2499
2500 private void fetchConferenceMembers(final Conversation conversation) {
2501 final Account account = conversation.getAccount();
2502 final AxolotlService axolotlService = account.getAxolotlService();
2503 final String[] affiliations = {"member", "admin", "owner"};
2504 OnIqPacketReceived callback = new OnIqPacketReceived() {
2505
2506 private int i = 0;
2507 private boolean success = true;
2508
2509 @Override
2510 public void onIqPacketReceived(Account account, IqPacket packet) {
2511 final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
2512 Element query = packet.query("http://jabber.org/protocol/muc#admin");
2513 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2514 for (Element child : query.getChildren()) {
2515 if ("item".equals(child.getName())) {
2516 MucOptions.User user = AbstractParser.parseItem(conversation, child);
2517 if (!user.realJidMatchesAccount()) {
2518 boolean isNew = conversation.getMucOptions().updateUser(user);
2519 Contact contact = user.getContact();
2520 if (omemoEnabled
2521 && isNew
2522 && user.getRealJid() != null
2523 && (contact == null || !contact.mutualPresenceSubscription())
2524 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2525 axolotlService.fetchDeviceIds(user.getRealJid());
2526 }
2527 }
2528 }
2529 }
2530 } else {
2531 success = false;
2532 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2533 }
2534 ++i;
2535 if (i >= affiliations.length) {
2536 List<Jid> members = conversation.getMucOptions().getMembers(true);
2537 if (success) {
2538 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2539 boolean changed = false;
2540 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2541 Jid jid = iterator.next();
2542 if (!members.contains(jid) && !members.contains(Jid.ofDomain(jid.getDomain()))) {
2543 iterator.remove();
2544 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2545 changed = true;
2546 }
2547 }
2548 if (changed) {
2549 conversation.setAcceptedCryptoTargets(cryptoTargets);
2550 updateConversation(conversation);
2551 }
2552 }
2553 getAvatarService().clear(conversation);
2554 updateMucRosterUi();
2555 updateConversationUi();
2556 }
2557 }
2558 };
2559 for (String affiliation : affiliations) {
2560 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2561 }
2562 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2563 }
2564
2565 public void providePasswordForMuc(Conversation conversation, String password) {
2566 if (conversation.getMode() == Conversation.MODE_MULTI) {
2567 conversation.getMucOptions().setPassword(password);
2568 if (conversation.getBookmark() != null) {
2569 if (synchronizeWithBookmarks()) {
2570 conversation.getBookmark().setAutojoin(true);
2571 }
2572 pushBookmarks(conversation.getAccount());
2573 }
2574 updateConversation(conversation);
2575 joinMuc(conversation);
2576 }
2577 }
2578
2579 private boolean hasEnabledAccounts() {
2580 if (this.accounts == null) {
2581 return false;
2582 }
2583 for (Account account : this.accounts) {
2584 if (account.isEnabled()) {
2585 return true;
2586 }
2587 }
2588 return false;
2589 }
2590
2591
2592 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
2593 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
2594 }
2595
2596 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2597 getAttachments(account.getUuid(),jid.asBareJid(),limit, onMediaLoaded);
2598 }
2599
2600
2601 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2602 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
2603 }
2604
2605 public void persistSelfNick(MucOptions.User self) {
2606 final Conversation conversation = self.getConversation();
2607 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
2608 Jid full = self.getFullJid();
2609 if (!full.equals(conversation.getJid())) {
2610 Log.d(Config.LOGTAG, "nick changed. updating");
2611 conversation.setContactJid(full);
2612 databaseBackend.updateConversation(conversation);
2613 }
2614
2615 final Bookmark bookmark = conversation.getBookmark();
2616 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
2617 if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
2618 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
2619 bookmark.setNick(full.getResource());
2620 pushBookmarks(bookmark.getAccount());
2621 }
2622 }
2623
2624 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2625 final MucOptions options = conversation.getMucOptions();
2626 final Jid joinJid = options.createJoinJid(nick);
2627 if (joinJid == null) {
2628 return false;
2629 }
2630 if (options.online()) {
2631 Account account = conversation.getAccount();
2632 options.setOnRenameListener(new OnRenameListener() {
2633
2634 @Override
2635 public void onSuccess() {
2636 callback.success(conversation);
2637 }
2638
2639 @Override
2640 public void onFailure() {
2641 callback.error(R.string.nick_in_use, conversation);
2642 }
2643 });
2644
2645 PresencePacket packet = new PresencePacket();
2646 packet.setTo(joinJid);
2647 packet.setFrom(conversation.getAccount().getJid());
2648
2649 String sig = account.getPgpSignature();
2650 if (sig != null) {
2651 packet.addChild("status").setContent("online");
2652 packet.addChild("x", "jabber:x:signed").setContent(sig);
2653 }
2654 sendPresencePacket(account, packet);
2655 } else {
2656 conversation.setContactJid(joinJid);
2657 databaseBackend.updateConversation(conversation);
2658 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2659 Bookmark bookmark = conversation.getBookmark();
2660 if (bookmark != null) {
2661 bookmark.setNick(nick);
2662 pushBookmarks(bookmark.getAccount());
2663 }
2664 joinMuc(conversation);
2665 }
2666 }
2667 return true;
2668 }
2669
2670 public void leaveMuc(Conversation conversation) {
2671 leaveMuc(conversation, false);
2672 }
2673
2674 private void leaveMuc(Conversation conversation, boolean now) {
2675 Account account = conversation.getAccount();
2676 account.pendingConferenceJoins.remove(conversation);
2677 account.pendingConferenceLeaves.remove(conversation);
2678 if (account.getStatus() == Account.State.ONLINE || now) {
2679 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2680 conversation.getMucOptions().setOffline();
2681 Bookmark bookmark = conversation.getBookmark();
2682 if (bookmark != null) {
2683 bookmark.setConversation(null);
2684 }
2685 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
2686 } else {
2687 account.pendingConferenceLeaves.add(conversation);
2688 }
2689 }
2690
2691 public String findConferenceServer(final Account account) {
2692 String server;
2693 if (account.getXmppConnection() != null) {
2694 server = account.getXmppConnection().getMucServer();
2695 if (server != null) {
2696 return server;
2697 }
2698 }
2699 for (Account other : getAccounts()) {
2700 if (other != account && other.getXmppConnection() != null) {
2701 server = other.getXmppConnection().getMucServer();
2702 if (server != null) {
2703 return server;
2704 }
2705 }
2706 }
2707 return null;
2708 }
2709
2710 public boolean createAdhocConference(final Account account,
2711 final String name,
2712 final Iterable<Jid> jids,
2713 final UiCallback<Conversation> callback) {
2714 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2715 if (account.getStatus() == Account.State.ONLINE) {
2716 try {
2717 String server = findConferenceServer(account);
2718 if (server == null) {
2719 if (callback != null) {
2720 callback.error(R.string.no_conference_server_found, null);
2721 }
2722 return false;
2723 }
2724 final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
2725 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2726 joinMuc(conversation, new OnConferenceJoined() {
2727 @Override
2728 public void onConferenceJoined(final Conversation conversation) {
2729 final Bundle configuration = IqGenerator.defaultRoomConfiguration();
2730 if (!TextUtils.isEmpty(name)) {
2731 configuration.putString("muc#roomconfig_roomname", name);
2732 }
2733 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
2734 @Override
2735 public void onPushSucceeded() {
2736 for (Jid invite : jids) {
2737 invite(conversation, invite);
2738 }
2739 if (account.countPresences() > 1) {
2740 directInvite(conversation, account.getJid().asBareJid());
2741 }
2742 saveConversationAsBookmark(conversation, name);
2743 if (callback != null) {
2744 callback.success(conversation);
2745 }
2746 }
2747
2748 @Override
2749 public void onPushFailed() {
2750 archiveConversation(conversation);
2751 if (callback != null) {
2752 callback.error(R.string.conference_creation_failed, conversation);
2753 }
2754 }
2755 });
2756 }
2757 });
2758 return true;
2759 } catch (IllegalArgumentException e) {
2760 if (callback != null) {
2761 callback.error(R.string.conference_creation_failed, null);
2762 }
2763 return false;
2764 }
2765 } else {
2766 if (callback != null) {
2767 callback.error(R.string.not_connected_try_again, null);
2768 }
2769 return false;
2770 }
2771 }
2772
2773 public void fetchConferenceConfiguration(final Conversation conversation) {
2774 fetchConferenceConfiguration(conversation, null);
2775 }
2776
2777 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2778 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2779 request.setTo(conversation.getJid().asBareJid());
2780 request.query("http://jabber.org/protocol/disco#info");
2781 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2782 @Override
2783 public void onIqPacketReceived(Account account, IqPacket packet) {
2784 if (packet.getType() == IqPacket.TYPE.RESULT) {
2785
2786 final MucOptions mucOptions = conversation.getMucOptions();
2787 final Bookmark bookmark = conversation.getBookmark();
2788 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
2789
2790 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
2791 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
2792 updateConversation(conversation);
2793 }
2794
2795 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
2796 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
2797 pushBookmarks(account);
2798 }
2799 }
2800
2801
2802 if (callback != null) {
2803 callback.onConferenceConfigurationFetched(conversation);
2804 }
2805
2806
2807
2808 updateConversationUi();
2809 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2810 if (callback != null) {
2811 callback.onFetchFailed(conversation, packet.getError());
2812 }
2813 }
2814 }
2815 });
2816 }
2817
2818 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
2819 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
2820 }
2821
2822 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2823 Log.d(Config.LOGTAG,"pushing node configuration");
2824 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
2825 @Override
2826 public void onIqPacketReceived(Account account, IqPacket packet) {
2827 if (packet.getType() == IqPacket.TYPE.RESULT) {
2828 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
2829 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2830 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
2831 if (x != null) {
2832 Data data = Data.parse(x);
2833 data.submit(options);
2834 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2835 @Override
2836 public void onIqPacketReceived(Account account, IqPacket packet) {
2837 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
2838 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully changed node configuration for node "+node);
2839 callback.onPushSucceeded();
2840 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2841 callback.onPushFailed();
2842 }
2843 }
2844 });
2845 } else if (callback != null) {
2846 callback.onPushFailed();
2847 }
2848 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2849 callback.onPushFailed();
2850 }
2851 }
2852 });
2853 }
2854
2855 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2856 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2857 request.setTo(conversation.getJid().asBareJid());
2858 request.query("http://jabber.org/protocol/muc#owner");
2859 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2860 @Override
2861 public void onIqPacketReceived(Account account, IqPacket packet) {
2862 if (packet.getType() == IqPacket.TYPE.RESULT) {
2863 Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
2864 data.submit(options);
2865 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2866 set.setTo(conversation.getJid().asBareJid());
2867 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2868 sendIqPacket(account, set, new OnIqPacketReceived() {
2869 @Override
2870 public void onIqPacketReceived(Account account, IqPacket packet) {
2871 if (callback != null) {
2872 if (packet.getType() == IqPacket.TYPE.RESULT) {
2873 callback.onPushSucceeded();
2874 } else {
2875 callback.onPushFailed();
2876 }
2877 }
2878 }
2879 });
2880 } else {
2881 if (callback != null) {
2882 callback.onPushFailed();
2883 }
2884 }
2885 }
2886 });
2887 }
2888
2889 public void pushSubjectToConference(final Conversation conference, final String subject) {
2890 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
2891 this.sendMessagePacket(conference.getAccount(), packet);
2892 }
2893
2894 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2895 final Jid jid = user.asBareJid();
2896 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2897 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2898 @Override
2899 public void onIqPacketReceived(Account account, IqPacket packet) {
2900 if (packet.getType() == IqPacket.TYPE.RESULT) {
2901 conference.getMucOptions().changeAffiliation(jid, affiliation);
2902 getAvatarService().clear(conference);
2903 callback.onAffiliationChangedSuccessful(jid);
2904 } else {
2905 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2906 }
2907 }
2908 });
2909 }
2910
2911 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2912 List<Jid> jids = new ArrayList<>();
2913 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2914 if (user.getAffiliation() == before && user.getRealJid() != null) {
2915 jids.add(user.getRealJid());
2916 }
2917 }
2918 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2919 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2920 }
2921
2922 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
2923 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2924 Log.d(Config.LOGTAG, request.toString());
2925 sendIqPacket(conference.getAccount(), request, (account, packet) -> {
2926 if (packet.getType() != IqPacket.TYPE.RESULT) {
2927 Log.d(Config.LOGTAG,account.getJid().asBareJid()+" unable to change role of "+nick);
2928 }
2929 });
2930 }
2931
2932 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
2933 IqPacket request = new IqPacket(IqPacket.TYPE.SET);
2934 request.setTo(conversation.getJid().asBareJid());
2935 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
2936 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2937 @Override
2938 public void onIqPacketReceived(Account account, IqPacket packet) {
2939 if (packet.getType() == IqPacket.TYPE.RESULT) {
2940 if (callback != null) {
2941 callback.onRoomDestroySucceeded();
2942 }
2943 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2944 if (callback != null) {
2945 callback.onRoomDestroyFailed();
2946 }
2947 }
2948 }
2949 });
2950 }
2951
2952 private void disconnect(Account account, boolean force) {
2953 if ((account.getStatus() == Account.State.ONLINE)
2954 || (account.getStatus() == Account.State.DISABLED)) {
2955 final XmppConnection connection = account.getXmppConnection();
2956 if (!force) {
2957 List<Conversation> conversations = getConversations();
2958 for (Conversation conversation : conversations) {
2959 if (conversation.getAccount() == account) {
2960 if (conversation.getMode() == Conversation.MODE_MULTI) {
2961 leaveMuc(conversation, true);
2962 }
2963 }
2964 }
2965 sendOfflinePresence(account);
2966 }
2967 connection.disconnect(force);
2968 }
2969 }
2970
2971 @Override
2972 public IBinder onBind(Intent intent) {
2973 return mBinder;
2974 }
2975
2976 public void updateMessage(Message message) {
2977 updateMessage(message, true);
2978 }
2979
2980 public void updateMessage(Message message, boolean includeBody) {
2981 databaseBackend.updateMessage(message, includeBody);
2982 updateConversationUi();
2983 }
2984
2985 public void updateMessage(Message message, String uuid) {
2986 if (!databaseBackend.updateMessage(message, uuid)) {
2987 Log.e(Config.LOGTAG,"error updated message in DB after edit");
2988 }
2989 updateConversationUi();
2990 }
2991
2992 protected void syncDirtyContacts(Account account) {
2993 for (Contact contact : account.getRoster().getContacts()) {
2994 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2995 pushContactToServer(contact);
2996 }
2997 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2998 deleteContactOnServer(contact);
2999 }
3000 }
3001 }
3002
3003 public void createContact(Contact contact, boolean autoGrant) {
3004 if (autoGrant) {
3005 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3006 contact.setOption(Contact.Options.ASKING);
3007 }
3008 pushContactToServer(contact);
3009 }
3010
3011 public void pushContactToServer(final Contact contact) {
3012 contact.resetOption(Contact.Options.DIRTY_DELETE);
3013 contact.setOption(Contact.Options.DIRTY_PUSH);
3014 final Account account = contact.getAccount();
3015 if (account.getStatus() == Account.State.ONLINE) {
3016 final boolean ask = contact.getOption(Contact.Options.ASKING);
3017 final boolean sendUpdates = contact
3018 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3019 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3020 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3021 iq.query(Namespace.ROSTER).addChild(contact.asElement());
3022 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3023 if (sendUpdates) {
3024 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3025 }
3026 if (ask) {
3027 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
3028 }
3029 } else {
3030 syncRoster(contact.getAccount());
3031 }
3032 }
3033
3034 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3035 new Thread(() -> {
3036 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3037 final int size = Config.AVATAR_SIZE;
3038 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3039 if (avatar != null) {
3040 if (!getFileBackend().save(avatar)) {
3041 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3042 return;
3043 }
3044 avatar.owner = conversation.getJid().asBareJid();
3045 publishMucAvatar(conversation, avatar, callback);
3046 } else {
3047 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3048 }
3049 }).start();
3050 }
3051
3052 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3053 new Thread(() -> {
3054 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3055 final int size = Config.AVATAR_SIZE;
3056 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3057 if (avatar != null) {
3058 if (!getFileBackend().save(avatar)) {
3059 Log.d(Config.LOGTAG,"unable to save vcard");
3060 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3061 return;
3062 }
3063 publishAvatar(account, avatar, callback);
3064 } else {
3065 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3066 }
3067 }).start();
3068
3069 }
3070
3071 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3072 final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3073 sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3074 boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3075 if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3076 Element vcard = response.findChild("vCard", "vcard-temp");
3077 if (vcard == null) {
3078 vcard = new Element("vCard", "vcard-temp");
3079 }
3080 Element photo = vcard.findChild("PHOTO");
3081 if (photo == null) {
3082 photo = vcard.addChild("PHOTO");
3083 }
3084 photo.clearChildren();
3085 photo.addChild("TYPE").setContent(avatar.type);
3086 photo.addChild("BINVAL").setContent(avatar.image);
3087 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3088 publication.setTo(conversation.getJid().asBareJid());
3089 publication.addChild(vcard);
3090 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3091 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3092 callback.onAvatarPublicationSucceeded();
3093 } else {
3094 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
3095 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3096 }
3097 });
3098 } else {
3099 Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
3100 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3101 }
3102 });
3103 }
3104
3105 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3106 final Bundle options;
3107 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3108 options = PublishOptions.openAccess();
3109 } else {
3110 options = null;
3111 }
3112 publishAvatar(account, avatar, options, true, callback);
3113 }
3114
3115 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3116 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": publishing avatar. options="+options);
3117 IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3118 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3119
3120 @Override
3121 public void onIqPacketReceived(Account account, IqPacket result) {
3122 if (result.getType() == IqPacket.TYPE.RESULT) {
3123 publishAvatarMetadata(account, avatar, options,true, callback);
3124 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3125 pushNodeConfiguration(account, "urn:xmpp:avatar:data", options, new OnConfigurationPushed() {
3126 @Override
3127 public void onPushSucceeded() {
3128 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": changed node configuration for avatar node");
3129 publishAvatar(account, avatar, options, false, callback);
3130 }
3131
3132 @Override
3133 public void onPushFailed() {
3134 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to change node configuration for avatar node");
3135 publishAvatar(account, avatar, null, false, callback);
3136 }
3137 });
3138 } else {
3139 Element error = result.findChild("error");
3140 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3141 if (callback != null) {
3142 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3143 }
3144 }
3145 }
3146 });
3147 }
3148
3149 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3150 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3151 sendIqPacket(account, packet, new OnIqPacketReceived() {
3152 @Override
3153 public void onIqPacketReceived(Account account, IqPacket result) {
3154 if (result.getType() == IqPacket.TYPE.RESULT) {
3155 if (account.setAvatar(avatar.getFilename())) {
3156 getAvatarService().clear(account);
3157 databaseBackend.updateAccount(account);
3158 notifyAccountAvatarHasChanged(account);
3159 }
3160 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3161 if (callback != null) {
3162 callback.onAvatarPublicationSucceeded();
3163 }
3164 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3165 pushNodeConfiguration(account, "urn:xmpp:avatar:metadata", options, new OnConfigurationPushed() {
3166 @Override
3167 public void onPushSucceeded() {
3168 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": changed node configuration for avatar meta data node");
3169 publishAvatarMetadata(account, avatar, options,false, callback);
3170 }
3171
3172 @Override
3173 public void onPushFailed() {
3174 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to change node configuration for avatar meta data node");
3175 publishAvatarMetadata(account, avatar, null,false, callback);
3176 }
3177 });
3178 } else {
3179 if (callback != null) {
3180 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3181 }
3182 }
3183 }
3184 });
3185 }
3186
3187 public void republishAvatarIfNeeded(Account account) {
3188 if (account.getAxolotlService().isPepBroken()) {
3189 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3190 return;
3191 }
3192 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3193 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3194
3195 private Avatar parseAvatar(IqPacket packet) {
3196 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3197 if (pubsub != null) {
3198 Element items = pubsub.findChild("items");
3199 if (items != null) {
3200 return Avatar.parseMetadata(items);
3201 }
3202 }
3203 return null;
3204 }
3205
3206 private boolean errorIsItemNotFound(IqPacket packet) {
3207 Element error = packet.findChild("error");
3208 return packet.getType() == IqPacket.TYPE.ERROR
3209 && error != null
3210 && error.hasChild("item-not-found");
3211 }
3212
3213 @Override
3214 public void onIqPacketReceived(Account account, IqPacket packet) {
3215 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
3216 Avatar serverAvatar = parseAvatar(packet);
3217 if (serverAvatar == null && account.getAvatar() != null) {
3218 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
3219 if (avatar != null) {
3220 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3221 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3222 } else {
3223 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3224 }
3225 }
3226 }
3227 }
3228 });
3229 }
3230
3231 public void fetchAvatar(Account account, Avatar avatar) {
3232 fetchAvatar(account, avatar, null);
3233 }
3234
3235 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3236 final String KEY = generateFetchKey(account, avatar);
3237 synchronized (this.mInProgressAvatarFetches) {
3238 if (mInProgressAvatarFetches.add(KEY)) {
3239 switch (avatar.origin) {
3240 case PEP:
3241 this.mInProgressAvatarFetches.add(KEY);
3242 fetchAvatarPep(account, avatar, callback);
3243 break;
3244 case VCARD:
3245 this.mInProgressAvatarFetches.add(KEY);
3246 fetchAvatarVcard(account, avatar, callback);
3247 break;
3248 }
3249 } else if (avatar.origin == Avatar.Origin.PEP) {
3250 mOmittedPepAvatarFetches.add(KEY);
3251 } else {
3252 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": already fetching "+avatar.origin+" avatar for "+avatar.owner);
3253 }
3254 }
3255 }
3256
3257 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3258 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3259 sendIqPacket(account, packet, (a, result) -> {
3260 synchronized (mInProgressAvatarFetches) {
3261 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3262 }
3263 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3264 if (result.getType() == IqPacket.TYPE.RESULT) {
3265 avatar.image = mIqParser.avatarData(result);
3266 if (avatar.image != null) {
3267 if (getFileBackend().save(avatar)) {
3268 if (a.getJid().asBareJid().equals(avatar.owner)) {
3269 if (a.setAvatar(avatar.getFilename())) {
3270 databaseBackend.updateAccount(a);
3271 }
3272 getAvatarService().clear(a);
3273 updateConversationUi();
3274 updateAccountUi();
3275 } else {
3276 Contact contact = a.getRoster().getContact(avatar.owner);
3277 if (contact.setAvatar(avatar)) {
3278 syncRoster(account);
3279 getAvatarService().clear(contact);
3280 updateConversationUi();
3281 updateRosterUi();
3282 }
3283 }
3284 if (callback != null) {
3285 callback.success(avatar);
3286 }
3287 Log.d(Config.LOGTAG, a.getJid().asBareJid()
3288 + ": successfully fetched pep avatar for " + avatar.owner);
3289 return;
3290 }
3291 } else {
3292
3293 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3294 }
3295 } else {
3296 Element error = result.findChild("error");
3297 if (error == null) {
3298 Log.d(Config.LOGTAG, ERROR + "(server error)");
3299 } else {
3300 Log.d(Config.LOGTAG, ERROR + error.toString());
3301 }
3302 }
3303 if (callback != null) {
3304 callback.error(0, null);
3305 }
3306
3307 });
3308 }
3309
3310 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3311 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3312 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3313 @Override
3314 public void onIqPacketReceived(Account account, IqPacket packet) {
3315 final boolean previouslyOmittedPepFetch;
3316 synchronized (mInProgressAvatarFetches) {
3317 final String KEY = generateFetchKey(account, avatar);
3318 mInProgressAvatarFetches.remove(KEY);
3319 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
3320 }
3321 if (packet.getType() == IqPacket.TYPE.RESULT) {
3322 Element vCard = packet.findChild("vCard", "vcard-temp");
3323 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3324 String image = photo != null ? photo.findChildContent("BINVAL") : null;
3325 if (image != null) {
3326 avatar.image = image;
3327 if (getFileBackend().save(avatar)) {
3328 Log.d(Config.LOGTAG, account.getJid().asBareJid()
3329 + ": successfully fetched vCard avatar for " + avatar.owner+" omittedPep="+previouslyOmittedPepFetch);
3330 if (avatar.owner.isBareJid()) {
3331 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3332 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3333 account.setAvatar(avatar.getFilename());
3334 databaseBackend.updateAccount(account);
3335 getAvatarService().clear(account);
3336 updateAccountUi();
3337 } else {
3338 Contact contact = account.getRoster().getContact(avatar.owner);
3339 if (contact.setAvatar(avatar, previouslyOmittedPepFetch)) {
3340 syncRoster(account);
3341 getAvatarService().clear(contact);
3342 updateRosterUi();
3343 }
3344 }
3345 updateConversationUi();
3346 } else {
3347 Conversation conversation = find(account, avatar.owner.asBareJid());
3348 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3349 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3350 if (user != null) {
3351 if (user.setAvatar(avatar)) {
3352 getAvatarService().clear(user);
3353 updateConversationUi();
3354 updateMucRosterUi();
3355 }
3356 if (user.getRealJid() != null) {
3357 Contact contact = account.getRoster().getContact(user.getRealJid());
3358 if (contact.setAvatar(avatar)) {
3359 syncRoster(account);
3360 getAvatarService().clear(contact);
3361 updateRosterUi();
3362 }
3363 }
3364 }
3365 }
3366 }
3367 }
3368 }
3369 }
3370 }
3371 });
3372 }
3373
3374 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3375 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3376 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3377
3378 @Override
3379 public void onIqPacketReceived(Account account, IqPacket packet) {
3380 if (packet.getType() == IqPacket.TYPE.RESULT) {
3381 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3382 if (pubsub != null) {
3383 Element items = pubsub.findChild("items");
3384 if (items != null) {
3385 Avatar avatar = Avatar.parseMetadata(items);
3386 if (avatar != null) {
3387 avatar.owner = account.getJid().asBareJid();
3388 if (fileBackend.isAvatarCached(avatar)) {
3389 if (account.setAvatar(avatar.getFilename())) {
3390 databaseBackend.updateAccount(account);
3391 }
3392 getAvatarService().clear(account);
3393 callback.success(avatar);
3394 } else {
3395 fetchAvatarPep(account, avatar, callback);
3396 }
3397 return;
3398 }
3399 }
3400 }
3401 }
3402 callback.error(0, null);
3403 }
3404 });
3405 }
3406
3407 public void notifyAccountAvatarHasChanged(final Account account) {
3408 final XmppConnection connection = account.getXmppConnection();
3409 if (connection != null && connection.getFeatures().bookmarksConversion()) {
3410 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": avatar changed. resending presence to online group chats");
3411 for(Conversation conversation : conversations) {
3412 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
3413 final MucOptions mucOptions = conversation.getMucOptions();
3414 if (mucOptions.online()) {
3415 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
3416 packet.setTo(mucOptions.getSelf().getFullJid());
3417 connection.sendPresencePacket(packet);
3418 }
3419 }
3420 }
3421 }
3422 }
3423
3424 public void deleteContactOnServer(Contact contact) {
3425 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3426 contact.resetOption(Contact.Options.DIRTY_PUSH);
3427 contact.setOption(Contact.Options.DIRTY_DELETE);
3428 Account account = contact.getAccount();
3429 if (account.getStatus() == Account.State.ONLINE) {
3430 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3431 Element item = iq.query(Namespace.ROSTER).addChild("item");
3432 item.setAttribute("jid", contact.getJid().toString());
3433 item.setAttribute("subscription", "remove");
3434 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3435 }
3436 }
3437
3438 public void updateConversation(final Conversation conversation) {
3439 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3440 }
3441
3442 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3443 synchronized (account) {
3444 XmppConnection connection = account.getXmppConnection();
3445 if (connection == null) {
3446 connection = createConnection(account);
3447 account.setXmppConnection(connection);
3448 }
3449 boolean hasInternet = hasInternetConnection();
3450 if (account.isEnabled() && hasInternet) {
3451 if (!force) {
3452 disconnect(account, false);
3453 }
3454 Thread thread = new Thread(connection);
3455 connection.setInteractive(interactive);
3456 connection.prepareNewConnection();
3457 connection.interrupt();
3458 thread.start();
3459 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3460 } else {
3461 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3462 account.getRoster().clearPresences();
3463 connection.resetEverything();
3464 final AxolotlService axolotlService = account.getAxolotlService();
3465 if (axolotlService != null) {
3466 axolotlService.resetBrokenness();
3467 }
3468 if (!hasInternet) {
3469 account.setStatus(Account.State.NO_INTERNET);
3470 }
3471 }
3472 }
3473 }
3474
3475 public void reconnectAccountInBackground(final Account account) {
3476 new Thread(() -> reconnectAccount(account, false, true)).start();
3477 }
3478
3479 public void invite(Conversation conversation, Jid contact) {
3480 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3481 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3482 sendMessagePacket(conversation.getAccount(), packet);
3483 }
3484
3485 public void directInvite(Conversation conversation, Jid jid) {
3486 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3487 sendMessagePacket(conversation.getAccount(), packet);
3488 }
3489
3490 public void resetSendingToWaiting(Account account) {
3491 for (Conversation conversation : getConversations()) {
3492 if (conversation.getAccount() == account) {
3493 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
3494 }
3495 }
3496 }
3497
3498 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3499 return markMessage(account, recipient, uuid, status, null);
3500 }
3501
3502 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3503 if (uuid == null) {
3504 return null;
3505 }
3506 for (Conversation conversation : getConversations()) {
3507 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3508 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3509 if (message != null) {
3510 markMessage(message, status, errorMessage);
3511 }
3512 return message;
3513 }
3514 }
3515 return null;
3516 }
3517
3518 public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3519 if (uuid == null) {
3520 return false;
3521 } else {
3522 Message message = conversation.findSentMessageWithUuid(uuid);
3523 if (message != null) {
3524 if (message.getServerMsgId() == null) {
3525 message.setServerMsgId(serverMessageId);
3526 }
3527 markMessage(message, status);
3528 return true;
3529 } else {
3530 return false;
3531 }
3532 }
3533 }
3534
3535 public void markMessage(Message message, int status) {
3536 markMessage(message, status, null);
3537 }
3538
3539
3540 public void markMessage(Message message, int status, String errorMessage) {
3541 final int c = message.getStatus();
3542 if (status == Message.STATUS_SEND_FAILED && (c == Message.STATUS_SEND_RECEIVED || c == Message.STATUS_SEND_DISPLAYED)) {
3543 return;
3544 }
3545 if (status == Message.STATUS_SEND_RECEIVED && c == Message.STATUS_SEND_DISPLAYED) {
3546 return;
3547 }
3548 message.setErrorMessage(errorMessage);
3549 message.setStatus(status);
3550 databaseBackend.updateMessage(message, false);
3551 updateConversationUi();
3552 }
3553
3554 private SharedPreferences getPreferences() {
3555 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3556 }
3557
3558 public long getAutomaticMessageDeletionDate() {
3559 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3560 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3561 }
3562
3563 public long getLongPreference(String name, @IntegerRes int res) {
3564 long defaultValue = getResources().getInteger(res);
3565 try {
3566 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3567 } catch (NumberFormatException e) {
3568 return defaultValue;
3569 }
3570 }
3571
3572 public boolean getBooleanPreference(String name, @BoolRes int res) {
3573 return getPreferences().getBoolean(name, getResources().getBoolean(res));
3574 }
3575
3576 public boolean confirmMessages() {
3577 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3578 }
3579
3580 public boolean allowMessageCorrection() {
3581 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3582 }
3583
3584 public boolean sendChatStates() {
3585 return getBooleanPreference("chat_states", R.bool.chat_states);
3586 }
3587
3588 private boolean synchronizeWithBookmarks() {
3589 return getBooleanPreference("autojoin", R.bool.autojoin);
3590 }
3591
3592 public boolean indicateReceived() {
3593 return getBooleanPreference("indicate_received", R.bool.indicate_received);
3594 }
3595
3596 public boolean useTorToConnect() {
3597 return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
3598 }
3599
3600 public boolean showExtendedConnectionOptions() {
3601 return QuickConversationsService.isConversations() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3602 }
3603
3604 public boolean broadcastLastActivity() {
3605 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3606 }
3607
3608 public int unreadCount() {
3609 int count = 0;
3610 for (Conversation conversation : getConversations()) {
3611 count += conversation.unreadCount();
3612 }
3613 return count;
3614 }
3615
3616
3617 private <T> List<T> threadSafeList(Set<T> set) {
3618 synchronized (LISTENER_LOCK) {
3619 return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
3620 }
3621 }
3622
3623 public void showErrorToastInUi(int resId) {
3624 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
3625 listener.onShowErrorToast(resId);
3626 }
3627 }
3628
3629 public void updateConversationUi() {
3630 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
3631 listener.onConversationUpdate();
3632 }
3633 }
3634
3635 public void updateAccountUi() {
3636 for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
3637 listener.onAccountUpdate();
3638 }
3639 }
3640
3641 public void updateRosterUi() {
3642 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
3643 listener.onRosterUpdate();
3644 }
3645 }
3646
3647 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3648 if (mOnCaptchaRequested.size() > 0) {
3649 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3650 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3651 (int) (captcha.getHeight() * metrics.scaledDensity), false);
3652 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
3653 listener.onCaptchaRequested(account, id, data, scaled);
3654 }
3655 return true;
3656 }
3657 return false;
3658 }
3659
3660 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3661 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
3662 listener.OnUpdateBlocklist(status);
3663 }
3664 }
3665
3666 public void updateMucRosterUi() {
3667 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
3668 listener.onMucRosterUpdate();
3669 }
3670 }
3671
3672 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3673 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
3674 listener.onKeyStatusUpdated(report);
3675 }
3676 }
3677
3678 public Account findAccountByJid(final Jid accountJid) {
3679 for (Account account : this.accounts) {
3680 if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3681 return account;
3682 }
3683 }
3684 return null;
3685 }
3686
3687 public Account findAccountByUuid(final String uuid) {
3688 for(Account account : this.accounts) {
3689 if (account.getUuid().equals(uuid)) {
3690 return account;
3691 }
3692 }
3693 return null;
3694 }
3695
3696 public Conversation findConversationByUuid(String uuid) {
3697 for (Conversation conversation : getConversations()) {
3698 if (conversation.getUuid().equals(uuid)) {
3699 return conversation;
3700 }
3701 }
3702 return null;
3703 }
3704
3705 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
3706 List<Conversation> findings = new ArrayList<>();
3707 for (Conversation c : getConversations()) {
3708 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
3709 findings.add(c);
3710 }
3711 }
3712 return findings.size() == 1 ? findings.get(0) : null;
3713 }
3714
3715 public boolean markRead(final Conversation conversation, boolean dismiss) {
3716 return markRead(conversation, null, dismiss).size() > 0;
3717 }
3718
3719 public void markRead(final Conversation conversation) {
3720 markRead(conversation, null, true);
3721 }
3722
3723 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
3724 if (dismiss) {
3725 mNotificationService.clear(conversation);
3726 }
3727 final List<Message> readMessages = conversation.markRead(upToUuid);
3728 if (readMessages.size() > 0) {
3729 Runnable runnable = () -> {
3730 for (Message message : readMessages) {
3731 databaseBackend.updateMessage(message, false);
3732 }
3733 };
3734 mDatabaseWriterExecutor.execute(runnable);
3735 updateUnreadCountBadge();
3736 return readMessages;
3737 } else {
3738 return readMessages;
3739 }
3740 }
3741
3742 public synchronized void updateUnreadCountBadge() {
3743 int count = unreadCount();
3744 if (unreadCount != count) {
3745 Log.d(Config.LOGTAG, "update unread count to " + count);
3746 if (count > 0) {
3747 ShortcutBadger.applyCount(getApplicationContext(), count);
3748 } else {
3749 ShortcutBadger.removeCount(getApplicationContext());
3750 }
3751 unreadCount = count;
3752 }
3753 }
3754
3755 public void sendReadMarker(final Conversation conversation, String upToUuid) {
3756 final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
3757 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
3758 if (readMessages.size() > 0) {
3759 updateConversationUi();
3760 }
3761 final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
3762 if (confirmMessages()
3763 && markable != null
3764 && (markable.trusted() || isPrivateAndNonAnonymousMuc)
3765 && markable.getRemoteMsgId() != null) {
3766 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3767 Account account = conversation.getAccount();
3768 final Jid to = markable.getCounterpart();
3769 final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3770 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3771 this.sendMessagePacket(conversation.getAccount(), packet);
3772 }
3773 }
3774
3775 public SecureRandom getRNG() {
3776 return this.mRandom;
3777 }
3778
3779 public MemorizingTrustManager getMemorizingTrustManager() {
3780 return this.mMemorizingTrustManager;
3781 }
3782
3783 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3784 this.mMemorizingTrustManager = trustManager;
3785 }
3786
3787 public void updateMemorizingTrustmanager() {
3788 final MemorizingTrustManager tm;
3789 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3790 if (dontTrustSystemCAs) {
3791 tm = new MemorizingTrustManager(getApplicationContext(), null);
3792 } else {
3793 tm = new MemorizingTrustManager(getApplicationContext());
3794 }
3795 setMemorizingTrustManager(tm);
3796 }
3797
3798 public LruCache<String, Bitmap> getBitmapCache() {
3799 return this.mBitmapCache;
3800 }
3801
3802 public Collection<String> getKnownHosts() {
3803 final Set<String> hosts = new HashSet<>();
3804 for (final Account account : getAccounts()) {
3805 hosts.add(account.getServer());
3806 for (final Contact contact : account.getRoster().getContacts()) {
3807 if (contact.showInRoster()) {
3808 final String server = contact.getServer();
3809 if (server != null) {
3810 hosts.add(server);
3811 }
3812 }
3813 }
3814 }
3815 if (Config.QUICKSY_DOMAIN != null) {
3816 hosts.remove(Config.QUICKSY_DOMAIN); //we only want to show this when we type a e164 number
3817 }
3818 if (Config.DOMAIN_LOCK != null) {
3819 hosts.add(Config.DOMAIN_LOCK);
3820 }
3821 if (Config.MAGIC_CREATE_DOMAIN != null) {
3822 hosts.add(Config.MAGIC_CREATE_DOMAIN);
3823 }
3824 return hosts;
3825 }
3826
3827 public Collection<String> getKnownConferenceHosts() {
3828 final Set<String> mucServers = new HashSet<>();
3829 for (final Account account : accounts) {
3830 if (account.getXmppConnection() != null) {
3831 mucServers.addAll(account.getXmppConnection().getMucServers());
3832 for (Bookmark bookmark : account.getBookmarks()) {
3833 final Jid jid = bookmark.getJid();
3834 final String s = jid == null ? null : jid.getDomain();
3835 if (s != null) {
3836 mucServers.add(s);
3837 }
3838 }
3839 }
3840 }
3841 return mucServers;
3842 }
3843
3844 public void sendMessagePacket(Account account, MessagePacket packet) {
3845 XmppConnection connection = account.getXmppConnection();
3846 if (connection != null) {
3847 connection.sendMessagePacket(packet);
3848 }
3849 }
3850
3851 public void sendPresencePacket(Account account, PresencePacket packet) {
3852 XmppConnection connection = account.getXmppConnection();
3853 if (connection != null) {
3854 connection.sendPresencePacket(packet);
3855 }
3856 }
3857
3858 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3859 final XmppConnection connection = account.getXmppConnection();
3860 if (connection != null) {
3861 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3862 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
3863 }
3864 }
3865
3866 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3867 final XmppConnection connection = account.getXmppConnection();
3868 if (connection != null) {
3869 connection.sendIqPacket(packet, callback);
3870 } else if (callback != null) {
3871 callback.onIqPacketReceived(account,new IqPacket(IqPacket.TYPE.TIMEOUT));
3872 }
3873 }
3874
3875 public void sendPresence(final Account account) {
3876 sendPresence(account, checkListeners() && broadcastLastActivity());
3877 }
3878
3879 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3880 Presence.Status status;
3881 if (manuallyChangePresence()) {
3882 status = account.getPresenceStatus();
3883 } else {
3884 status = getTargetPresence();
3885 }
3886 PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
3887 String message = account.getPresenceStatusMessage();
3888 if (message != null && !message.isEmpty()) {
3889 packet.addChild(new Element("status").setContent(message));
3890 }
3891 if (mLastActivity > 0 && includeIdleTimestamp) {
3892 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3893 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3894 }
3895 sendPresencePacket(account, packet);
3896 }
3897
3898 private void deactivateGracePeriod() {
3899 for (Account account : getAccounts()) {
3900 account.deactivateGracePeriod();
3901 }
3902 }
3903
3904 public void refreshAllPresences() {
3905 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3906 for (Account account : getAccounts()) {
3907 if (account.isEnabled()) {
3908 sendPresence(account, includeIdleTimestamp);
3909 }
3910 }
3911 }
3912
3913 private void refreshAllFcmTokens() {
3914 for (Account account : getAccounts()) {
3915 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3916 mPushManagementService.registerPushTokenOnServer(account);
3917 }
3918 }
3919 }
3920
3921 private void sendOfflinePresence(final Account account) {
3922 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
3923 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3924 }
3925
3926 public MessageGenerator getMessageGenerator() {
3927 return this.mMessageGenerator;
3928 }
3929
3930 public PresenceGenerator getPresenceGenerator() {
3931 return this.mPresenceGenerator;
3932 }
3933
3934 public IqGenerator getIqGenerator() {
3935 return this.mIqGenerator;
3936 }
3937
3938 public IqParser getIqParser() {
3939 return this.mIqParser;
3940 }
3941
3942 public JingleConnectionManager getJingleConnectionManager() {
3943 return this.mJingleConnectionManager;
3944 }
3945
3946 public MessageArchiveService getMessageArchiveService() {
3947 return this.mMessageArchiveService;
3948 }
3949
3950 public QuickConversationsService getQuickConversationsService() {
3951 return this.mQuickConversationsService;
3952 }
3953
3954 public List<Contact> findContacts(Jid jid, String accountJid) {
3955 ArrayList<Contact> contacts = new ArrayList<>();
3956 for (Account account : getAccounts()) {
3957 if ((account.isEnabled() || accountJid != null)
3958 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
3959 Contact contact = account.getRoster().getContactFromContactList(jid);
3960 if (contact != null) {
3961 contacts.add(contact);
3962 }
3963 }
3964 }
3965 return contacts;
3966 }
3967
3968 public Conversation findFirstMuc(Jid jid) {
3969 for (Conversation conversation : getConversations()) {
3970 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
3971 return conversation;
3972 }
3973 }
3974 return null;
3975 }
3976
3977 public NotificationService getNotificationService() {
3978 return this.mNotificationService;
3979 }
3980
3981 public HttpConnectionManager getHttpConnectionManager() {
3982 return this.mHttpConnectionManager;
3983 }
3984
3985 public void resendFailedMessages(final Message message) {
3986 final Collection<Message> messages = new ArrayList<>();
3987 Message current = message;
3988 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3989 messages.add(current);
3990 if (current.mergeable(current.next())) {
3991 current = current.next();
3992 } else {
3993 break;
3994 }
3995 }
3996 for (final Message msg : messages) {
3997 msg.setTime(System.currentTimeMillis());
3998 markMessage(msg, Message.STATUS_WAITING);
3999 this.resendMessage(msg, false);
4000 }
4001 if (message.getConversation() instanceof Conversation) {
4002 ((Conversation) message.getConversation()).sort();
4003 }
4004 updateConversationUi();
4005 }
4006
4007 public void clearConversationHistory(final Conversation conversation) {
4008 final long clearDate;
4009 final String reference;
4010 if (conversation.countMessages() > 0) {
4011 Message latestMessage = conversation.getLatestMessage();
4012 clearDate = latestMessage.getTimeSent() + 1000;
4013 reference = latestMessage.getServerMsgId();
4014 } else {
4015 clearDate = System.currentTimeMillis();
4016 reference = null;
4017 }
4018 conversation.clearMessages();
4019 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4020 conversation.setLastClearHistory(clearDate, reference);
4021 Runnable runnable = () -> {
4022 databaseBackend.deleteMessagesInConversation(conversation);
4023 databaseBackend.updateConversation(conversation);
4024 };
4025 mDatabaseWriterExecutor.execute(runnable);
4026 }
4027
4028 public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
4029 if (blockable != null && blockable.getBlockedJid() != null) {
4030 final Jid jid = blockable.getBlockedJid();
4031 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
4032
4033 @Override
4034 public void onIqPacketReceived(final Account account, final IqPacket packet) {
4035 if (packet.getType() == IqPacket.TYPE.RESULT) {
4036 account.getBlocklist().add(jid);
4037 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4038 }
4039 }
4040 });
4041 if (removeBlockedConversations(blockable.getAccount(), jid)) {
4042 updateConversationUi();
4043 return true;
4044 } else {
4045 return false;
4046 }
4047 } else {
4048 return false;
4049 }
4050 }
4051
4052 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4053 boolean removed = false;
4054 synchronized (this.conversations) {
4055 boolean domainJid = blockedJid.getLocal() == null;
4056 for (Conversation conversation : this.conversations) {
4057 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4058 || blockedJid.equals(conversation.getJid().asBareJid());
4059 if (conversation.getAccount() == account
4060 && conversation.getMode() == Conversation.MODE_SINGLE
4061 && jidMatches) {
4062 this.conversations.remove(conversation);
4063 markRead(conversation);
4064 conversation.setStatus(Conversation.STATUS_ARCHIVED);
4065 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4066 updateConversation(conversation);
4067 removed = true;
4068 }
4069 }
4070 }
4071 return removed;
4072 }
4073
4074 public void sendUnblockRequest(final Blockable blockable) {
4075 if (blockable != null && blockable.getJid() != null) {
4076 final Jid jid = blockable.getBlockedJid();
4077 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4078 @Override
4079 public void onIqPacketReceived(final Account account, final IqPacket packet) {
4080 if (packet.getType() == IqPacket.TYPE.RESULT) {
4081 account.getBlocklist().remove(jid);
4082 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4083 }
4084 }
4085 });
4086 }
4087 }
4088
4089 public void publishDisplayName(Account account) {
4090 String displayName = account.getDisplayName();
4091 final IqPacket request;
4092 if (TextUtils.isEmpty(displayName)) {
4093 request = mIqGenerator.deleteNode(Namespace.NICK);
4094 } else {
4095 request = mIqGenerator.publishNick(displayName);
4096 }
4097 mAvatarService.clear(account);
4098 sendIqPacket(account, request, (account1, packet) -> {
4099 if (packet.getType() == IqPacket.TYPE.ERROR) {
4100 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name "+packet.toString());
4101 }
4102 });
4103 }
4104
4105 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4106 ServiceDiscoveryResult result = discoCache.get(key);
4107 if (result != null) {
4108 return result;
4109 } else {
4110 result = databaseBackend.findDiscoveryResult(key.first, key.second);
4111 if (result != null) {
4112 discoCache.put(key, result);
4113 }
4114 return result;
4115 }
4116 }
4117
4118 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
4119 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
4120 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
4121 if (disco != null) {
4122 presence.setServiceDiscoveryResult(disco);
4123 } else {
4124 if (!account.inProgressDiscoFetches.contains(key)) {
4125 account.inProgressDiscoFetches.add(key);
4126 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4127 request.setTo(jid);
4128 final String node = presence.getNode();
4129 final String ver = presence.getVer();
4130 final Element query = request.query("http://jabber.org/protocol/disco#info");
4131 if (node != null && ver != null) {
4132 query.setAttribute("node",node+"#"+ver);
4133 }
4134 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
4135 sendIqPacket(account, request, (a, response) -> {
4136 if (response.getType() == IqPacket.TYPE.RESULT) {
4137 ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
4138 if (presence.getVer().equals(discoveryResult.getVer())) {
4139 databaseBackend.insertDiscoveryResult(discoveryResult);
4140 injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
4141 } else {
4142 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
4143 }
4144 }
4145 a.inProgressDiscoFetches.remove(key);
4146 });
4147 }
4148 }
4149 }
4150
4151 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
4152 for (Contact contact : roster.getContacts()) {
4153 for (Presence presence : contact.getPresences().getPresences().values()) {
4154 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
4155 presence.setServiceDiscoveryResult(disco);
4156 }
4157 }
4158 }
4159 }
4160
4161 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
4162 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
4163 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4164 request.addChild("prefs", version.namespace);
4165 sendIqPacket(account, request, (account1, packet) -> {
4166 Element prefs = packet.findChild("prefs", version.namespace);
4167 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
4168 callback.onPreferencesFetched(prefs);
4169 } else {
4170 callback.onPreferencesFetchFailed();
4171 }
4172 });
4173 }
4174
4175 public PushManagementService getPushManagementService() {
4176 return mPushManagementService;
4177 }
4178
4179 public void changeStatus(Account account, PresenceTemplate template, String signature) {
4180 if (!template.getStatusMessage().isEmpty()) {
4181 databaseBackend.insertPresenceTemplate(template);
4182 }
4183 account.setPgpSignature(signature);
4184 account.setPresenceStatus(template.getStatus());
4185 account.setPresenceStatusMessage(template.getStatusMessage());
4186 databaseBackend.updateAccount(account);
4187 sendPresence(account);
4188 }
4189
4190 public List<PresenceTemplate> getPresenceTemplates(Account account) {
4191 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
4192 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
4193 if (!templates.contains(template)) {
4194 templates.add(0, template);
4195 }
4196 }
4197 return templates;
4198 }
4199
4200 public void saveConversationAsBookmark(Conversation conversation, String name) {
4201 Account account = conversation.getAccount();
4202 Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
4203 if (!conversation.getJid().isBareJid()) {
4204 bookmark.setNick(conversation.getJid().getResource());
4205 }
4206 if (!TextUtils.isEmpty(name)) {
4207 bookmark.setBookmarkName(name);
4208 }
4209 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
4210 account.getBookmarks().add(bookmark);
4211 pushBookmarks(account);
4212 bookmark.setConversation(conversation);
4213 }
4214
4215 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
4216 boolean performedVerification = false;
4217 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
4218 for (XmppUri.Fingerprint fp : fingerprints) {
4219 if (fp.type == XmppUri.FingerprintType.OMEMO) {
4220 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4221 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4222 if (fingerprintStatus != null) {
4223 if (!fingerprintStatus.isVerified()) {
4224 performedVerification = true;
4225 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4226 }
4227 } else {
4228 axolotlService.preVerifyFingerprint(contact, fingerprint);
4229 }
4230 }
4231 }
4232 return performedVerification;
4233 }
4234
4235 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
4236 final AxolotlService axolotlService = account.getAxolotlService();
4237 boolean verifiedSomething = false;
4238 for (XmppUri.Fingerprint fp : fingerprints) {
4239 if (fp.type == XmppUri.FingerprintType.OMEMO) {
4240 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4241 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
4242 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4243 if (fingerprintStatus != null) {
4244 if (!fingerprintStatus.isVerified()) {
4245 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4246 verifiedSomething = true;
4247 }
4248 } else {
4249 axolotlService.preVerifyFingerprint(account, fingerprint);
4250 verifiedSomething = true;
4251 }
4252 }
4253 }
4254 return verifiedSomething;
4255 }
4256
4257 public boolean blindTrustBeforeVerification() {
4258 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4259 }
4260
4261 public ShortcutService getShortcutService() {
4262 return mShortcutService;
4263 }
4264
4265 public void pushMamPreferences(Account account, Element prefs) {
4266 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4267 set.addChild(prefs);
4268 sendIqPacket(account, set, null);
4269 }
4270
4271 public interface OnMamPreferencesFetched {
4272 void onPreferencesFetched(Element prefs);
4273
4274 void onPreferencesFetchFailed();
4275 }
4276
4277 public interface OnAccountCreated {
4278 void onAccountCreated(Account account);
4279
4280 void informUser(int r);
4281 }
4282
4283 public interface OnMoreMessagesLoaded {
4284 void onMoreMessagesLoaded(int count, Conversation conversation);
4285
4286 void informUser(int r);
4287 }
4288
4289 public interface OnAccountPasswordChanged {
4290 void onPasswordChangeSucceeded();
4291
4292 void onPasswordChangeFailed();
4293 }
4294
4295 public interface OnRoomDestroy {
4296 void onRoomDestroySucceeded();
4297
4298 void onRoomDestroyFailed();
4299 }
4300
4301 public interface OnAffiliationChanged {
4302 void onAffiliationChangedSuccessful(Jid jid);
4303
4304 void onAffiliationChangeFailed(Jid jid, int resId);
4305 }
4306
4307 public interface OnConversationUpdate {
4308 void onConversationUpdate();
4309 }
4310
4311 public interface OnAccountUpdate {
4312 void onAccountUpdate();
4313 }
4314
4315 public interface OnCaptchaRequested {
4316 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4317 }
4318
4319 public interface OnRosterUpdate {
4320 void onRosterUpdate();
4321 }
4322
4323 public interface OnMucRosterUpdate {
4324 void onMucRosterUpdate();
4325 }
4326
4327 public interface OnConferenceConfigurationFetched {
4328 void onConferenceConfigurationFetched(Conversation conversation);
4329
4330 void onFetchFailed(Conversation conversation, Element error);
4331 }
4332
4333 public interface OnConferenceJoined {
4334 void onConferenceJoined(Conversation conversation);
4335 }
4336
4337 public interface OnConfigurationPushed {
4338 void onPushSucceeded();
4339
4340 void onPushFailed();
4341 }
4342
4343 public interface OnShowErrorToast {
4344 void onShowErrorToast(int resId);
4345 }
4346
4347 public class XmppConnectionBinder extends Binder {
4348 public XmppConnectionService getService() {
4349 return XmppConnectionService.this;
4350 }
4351 }
4352
4353 private class InternalEventReceiver extends BroadcastReceiver {
4354
4355 @Override
4356 public void onReceive(Context context, Intent intent) {
4357 onStartCommand(intent,0,0);
4358 }
4359 }
4360}