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