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