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