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 account.removeBookmark(bookmark);
1847 final XmppConnection connection = account.getXmppConnection();
1848 if (connection.getFeatures().bookmarks2()) {
1849 IqPacket request = mIqGenerator.deleteItem(Namespace.BOOKMARKS2, bookmark.getJid().asBareJid().toEscapedString());
1850 sendIqPacket(account, request, (a, response) -> {
1851 if (response.getType() == IqPacket.TYPE.ERROR) {
1852 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": unable to delete bookmark " + response.getErrorCondition());
1853 }
1854 });
1855 } else if (connection.getFeatures().bookmarksConversion()) {
1856 pushBookmarksPep(account);
1857 } else {
1858 pushBookmarksPrivateXml(account);
1859 }
1860 }
1861
1862 private void pushBookmarksPrivateXml(Account account) {
1863 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
1864 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1865 Element query = iqPacket.query("jabber:iq:private");
1866 Element storage = query.addChild("storage", "storage:bookmarks");
1867 for (Bookmark bookmark : account.getBookmarks()) {
1868 storage.addChild(bookmark);
1869 }
1870 sendIqPacket(account, iqPacket, mDefaultIqHandler);
1871 }
1872
1873 private void pushBookmarksPep(Account account) {
1874 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
1875 Element storage = new Element("storage", "storage:bookmarks");
1876 for (Bookmark bookmark : account.getBookmarks()) {
1877 storage.addChild(bookmark);
1878 }
1879 pushNodeAndEnforcePublishOptions(account, Namespace.BOOKMARKS, storage, "current", PublishOptions.persistentWhitelistAccess());
1880
1881 }
1882
1883 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options) {
1884 pushNodeAndEnforcePublishOptions(account, node, element, id, options, true);
1885
1886 }
1887
1888 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final String id, final Bundle options, final boolean retry) {
1889 final IqPacket packet = mIqGenerator.publishElement(node, element, id, options);
1890 sendIqPacket(account, packet, (a, response) -> {
1891 if (response.getType() == IqPacket.TYPE.RESULT) {
1892 return;
1893 }
1894 if (retry && PublishOptions.preconditionNotMet(response)) {
1895 pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
1896 @Override
1897 public void onPushSucceeded() {
1898 pushNodeAndEnforcePublishOptions(account, node, element, id, options, false);
1899 }
1900
1901 @Override
1902 public void onPushFailed() {
1903 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to push node configuration (" + node + ")");
1904 }
1905 });
1906 } else {
1907 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error publishing bookmarks (retry=" + retry + ") " + response);
1908 }
1909 });
1910 }
1911
1912 private void restoreFromDatabase() {
1913 synchronized (this.conversations) {
1914 final Map<String, Account> accountLookupTable = new Hashtable<>();
1915 for (Account account : this.accounts) {
1916 accountLookupTable.put(account.getUuid(), account);
1917 }
1918 Log.d(Config.LOGTAG, "restoring conversations...");
1919 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1920 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1921 for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1922 Conversation conversation = iterator.next();
1923 Account account = accountLookupTable.get(conversation.getAccountUuid());
1924 if (account != null) {
1925 conversation.setAccount(account);
1926 } else {
1927 Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1928 iterator.remove();
1929 }
1930 }
1931 long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1932 Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1933 Runnable runnable = () -> {
1934 if (DatabaseBackend.requiresMessageIndexRebuild()) {
1935 DatabaseBackend.getInstance(this).rebuildMessagesIndex();
1936 }
1937 final long deletionDate = getAutomaticMessageDeletionDate();
1938 mLastExpiryRun.set(SystemClock.elapsedRealtime());
1939 if (deletionDate > 0) {
1940 Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1941 databaseBackend.expireOldMessages(deletionDate);
1942 }
1943 Log.d(Config.LOGTAG, "restoring roster...");
1944 for (Account account : accounts) {
1945 databaseBackend.readRoster(account.getRoster());
1946 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1947 }
1948 getBitmapCache().evictAll();
1949 loadPhoneContacts();
1950 Log.d(Config.LOGTAG, "restoring messages...");
1951 final long startMessageRestore = SystemClock.elapsedRealtime();
1952 final Conversation quickLoad = QuickLoader.get(this.conversations);
1953 if (quickLoad != null) {
1954 restoreMessages(quickLoad);
1955 updateConversationUi();
1956 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1957 Log.d(Config.LOGTAG, "quickly restored " + quickLoad.getName() + " after " + diffMessageRestore + "ms");
1958 }
1959 for (Conversation conversation : this.conversations) {
1960 if (quickLoad != conversation) {
1961 restoreMessages(conversation);
1962 }
1963 }
1964 mNotificationService.finishBacklog(false);
1965 restoredFromDatabaseLatch.countDown();
1966 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1967 Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
1968 updateConversationUi();
1969 };
1970 mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
1971 }
1972 }
1973
1974 private void restoreMessages(Conversation conversation) {
1975 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1976 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
1977 conversation.findUnreadMessagesAndCalls(mNotificationService::pushFromBacklog);
1978 }
1979
1980 public void loadPhoneContacts() {
1981 mContactMergerExecutor.execute(() -> {
1982 Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
1983 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1984 for (Account account : accounts) {
1985 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
1986 for (JabberIdContact jidContact : contacts.values()) {
1987 final Contact contact = account.getRoster().getContact(jidContact.getJid());
1988 boolean needsCacheClean = contact.setPhoneContact(jidContact);
1989 if (needsCacheClean) {
1990 getAvatarService().clear(contact);
1991 }
1992 withSystemAccounts.remove(contact);
1993 }
1994 for (Contact contact : withSystemAccounts) {
1995 boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
1996 if (needsCacheClean) {
1997 getAvatarService().clear(contact);
1998 }
1999 }
2000 }
2001 Log.d(Config.LOGTAG, "finished merging phone contacts");
2002 mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
2003 updateRosterUi();
2004 mQuickConversationsService.considerSync();
2005 });
2006 }
2007
2008
2009 public void syncRoster(final Account account) {
2010 unregisterPhoneAccounts(account);
2011 mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
2012 }
2013
2014 public List<Conversation> getConversations() {
2015 return this.conversations;
2016 }
2017
2018 private void markFileDeleted(final File file) {
2019 synchronized (FILENAMES_TO_IGNORE_DELETION) {
2020 if (FILENAMES_TO_IGNORE_DELETION.remove(file.getAbsolutePath())) {
2021 Log.d(Config.LOGTAG, "ignored deletion of " + file.getAbsolutePath());
2022 return;
2023 }
2024 }
2025 final boolean isInternalFile = fileBackend.isInternalFile(file);
2026 final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
2027 Log.d(Config.LOGTAG, "deleted file " + file.getAbsolutePath() + " internal=" + isInternalFile + ", database hits=" + uuids.size());
2028 markUuidsAsDeletedFiles(uuids);
2029 }
2030
2031 private void markUuidsAsDeletedFiles(List<String> uuids) {
2032 boolean deleted = false;
2033 for (Conversation conversation : getConversations()) {
2034 deleted |= conversation.markAsDeleted(uuids);
2035 }
2036 for (final String uuid : uuids) {
2037 evictPreview(uuid);
2038 }
2039 if (deleted) {
2040 updateConversationUi();
2041 }
2042 }
2043
2044 private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
2045 boolean changed = false;
2046 for (Conversation conversation : getConversations()) {
2047 changed |= conversation.markAsChanged(infos);
2048 }
2049 if (changed) {
2050 updateConversationUi();
2051 }
2052 }
2053
2054 public void populateWithOrderedConversations(final List<Conversation> list) {
2055 populateWithOrderedConversations(list, true, true);
2056 }
2057
2058 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
2059 populateWithOrderedConversations(list, includeNoFileUpload, true);
2060 }
2061
2062 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
2063 final List<String> orderedUuids;
2064 if (sort) {
2065 orderedUuids = null;
2066 } else {
2067 orderedUuids = new ArrayList<>();
2068 for (Conversation conversation : list) {
2069 orderedUuids.add(conversation.getUuid());
2070 }
2071 }
2072 list.clear();
2073 if (includeNoFileUpload) {
2074 list.addAll(getConversations());
2075 } else {
2076 for (Conversation conversation : getConversations()) {
2077 if (conversation.getMode() == Conversation.MODE_SINGLE
2078 || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
2079 list.add(conversation);
2080 }
2081 }
2082 }
2083 try {
2084 if (orderedUuids != null) {
2085 Collections.sort(list, (a, b) -> {
2086 final int indexA = orderedUuids.indexOf(a.getUuid());
2087 final int indexB = orderedUuids.indexOf(b.getUuid());
2088 if (indexA == -1 || indexB == -1 || indexA == indexB) {
2089 return a.compareTo(b);
2090 }
2091 return indexA - indexB;
2092 });
2093 } else {
2094 Collections.sort(list);
2095 }
2096 } catch (IllegalArgumentException e) {
2097 //ignore
2098 }
2099 }
2100
2101 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
2102 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
2103 return;
2104 } else if (timestamp == 0) {
2105 return;
2106 }
2107 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
2108 final Runnable runnable = () -> {
2109 final Account account = conversation.getAccount();
2110 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
2111 if (messages.size() > 0) {
2112 conversation.addAll(0, messages);
2113 callback.onMoreMessagesLoaded(messages.size(), conversation);
2114 } else if (conversation.hasMessagesLeftOnServer()
2115 && account.isOnlineAndConnected()
2116 && conversation.getLastClearHistory().getTimestamp() == 0) {
2117 final boolean mamAvailable;
2118 if (conversation.getMode() == Conversation.MODE_SINGLE) {
2119 mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
2120 } else {
2121 mamAvailable = conversation.getMucOptions().mamSupport();
2122 }
2123 if (mamAvailable) {
2124 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
2125 if (query != null) {
2126 query.setCallback(callback);
2127 callback.informUser(R.string.fetching_history_from_server);
2128 } else {
2129 callback.informUser(R.string.not_fetching_history_retention_period);
2130 }
2131
2132 }
2133 }
2134 };
2135 mDatabaseReaderExecutor.execute(runnable);
2136 }
2137
2138 public List<Account> getAccounts() {
2139 return this.accounts;
2140 }
2141
2142
2143 /**
2144 * 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)
2145 */
2146 public List<Conversation> findAllConferencesWith(Contact contact) {
2147 final ArrayList<Conversation> results = new ArrayList<>();
2148 for (final Conversation c : conversations) {
2149 if (c.getMode() != Conversation.MODE_MULTI) {
2150 continue;
2151 }
2152 final MucOptions mucOptions = c.getMucOptions();
2153 if (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || (mucOptions != null && mucOptions.isContactInRoom(contact))) {
2154 results.add(c);
2155 }
2156 }
2157 return results;
2158 }
2159
2160 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
2161 for (final Conversation conversation : haystack) {
2162 if (conversation.getContact() == contact) {
2163 return conversation;
2164 }
2165 }
2166 return null;
2167 }
2168
2169 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
2170 if (jid == null) {
2171 return null;
2172 }
2173 for (final Conversation conversation : haystack) {
2174 if ((account == null || conversation.getAccount() == account)
2175 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
2176 return conversation;
2177 }
2178 }
2179 return null;
2180 }
2181
2182 public boolean isConversationsListEmpty(final Conversation ignore) {
2183 synchronized (this.conversations) {
2184 final int size = this.conversations.size();
2185 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
2186 }
2187 }
2188
2189 public boolean isConversationStillOpen(final Conversation conversation) {
2190 synchronized (this.conversations) {
2191 for (Conversation current : this.conversations) {
2192 if (current == conversation) {
2193 return true;
2194 }
2195 }
2196 }
2197 return false;
2198 }
2199
2200 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
2201 return this.findOrCreateConversation(account, jid, muc, false, async);
2202 }
2203
2204 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
2205 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
2206 }
2207
2208 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
2209 synchronized (this.conversations) {
2210 Conversation conversation = find(account, jid);
2211 if (conversation != null) {
2212 return conversation;
2213 }
2214 conversation = databaseBackend.findConversation(account, jid);
2215 final boolean loadMessagesFromDb;
2216 if (conversation != null) {
2217 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2218 conversation.setAccount(account);
2219 if (muc) {
2220 conversation.setMode(Conversation.MODE_MULTI);
2221 conversation.setContactJid(jid);
2222 } else {
2223 conversation.setMode(Conversation.MODE_SINGLE);
2224 conversation.setContactJid(jid.asBareJid());
2225 }
2226 databaseBackend.updateConversation(conversation);
2227 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2228 } else {
2229 String conversationName;
2230 Contact contact = account.getRoster().getContact(jid);
2231 if (contact != null) {
2232 conversationName = contact.getDisplayName();
2233 } else {
2234 conversationName = jid.getLocal();
2235 }
2236 if (muc) {
2237 conversation = new Conversation(conversationName, account, jid,
2238 Conversation.MODE_MULTI);
2239 } else {
2240 conversation = new Conversation(conversationName, account, jid.asBareJid(),
2241 Conversation.MODE_SINGLE);
2242 }
2243 this.databaseBackend.createConversation(conversation);
2244 loadMessagesFromDb = false;
2245 }
2246 final Conversation c = conversation;
2247 final Runnable runnable = () -> {
2248 if (loadMessagesFromDb) {
2249 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2250 updateConversationUi();
2251 c.messagesLoaded.set(true);
2252 }
2253 if (account.getXmppConnection() != null
2254 && !c.getContact().isBlocked()
2255 && account.getXmppConnection().getFeatures().mam()
2256 && !muc) {
2257 if (query == null) {
2258 mMessageArchiveService.query(c);
2259 } else {
2260 if (query.getConversation() == null) {
2261 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2262 }
2263 }
2264 }
2265 if (joinAfterCreate) {
2266 joinMuc(c);
2267 }
2268 };
2269 if (async) {
2270 mDatabaseReaderExecutor.execute(runnable);
2271 } else {
2272 runnable.run();
2273 }
2274 this.conversations.add(conversation);
2275 updateConversationUi();
2276 return conversation;
2277 }
2278 }
2279
2280 public void archiveConversation(Conversation conversation) {
2281 archiveConversation(conversation, true);
2282 }
2283
2284 private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2285 getNotificationService().clear(conversation);
2286 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2287 conversation.setNextMessage(null);
2288 synchronized (this.conversations) {
2289 getMessageArchiveService().kill(conversation);
2290 if (conversation.getMode() == Conversation.MODE_MULTI) {
2291 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2292 final Bookmark bookmark = conversation.getBookmark();
2293 if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2294 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2295 Account account = bookmark.getAccount();
2296 bookmark.setConversation(null);
2297 deleteBookmark(account, bookmark);
2298 } else if (bookmark.autojoin()) {
2299 bookmark.setAutojoin(false);
2300 createBookmark(bookmark.getAccount(), bookmark);
2301 }
2302 }
2303 }
2304 leaveMuc(conversation);
2305 } else {
2306 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2307 stopPresenceUpdatesTo(conversation.getContact());
2308 }
2309 }
2310 updateConversation(conversation);
2311 this.conversations.remove(conversation);
2312 updateConversationUi();
2313 }
2314 }
2315
2316 public void stopPresenceUpdatesTo(Contact contact) {
2317 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2318 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2319 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2320 }
2321
2322 public void createAccount(final Account account) {
2323 account.initAccountServices(this);
2324 databaseBackend.createAccount(account);
2325 this.accounts.add(account);
2326 this.reconnectAccountInBackground(account);
2327 updateAccountUi();
2328 syncEnabledAccountSetting();
2329 toggleForegroundService();
2330 }
2331
2332 private void syncEnabledAccountSetting() {
2333 final boolean hasEnabledAccounts = hasEnabledAccounts();
2334 getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2335 toggleSetProfilePictureActivity(hasEnabledAccounts);
2336 }
2337
2338 private void toggleSetProfilePictureActivity(final boolean enabled) {
2339 try {
2340 final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2341 final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2342 getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2343 } catch (IllegalStateException e) {
2344 Log.d(Config.LOGTAG, "unable to toggle profile picture actvitiy");
2345 }
2346 }
2347
2348 private void provisionAccount(final String address, final String password) {
2349 final Jid jid = Jid.ofEscaped(address);
2350 final Account account = new Account(jid, password);
2351 account.setOption(Account.OPTION_DISABLED, true);
2352 Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
2353 createAccount(account);
2354 }
2355
2356 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2357 new Thread(() -> {
2358 try {
2359 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2360 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2361 if (cert == null) {
2362 callback.informUser(R.string.unable_to_parse_certificate);
2363 return;
2364 }
2365 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2366 if (info == null) {
2367 callback.informUser(R.string.certificate_does_not_contain_jid);
2368 return;
2369 }
2370 if (findAccountByJid(info.first) == null) {
2371 final Account account = new Account(info.first, "");
2372 account.setPrivateKeyAlias(alias);
2373 account.setOption(Account.OPTION_DISABLED, true);
2374 account.setOption(Account.OPTION_FIXED_USERNAME, true);
2375 account.setDisplayName(info.second);
2376 createAccount(account);
2377 callback.onAccountCreated(account);
2378 if (Config.X509_VERIFICATION) {
2379 try {
2380 getMemorizingTrustManager().getNonInteractive(account.getServer()).checkClientTrusted(chain, "RSA");
2381 } catch (CertificateException e) {
2382 callback.informUser(R.string.certificate_chain_is_not_trusted);
2383 }
2384 }
2385 } else {
2386 callback.informUser(R.string.account_already_exists);
2387 }
2388 } catch (Exception e) {
2389 callback.informUser(R.string.unable_to_parse_certificate);
2390 }
2391 }).start();
2392
2393 }
2394
2395 public void updateKeyInAccount(final Account account, final String alias) {
2396 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2397 try {
2398 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2399 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2400 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2401 if (info == null) {
2402 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2403 return;
2404 }
2405 if (account.getJid().asBareJid().equals(info.first)) {
2406 account.setPrivateKeyAlias(alias);
2407 account.setDisplayName(info.second);
2408 databaseBackend.updateAccount(account);
2409 if (Config.X509_VERIFICATION) {
2410 try {
2411 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2412 } catch (CertificateException e) {
2413 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2414 }
2415 account.getAxolotlService().regenerateKeys(true);
2416 }
2417 } else {
2418 showErrorToastInUi(R.string.jid_does_not_match_certificate);
2419 }
2420 } catch (Exception e) {
2421 e.printStackTrace();
2422 }
2423 }
2424
2425 public boolean updateAccount(final Account account) {
2426 if (databaseBackend.updateAccount(account)) {
2427 account.setShowErrorNotification(true);
2428 this.statusListener.onStatusChanged(account);
2429 databaseBackend.updateAccount(account);
2430 reconnectAccountInBackground(account);
2431 updateAccountUi();
2432 getNotificationService().updateErrorNotification();
2433 toggleForegroundService();
2434 syncEnabledAccountSetting();
2435 mChannelDiscoveryService.cleanCache();
2436 return true;
2437 } else {
2438 return false;
2439 }
2440 }
2441
2442 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2443 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2444 sendIqPacket(account, iq, (a, packet) -> {
2445 if (packet.getType() == IqPacket.TYPE.RESULT) {
2446 a.setPassword(newPassword);
2447 a.setOption(Account.OPTION_MAGIC_CREATE, false);
2448 databaseBackend.updateAccount(a);
2449 callback.onPasswordChangeSucceeded();
2450 } else {
2451 callback.onPasswordChangeFailed();
2452 }
2453 });
2454 }
2455
2456 public void deleteAccount(final Account account) {
2457 final boolean connected = account.getStatus() == Account.State.ONLINE;
2458 synchronized (this.conversations) {
2459 if (connected) {
2460 account.getAxolotlService().deleteOmemoIdentity();
2461 }
2462 for (final Conversation conversation : conversations) {
2463 if (conversation.getAccount() == account) {
2464 if (conversation.getMode() == Conversation.MODE_MULTI) {
2465 if (connected) {
2466 leaveMuc(conversation);
2467 }
2468 }
2469 conversations.remove(conversation);
2470 mNotificationService.clear(conversation);
2471 }
2472 }
2473 new Thread(() -> {
2474 for (final Contact contact : account.getRoster().getContacts()) {
2475 contact.unregisterAsPhoneAccount(this);
2476 }
2477 }).start();
2478 if (account.getXmppConnection() != null) {
2479 new Thread(() -> disconnect(account, !connected)).start();
2480 }
2481 final Runnable runnable = () -> {
2482 if (!databaseBackend.deleteAccount(account)) {
2483 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2484 }
2485 };
2486 mDatabaseWriterExecutor.execute(runnable);
2487 this.accounts.remove(account);
2488 this.mRosterSyncTaskManager.clear(account);
2489 updateAccountUi();
2490 mNotificationService.updateErrorNotification();
2491 syncEnabledAccountSetting();
2492 toggleForegroundService();
2493 }
2494 }
2495
2496 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2497 final boolean remainingListeners;
2498 synchronized (LISTENER_LOCK) {
2499 remainingListeners = checkListeners();
2500 if (!this.mOnConversationUpdates.add(listener)) {
2501 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
2502 }
2503 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2504 }
2505 if (remainingListeners) {
2506 switchToForeground();
2507 }
2508 }
2509
2510 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2511 final boolean remainingListeners;
2512 synchronized (LISTENER_LOCK) {
2513 this.mOnConversationUpdates.remove(listener);
2514 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2515 remainingListeners = checkListeners();
2516 }
2517 if (remainingListeners) {
2518 switchToBackground();
2519 }
2520 }
2521
2522 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2523 final boolean remainingListeners;
2524 synchronized (LISTENER_LOCK) {
2525 remainingListeners = checkListeners();
2526 if (!this.mOnShowErrorToasts.add(listener)) {
2527 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
2528 }
2529 }
2530 if (remainingListeners) {
2531 switchToForeground();
2532 }
2533 }
2534
2535 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2536 final boolean remainingListeners;
2537 synchronized (LISTENER_LOCK) {
2538 this.mOnShowErrorToasts.remove(onShowErrorToast);
2539 remainingListeners = checkListeners();
2540 }
2541 if (remainingListeners) {
2542 switchToBackground();
2543 }
2544 }
2545
2546 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2547 final boolean remainingListeners;
2548 synchronized (LISTENER_LOCK) {
2549 remainingListeners = checkListeners();
2550 if (!this.mOnAccountUpdates.add(listener)) {
2551 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
2552 }
2553 }
2554 if (remainingListeners) {
2555 switchToForeground();
2556 }
2557 }
2558
2559 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2560 final boolean remainingListeners;
2561 synchronized (LISTENER_LOCK) {
2562 this.mOnAccountUpdates.remove(listener);
2563 remainingListeners = checkListeners();
2564 }
2565 if (remainingListeners) {
2566 switchToBackground();
2567 }
2568 }
2569
2570 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2571 final boolean remainingListeners;
2572 synchronized (LISTENER_LOCK) {
2573 remainingListeners = checkListeners();
2574 if (!this.mOnCaptchaRequested.add(listener)) {
2575 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
2576 }
2577 }
2578 if (remainingListeners) {
2579 switchToForeground();
2580 }
2581 }
2582
2583 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2584 final boolean remainingListeners;
2585 synchronized (LISTENER_LOCK) {
2586 this.mOnCaptchaRequested.remove(listener);
2587 remainingListeners = checkListeners();
2588 }
2589 if (remainingListeners) {
2590 switchToBackground();
2591 }
2592 }
2593
2594 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2595 final boolean remainingListeners;
2596 synchronized (LISTENER_LOCK) {
2597 remainingListeners = checkListeners();
2598 if (!this.mOnRosterUpdates.add(listener)) {
2599 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
2600 }
2601 }
2602 if (remainingListeners) {
2603 switchToForeground();
2604 }
2605 }
2606
2607 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2608 final boolean remainingListeners;
2609 synchronized (LISTENER_LOCK) {
2610 this.mOnRosterUpdates.remove(listener);
2611 remainingListeners = checkListeners();
2612 }
2613 if (remainingListeners) {
2614 switchToBackground();
2615 }
2616 }
2617
2618 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2619 final boolean remainingListeners;
2620 synchronized (LISTENER_LOCK) {
2621 remainingListeners = checkListeners();
2622 if (!this.mOnUpdateBlocklist.add(listener)) {
2623 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
2624 }
2625 }
2626 if (remainingListeners) {
2627 switchToForeground();
2628 }
2629 }
2630
2631 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2632 final boolean remainingListeners;
2633 synchronized (LISTENER_LOCK) {
2634 this.mOnUpdateBlocklist.remove(listener);
2635 remainingListeners = checkListeners();
2636 }
2637 if (remainingListeners) {
2638 switchToBackground();
2639 }
2640 }
2641
2642 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2643 final boolean remainingListeners;
2644 synchronized (LISTENER_LOCK) {
2645 remainingListeners = checkListeners();
2646 if (!this.mOnKeyStatusUpdated.add(listener)) {
2647 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
2648 }
2649 }
2650 if (remainingListeners) {
2651 switchToForeground();
2652 }
2653 }
2654
2655 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2656 final boolean remainingListeners;
2657 synchronized (LISTENER_LOCK) {
2658 this.mOnKeyStatusUpdated.remove(listener);
2659 remainingListeners = checkListeners();
2660 }
2661 if (remainingListeners) {
2662 switchToBackground();
2663 }
2664 }
2665
2666 public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2667 final boolean remainingListeners;
2668 synchronized (LISTENER_LOCK) {
2669 remainingListeners = checkListeners();
2670 if (!this.onJingleRtpConnectionUpdate.add(listener)) {
2671 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
2672 }
2673 }
2674 if (remainingListeners) {
2675 switchToForeground();
2676 }
2677 }
2678
2679 public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
2680 final boolean remainingListeners;
2681 synchronized (LISTENER_LOCK) {
2682 this.onJingleRtpConnectionUpdate.remove(listener);
2683 remainingListeners = checkListeners();
2684 }
2685 if (remainingListeners) {
2686 switchToBackground();
2687 }
2688 }
2689
2690 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2691 final boolean remainingListeners;
2692 synchronized (LISTENER_LOCK) {
2693 remainingListeners = checkListeners();
2694 if (!this.mOnMucRosterUpdate.add(listener)) {
2695 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
2696 }
2697 }
2698 if (remainingListeners) {
2699 switchToForeground();
2700 }
2701 }
2702
2703 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2704 final boolean remainingListeners;
2705 synchronized (LISTENER_LOCK) {
2706 this.mOnMucRosterUpdate.remove(listener);
2707 remainingListeners = checkListeners();
2708 }
2709 if (remainingListeners) {
2710 switchToBackground();
2711 }
2712 }
2713
2714 public boolean checkListeners() {
2715 return (this.mOnAccountUpdates.size() == 0
2716 && this.mOnConversationUpdates.size() == 0
2717 && this.mOnRosterUpdates.size() == 0
2718 && this.mOnCaptchaRequested.size() == 0
2719 && this.mOnMucRosterUpdate.size() == 0
2720 && this.mOnUpdateBlocklist.size() == 0
2721 && this.mOnShowErrorToasts.size() == 0
2722 && this.onJingleRtpConnectionUpdate.size() == 0
2723 && this.mOnKeyStatusUpdated.size() == 0);
2724 }
2725
2726 private void switchToForeground() {
2727 final boolean broadcastLastActivity = broadcastLastActivity();
2728 for (Conversation conversation : getConversations()) {
2729 if (conversation.getMode() == Conversation.MODE_MULTI) {
2730 conversation.getMucOptions().resetChatState();
2731 } else {
2732 conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
2733 }
2734 }
2735 for (Account account : getAccounts()) {
2736 if (account.getStatus() == Account.State.ONLINE) {
2737 account.deactivateGracePeriod();
2738 final XmppConnection connection = account.getXmppConnection();
2739 if (connection != null) {
2740 if (connection.getFeatures().csi()) {
2741 connection.sendActive();
2742 }
2743 if (broadcastLastActivity) {
2744 sendPresence(account, false); //send new presence but don't include idle because we are not
2745 }
2746 }
2747 }
2748 }
2749 Log.d(Config.LOGTAG, "app switched into foreground");
2750 }
2751
2752 private void switchToBackground() {
2753 final boolean broadcastLastActivity = broadcastLastActivity();
2754 if (broadcastLastActivity) {
2755 mLastActivity = System.currentTimeMillis();
2756 final SharedPreferences.Editor editor = getPreferences().edit();
2757 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2758 editor.apply();
2759 }
2760 for (Account account : getAccounts()) {
2761 if (account.getStatus() == Account.State.ONLINE) {
2762 XmppConnection connection = account.getXmppConnection();
2763 if (connection != null) {
2764 if (broadcastLastActivity) {
2765 sendPresence(account, true);
2766 }
2767 if (connection.getFeatures().csi()) {
2768 connection.sendInactive();
2769 }
2770 }
2771 }
2772 }
2773 this.mNotificationService.setIsInForeground(false);
2774 Log.d(Config.LOGTAG, "app switched into background");
2775 }
2776
2777 private void connectMultiModeConversations(Account account) {
2778 List<Conversation> conversations = getConversations();
2779 for (Conversation conversation : conversations) {
2780 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2781 joinMuc(conversation);
2782 }
2783 }
2784 }
2785
2786 public void mucSelfPingAndRejoin(final Conversation conversation) {
2787 final Account account = conversation.getAccount();
2788 synchronized (account.inProgressConferenceJoins) {
2789 if (account.inProgressConferenceJoins.contains(conversation)) {
2790 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
2791 return;
2792 }
2793 }
2794 synchronized (account.inProgressConferencePings) {
2795 if (!account.inProgressConferencePings.add(conversation)) {
2796 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
2797 return;
2798 }
2799 }
2800 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
2801 final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
2802 ping.setTo(self);
2803 ping.addChild("ping", Namespace.PING);
2804 sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
2805 if (response.getType() == IqPacket.TYPE.ERROR) {
2806 Element error = response.findChild("error");
2807 if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
2808 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
2809 } else {
2810 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
2811 joinMuc(conversation);
2812 }
2813 } else if (response.getType() == IqPacket.TYPE.RESULT) {
2814 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
2815 }
2816 synchronized (account.inProgressConferencePings) {
2817 account.inProgressConferencePings.remove(conversation);
2818 }
2819 });
2820 }
2821
2822 public void joinMuc(Conversation conversation) {
2823 joinMuc(conversation, null, false);
2824 }
2825
2826 public void joinMuc(Conversation conversation, boolean followedInvite) {
2827 joinMuc(conversation, null, followedInvite);
2828 }
2829
2830 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2831 joinMuc(conversation, onConferenceJoined, false);
2832 }
2833
2834 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2835 final Account account = conversation.getAccount();
2836 synchronized (account.pendingConferenceJoins) {
2837 account.pendingConferenceJoins.remove(conversation);
2838 }
2839 synchronized (account.pendingConferenceLeaves) {
2840 account.pendingConferenceLeaves.remove(conversation);
2841 }
2842 if (account.getStatus() == Account.State.ONLINE) {
2843 synchronized (account.inProgressConferenceJoins) {
2844 account.inProgressConferenceJoins.add(conversation);
2845 }
2846 if (Config.MUC_LEAVE_BEFORE_JOIN) {
2847 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2848 }
2849 conversation.resetMucOptions();
2850 if (onConferenceJoined != null) {
2851 conversation.getMucOptions().flagNoAutoPushConfiguration();
2852 }
2853 conversation.setHasMessagesLeftOnServer(false);
2854 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2855
2856 private void join(Conversation conversation) {
2857 Account account = conversation.getAccount();
2858 final MucOptions mucOptions = conversation.getMucOptions();
2859
2860 if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
2861 synchronized (account.inProgressConferenceJoins) {
2862 account.inProgressConferenceJoins.remove(conversation);
2863 }
2864 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
2865 updateConversationUi();
2866 if (onConferenceJoined != null) {
2867 onConferenceJoined.onConferenceJoined(conversation);
2868 }
2869 return;
2870 }
2871
2872 final Jid joinJid = mucOptions.getSelf().getFullJid();
2873 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2874 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2875 packet.setTo(joinJid);
2876 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2877 if (conversation.getMucOptions().getPassword() != null) {
2878 x.addChild("password").setContent(mucOptions.getPassword());
2879 }
2880
2881 if (mucOptions.mamSupport()) {
2882 // Use MAM instead of the limited muc history to get history
2883 x.addChild("history").setAttribute("maxchars", "0");
2884 } else {
2885 // Fallback to muc history
2886 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2887 }
2888 sendPresencePacket(account, packet);
2889 if (onConferenceJoined != null) {
2890 onConferenceJoined.onConferenceJoined(conversation);
2891 }
2892 if (!joinJid.equals(conversation.getJid())) {
2893 conversation.setContactJid(joinJid);
2894 databaseBackend.updateConversation(conversation);
2895 }
2896
2897 if (mucOptions.mamSupport()) {
2898 getMessageArchiveService().catchupMUC(conversation);
2899 }
2900 if (mucOptions.isPrivateAndNonAnonymous()) {
2901 fetchConferenceMembers(conversation);
2902
2903 if (followedInvite) {
2904 final Bookmark bookmark = conversation.getBookmark();
2905 if (bookmark != null) {
2906 if (!bookmark.autojoin()) {
2907 bookmark.setAutojoin(true);
2908 createBookmark(account, bookmark);
2909 }
2910 } else {
2911 saveConversationAsBookmark(conversation, null);
2912 }
2913 }
2914 }
2915 synchronized (account.inProgressConferenceJoins) {
2916 account.inProgressConferenceJoins.remove(conversation);
2917 sendUnsentMessages(conversation);
2918 }
2919 }
2920
2921 @Override
2922 public void onConferenceConfigurationFetched(Conversation conversation) {
2923 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2924 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2925 return;
2926 }
2927 join(conversation);
2928 }
2929
2930 @Override
2931 public void onFetchFailed(final Conversation conversation, final String errorCondition) {
2932 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2933 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
2934 return;
2935 }
2936 if ("remote-server-not-found".equals(errorCondition)) {
2937 synchronized (account.inProgressConferenceJoins) {
2938 account.inProgressConferenceJoins.remove(conversation);
2939 }
2940 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2941 updateConversationUi();
2942 } else {
2943 join(conversation);
2944 fetchConferenceConfiguration(conversation);
2945 }
2946 }
2947 });
2948 updateConversationUi();
2949 } else {
2950 synchronized (account.pendingConferenceJoins) {
2951 account.pendingConferenceJoins.add(conversation);
2952 }
2953 conversation.resetMucOptions();
2954 conversation.setHasMessagesLeftOnServer(false);
2955 updateConversationUi();
2956 }
2957 }
2958
2959 private void fetchConferenceMembers(final Conversation conversation) {
2960 final Account account = conversation.getAccount();
2961 final AxolotlService axolotlService = account.getAxolotlService();
2962 final String[] affiliations = {"member", "admin", "owner"};
2963 OnIqPacketReceived callback = new OnIqPacketReceived() {
2964
2965 private int i = 0;
2966 private boolean success = true;
2967
2968 @Override
2969 public void onIqPacketReceived(Account account, IqPacket packet) {
2970 final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
2971 Element query = packet.query("http://jabber.org/protocol/muc#admin");
2972 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2973 for (Element child : query.getChildren()) {
2974 if ("item".equals(child.getName())) {
2975 MucOptions.User user = AbstractParser.parseItem(conversation, child);
2976 if (!user.realJidMatchesAccount()) {
2977 boolean isNew = conversation.getMucOptions().updateUser(user);
2978 Contact contact = user.getContact();
2979 if (omemoEnabled
2980 && isNew
2981 && user.getRealJid() != null
2982 && (contact == null || !contact.mutualPresenceSubscription())
2983 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2984 axolotlService.fetchDeviceIds(user.getRealJid());
2985 }
2986 }
2987 }
2988 }
2989 } else {
2990 success = false;
2991 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2992 }
2993 ++i;
2994 if (i >= affiliations.length) {
2995 List<Jid> members = conversation.getMucOptions().getMembers(true);
2996 if (success) {
2997 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2998 boolean changed = false;
2999 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
3000 Jid jid = iterator.next();
3001 if (!members.contains(jid) && !members.contains(jid.getDomain())) {
3002 iterator.remove();
3003 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
3004 changed = true;
3005 }
3006 }
3007 if (changed) {
3008 conversation.setAcceptedCryptoTargets(cryptoTargets);
3009 updateConversation(conversation);
3010 }
3011 }
3012 getAvatarService().clear(conversation);
3013 updateMucRosterUi();
3014 updateConversationUi();
3015 }
3016 }
3017 };
3018 for (String affiliation : affiliations) {
3019 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3020 }
3021 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3022 }
3023
3024 public void providePasswordForMuc(Conversation conversation, String password) {
3025 if (conversation.getMode() == Conversation.MODE_MULTI) {
3026 conversation.getMucOptions().setPassword(password);
3027 if (conversation.getBookmark() != null) {
3028 final Bookmark bookmark = conversation.getBookmark();
3029 if (synchronizeWithBookmarks()) {
3030 bookmark.setAutojoin(true);
3031 }
3032 createBookmark(conversation.getAccount(), bookmark);
3033 }
3034 updateConversation(conversation);
3035 joinMuc(conversation);
3036 }
3037 }
3038
3039 private boolean hasEnabledAccounts() {
3040 if (this.accounts == null) {
3041 return false;
3042 }
3043 for (Account account : this.accounts) {
3044 if (account.isEnabled()) {
3045 return true;
3046 }
3047 }
3048 return false;
3049 }
3050
3051
3052 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3053 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3054 }
3055
3056 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3057 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3058 }
3059
3060
3061 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3062 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
3063 }
3064
3065 public void persistSelfNick(MucOptions.User self) {
3066 final Conversation conversation = self.getConversation();
3067 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
3068 Jid full = self.getFullJid();
3069 if (!full.equals(conversation.getJid())) {
3070 Log.d(Config.LOGTAG, "nick changed. updating");
3071 conversation.setContactJid(full);
3072 databaseBackend.updateConversation(conversation);
3073 }
3074
3075 final Bookmark bookmark = conversation.getBookmark();
3076 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
3077 if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
3078 final Account account = conversation.getAccount();
3079 final String defaultNick = MucOptions.defaultNick(account);
3080 if (TextUtils.isEmpty(bookmarkedNick) && full.getResource().equals(defaultNick)) {
3081 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not overwrite empty bookmark nick with default nick for " + conversation.getJid().asBareJid());
3082 return;
3083 }
3084 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
3085 bookmark.setNick(full.getResource());
3086 createBookmark(bookmark.getAccount(), bookmark);
3087 }
3088 }
3089
3090 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3091 final MucOptions options = conversation.getMucOptions();
3092 final Jid joinJid = options.createJoinJid(nick);
3093 if (joinJid == null) {
3094 return false;
3095 }
3096 if (options.online()) {
3097 Account account = conversation.getAccount();
3098 options.setOnRenameListener(new OnRenameListener() {
3099
3100 @Override
3101 public void onSuccess() {
3102 callback.success(conversation);
3103 }
3104
3105 @Override
3106 public void onFailure() {
3107 callback.error(R.string.nick_in_use, conversation);
3108 }
3109 });
3110
3111 final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous());
3112 packet.setTo(joinJid);
3113 sendPresencePacket(account, packet);
3114 } else {
3115 conversation.setContactJid(joinJid);
3116 databaseBackend.updateConversation(conversation);
3117 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3118 Bookmark bookmark = conversation.getBookmark();
3119 if (bookmark != null) {
3120 bookmark.setNick(nick);
3121 createBookmark(bookmark.getAccount(), bookmark);
3122 }
3123 joinMuc(conversation);
3124 }
3125 }
3126 return true;
3127 }
3128
3129 public void leaveMuc(Conversation conversation) {
3130 leaveMuc(conversation, false);
3131 }
3132
3133 private void leaveMuc(Conversation conversation, boolean now) {
3134 final Account account = conversation.getAccount();
3135 synchronized (account.pendingConferenceJoins) {
3136 account.pendingConferenceJoins.remove(conversation);
3137 }
3138 synchronized (account.pendingConferenceLeaves) {
3139 account.pendingConferenceLeaves.remove(conversation);
3140 }
3141 if (account.getStatus() == Account.State.ONLINE || now) {
3142 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3143 conversation.getMucOptions().setOffline();
3144 Bookmark bookmark = conversation.getBookmark();
3145 if (bookmark != null) {
3146 bookmark.setConversation(null);
3147 }
3148 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3149 } else {
3150 synchronized (account.pendingConferenceLeaves) {
3151 account.pendingConferenceLeaves.add(conversation);
3152 }
3153 }
3154 }
3155
3156 public String findConferenceServer(final Account account) {
3157 String server;
3158 if (account.getXmppConnection() != null) {
3159 server = account.getXmppConnection().getMucServer();
3160 if (server != null) {
3161 return server;
3162 }
3163 }
3164 for (Account other : getAccounts()) {
3165 if (other != account && other.getXmppConnection() != null) {
3166 server = other.getXmppConnection().getMucServer();
3167 if (server != null) {
3168 return server;
3169 }
3170 }
3171 }
3172 return null;
3173 }
3174
3175
3176 public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3177 joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3178 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3179 if (!TextUtils.isEmpty(name)) {
3180 configuration.putString("muc#roomconfig_roomname", name);
3181 }
3182 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3183 @Override
3184 public void onPushSucceeded() {
3185 saveConversationAsBookmark(conversation, name);
3186 callback.success(conversation);
3187 }
3188
3189 @Override
3190 public void onPushFailed() {
3191 if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3192 callback.error(R.string.unable_to_set_channel_configuration, conversation);
3193 } else {
3194 callback.error(R.string.joined_an_existing_channel, conversation);
3195 }
3196 }
3197 });
3198 });
3199 }
3200
3201 public boolean createAdhocConference(final Account account,
3202 final String name,
3203 final Iterable<Jid> jids,
3204 final UiCallback<Conversation> callback) {
3205 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3206 if (account.getStatus() == Account.State.ONLINE) {
3207 try {
3208 String server = findConferenceServer(account);
3209 if (server == null) {
3210 if (callback != null) {
3211 callback.error(R.string.no_conference_server_found, null);
3212 }
3213 return false;
3214 }
3215 final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
3216 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3217 joinMuc(conversation, new OnConferenceJoined() {
3218 @Override
3219 public void onConferenceJoined(final Conversation conversation) {
3220 final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3221 if (!TextUtils.isEmpty(name)) {
3222 configuration.putString("muc#roomconfig_roomname", name);
3223 }
3224 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3225 @Override
3226 public void onPushSucceeded() {
3227 for (Jid invite : jids) {
3228 invite(conversation, invite);
3229 }
3230 for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3231 Jid other = account.getJid().withResource(resource);
3232 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3233 directInvite(conversation, other);
3234 }
3235 saveConversationAsBookmark(conversation, name);
3236 if (callback != null) {
3237 callback.success(conversation);
3238 }
3239 }
3240
3241 @Override
3242 public void onPushFailed() {
3243 archiveConversation(conversation);
3244 if (callback != null) {
3245 callback.error(R.string.conference_creation_failed, conversation);
3246 }
3247 }
3248 });
3249 }
3250 });
3251 return true;
3252 } catch (IllegalArgumentException e) {
3253 if (callback != null) {
3254 callback.error(R.string.conference_creation_failed, null);
3255 }
3256 return false;
3257 }
3258 } else {
3259 if (callback != null) {
3260 callback.error(R.string.not_connected_try_again, null);
3261 }
3262 return false;
3263 }
3264 }
3265
3266 public void fetchConferenceConfiguration(final Conversation conversation) {
3267 fetchConferenceConfiguration(conversation, null);
3268 }
3269
3270 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3271 IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
3272 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3273 @Override
3274 public void onIqPacketReceived(Account account, IqPacket packet) {
3275 if (packet.getType() == IqPacket.TYPE.RESULT) {
3276 final MucOptions mucOptions = conversation.getMucOptions();
3277 final Bookmark bookmark = conversation.getBookmark();
3278 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3279
3280 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3281 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3282 updateConversation(conversation);
3283 }
3284
3285 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3286 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3287 createBookmark(account, bookmark);
3288 }
3289 }
3290
3291
3292 if (callback != null) {
3293 callback.onConferenceConfigurationFetched(conversation);
3294 }
3295
3296
3297 updateConversationUi();
3298 } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3299 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3300 } else {
3301 if (callback != null) {
3302 callback.onFetchFailed(conversation, packet.getErrorCondition());
3303 }
3304 }
3305 }
3306 });
3307 }
3308
3309 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3310 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3311 }
3312
3313 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3314 Log.d(Config.LOGTAG, "pushing node configuration");
3315 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3316 @Override
3317 public void onIqPacketReceived(Account account, IqPacket packet) {
3318 if (packet.getType() == IqPacket.TYPE.RESULT) {
3319 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3320 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3321 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3322 if (x != null) {
3323 Data data = Data.parse(x);
3324 data.submit(options);
3325 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3326 @Override
3327 public void onIqPacketReceived(Account account, IqPacket packet) {
3328 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3329 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3330 callback.onPushSucceeded();
3331 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3332 callback.onPushFailed();
3333 }
3334 }
3335 });
3336 } else if (callback != null) {
3337 callback.onPushFailed();
3338 }
3339 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3340 callback.onPushFailed();
3341 }
3342 }
3343 });
3344 }
3345
3346 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3347 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3348 conversation.setAttribute("accept_non_anonymous", true);
3349 updateConversation(conversation);
3350 }
3351 if (options.containsKey("muc#roomconfig_moderatedroom")) {
3352 final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
3353 options.putString("members_by_default", moderated ? "0" : "1");
3354 }
3355 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3356 request.setTo(conversation.getJid().asBareJid());
3357 request.query("http://jabber.org/protocol/muc#owner");
3358 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3359 @Override
3360 public void onIqPacketReceived(Account account, IqPacket packet) {
3361 if (packet.getType() == IqPacket.TYPE.RESULT) {
3362 final Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3363 data.submit(options);
3364 final IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3365 set.setTo(conversation.getJid().asBareJid());
3366 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3367 sendIqPacket(account, set, new OnIqPacketReceived() {
3368 @Override
3369 public void onIqPacketReceived(Account account, IqPacket packet) {
3370 if (callback != null) {
3371 if (packet.getType() == IqPacket.TYPE.RESULT) {
3372 callback.onPushSucceeded();
3373 } else {
3374 callback.onPushFailed();
3375 }
3376 }
3377 }
3378 });
3379 } else {
3380 if (callback != null) {
3381 callback.onPushFailed();
3382 }
3383 }
3384 }
3385 });
3386 }
3387
3388 public void pushSubjectToConference(final Conversation conference, final String subject) {
3389 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
3390 this.sendMessagePacket(conference.getAccount(), packet);
3391 }
3392
3393 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
3394 final Jid jid = user.asBareJid();
3395 final IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
3396 sendIqPacket(conference.getAccount(), request, (account, response) -> {
3397 if (response.getType() == IqPacket.TYPE.RESULT) {
3398 conference.getMucOptions().changeAffiliation(jid, affiliation);
3399 getAvatarService().clear(conference);
3400 if (callback != null) {
3401 callback.onAffiliationChangedSuccessful(jid);
3402 } else {
3403 Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
3404 }
3405 } else if (callback != null) {
3406 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
3407 } else {
3408 Log.d(Config.LOGTAG, "unable to change affiliation");
3409 }
3410 });
3411 }
3412
3413 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3414 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3415 sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3416 if (packet.getType() != IqPacket.TYPE.RESULT) {
3417 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
3418 }
3419 });
3420 }
3421
3422 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3423 IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3424 request.setTo(conversation.getJid().asBareJid());
3425 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3426 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3427 @Override
3428 public void onIqPacketReceived(Account account, IqPacket packet) {
3429 if (packet.getType() == IqPacket.TYPE.RESULT) {
3430 if (callback != null) {
3431 callback.onRoomDestroySucceeded();
3432 }
3433 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3434 if (callback != null) {
3435 callback.onRoomDestroyFailed();
3436 }
3437 }
3438 }
3439 });
3440 }
3441
3442 private void disconnect(Account account, boolean force) {
3443 if ((account.getStatus() == Account.State.ONLINE)
3444 || (account.getStatus() == Account.State.DISABLED)) {
3445 final XmppConnection connection = account.getXmppConnection();
3446 if (!force) {
3447 List<Conversation> conversations = getConversations();
3448 for (Conversation conversation : conversations) {
3449 if (conversation.getAccount() == account) {
3450 if (conversation.getMode() == Conversation.MODE_MULTI) {
3451 leaveMuc(conversation, true);
3452 }
3453 }
3454 }
3455 sendOfflinePresence(account);
3456 }
3457 connection.disconnect(force);
3458 }
3459 }
3460
3461 @Override
3462 public IBinder onBind(Intent intent) {
3463 return mBinder;
3464 }
3465
3466 public void updateMessage(Message message) {
3467 updateMessage(message, true);
3468 }
3469
3470 public void updateMessage(Message message, boolean includeBody) {
3471 databaseBackend.updateMessage(message, includeBody);
3472 updateConversationUi();
3473 }
3474
3475 public void createMessageAsync(final Message message) {
3476 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
3477 }
3478
3479 public void updateMessage(Message message, String uuid) {
3480 if (!databaseBackend.updateMessage(message, uuid)) {
3481 Log.e(Config.LOGTAG, "error updated message in DB after edit");
3482 }
3483 updateConversationUi();
3484 }
3485
3486 protected void syncDirtyContacts(Account account) {
3487 for (Contact contact : account.getRoster().getContacts()) {
3488 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3489 pushContactToServer(contact);
3490 }
3491 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3492 deleteContactOnServer(contact);
3493 }
3494 }
3495 }
3496
3497 protected void unregisterPhoneAccounts(final Account account) {
3498 for (final Contact contact : account.getRoster().getContacts()) {
3499 if (!contact.showInRoster()) {
3500 contact.unregisterAsPhoneAccount(this);
3501 }
3502 }
3503 }
3504
3505 public void createContact(final Contact contact, final boolean autoGrant) {
3506 createContact(contact, autoGrant, null);
3507 }
3508
3509 public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
3510 if (autoGrant) {
3511 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3512 contact.setOption(Contact.Options.ASKING);
3513 }
3514 pushContactToServer(contact, preAuth);
3515 }
3516
3517 public void pushContactToServer(final Contact contact) {
3518 pushContactToServer(contact, null);
3519 }
3520
3521 private void pushContactToServer(final Contact contact, final String preAuth) {
3522 contact.resetOption(Contact.Options.DIRTY_DELETE);
3523 contact.setOption(Contact.Options.DIRTY_PUSH);
3524 final Account account = contact.getAccount();
3525 if (account.getStatus() == Account.State.ONLINE) {
3526 final boolean ask = contact.getOption(Contact.Options.ASKING);
3527 final boolean sendUpdates = contact
3528 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3529 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3530 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3531 iq.query(Namespace.ROSTER).addChild(contact.asElement());
3532 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3533 if (sendUpdates) {
3534 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3535 }
3536 if (ask) {
3537 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
3538 }
3539 } else {
3540 syncRoster(contact.getAccount());
3541 }
3542 }
3543
3544 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3545 new Thread(() -> {
3546 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3547 final int size = Config.AVATAR_SIZE;
3548 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3549 if (avatar != null) {
3550 if (!getFileBackend().save(avatar)) {
3551 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3552 return;
3553 }
3554 avatar.owner = conversation.getJid().asBareJid();
3555 publishMucAvatar(conversation, avatar, callback);
3556 } else {
3557 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3558 }
3559 }).start();
3560 }
3561
3562 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3563 new Thread(() -> {
3564 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3565 final int size = Config.AVATAR_SIZE;
3566 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3567 if (avatar != null) {
3568 if (!getFileBackend().save(avatar)) {
3569 Log.d(Config.LOGTAG, "unable to save vcard");
3570 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3571 return;
3572 }
3573 publishAvatar(account, avatar, callback);
3574 } else {
3575 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3576 }
3577 }).start();
3578
3579 }
3580
3581 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3582 final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3583 sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3584 boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3585 if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3586 Element vcard = response.findChild("vCard", "vcard-temp");
3587 if (vcard == null) {
3588 vcard = new Element("vCard", "vcard-temp");
3589 }
3590 Element photo = vcard.findChild("PHOTO");
3591 if (photo == null) {
3592 photo = vcard.addChild("PHOTO");
3593 }
3594 photo.clearChildren();
3595 photo.addChild("TYPE").setContent(avatar.type);
3596 photo.addChild("BINVAL").setContent(avatar.image);
3597 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3598 publication.setTo(conversation.getJid().asBareJid());
3599 publication.addChild(vcard);
3600 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3601 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3602 callback.onAvatarPublicationSucceeded();
3603 } else {
3604 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3605 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3606 }
3607 });
3608 } else {
3609 Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
3610 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3611 }
3612 });
3613 }
3614
3615 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3616 final Bundle options;
3617 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3618 options = PublishOptions.openAccess();
3619 } else {
3620 options = null;
3621 }
3622 publishAvatar(account, avatar, options, true, callback);
3623 }
3624
3625 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3626 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
3627 IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3628 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3629
3630 @Override
3631 public void onIqPacketReceived(Account account, IqPacket result) {
3632 if (result.getType() == IqPacket.TYPE.RESULT) {
3633 publishAvatarMetadata(account, avatar, options, true, callback);
3634 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3635 pushNodeConfiguration(account, "urn:xmpp:avatar:data", options, new OnConfigurationPushed() {
3636 @Override
3637 public void onPushSucceeded() {
3638 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
3639 publishAvatar(account, avatar, options, false, callback);
3640 }
3641
3642 @Override
3643 public void onPushFailed() {
3644 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
3645 publishAvatar(account, avatar, null, false, callback);
3646 }
3647 });
3648 } else {
3649 Element error = result.findChild("error");
3650 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3651 if (callback != null) {
3652 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3653 }
3654 }
3655 }
3656 });
3657 }
3658
3659 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3660 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3661 sendIqPacket(account, packet, new OnIqPacketReceived() {
3662 @Override
3663 public void onIqPacketReceived(Account account, IqPacket result) {
3664 if (result.getType() == IqPacket.TYPE.RESULT) {
3665 if (account.setAvatar(avatar.getFilename())) {
3666 getAvatarService().clear(account);
3667 databaseBackend.updateAccount(account);
3668 notifyAccountAvatarHasChanged(account);
3669 }
3670 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3671 if (callback != null) {
3672 callback.onAvatarPublicationSucceeded();
3673 }
3674 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3675 pushNodeConfiguration(account, "urn:xmpp:avatar:metadata", options, new OnConfigurationPushed() {
3676 @Override
3677 public void onPushSucceeded() {
3678 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
3679 publishAvatarMetadata(account, avatar, options, false, callback);
3680 }
3681
3682 @Override
3683 public void onPushFailed() {
3684 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
3685 publishAvatarMetadata(account, avatar, null, false, callback);
3686 }
3687 });
3688 } else {
3689 if (callback != null) {
3690 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3691 }
3692 }
3693 }
3694 });
3695 }
3696
3697 public void republishAvatarIfNeeded(Account account) {
3698 if (account.getAxolotlService().isPepBroken()) {
3699 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3700 return;
3701 }
3702 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3703 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3704
3705 private Avatar parseAvatar(IqPacket packet) {
3706 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3707 if (pubsub != null) {
3708 Element items = pubsub.findChild("items");
3709 if (items != null) {
3710 return Avatar.parseMetadata(items);
3711 }
3712 }
3713 return null;
3714 }
3715
3716 private boolean errorIsItemNotFound(IqPacket packet) {
3717 Element error = packet.findChild("error");
3718 return packet.getType() == IqPacket.TYPE.ERROR
3719 && error != null
3720 && error.hasChild("item-not-found");
3721 }
3722
3723 @Override
3724 public void onIqPacketReceived(Account account, IqPacket packet) {
3725 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
3726 Avatar serverAvatar = parseAvatar(packet);
3727 if (serverAvatar == null && account.getAvatar() != null) {
3728 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
3729 if (avatar != null) {
3730 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3731 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3732 } else {
3733 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3734 }
3735 }
3736 }
3737 }
3738 });
3739 }
3740
3741 public void fetchAvatar(Account account, Avatar avatar) {
3742 fetchAvatar(account, avatar, null);
3743 }
3744
3745 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3746 final String KEY = generateFetchKey(account, avatar);
3747 synchronized (this.mInProgressAvatarFetches) {
3748 if (mInProgressAvatarFetches.add(KEY)) {
3749 switch (avatar.origin) {
3750 case PEP:
3751 this.mInProgressAvatarFetches.add(KEY);
3752 fetchAvatarPep(account, avatar, callback);
3753 break;
3754 case VCARD:
3755 this.mInProgressAvatarFetches.add(KEY);
3756 fetchAvatarVcard(account, avatar, callback);
3757 break;
3758 }
3759 } else if (avatar.origin == Avatar.Origin.PEP) {
3760 mOmittedPepAvatarFetches.add(KEY);
3761 } else {
3762 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
3763 }
3764 }
3765 }
3766
3767 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3768 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3769 sendIqPacket(account, packet, (a, result) -> {
3770 synchronized (mInProgressAvatarFetches) {
3771 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3772 }
3773 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3774 if (result.getType() == IqPacket.TYPE.RESULT) {
3775 avatar.image = mIqParser.avatarData(result);
3776 if (avatar.image != null) {
3777 if (getFileBackend().save(avatar)) {
3778 if (a.getJid().asBareJid().equals(avatar.owner)) {
3779 if (a.setAvatar(avatar.getFilename())) {
3780 databaseBackend.updateAccount(a);
3781 }
3782 getAvatarService().clear(a);
3783 updateConversationUi();
3784 updateAccountUi();
3785 } else {
3786 final Contact contact = a.getRoster().getContact(avatar.owner);
3787 contact.setAvatar(avatar);
3788 syncRoster(account);
3789 getAvatarService().clear(contact);
3790 updateConversationUi();
3791 updateRosterUi();
3792 }
3793 if (callback != null) {
3794 callback.success(avatar);
3795 }
3796 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
3797 return;
3798 }
3799 } else {
3800
3801 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3802 }
3803 } else {
3804 Element error = result.findChild("error");
3805 if (error == null) {
3806 Log.d(Config.LOGTAG, ERROR + "(server error)");
3807 } else {
3808 Log.d(Config.LOGTAG, ERROR + error.toString());
3809 }
3810 }
3811 if (callback != null) {
3812 callback.error(0, null);
3813 }
3814
3815 });
3816 }
3817
3818 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3819 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3820 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3821 @Override
3822 public void onIqPacketReceived(Account account, IqPacket packet) {
3823 final boolean previouslyOmittedPepFetch;
3824 synchronized (mInProgressAvatarFetches) {
3825 final String KEY = generateFetchKey(account, avatar);
3826 mInProgressAvatarFetches.remove(KEY);
3827 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
3828 }
3829 if (packet.getType() == IqPacket.TYPE.RESULT) {
3830 Element vCard = packet.findChild("vCard", "vcard-temp");
3831 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3832 String image = photo != null ? photo.findChildContent("BINVAL") : null;
3833 if (image != null) {
3834 avatar.image = image;
3835 if (getFileBackend().save(avatar)) {
3836 Log.d(Config.LOGTAG, account.getJid().asBareJid()
3837 + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
3838 if (avatar.owner.isBareJid()) {
3839 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3840 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3841 account.setAvatar(avatar.getFilename());
3842 databaseBackend.updateAccount(account);
3843 getAvatarService().clear(account);
3844 updateAccountUi();
3845 } else {
3846 final Contact contact = account.getRoster().getContact(avatar.owner);
3847 contact.setAvatar(avatar, previouslyOmittedPepFetch);
3848 syncRoster(account);
3849 getAvatarService().clear(contact);
3850 updateRosterUi();
3851 }
3852 updateConversationUi();
3853 } else {
3854 Conversation conversation = find(account, avatar.owner.asBareJid());
3855 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3856 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3857 if (user != null) {
3858 if (user.setAvatar(avatar)) {
3859 getAvatarService().clear(user);
3860 updateConversationUi();
3861 updateMucRosterUi();
3862 }
3863 if (user.getRealJid() != null) {
3864 Contact contact = account.getRoster().getContact(user.getRealJid());
3865 contact.setAvatar(avatar);
3866 syncRoster(account);
3867 getAvatarService().clear(contact);
3868 updateRosterUi();
3869 }
3870 }
3871 }
3872 }
3873 }
3874 }
3875 }
3876 }
3877 });
3878 }
3879
3880 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3881 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3882 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3883
3884 @Override
3885 public void onIqPacketReceived(Account account, IqPacket packet) {
3886 if (packet.getType() == IqPacket.TYPE.RESULT) {
3887 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3888 if (pubsub != null) {
3889 Element items = pubsub.findChild("items");
3890 if (items != null) {
3891 Avatar avatar = Avatar.parseMetadata(items);
3892 if (avatar != null) {
3893 avatar.owner = account.getJid().asBareJid();
3894 if (fileBackend.isAvatarCached(avatar)) {
3895 if (account.setAvatar(avatar.getFilename())) {
3896 databaseBackend.updateAccount(account);
3897 }
3898 getAvatarService().clear(account);
3899 callback.success(avatar);
3900 } else {
3901 fetchAvatarPep(account, avatar, callback);
3902 }
3903 return;
3904 }
3905 }
3906 }
3907 }
3908 callback.error(0, null);
3909 }
3910 });
3911 }
3912
3913 public void notifyAccountAvatarHasChanged(final Account account) {
3914 final XmppConnection connection = account.getXmppConnection();
3915 if (connection != null && connection.getFeatures().bookmarksConversion()) {
3916 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
3917 for (Conversation conversation : conversations) {
3918 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
3919 final MucOptions mucOptions = conversation.getMucOptions();
3920 if (mucOptions.online()) {
3921 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
3922 packet.setTo(mucOptions.getSelf().getFullJid());
3923 connection.sendPresencePacket(packet);
3924 }
3925 }
3926 }
3927 }
3928 }
3929
3930 public void deleteContactOnServer(Contact contact) {
3931 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3932 contact.resetOption(Contact.Options.DIRTY_PUSH);
3933 contact.setOption(Contact.Options.DIRTY_DELETE);
3934 Account account = contact.getAccount();
3935 if (account.getStatus() == Account.State.ONLINE) {
3936 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3937 Element item = iq.query(Namespace.ROSTER).addChild("item");
3938 item.setAttribute("jid", contact.getJid());
3939 item.setAttribute("subscription", "remove");
3940 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3941 }
3942 }
3943
3944 public void updateConversation(final Conversation conversation) {
3945 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3946 }
3947
3948 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3949 synchronized (account) {
3950 XmppConnection connection = account.getXmppConnection();
3951 if (connection == null) {
3952 connection = createConnection(account);
3953 account.setXmppConnection(connection);
3954 }
3955 boolean hasInternet = hasInternetConnection();
3956 if (account.isEnabled() && hasInternet) {
3957 if (!force) {
3958 disconnect(account, false);
3959 }
3960 Thread thread = new Thread(connection);
3961 connection.setInteractive(interactive);
3962 connection.prepareNewConnection();
3963 connection.interrupt();
3964 thread.start();
3965 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3966 } else {
3967 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3968 account.getRoster().clearPresences();
3969 connection.resetEverything();
3970 final AxolotlService axolotlService = account.getAxolotlService();
3971 if (axolotlService != null) {
3972 axolotlService.resetBrokenness();
3973 }
3974 if (!hasInternet) {
3975 account.setStatus(Account.State.NO_INTERNET);
3976 }
3977 }
3978 }
3979 }
3980
3981 public void reconnectAccountInBackground(final Account account) {
3982 new Thread(() -> reconnectAccount(account, false, true)).start();
3983 }
3984
3985 public void invite(final Conversation conversation, final Jid contact) {
3986 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3987 final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
3988 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
3989 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
3990 }
3991 final MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3992 sendMessagePacket(conversation.getAccount(), packet);
3993 }
3994
3995 public void directInvite(Conversation conversation, Jid jid) {
3996 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3997 sendMessagePacket(conversation.getAccount(), packet);
3998 }
3999
4000 public void resetSendingToWaiting(Account account) {
4001 for (Conversation conversation : getConversations()) {
4002 if (conversation.getAccount() == account) {
4003 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4004 }
4005 }
4006 }
4007
4008 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4009 return markMessage(account, recipient, uuid, status, null);
4010 }
4011
4012 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4013 if (uuid == null) {
4014 return null;
4015 }
4016 for (Conversation conversation : getConversations()) {
4017 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4018 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4019 if (message != null) {
4020 markMessage(message, status, errorMessage);
4021 }
4022 return message;
4023 }
4024 }
4025 return null;
4026 }
4027
4028 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4029 return markMessage(conversation, uuid, status, serverMessageId, null);
4030 }
4031
4032 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body) {
4033 if (uuid == null) {
4034 return false;
4035 } else {
4036 final Message message = conversation.findSentMessageWithUuid(uuid);
4037 if (message != null) {
4038 if (message.getServerMsgId() == null) {
4039 message.setServerMsgId(serverMessageId);
4040 }
4041 if (message.getEncryption() == Message.ENCRYPTION_NONE
4042 && message.isTypeText()
4043 && isBodyModified(message, body)) {
4044 message.setBody(body.content);
4045 if (body.count > 1) {
4046 message.setBodyLanguage(body.language);
4047 }
4048 markMessage(message, status, null, true);
4049 } else {
4050 markMessage(message, status);
4051 }
4052 return true;
4053 } else {
4054 return false;
4055 }
4056 }
4057 }
4058
4059 private static boolean isBodyModified(final Message message, final LocalizedContent body) {
4060 if (body == null || body.content == null) {
4061 return false;
4062 }
4063 return !body.content.equals(message.getBody());
4064 }
4065
4066 public void markMessage(Message message, int status) {
4067 markMessage(message, status, null);
4068 }
4069
4070
4071 public void markMessage(final Message message, final int status, final String errorMessage) {
4072 markMessage(message, status, errorMessage, false);
4073 }
4074
4075 public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4076 final int oldStatus = message.getStatus();
4077 if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4078 return;
4079 }
4080 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4081 return;
4082 }
4083 message.setErrorMessage(errorMessage);
4084 message.setStatus(status);
4085 databaseBackend.updateMessage(message, includeBody);
4086 updateConversationUi();
4087 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4088 mNotificationService.pushFailedDelivery(message);
4089 }
4090 }
4091
4092 private SharedPreferences getPreferences() {
4093 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4094 }
4095
4096 public long getAutomaticMessageDeletionDate() {
4097 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
4098 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4099 }
4100
4101 public long getLongPreference(String name, @IntegerRes int res) {
4102 long defaultValue = getResources().getInteger(res);
4103 try {
4104 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4105 } catch (NumberFormatException e) {
4106 return defaultValue;
4107 }
4108 }
4109
4110 public boolean getBooleanPreference(String name, @BoolRes int res) {
4111 return getPreferences().getBoolean(name, getResources().getBoolean(res));
4112 }
4113
4114 public boolean confirmMessages() {
4115 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4116 }
4117
4118 public boolean allowMessageCorrection() {
4119 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
4120 }
4121
4122 public boolean sendChatStates() {
4123 return getBooleanPreference("chat_states", R.bool.chat_states);
4124 }
4125
4126 private boolean synchronizeWithBookmarks() {
4127 return getBooleanPreference("autojoin", R.bool.autojoin);
4128 }
4129
4130 public boolean useTorToConnect() {
4131 return getBooleanPreference("use_tor", R.bool.use_tor);
4132 }
4133
4134 public boolean showExtendedConnectionOptions() {
4135 return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
4136 }
4137
4138 public boolean broadcastLastActivity() {
4139 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
4140 }
4141
4142 public int unreadCount() {
4143 int count = 0;
4144 for (Conversation conversation : getConversations()) {
4145 count += conversation.unreadCount();
4146 }
4147 return count;
4148 }
4149
4150
4151 private <T> List<T> threadSafeList(Set<T> set) {
4152 synchronized (LISTENER_LOCK) {
4153 return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
4154 }
4155 }
4156
4157 public void showErrorToastInUi(int resId) {
4158 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4159 listener.onShowErrorToast(resId);
4160 }
4161 }
4162
4163 public void updateConversationUi() {
4164 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4165 listener.onConversationUpdate();
4166 }
4167 }
4168
4169 public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
4170 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4171 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4172 }
4173 }
4174
4175 public void notifyJingleRtpConnectionUpdate(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
4176 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4177 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4178 }
4179 }
4180
4181 public void updateAccountUi() {
4182 for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4183 listener.onAccountUpdate();
4184 }
4185 }
4186
4187 public void updateRosterUi() {
4188 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4189 listener.onRosterUpdate();
4190 }
4191 }
4192
4193 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4194 if (mOnCaptchaRequested.size() > 0) {
4195 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4196 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
4197 (int) (captcha.getHeight() * metrics.scaledDensity), false);
4198 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4199 listener.onCaptchaRequested(account, id, data, scaled);
4200 }
4201 return true;
4202 }
4203 return false;
4204 }
4205
4206 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
4207 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
4208 listener.OnUpdateBlocklist(status);
4209 }
4210 }
4211
4212 public void updateMucRosterUi() {
4213 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
4214 listener.onMucRosterUpdate();
4215 }
4216 }
4217
4218 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
4219 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
4220 listener.onKeyStatusUpdated(report);
4221 }
4222 }
4223
4224 public Account findAccountByJid(final Jid jid) {
4225 for (final Account account : this.accounts) {
4226 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
4227 return account;
4228 }
4229 }
4230 return null;
4231 }
4232
4233 public Account findAccountByUuid(final String uuid) {
4234 for (Account account : this.accounts) {
4235 if (account.getUuid().equals(uuid)) {
4236 return account;
4237 }
4238 }
4239 return null;
4240 }
4241
4242 public Conversation findConversationByUuid(String uuid) {
4243 for (Conversation conversation : getConversations()) {
4244 if (conversation.getUuid().equals(uuid)) {
4245 return conversation;
4246 }
4247 }
4248 return null;
4249 }
4250
4251 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4252 List<Conversation> findings = new ArrayList<>();
4253 for (Conversation c : getConversations()) {
4254 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4255 findings.add(c);
4256 }
4257 }
4258 return findings.size() == 1 ? findings.get(0) : null;
4259 }
4260
4261 public boolean markRead(final Conversation conversation, boolean dismiss) {
4262 return markRead(conversation, null, dismiss).size() > 0;
4263 }
4264
4265 public void markRead(final Conversation conversation) {
4266 markRead(conversation, null, true);
4267 }
4268
4269 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4270 if (dismiss) {
4271 mNotificationService.clear(conversation);
4272 }
4273 final List<Message> readMessages = conversation.markRead(upToUuid);
4274 if (readMessages.size() > 0) {
4275 Runnable runnable = () -> {
4276 for (Message message : readMessages) {
4277 databaseBackend.updateMessage(message, false);
4278 }
4279 };
4280 mDatabaseWriterExecutor.execute(runnable);
4281 updateConversationUi();
4282 updateUnreadCountBadge();
4283 return readMessages;
4284 } else {
4285 return readMessages;
4286 }
4287 }
4288
4289 public synchronized void updateUnreadCountBadge() {
4290 int count = unreadCount();
4291 if (unreadCount != count) {
4292 Log.d(Config.LOGTAG, "update unread count to " + count);
4293 if (count > 0) {
4294 ShortcutBadger.applyCount(getApplicationContext(), count);
4295 } else {
4296 ShortcutBadger.removeCount(getApplicationContext());
4297 }
4298 unreadCount = count;
4299 }
4300 }
4301
4302 public void sendReadMarker(final Conversation conversation, String upToUuid) {
4303 final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
4304 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4305 if (readMessages.size() > 0) {
4306 updateConversationUi();
4307 }
4308 final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
4309 if (confirmMessages()
4310 && markable != null
4311 && (markable.trusted() || isPrivateAndNonAnonymousMuc)
4312 && markable.getRemoteMsgId() != null) {
4313 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
4314 final Account account = conversation.getAccount();
4315 final MessagePacket packet = mMessageGenerator.confirm(markable);
4316 this.sendMessagePacket(account, packet);
4317 }
4318 }
4319
4320 public SecureRandom getRNG() {
4321 return this.mRandom;
4322 }
4323
4324 public MemorizingTrustManager getMemorizingTrustManager() {
4325 return this.mMemorizingTrustManager;
4326 }
4327
4328 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4329 this.mMemorizingTrustManager = trustManager;
4330 }
4331
4332 public void updateMemorizingTrustmanager() {
4333 final MemorizingTrustManager tm;
4334 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
4335 if (dontTrustSystemCAs) {
4336 tm = new MemorizingTrustManager(getApplicationContext(), null);
4337 } else {
4338 tm = new MemorizingTrustManager(getApplicationContext());
4339 }
4340 setMemorizingTrustManager(tm);
4341 }
4342
4343 public LruCache<String, Bitmap> getBitmapCache() {
4344 return this.mBitmapCache;
4345 }
4346
4347 public LruCache<String, Drawable> getDrawableCache() {
4348 return this.mDrawableCache;
4349 }
4350
4351 public Collection<String> getKnownHosts() {
4352 final Set<String> hosts = new HashSet<>();
4353 for (final Account account : getAccounts()) {
4354 hosts.add(account.getServer());
4355 for (final Contact contact : account.getRoster().getContacts()) {
4356 if (contact.showInRoster()) {
4357 final String server = contact.getServer();
4358 if (server != null) {
4359 hosts.add(server);
4360 }
4361 }
4362 }
4363 }
4364 if (Config.QUICKSY_DOMAIN != null) {
4365 hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
4366 }
4367 if (Config.DOMAIN_LOCK != null) {
4368 hosts.add(Config.DOMAIN_LOCK);
4369 }
4370 if (Config.MAGIC_CREATE_DOMAIN != null) {
4371 hosts.add(Config.MAGIC_CREATE_DOMAIN);
4372 }
4373 return hosts;
4374 }
4375
4376 public Collection<String> getKnownConferenceHosts() {
4377 final Set<String> mucServers = new HashSet<>();
4378 for (final Account account : accounts) {
4379 if (account.getXmppConnection() != null) {
4380 mucServers.addAll(account.getXmppConnection().getMucServers());
4381 for (Bookmark bookmark : account.getBookmarks()) {
4382 final Jid jid = bookmark.getJid();
4383 final String s = jid == null ? null : jid.getDomain().toEscapedString();
4384 if (s != null) {
4385 mucServers.add(s);
4386 }
4387 }
4388 }
4389 }
4390 return mucServers;
4391 }
4392
4393 public void sendMessagePacket(Account account, MessagePacket packet) {
4394 final XmppConnection connection = account.getXmppConnection();
4395 if (connection != null) {
4396 connection.sendMessagePacket(packet);
4397 }
4398 }
4399
4400 public void sendPresencePacket(Account account, PresencePacket packet) {
4401 XmppConnection connection = account.getXmppConnection();
4402 if (connection != null) {
4403 connection.sendPresencePacket(packet);
4404 }
4405 }
4406
4407 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
4408 final XmppConnection connection = account.getXmppConnection();
4409 if (connection != null) {
4410 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
4411 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
4412 }
4413 }
4414
4415 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
4416 final XmppConnection connection = account.getXmppConnection();
4417 if (connection != null) {
4418 connection.sendIqPacket(packet, callback);
4419 } else if (callback != null) {
4420 callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
4421 }
4422 }
4423
4424 public void sendPresence(final Account account) {
4425 sendPresence(account, checkListeners() && broadcastLastActivity());
4426 }
4427
4428 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
4429 final Presence.Status status;
4430 if (manuallyChangePresence()) {
4431 status = account.getPresenceStatus();
4432 } else {
4433 status = getTargetPresence();
4434 }
4435 final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
4436 if (mLastActivity > 0 && includeIdleTimestamp) {
4437 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
4438 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
4439 }
4440 sendPresencePacket(account, packet);
4441 }
4442
4443 private void deactivateGracePeriod() {
4444 for (Account account : getAccounts()) {
4445 account.deactivateGracePeriod();
4446 }
4447 }
4448
4449 public void refreshAllPresences() {
4450 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
4451 for (Account account : getAccounts()) {
4452 if (account.isEnabled()) {
4453 sendPresence(account, includeIdleTimestamp);
4454 }
4455 }
4456 }
4457
4458 private void refreshAllFcmTokens() {
4459 for (Account account : getAccounts()) {
4460 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4461 mPushManagementService.registerPushTokenOnServer(account);
4462 //TODO renew mucs
4463 }
4464 }
4465 }
4466
4467 private void sendOfflinePresence(final Account account) {
4468 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4469 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4470 }
4471
4472 public MessageGenerator getMessageGenerator() {
4473 return this.mMessageGenerator;
4474 }
4475
4476 public PresenceGenerator getPresenceGenerator() {
4477 return this.mPresenceGenerator;
4478 }
4479
4480 public IqGenerator getIqGenerator() {
4481 return this.mIqGenerator;
4482 }
4483
4484 public IqParser getIqParser() {
4485 return this.mIqParser;
4486 }
4487
4488 public JingleConnectionManager getJingleConnectionManager() {
4489 return this.mJingleConnectionManager;
4490 }
4491
4492 public MessageArchiveService getMessageArchiveService() {
4493 return this.mMessageArchiveService;
4494 }
4495
4496 public QuickConversationsService getQuickConversationsService() {
4497 return this.mQuickConversationsService;
4498 }
4499
4500 public List<Contact> findContacts(Jid jid, String accountJid) {
4501 ArrayList<Contact> contacts = new ArrayList<>();
4502 for (Account account : getAccounts()) {
4503 if ((account.isEnabled() || accountJid != null)
4504 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4505 Contact contact = account.getRoster().getContactFromContactList(jid);
4506 if (contact != null) {
4507 contacts.add(contact);
4508 }
4509 }
4510 }
4511 return contacts;
4512 }
4513
4514 public Conversation findFirstMuc(Jid jid) {
4515 for (Conversation conversation : getConversations()) {
4516 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4517 return conversation;
4518 }
4519 }
4520 return null;
4521 }
4522
4523 public NotificationService getNotificationService() {
4524 return this.mNotificationService;
4525 }
4526
4527 public HttpConnectionManager getHttpConnectionManager() {
4528 return this.mHttpConnectionManager;
4529 }
4530
4531 public void resendFailedMessages(final Message message) {
4532 final Collection<Message> messages = new ArrayList<>();
4533 Message current = message;
4534 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4535 messages.add(current);
4536 if (current.mergeable(current.next())) {
4537 current = current.next();
4538 } else {
4539 break;
4540 }
4541 }
4542 for (final Message msg : messages) {
4543 msg.setTime(System.currentTimeMillis());
4544 markMessage(msg, Message.STATUS_WAITING);
4545 this.resendMessage(msg, false);
4546 }
4547 if (message.getConversation() instanceof Conversation) {
4548 ((Conversation) message.getConversation()).sort();
4549 }
4550 updateConversationUi();
4551 }
4552
4553 public void clearConversationHistory(final Conversation conversation) {
4554 final long clearDate;
4555 final String reference;
4556 if (conversation.countMessages() > 0) {
4557 Message latestMessage = conversation.getLatestMessage();
4558 clearDate = latestMessage.getTimeSent() + 1000;
4559 reference = latestMessage.getServerMsgId();
4560 } else {
4561 clearDate = System.currentTimeMillis();
4562 reference = null;
4563 }
4564 conversation.clearMessages();
4565 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4566 conversation.setLastClearHistory(clearDate, reference);
4567 Runnable runnable = () -> {
4568 databaseBackend.deleteMessagesInConversation(conversation);
4569 databaseBackend.updateConversation(conversation);
4570 };
4571 mDatabaseWriterExecutor.execute(runnable);
4572 }
4573
4574 public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
4575 if (blockable != null && blockable.getBlockedJid() != null) {
4576 final Jid jid = blockable.getBlockedJid();
4577 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), (a, response) -> {
4578 if (response.getType() == IqPacket.TYPE.RESULT) {
4579 a.getBlocklist().add(jid);
4580 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4581 }
4582 });
4583 if (blockable.getBlockedJid().isFullJid()) {
4584 return false;
4585 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
4586 updateConversationUi();
4587 return true;
4588 } else {
4589 return false;
4590 }
4591 } else {
4592 return false;
4593 }
4594 }
4595
4596 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4597 boolean removed = false;
4598 synchronized (this.conversations) {
4599 boolean domainJid = blockedJid.getLocal() == null;
4600 for (Conversation conversation : this.conversations) {
4601 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4602 || blockedJid.equals(conversation.getJid().asBareJid());
4603 if (conversation.getAccount() == account
4604 && conversation.getMode() == Conversation.MODE_SINGLE
4605 && jidMatches) {
4606 this.conversations.remove(conversation);
4607 markRead(conversation);
4608 conversation.setStatus(Conversation.STATUS_ARCHIVED);
4609 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4610 updateConversation(conversation);
4611 removed = true;
4612 }
4613 }
4614 }
4615 return removed;
4616 }
4617
4618 public void sendUnblockRequest(final Blockable blockable) {
4619 if (blockable != null && blockable.getJid() != null) {
4620 final Jid jid = blockable.getBlockedJid();
4621 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4622 @Override
4623 public void onIqPacketReceived(final Account account, final IqPacket packet) {
4624 if (packet.getType() == IqPacket.TYPE.RESULT) {
4625 account.getBlocklist().remove(jid);
4626 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4627 }
4628 }
4629 });
4630 }
4631 }
4632
4633 public void publishDisplayName(Account account) {
4634 String displayName = account.getDisplayName();
4635 final IqPacket request;
4636 if (TextUtils.isEmpty(displayName)) {
4637 request = mIqGenerator.deleteNode(Namespace.NICK);
4638 } else {
4639 request = mIqGenerator.publishNick(displayName);
4640 }
4641 mAvatarService.clear(account);
4642 sendIqPacket(account, request, (account1, packet) -> {
4643 if (packet.getType() == IqPacket.TYPE.ERROR) {
4644 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet.toString());
4645 }
4646 });
4647 }
4648
4649 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4650 ServiceDiscoveryResult result = discoCache.get(key);
4651 if (result != null) {
4652 return result;
4653 } else {
4654 result = databaseBackend.findDiscoveryResult(key.first, key.second);
4655 if (result != null) {
4656 discoCache.put(key, result);
4657 }
4658 return result;
4659 }
4660 }
4661
4662 public void fetchFromGateway(Account account, final Jid jid, final String input, final OnGatewayResult callback) {
4663 IqPacket request = new IqPacket(input == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
4664 request.setTo(jid);
4665 Element query = request.query("jabber:iq:gateway");
4666 if (input != null) {
4667 Element prompt = query.addChild("prompt");
4668 prompt.setContent(input);
4669 }
4670 sendIqPacket(account, request, (Account acct, IqPacket packet) -> {
4671 if (packet.getType() == IqPacket.TYPE.RESULT) {
4672 callback.onGatewayResult(packet.query().findChildContent(input == null ? "prompt" : "jid"), null);
4673 } else {
4674 Element error = packet.findChild("error");
4675 callback.onGatewayResult(null, error == null ? null : error.findChildContent("text"));
4676 }
4677 });
4678 }
4679
4680 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
4681 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
4682 final ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
4683
4684 if (disco != null) {
4685 presence.setServiceDiscoveryResult(disco);
4686 final Contact contact = account.getRoster().getContact(jid);
4687 if (contact.refreshRtpCapability()) {
4688 syncRoster(account);
4689 }
4690 if (disco.hasIdentity("gateway", "pstn")) {
4691 contact.registerAsPhoneAccount(this);
4692 }
4693 } else {
4694 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4695 request.setTo(jid);
4696 final String node = presence.getNode();
4697 final String ver = presence.getVer();
4698 final Element query = request.query(Namespace.DISCO_INFO);
4699 if (node != null && ver != null) {
4700 query.setAttribute("node", node + "#" + ver);
4701 }
4702 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
4703 sendIqPacket(account, request, (a, response) -> {
4704 if (response.getType() == IqPacket.TYPE.RESULT) {
4705 final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
4706 if (presence.getVer().equals(discoveryResult.getVer())) {
4707 databaseBackend.insertDiscoveryResult(discoveryResult);
4708 injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
4709 if (discoveryResult.hasIdentity("gateway", "pstn")) {
4710 final Contact contact = account.getRoster().getContact(jid);
4711 contact.registerAsPhoneAccount(this);
4712 }
4713 } else {
4714 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
4715 }
4716 } else {
4717 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
4718 }
4719 });
4720 }
4721 }
4722
4723 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
4724 boolean rosterNeedsSync = false;
4725 for (final Contact contact : roster.getContacts()) {
4726 boolean serviceDiscoverySet = false;
4727 for (final Presence presence : contact.getPresences().getPresences()) {
4728 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
4729 presence.setServiceDiscoveryResult(disco);
4730 serviceDiscoverySet = true;
4731 }
4732 }
4733 if (serviceDiscoverySet) {
4734 rosterNeedsSync |= contact.refreshRtpCapability();
4735 }
4736 }
4737 if (rosterNeedsSync) {
4738 syncRoster(roster.getAccount());
4739 }
4740 }
4741
4742 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
4743 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
4744 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4745 request.addChild("prefs", version.namespace);
4746 sendIqPacket(account, request, (account1, packet) -> {
4747 Element prefs = packet.findChild("prefs", version.namespace);
4748 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
4749 callback.onPreferencesFetched(prefs);
4750 } else {
4751 callback.onPreferencesFetchFailed();
4752 }
4753 });
4754 }
4755
4756 public PushManagementService getPushManagementService() {
4757 return mPushManagementService;
4758 }
4759
4760 public void changeStatus(Account account, PresenceTemplate template, String signature) {
4761 if (!template.getStatusMessage().isEmpty()) {
4762 databaseBackend.insertPresenceTemplate(template);
4763 }
4764 account.setPgpSignature(signature);
4765 account.setPresenceStatus(template.getStatus());
4766 account.setPresenceStatusMessage(template.getStatusMessage());
4767 databaseBackend.updateAccount(account);
4768 sendPresence(account);
4769 }
4770
4771 public List<PresenceTemplate> getPresenceTemplates(Account account) {
4772 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
4773 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
4774 if (!templates.contains(template)) {
4775 templates.add(0, template);
4776 }
4777 }
4778 return templates;
4779 }
4780
4781 public void saveConversationAsBookmark(Conversation conversation, String name) {
4782 final Account account = conversation.getAccount();
4783 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
4784 final String nick = conversation.getJid().getResource();
4785 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
4786 bookmark.setNick(nick);
4787 }
4788 if (!TextUtils.isEmpty(name)) {
4789 bookmark.setBookmarkName(name);
4790 }
4791 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
4792 createBookmark(account, bookmark);
4793 bookmark.setConversation(conversation);
4794 }
4795
4796 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
4797 boolean performedVerification = false;
4798 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
4799 for (XmppUri.Fingerprint fp : fingerprints) {
4800 if (fp.type == XmppUri.FingerprintType.OMEMO) {
4801 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4802 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4803 if (fingerprintStatus != null) {
4804 if (!fingerprintStatus.isVerified()) {
4805 performedVerification = true;
4806 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4807 }
4808 } else {
4809 axolotlService.preVerifyFingerprint(contact, fingerprint);
4810 }
4811 }
4812 }
4813 return performedVerification;
4814 }
4815
4816 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
4817 final AxolotlService axolotlService = account.getAxolotlService();
4818 boolean verifiedSomething = false;
4819 for (XmppUri.Fingerprint fp : fingerprints) {
4820 if (fp.type == XmppUri.FingerprintType.OMEMO) {
4821 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4822 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
4823 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4824 if (fingerprintStatus != null) {
4825 if (!fingerprintStatus.isVerified()) {
4826 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4827 verifiedSomething = true;
4828 }
4829 } else {
4830 axolotlService.preVerifyFingerprint(account, fingerprint);
4831 verifiedSomething = true;
4832 }
4833 }
4834 }
4835 return verifiedSomething;
4836 }
4837
4838 public boolean blindTrustBeforeVerification() {
4839 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4840 }
4841
4842 public ShortcutService getShortcutService() {
4843 return mShortcutService;
4844 }
4845
4846 public void pushMamPreferences(Account account, Element prefs) {
4847 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4848 set.addChild(prefs);
4849 sendIqPacket(account, set, null);
4850 }
4851
4852 public void evictPreview(String uuid) {
4853 if (mBitmapCache.remove(uuid) != null) {
4854 Log.d(Config.LOGTAG, "deleted cached preview");
4855 }
4856 }
4857
4858 public interface OnMamPreferencesFetched {
4859 void onPreferencesFetched(Element prefs);
4860
4861 void onPreferencesFetchFailed();
4862 }
4863
4864 public interface OnAccountCreated {
4865 void onAccountCreated(Account account);
4866
4867 void informUser(int r);
4868 }
4869
4870 public interface OnMoreMessagesLoaded {
4871 void onMoreMessagesLoaded(int count, Conversation conversation);
4872
4873 void informUser(int r);
4874 }
4875
4876 public interface OnAccountPasswordChanged {
4877 void onPasswordChangeSucceeded();
4878
4879 void onPasswordChangeFailed();
4880 }
4881
4882 public interface OnRoomDestroy {
4883 void onRoomDestroySucceeded();
4884
4885 void onRoomDestroyFailed();
4886 }
4887
4888 public interface OnAffiliationChanged {
4889 void onAffiliationChangedSuccessful(Jid jid);
4890
4891 void onAffiliationChangeFailed(Jid jid, int resId);
4892 }
4893
4894 public interface OnConversationUpdate {
4895 void onConversationUpdate();
4896 }
4897
4898 public interface OnJingleRtpConnectionUpdate {
4899 void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
4900
4901 void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
4902 }
4903
4904 public interface OnAccountUpdate {
4905 void onAccountUpdate();
4906 }
4907
4908 public interface OnCaptchaRequested {
4909 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4910 }
4911
4912 public interface OnRosterUpdate {
4913 void onRosterUpdate();
4914 }
4915
4916 public interface OnMucRosterUpdate {
4917 void onMucRosterUpdate();
4918 }
4919
4920 public interface OnConferenceConfigurationFetched {
4921 void onConferenceConfigurationFetched(Conversation conversation);
4922
4923 void onFetchFailed(Conversation conversation, String errorCondition);
4924 }
4925
4926 public interface OnConferenceJoined {
4927 void onConferenceJoined(Conversation conversation);
4928 }
4929
4930 public interface OnConfigurationPushed {
4931 void onPushSucceeded();
4932
4933 void onPushFailed();
4934 }
4935
4936 public interface OnShowErrorToast {
4937 void onShowErrorToast(int resId);
4938 }
4939
4940 public class XmppConnectionBinder extends Binder {
4941 public XmppConnectionService getService() {
4942 return XmppConnectionService.this;
4943 }
4944 }
4945
4946 private class InternalEventReceiver extends BroadcastReceiver {
4947
4948 @Override
4949 public void onReceive(Context context, Intent intent) {
4950 onStartCommand(intent, 0, 0);
4951 }
4952 }
4953
4954 public static class OngoingCall {
4955 public final AbstractJingleConnection.Id id;
4956 public final Set<Media> media;
4957 public final boolean reconnecting;
4958
4959 public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
4960 this.id = id;
4961 this.media = media;
4962 this.reconnecting = reconnecting;
4963 }
4964
4965 @Override
4966 public boolean equals(Object o) {
4967 if (this == o) return true;
4968 if (o == null || getClass() != o.getClass()) return false;
4969 OngoingCall that = (OngoingCall) o;
4970 return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
4971 }
4972
4973 @Override
4974 public int hashCode() {
4975 return Objects.hashCode(id, media, reconnecting);
4976 }
4977 }
4978}