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