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