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