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, null);
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 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, query, async, null);
2687 }
2688
2689 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async, final String password) {
2690 synchronized (this.conversations) {
2691 Conversation conversation = find(account, jid);
2692 if (conversation != null) {
2693 return conversation;
2694 }
2695 conversation = databaseBackend.findConversation(account, jid);
2696 final boolean loadMessagesFromDb;
2697 if (conversation != null) {
2698 conversation.setStatus(Conversation.STATUS_AVAILABLE);
2699 conversation.setAccount(account);
2700 if (muc) {
2701 conversation.setMode(Conversation.MODE_MULTI);
2702 conversation.setContactJid(jid);
2703 if (password != null) conversation.getMucOptions().setPassword(password);
2704 } else {
2705 conversation.setMode(Conversation.MODE_SINGLE);
2706 conversation.setContactJid(jid.asBareJid());
2707 }
2708 databaseBackend.updateConversation(conversation);
2709 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
2710 } else {
2711 String conversationName;
2712 Contact contact = account.getRoster().getContact(jid);
2713 if (contact != null) {
2714 conversationName = contact.getDisplayName();
2715 } else {
2716 conversationName = jid.getLocal();
2717 }
2718 if (muc) {
2719 conversation = new Conversation(conversationName, account, jid,
2720 Conversation.MODE_MULTI);
2721 if (password != null) conversation.getMucOptions().setPassword(password);
2722 } else {
2723 conversation = new Conversation(conversationName, account, jid.asBareJid(),
2724 Conversation.MODE_SINGLE);
2725 }
2726 this.databaseBackend.createConversation(conversation);
2727 loadMessagesFromDb = false;
2728 }
2729 final Conversation c = conversation;
2730 final Runnable runnable = () -> {
2731 if (loadMessagesFromDb) {
2732 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
2733 updateConversationUi();
2734 c.messagesLoaded.set(true);
2735 }
2736 if (account.getXmppConnection() != null
2737 && !c.getContact().isBlocked()
2738 && account.getXmppConnection().getFeatures().mam()
2739 && !muc) {
2740 if (query == null) {
2741 mMessageArchiveService.query(c);
2742 } else {
2743 if (query.getConversation() == null) {
2744 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
2745 }
2746 }
2747 }
2748 if (joinAfterCreate) {
2749 joinMuc(c);
2750 }
2751 };
2752 if (async) {
2753 mDatabaseReaderExecutor.execute(runnable);
2754 } else {
2755 runnable.run();
2756 }
2757 this.conversations.add(conversation);
2758 updateConversationUi();
2759 return conversation;
2760 }
2761 }
2762
2763 public void archiveConversation(Conversation conversation) {
2764 archiveConversation(conversation, true);
2765 }
2766
2767 private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
2768 if (isOnboarding()) return;
2769
2770 getNotificationService().clear(conversation);
2771 conversation.setStatus(Conversation.STATUS_ARCHIVED);
2772 conversation.setNextMessage(null);
2773 synchronized (this.conversations) {
2774 getMessageArchiveService().kill(conversation);
2775 if (conversation.getMode() == Conversation.MODE_MULTI) {
2776 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2777 final Bookmark bookmark = conversation.getBookmark();
2778 if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
2779 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
2780 Account account = bookmark.getAccount();
2781 bookmark.setConversation(null);
2782 deleteBookmark(account, bookmark);
2783 } else if (bookmark.autojoin()) {
2784 bookmark.setAutojoin(false);
2785 createBookmark(bookmark.getAccount(), bookmark);
2786 }
2787 }
2788 }
2789 leaveMuc(conversation);
2790 } else {
2791 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2792 stopPresenceUpdatesTo(conversation.getContact());
2793 }
2794 }
2795 updateConversation(conversation);
2796 this.conversations.remove(conversation);
2797 updateConversationUi();
2798 }
2799 }
2800
2801 public void stopPresenceUpdatesTo(Contact contact) {
2802 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2803 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2804 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2805 }
2806
2807 public void createAccount(final Account account) {
2808 account.initAccountServices(this);
2809 databaseBackend.createAccount(account);
2810 this.accounts.add(account);
2811 this.reconnectAccountInBackground(account);
2812 updateAccountUi();
2813 syncEnabledAccountSetting();
2814 toggleForegroundService();
2815 }
2816
2817 private void syncEnabledAccountSetting() {
2818 final boolean hasEnabledAccounts = hasEnabledAccounts();
2819 getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2820 toggleSetProfilePictureActivity(hasEnabledAccounts);
2821 }
2822
2823 private void toggleSetProfilePictureActivity(final boolean enabled) {
2824 try {
2825 final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2826 final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2827 getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2828 } catch (IllegalStateException e) {
2829 Log.d(Config.LOGTAG, "unable to toggle profile picture activity");
2830 }
2831 }
2832
2833 public boolean reconfigurePushDistributor() {
2834 return this.unifiedPushBroker.reconfigurePushDistributor();
2835 }
2836
2837 private Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints(final UnifiedPushBroker.PushTargetMessenger pushTargetMessenger) {
2838 return this.unifiedPushBroker.renewUnifiedPushEndpoints(pushTargetMessenger);
2839 }
2840
2841 public Optional<UnifiedPushBroker.Transport> renewUnifiedPushEndpoints() {
2842 return this.unifiedPushBroker.renewUnifiedPushEndpoints(null);
2843 }
2844
2845 private void provisionAccount(final String address, final String password) {
2846 final Jid jid = Jid.ofEscaped(address);
2847 final Account account = new Account(jid, password);
2848 account.setOption(Account.OPTION_DISABLED, true);
2849 Log.d(Config.LOGTAG, jid.asBareJid().toEscapedString() + ": provisioning account");
2850 createAccount(account);
2851 }
2852
2853 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2854 new Thread(() -> {
2855 try {
2856 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2857 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2858 if (cert == null) {
2859 callback.informUser(R.string.unable_to_parse_certificate);
2860 return;
2861 }
2862 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2863 if (info == null) {
2864 callback.informUser(R.string.certificate_does_not_contain_jid);
2865 return;
2866 }
2867 if (findAccountByJid(info.first) == null) {
2868 final Account account = new Account(info.first, "");
2869 account.setPrivateKeyAlias(alias);
2870 account.setOption(Account.OPTION_DISABLED, true);
2871 account.setOption(Account.OPTION_FIXED_USERNAME, true);
2872 account.setDisplayName(info.second);
2873 createAccount(account);
2874 callback.onAccountCreated(account);
2875 if (Config.X509_VERIFICATION) {
2876 try {
2877 getMemorizingTrustManager().getNonInteractive(account.getServer(), null, 0, null).checkClientTrusted(chain, "RSA");
2878 } catch (CertificateException e) {
2879 callback.informUser(R.string.certificate_chain_is_not_trusted);
2880 }
2881 }
2882 } else {
2883 callback.informUser(R.string.account_already_exists);
2884 }
2885 } catch (Exception e) {
2886 callback.informUser(R.string.unable_to_parse_certificate);
2887 }
2888 }).start();
2889
2890 }
2891
2892 public void updateKeyInAccount(final Account account, final String alias) {
2893 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2894 try {
2895 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2896 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2897 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2898 if (info == null) {
2899 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2900 return;
2901 }
2902 if (account.getJid().asBareJid().equals(info.first)) {
2903 account.setPrivateKeyAlias(alias);
2904 account.setDisplayName(info.second);
2905 databaseBackend.updateAccount(account);
2906 if (Config.X509_VERIFICATION) {
2907 try {
2908 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2909 } catch (CertificateException e) {
2910 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2911 }
2912 account.getAxolotlService().regenerateKeys(true);
2913 }
2914 } else {
2915 showErrorToastInUi(R.string.jid_does_not_match_certificate);
2916 }
2917 } catch (Exception e) {
2918 e.printStackTrace();
2919 }
2920 }
2921
2922 public boolean updateAccount(final Account account) {
2923 if (databaseBackend.updateAccount(account)) {
2924 Integer color = account.getColorToSave();
2925 if (color == null) {
2926 getPreferences().edit().remove("account_color:" + account.getUuid()).commit();
2927 } else {
2928 getPreferences().edit().putInt("account_color:" + account.getUuid(), color.intValue()).commit();
2929 }
2930 account.setShowErrorNotification(true);
2931 this.statusListener.onStatusChanged(account);
2932 databaseBackend.updateAccount(account);
2933 reconnectAccountInBackground(account);
2934 updateAccountUi();
2935 getNotificationService().updateErrorNotification();
2936 toggleForegroundService();
2937 syncEnabledAccountSetting();
2938 mChannelDiscoveryService.cleanCache();
2939 return true;
2940 } else {
2941 return false;
2942 }
2943 }
2944
2945 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2946 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2947 sendIqPacket(account, iq, (a, packet) -> {
2948 if (packet.getType() == IqPacket.TYPE.RESULT) {
2949 a.setPassword(newPassword);
2950 a.setOption(Account.OPTION_MAGIC_CREATE, false);
2951 databaseBackend.updateAccount(a);
2952 callback.onPasswordChangeSucceeded();
2953 } else {
2954 callback.onPasswordChangeFailed();
2955 }
2956 });
2957 }
2958
2959 public void unregisterAccount(final Account account, final Consumer<Boolean> callback) {
2960 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
2961 final Element query = iqPacket.addChild("query",Namespace.REGISTER);
2962 query.addChild("remove");
2963 sendIqPacket(account, iqPacket, (a, response) -> {
2964 if (response.getType() == IqPacket.TYPE.RESULT) {
2965 deleteAccount(a);
2966 callback.accept(true);
2967 } else {
2968 callback.accept(false);
2969 }
2970 });
2971 }
2972
2973 public void deleteAccount(final Account account) {
2974 getPreferences().edit().remove("onboarding_continued").commit();
2975 final boolean connected = account.getStatus() == Account.State.ONLINE;
2976 synchronized (this.conversations) {
2977 if (connected) {
2978 account.getAxolotlService().deleteOmemoIdentity();
2979 }
2980 for (final Conversation conversation : conversations) {
2981 if (conversation.getAccount() == account) {
2982 if (conversation.getMode() == Conversation.MODE_MULTI) {
2983 if (connected) {
2984 leaveMuc(conversation);
2985 }
2986 }
2987 conversations.remove(conversation);
2988 mNotificationService.clear(conversation);
2989 }
2990 }
2991 new Thread(() -> {
2992 for (final Contact contact : account.getRoster().getContacts()) {
2993 contact.unregisterAsPhoneAccount(this);
2994 }
2995 }).start();
2996 if (account.getXmppConnection() != null) {
2997 new Thread(() -> disconnect(account, !connected)).start();
2998 }
2999 final Runnable runnable = () -> {
3000 if (!databaseBackend.deleteAccount(account)) {
3001 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
3002 }
3003 };
3004 mDatabaseWriterExecutor.execute(runnable);
3005 this.accounts.remove(account);
3006 this.mRosterSyncTaskManager.clear(account);
3007 updateAccountUi();
3008 mNotificationService.updateErrorNotification();
3009 syncEnabledAccountSetting();
3010 toggleForegroundService();
3011 }
3012 }
3013
3014 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
3015 final boolean remainingListeners;
3016 synchronized (LISTENER_LOCK) {
3017 remainingListeners = checkListeners();
3018 if (!this.mOnConversationUpdates.add(listener)) {
3019 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as ConversationListChangedListener");
3020 }
3021 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
3022 }
3023 if (remainingListeners) {
3024 switchToForeground();
3025 }
3026 }
3027
3028 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
3029 final boolean remainingListeners;
3030 synchronized (LISTENER_LOCK) {
3031 this.mOnConversationUpdates.remove(listener);
3032 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
3033 remainingListeners = checkListeners();
3034 }
3035 if (remainingListeners) {
3036 switchToBackground();
3037 }
3038 }
3039
3040 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
3041 final boolean remainingListeners;
3042 synchronized (LISTENER_LOCK) {
3043 remainingListeners = checkListeners();
3044 if (!this.mOnShowErrorToasts.add(listener)) {
3045 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnShowErrorToastListener");
3046 }
3047 }
3048 if (remainingListeners) {
3049 switchToForeground();
3050 }
3051 }
3052
3053 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
3054 final boolean remainingListeners;
3055 synchronized (LISTENER_LOCK) {
3056 this.mOnShowErrorToasts.remove(onShowErrorToast);
3057 remainingListeners = checkListeners();
3058 }
3059 if (remainingListeners) {
3060 switchToBackground();
3061 }
3062 }
3063
3064 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
3065 final boolean remainingListeners;
3066 synchronized (LISTENER_LOCK) {
3067 remainingListeners = checkListeners();
3068 if (!this.mOnAccountUpdates.add(listener)) {
3069 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnAccountListChangedtListener");
3070 }
3071 }
3072 if (remainingListeners) {
3073 switchToForeground();
3074 }
3075 }
3076
3077 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
3078 final boolean remainingListeners;
3079 synchronized (LISTENER_LOCK) {
3080 this.mOnAccountUpdates.remove(listener);
3081 remainingListeners = checkListeners();
3082 }
3083 if (remainingListeners) {
3084 switchToBackground();
3085 }
3086 }
3087
3088 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3089 final boolean remainingListeners;
3090 synchronized (LISTENER_LOCK) {
3091 remainingListeners = checkListeners();
3092 if (!this.mOnCaptchaRequested.add(listener)) {
3093 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnCaptchaRequestListener");
3094 }
3095 }
3096 if (remainingListeners) {
3097 switchToForeground();
3098 }
3099 }
3100
3101 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
3102 final boolean remainingListeners;
3103 synchronized (LISTENER_LOCK) {
3104 this.mOnCaptchaRequested.remove(listener);
3105 remainingListeners = checkListeners();
3106 }
3107 if (remainingListeners) {
3108 switchToBackground();
3109 }
3110 }
3111
3112 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
3113 final boolean remainingListeners;
3114 synchronized (LISTENER_LOCK) {
3115 remainingListeners = checkListeners();
3116 if (!this.mOnRosterUpdates.add(listener)) {
3117 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnRosterUpdateListener");
3118 }
3119 }
3120 if (remainingListeners) {
3121 switchToForeground();
3122 }
3123 }
3124
3125 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
3126 final boolean remainingListeners;
3127 synchronized (LISTENER_LOCK) {
3128 this.mOnRosterUpdates.remove(listener);
3129 remainingListeners = checkListeners();
3130 }
3131 if (remainingListeners) {
3132 switchToBackground();
3133 }
3134 }
3135
3136 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3137 final boolean remainingListeners;
3138 synchronized (LISTENER_LOCK) {
3139 remainingListeners = checkListeners();
3140 if (!this.mOnUpdateBlocklist.add(listener)) {
3141 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnUpdateBlocklistListener");
3142 }
3143 }
3144 if (remainingListeners) {
3145 switchToForeground();
3146 }
3147 }
3148
3149 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
3150 final boolean remainingListeners;
3151 synchronized (LISTENER_LOCK) {
3152 this.mOnUpdateBlocklist.remove(listener);
3153 remainingListeners = checkListeners();
3154 }
3155 if (remainingListeners) {
3156 switchToBackground();
3157 }
3158 }
3159
3160 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
3161 final boolean remainingListeners;
3162 synchronized (LISTENER_LOCK) {
3163 remainingListeners = checkListeners();
3164 if (!this.mOnKeyStatusUpdated.add(listener)) {
3165 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnKeyStatusUpdateListener");
3166 }
3167 }
3168 if (remainingListeners) {
3169 switchToForeground();
3170 }
3171 }
3172
3173 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
3174 final boolean remainingListeners;
3175 synchronized (LISTENER_LOCK) {
3176 this.mOnKeyStatusUpdated.remove(listener);
3177 remainingListeners = checkListeners();
3178 }
3179 if (remainingListeners) {
3180 switchToBackground();
3181 }
3182 }
3183
3184 public void setOnRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3185 final boolean remainingListeners;
3186 synchronized (LISTENER_LOCK) {
3187 remainingListeners = checkListeners();
3188 if (!this.onJingleRtpConnectionUpdate.add(listener)) {
3189 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnJingleRtpConnectionUpdate");
3190 }
3191 }
3192 if (remainingListeners) {
3193 switchToForeground();
3194 }
3195 }
3196
3197 public void removeRtpConnectionUpdateListener(final OnJingleRtpConnectionUpdate listener) {
3198 final boolean remainingListeners;
3199 synchronized (LISTENER_LOCK) {
3200 this.onJingleRtpConnectionUpdate.remove(listener);
3201 remainingListeners = checkListeners();
3202 }
3203 if (remainingListeners) {
3204 switchToBackground();
3205 }
3206 }
3207
3208 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
3209 final boolean remainingListeners;
3210 synchronized (LISTENER_LOCK) {
3211 remainingListeners = checkListeners();
3212 if (!this.mOnMucRosterUpdate.add(listener)) {
3213 Log.w(Config.LOGTAG, listener.getClass().getName() + " is already registered as OnMucRosterListener");
3214 }
3215 }
3216 if (remainingListeners) {
3217 switchToForeground();
3218 }
3219 }
3220
3221 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
3222 final boolean remainingListeners;
3223 synchronized (LISTENER_LOCK) {
3224 this.mOnMucRosterUpdate.remove(listener);
3225 remainingListeners = checkListeners();
3226 }
3227 if (remainingListeners) {
3228 switchToBackground();
3229 }
3230 }
3231
3232 public boolean checkListeners() {
3233 return (this.mOnAccountUpdates.size() == 0
3234 && this.mOnConversationUpdates.size() == 0
3235 && this.mOnRosterUpdates.size() == 0
3236 && this.mOnCaptchaRequested.size() == 0
3237 && this.mOnMucRosterUpdate.size() == 0
3238 && this.mOnUpdateBlocklist.size() == 0
3239 && this.mOnShowErrorToasts.size() == 0
3240 && this.onJingleRtpConnectionUpdate.size() == 0
3241 && this.mOnKeyStatusUpdated.size() == 0);
3242 }
3243
3244 private void switchToForeground() {
3245 toggleSoftDisabled(false);
3246 final boolean broadcastLastActivity = broadcastLastActivity();
3247 for (Conversation conversation : getConversations()) {
3248 if (conversation.getMode() == Conversation.MODE_MULTI) {
3249 conversation.getMucOptions().resetChatState();
3250 } else {
3251 conversation.setIncomingChatState(Config.DEFAULT_CHAT_STATE);
3252 }
3253 }
3254 for (Account account : getAccounts()) {
3255 if (account.getStatus() == Account.State.ONLINE) {
3256 account.deactivateGracePeriod();
3257 final XmppConnection connection = account.getXmppConnection();
3258 if (connection != null) {
3259 if (connection.getFeatures().csi()) {
3260 connection.sendActive();
3261 }
3262 if (broadcastLastActivity) {
3263 sendPresence(account, false); //send new presence but don't include idle because we are not
3264 }
3265 }
3266 }
3267 }
3268 Log.d(Config.LOGTAG, "app switched into foreground");
3269 }
3270
3271 private void switchToBackground() {
3272 final boolean broadcastLastActivity = broadcastLastActivity();
3273 if (broadcastLastActivity) {
3274 mLastActivity = System.currentTimeMillis();
3275 final SharedPreferences.Editor editor = getPreferences().edit();
3276 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
3277 editor.apply();
3278 }
3279 for (Account account : getAccounts()) {
3280 if (account.getStatus() == Account.State.ONLINE) {
3281 XmppConnection connection = account.getXmppConnection();
3282 if (connection != null) {
3283 if (broadcastLastActivity) {
3284 sendPresence(account, true);
3285 }
3286 if (connection.getFeatures().csi()) {
3287 connection.sendInactive();
3288 }
3289 }
3290 }
3291 }
3292 this.mNotificationService.setIsInForeground(false);
3293 Log.d(Config.LOGTAG, "app switched into background");
3294 }
3295
3296 private void connectMultiModeConversations(Account account) {
3297 List<Conversation> conversations = getConversations();
3298 for (Conversation conversation : conversations) {
3299 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
3300 joinMuc(conversation);
3301 }
3302 }
3303 }
3304
3305 public void mucSelfPingAndRejoin(final Conversation conversation) {
3306 final Account account = conversation.getAccount();
3307 synchronized (account.inProgressConferenceJoins) {
3308 if (account.inProgressConferenceJoins.contains(conversation)) {
3309 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because join is already under way");
3310 return;
3311 }
3312 }
3313 synchronized (account.inProgressConferencePings) {
3314 if (!account.inProgressConferencePings.add(conversation)) {
3315 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": canceling muc self ping because ping is already under way");
3316 return;
3317 }
3318 }
3319 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
3320 final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
3321 ping.setTo(self);
3322 ping.addChild("ping", Namespace.PING);
3323 sendIqPacket(conversation.getAccount(), ping, (a, response) -> {
3324 if (response.getType() == IqPacket.TYPE.ERROR) {
3325 Element error = response.findChild("error");
3326 if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
3327 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back as ignorable error");
3328 } else {
3329 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " failed. attempting rejoin");
3330 joinMuc(conversation);
3331 }
3332 } else if (response.getType() == IqPacket.TYPE.RESULT) {
3333 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": ping to " + self + " came back fine");
3334 }
3335 synchronized (account.inProgressConferencePings) {
3336 account.inProgressConferencePings.remove(conversation);
3337 }
3338 });
3339 }
3340 public void joinMuc(Conversation conversation) {
3341 joinMuc(conversation, null, false);
3342 }
3343
3344 public void joinMuc(Conversation conversation, boolean followedInvite) {
3345 joinMuc(conversation, null, followedInvite);
3346 }
3347
3348 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
3349 joinMuc(conversation, onConferenceJoined, false);
3350 }
3351
3352 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
3353 final Account account = conversation.getAccount();
3354 synchronized (account.pendingConferenceJoins) {
3355 account.pendingConferenceJoins.remove(conversation);
3356 }
3357 synchronized (account.pendingConferenceLeaves) {
3358 account.pendingConferenceLeaves.remove(conversation);
3359 }
3360 if (account.getStatus() == Account.State.ONLINE) {
3361 synchronized (account.inProgressConferenceJoins) {
3362 account.inProgressConferenceJoins.add(conversation);
3363 }
3364 if (Config.MUC_LEAVE_BEFORE_JOIN) {
3365 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
3366 }
3367 conversation.resetMucOptions();
3368 if (onConferenceJoined != null) {
3369 conversation.getMucOptions().flagNoAutoPushConfiguration();
3370 }
3371 conversation.setHasMessagesLeftOnServer(false);
3372 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
3373
3374 private void join(Conversation conversation) {
3375 Account account = conversation.getAccount();
3376 final MucOptions mucOptions = conversation.getMucOptions();
3377
3378 if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
3379 synchronized (account.inProgressConferenceJoins) {
3380 account.inProgressConferenceJoins.remove(conversation);
3381 }
3382 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
3383 updateConversationUi();
3384 if (onConferenceJoined != null) {
3385 onConferenceJoined.onConferenceJoined(conversation);
3386 }
3387 return;
3388 }
3389
3390 final Jid joinJid = mucOptions.getSelf().getFullJid();
3391 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
3392 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null, mucOptions.getSelf().getNick());
3393 packet.setTo(joinJid);
3394 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
3395 if (conversation.getMucOptions().getPassword() != null) {
3396 x.addChild("password").setContent(mucOptions.getPassword());
3397 }
3398
3399 if (mucOptions.mamSupport()) {
3400 // Use MAM instead of the limited muc history to get history
3401 x.addChild("history").setAttribute("maxchars", "0");
3402 } else {
3403 // Fallback to muc history
3404 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
3405 }
3406 sendPresencePacket(account, packet);
3407 if (onConferenceJoined != null) {
3408 onConferenceJoined.onConferenceJoined(conversation);
3409 }
3410 if (!joinJid.equals(conversation.getJid())) {
3411 conversation.setContactJid(joinJid);
3412 databaseBackend.updateConversation(conversation);
3413 }
3414
3415 if (mucOptions.mamSupport()) {
3416 getMessageArchiveService().catchupMUC(conversation);
3417 }
3418 if (mucOptions.isPrivateAndNonAnonymous()) {
3419 fetchConferenceMembers(conversation);
3420
3421 if (followedInvite) {
3422 final Bookmark bookmark = conversation.getBookmark();
3423 if (bookmark != null) {
3424 if (!bookmark.autojoin()) {
3425 bookmark.setAutojoin(true);
3426 createBookmark(account, bookmark);
3427 }
3428 } else {
3429 saveConversationAsBookmark(conversation, null);
3430 }
3431 }
3432 }
3433 synchronized (account.inProgressConferenceJoins) {
3434 account.inProgressConferenceJoins.remove(conversation);
3435 sendUnsentMessages(conversation);
3436 }
3437 }
3438
3439 @Override
3440 public void onConferenceConfigurationFetched(Conversation conversation) {
3441 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3442 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3443 return;
3444 }
3445 join(conversation);
3446 }
3447
3448 @Override
3449 public void onFetchFailed(final Conversation conversation, final String errorCondition) {
3450 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
3451 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": conversation (" + conversation.getJid() + ") got archived before IQ result");
3452 return;
3453 }
3454 if ("remote-server-not-found".equals(errorCondition)) {
3455 synchronized (account.inProgressConferenceJoins) {
3456 account.inProgressConferenceJoins.remove(conversation);
3457 }
3458 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
3459 updateConversationUi();
3460 } else {
3461 join(conversation);
3462 fetchConferenceConfiguration(conversation);
3463 }
3464 }
3465 });
3466 updateConversationUi();
3467 } else {
3468 synchronized (account.pendingConferenceJoins) {
3469 account.pendingConferenceJoins.add(conversation);
3470 }
3471 conversation.resetMucOptions();
3472 conversation.setHasMessagesLeftOnServer(false);
3473 updateConversationUi();
3474 }
3475 }
3476
3477 private void fetchConferenceMembers(final Conversation conversation) {
3478 final Account account = conversation.getAccount();
3479 final AxolotlService axolotlService = account.getAxolotlService();
3480 final String[] affiliations = {"member", "admin", "owner"};
3481 OnIqPacketReceived callback = new OnIqPacketReceived() {
3482
3483 private int i = 0;
3484 private boolean success = true;
3485
3486 @Override
3487 public void onIqPacketReceived(Account account, IqPacket packet) {
3488 final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
3489 Element query = packet.query("http://jabber.org/protocol/muc#admin");
3490 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
3491 for (Element child : query.getChildren()) {
3492 if ("item".equals(child.getName())) {
3493 MucOptions.User user = AbstractParser.parseItem(conversation, child);
3494 if (!user.realJidMatchesAccount()) {
3495 boolean isNew = conversation.getMucOptions().updateUser(user);
3496 Contact contact = user.getContact();
3497 if (omemoEnabled
3498 && isNew
3499 && user.getRealJid() != null
3500 && (contact == null || !contact.mutualPresenceSubscription())
3501 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
3502 axolotlService.fetchDeviceIds(user.getRealJid());
3503 }
3504 }
3505 }
3506 }
3507 } else {
3508 success = false;
3509 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
3510 }
3511 ++i;
3512 if (i >= affiliations.length) {
3513 List<Jid> members = conversation.getMucOptions().getMembers(true);
3514 if (success) {
3515 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
3516 boolean changed = false;
3517 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
3518 Jid jid = iterator.next();
3519 if (!members.contains(jid) && !members.contains(jid.getDomain())) {
3520 iterator.remove();
3521 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
3522 changed = true;
3523 }
3524 }
3525 if (changed) {
3526 conversation.setAcceptedCryptoTargets(cryptoTargets);
3527 updateConversation(conversation);
3528 }
3529 }
3530 getAvatarService().clear(conversation);
3531 updateMucRosterUi();
3532 updateConversationUi();
3533 }
3534 }
3535 };
3536 for (String affiliation : affiliations) {
3537 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
3538 }
3539 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
3540 }
3541
3542 public void providePasswordForMuc(Conversation conversation, String password) {
3543 if (conversation.getMode() == Conversation.MODE_MULTI) {
3544 conversation.getMucOptions().setPassword(password);
3545 if (conversation.getBookmark() != null) {
3546 final Bookmark bookmark = conversation.getBookmark();
3547 if (synchronizeWithBookmarks()) {
3548 bookmark.setAutojoin(true);
3549 }
3550 createBookmark(conversation.getAccount(), bookmark);
3551 }
3552 updateConversation(conversation);
3553 joinMuc(conversation);
3554 }
3555 }
3556
3557 public void deleteAvatar(final Account account) {
3558 final AtomicBoolean executed = new AtomicBoolean(false);
3559 final Runnable onDeleted =
3560 () -> {
3561 if (executed.compareAndSet(false, true)) {
3562 account.setAvatar(null);
3563 databaseBackend.updateAccount(account);
3564 getAvatarService().clear(account);
3565 updateAccountUi();
3566 }
3567 };
3568 deleteVcardAvatar(account, onDeleted);
3569 deletePepNode(account, Namespace.AVATAR_DATA);
3570 deletePepNode(account, Namespace.AVATAR_METADATA, onDeleted);
3571 }
3572
3573 public void deletePepNode(final Account account, final String node) {
3574 deletePepNode(account, node, null);
3575 }
3576
3577 private void deletePepNode(final Account account, final String node, final Runnable runnable) {
3578 final IqPacket request = mIqGenerator.deleteNode(node);
3579 sendIqPacket(account, request, (a, packet) -> {
3580 if (packet.getType() == IqPacket.TYPE.RESULT) {
3581 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": successfully deleted pep node "+node);
3582 if (runnable != null) {
3583 runnable.run();
3584 }
3585 } else {
3586 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": failed to delete "+ packet);
3587 }
3588 });
3589 }
3590
3591 private void deleteVcardAvatar(final Account account, @NonNull final Runnable runnable) {
3592 final IqPacket retrieveVcard = mIqGenerator.retrieveVcardAvatar(account.getJid().asBareJid());
3593 sendIqPacket(account, retrieveVcard, (a, response) -> {
3594 if (response.getType() != IqPacket.TYPE.RESULT) {
3595 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3596 return;
3597 }
3598 final Element vcard = response.findChild("vCard", "vcard-temp");
3599 if (vcard == null) {
3600 Log.d(Config.LOGTAG,a.getJid().asBareJid()+": no vCard set. nothing to do");
3601 return;
3602 }
3603 Element photo = vcard.findChild("PHOTO");
3604 if (photo == null) {
3605 photo = vcard.addChild("PHOTO");
3606 }
3607 photo.clearChildren();
3608 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3609 publication.setTo(a.getJid().asBareJid());
3610 publication.addChild(vcard);
3611 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3612 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3613 Log.d(Config.LOGTAG,a1.getJid().asBareJid()+": successfully deleted vcard avatar");
3614 runnable.run();
3615 } else {
3616 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
3617 }
3618 });
3619 });
3620 }
3621
3622 private boolean hasEnabledAccounts() {
3623 if (this.accounts == null) {
3624 return false;
3625 }
3626 for (final Account account : this.accounts) {
3627 if (account.isConnectionEnabled()) {
3628 return true;
3629 }
3630 }
3631 return false;
3632 }
3633
3634
3635 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
3636 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
3637 }
3638
3639 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3640 getAttachments(account.getUuid(), jid.asBareJid(), limit, onMediaLoaded);
3641 }
3642
3643
3644 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
3645 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
3646 }
3647
3648 public void persistSelfNick(MucOptions.User self) {
3649 final Conversation conversation = self.getConversation();
3650 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
3651 Jid full = self.getFullJid();
3652 if (!full.equals(conversation.getJid())) {
3653 Log.d(Config.LOGTAG, "nick changed. updating");
3654 conversation.setContactJid(full);
3655 databaseBackend.updateConversation(conversation);
3656 }
3657
3658 final String nick = self.getNick();
3659 final Bookmark bookmark = conversation.getBookmark();
3660 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
3661 if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !nick.equals(bookmarkedNick)) {
3662 final Account account = conversation.getAccount();
3663 final String defaultNick = MucOptions.defaultNick(account);
3664 if (TextUtils.isEmpty(bookmarkedNick) && nick.equals(defaultNick)) {
3665 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not overwrite empty bookmark nick with default nick for " + conversation.getJid().asBareJid());
3666 return;
3667 }
3668 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": persist nick '" + nick + "' into bookmark for " + conversation.getJid().asBareJid());
3669 bookmark.setNick(nick);
3670 createBookmark(bookmark.getAccount(), bookmark);
3671 }
3672 }
3673
3674 public void presenceToMuc(final Conversation conversation) {
3675 final MucOptions options = conversation.getMucOptions();
3676 if (options.online()) {
3677 Account account = conversation.getAccount();
3678 final Jid joinJid = options.getSelf().getFullJid();
3679 final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), options.getSelf().getNick());
3680 packet.setTo(joinJid);
3681 sendPresencePacket(account, packet);
3682 }
3683 }
3684
3685 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
3686 final MucOptions options = conversation.getMucOptions();
3687 final Jid joinJid = options.createJoinJid(nick);
3688 if (joinJid == null) {
3689 return false;
3690 }
3691 if (options.online()) {
3692 Account account = conversation.getAccount();
3693 options.setOnRenameListener(new OnRenameListener() {
3694
3695 @Override
3696 public void onSuccess() {
3697 final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), nick);
3698 packet.setTo(joinJid);
3699 sendPresencePacket(account, packet);
3700 callback.success(conversation);
3701 }
3702
3703 @Override
3704 public void onFailure() {
3705 callback.error(R.string.nick_in_use, conversation);
3706 }
3707 });
3708
3709 final PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, options.nonanonymous(), nick);
3710 packet.setTo(joinJid);
3711 sendPresencePacket(account, packet);
3712 } else {
3713 conversation.setContactJid(joinJid);
3714 databaseBackend.updateConversation(conversation);
3715 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
3716 Bookmark bookmark = conversation.getBookmark();
3717 if (bookmark != null) {
3718 bookmark.setNick(nick);
3719 createBookmark(bookmark.getAccount(), bookmark);
3720 }
3721 joinMuc(conversation);
3722 }
3723 }
3724 return true;
3725 }
3726
3727 public void leaveMuc(Conversation conversation) {
3728 leaveMuc(conversation, false);
3729 }
3730
3731 private void leaveMuc(Conversation conversation, boolean now) {
3732 final Account account = conversation.getAccount();
3733 synchronized (account.pendingConferenceJoins) {
3734 account.pendingConferenceJoins.remove(conversation);
3735 }
3736 synchronized (account.pendingConferenceLeaves) {
3737 account.pendingConferenceLeaves.remove(conversation);
3738 }
3739 if (account.getStatus() == Account.State.ONLINE || now) {
3740 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
3741 conversation.getMucOptions().setOffline();
3742 Bookmark bookmark = conversation.getBookmark();
3743 if (bookmark != null) {
3744 bookmark.setConversation(null);
3745 }
3746 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
3747 } else {
3748 synchronized (account.pendingConferenceLeaves) {
3749 account.pendingConferenceLeaves.add(conversation);
3750 }
3751 }
3752 }
3753
3754 public String findConferenceServer(final Account account) {
3755 String server;
3756 if (account.getXmppConnection() != null) {
3757 server = account.getXmppConnection().getMucServer();
3758 if (server != null) {
3759 return server;
3760 }
3761 }
3762 for (Account other : getAccounts()) {
3763 if (other != account && other.getXmppConnection() != null) {
3764 server = other.getXmppConnection().getMucServer();
3765 if (server != null) {
3766 return server;
3767 }
3768 }
3769 }
3770 return null;
3771 }
3772
3773
3774 public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
3775 joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
3776 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
3777 if (!TextUtils.isEmpty(name)) {
3778 configuration.putString("muc#roomconfig_roomname", name);
3779 }
3780 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3781 @Override
3782 public void onPushSucceeded() {
3783 saveConversationAsBookmark(conversation, name);
3784 callback.success(conversation);
3785 }
3786
3787 @Override
3788 public void onPushFailed() {
3789 if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
3790 callback.error(R.string.unable_to_set_channel_configuration, conversation);
3791 } else {
3792 callback.error(R.string.joined_an_existing_channel, conversation);
3793 }
3794 }
3795 });
3796 });
3797 }
3798
3799 public boolean createAdhocConference(final Account account,
3800 final String name,
3801 final Iterable<Jid> jids,
3802 final UiCallback<Conversation> callback) {
3803 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
3804 if (account.getStatus() == Account.State.ONLINE) {
3805 try {
3806 String server = findConferenceServer(account);
3807 if (server == null) {
3808 if (callback != null) {
3809 callback.error(R.string.no_conference_server_found, null);
3810 }
3811 return false;
3812 }
3813 final Jid jid = Jid.of(CryptoHelper.pronounceable(), server, null);
3814 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
3815 joinMuc(conversation, new OnConferenceJoined() {
3816 @Override
3817 public void onConferenceJoined(final Conversation conversation) {
3818 final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
3819 if (!TextUtils.isEmpty(name)) {
3820 configuration.putString("muc#roomconfig_roomname", name);
3821 }
3822 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
3823 @Override
3824 public void onPushSucceeded() {
3825 for (Jid invite : jids) {
3826 invite(conversation, invite);
3827 }
3828 for (String resource : account.getSelfContact().getPresences().toResourceArray()) {
3829 if (resource == null || "".equals(resource)) continue;
3830 Jid other = account.getJid().withResource(resource);
3831 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending direct invite to " + other);
3832 directInvite(conversation, other);
3833 }
3834 saveConversationAsBookmark(conversation, name);
3835 if (callback != null) {
3836 callback.success(conversation);
3837 }
3838 }
3839
3840 @Override
3841 public void onPushFailed() {
3842 archiveConversation(conversation);
3843 if (callback != null) {
3844 callback.error(R.string.conference_creation_failed, conversation);
3845 }
3846 }
3847 });
3848 }
3849 });
3850 return true;
3851 } catch (IllegalArgumentException e) {
3852 if (callback != null) {
3853 callback.error(R.string.conference_creation_failed, null);
3854 }
3855 return false;
3856 }
3857 } else {
3858 if (callback != null) {
3859 callback.error(R.string.not_connected_try_again, null);
3860 }
3861 return false;
3862 }
3863 }
3864
3865 public void checkIfMuc(final Account account, final Jid jid, Consumer<Boolean> cb) {
3866 if (jid.isDomainJid()) {
3867 // Spec basically says MUC needs to have a node
3868 // And also specifies that MUC and MUC service should have the same identity...
3869 cb.accept(false);
3870 return;
3871 }
3872
3873 IqPacket request = mIqGenerator.queryDiscoInfo(jid.asBareJid());
3874 sendIqPacket(account, request, (acct, reply) -> {
3875 ServiceDiscoveryResult result = new ServiceDiscoveryResult(reply);
3876 cb.accept(
3877 result.getFeatures().contains("http://jabber.org/protocol/muc") &&
3878 result.hasIdentity("conference", null)
3879 );
3880 });
3881 }
3882
3883 public void fetchConferenceConfiguration(final Conversation conversation) {
3884 fetchConferenceConfiguration(conversation, null);
3885 }
3886
3887 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
3888 IqPacket request = mIqGenerator.queryDiscoInfo(conversation.getJid().asBareJid());
3889 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3890 @Override
3891 public void onIqPacketReceived(Account account, IqPacket packet) {
3892 if (packet.getType() == IqPacket.TYPE.RESULT) {
3893 final MucOptions mucOptions = conversation.getMucOptions();
3894 final Bookmark bookmark = conversation.getBookmark();
3895 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
3896
3897 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
3898 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
3899 updateConversation(conversation);
3900 }
3901
3902 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
3903 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
3904 createBookmark(account, bookmark);
3905 }
3906 }
3907
3908
3909 if (callback != null) {
3910 callback.onConferenceConfigurationFetched(conversation);
3911 }
3912
3913
3914 updateConversationUi();
3915 } else if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
3916 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received timeout waiting for conference configuration fetch");
3917 } else {
3918 if (callback != null) {
3919 callback.onFetchFailed(conversation, packet.getErrorCondition());
3920 }
3921 }
3922 }
3923 });
3924 }
3925
3926 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
3927 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
3928 }
3929
3930 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
3931 Log.d(Config.LOGTAG, "pushing node configuration");
3932 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
3933 @Override
3934 public void onIqPacketReceived(Account account, IqPacket packet) {
3935 if (packet.getType() == IqPacket.TYPE.RESULT) {
3936 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
3937 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
3938 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
3939 if (x != null) {
3940 Data data = Data.parse(x);
3941 data.submit(options);
3942 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
3943 @Override
3944 public void onIqPacketReceived(Account account, IqPacket packet) {
3945 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
3946 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully changed node configuration for node " + node);
3947 callback.onPushSucceeded();
3948 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3949 callback.onPushFailed();
3950 }
3951 }
3952 });
3953 } else if (callback != null) {
3954 callback.onPushFailed();
3955 }
3956 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
3957 callback.onPushFailed();
3958 }
3959 }
3960 });
3961 }
3962
3963 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
3964 if (options.getString("muc#roomconfig_whois", "moderators").equals("anyone")) {
3965 conversation.setAttribute("accept_non_anonymous", true);
3966 updateConversation(conversation);
3967 }
3968 if (options.containsKey("muc#roomconfig_moderatedroom")) {
3969 final boolean moderated = "1".equals(options.getString("muc#roomconfig_moderatedroom"));
3970 options.putString("members_by_default", moderated ? "0" : "1");
3971 }
3972 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3973 request.setTo(conversation.getJid().asBareJid());
3974 request.query("http://jabber.org/protocol/muc#owner");
3975 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3976 @Override
3977 public void onIqPacketReceived(Account account, IqPacket packet) {
3978 if (packet.getType() == IqPacket.TYPE.RESULT) {
3979 final Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
3980 data.submit(options);
3981 final IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3982 set.setTo(conversation.getJid().asBareJid());
3983 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
3984 sendIqPacket(account, set, new OnIqPacketReceived() {
3985 @Override
3986 public void onIqPacketReceived(Account account, IqPacket packet) {
3987 if (callback != null) {
3988 if (packet.getType() == IqPacket.TYPE.RESULT) {
3989 callback.onPushSucceeded();
3990 } else {
3991 callback.onPushFailed();
3992 }
3993 }
3994 }
3995 });
3996 } else {
3997 if (callback != null) {
3998 callback.onPushFailed();
3999 }
4000 }
4001 }
4002 });
4003 }
4004
4005 public void pushSubjectToConference(final Conversation conference, final String subject) {
4006 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
4007 this.sendMessagePacket(conference.getAccount(), packet);
4008 }
4009
4010 public void requestVoice(final Account account, final Jid jid) {
4011 MessagePacket packet = this.getMessageGenerator().requestVoice(jid);
4012 this.sendMessagePacket(account, packet);
4013 }
4014
4015 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
4016 final Jid jid = user.asBareJid();
4017 final IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
4018 sendIqPacket(conference.getAccount(), request, (account, response) -> {
4019 if (response.getType() == IqPacket.TYPE.RESULT) {
4020 conference.getMucOptions().changeAffiliation(jid, affiliation);
4021 getAvatarService().clear(conference);
4022 if (callback != null) {
4023 callback.onAffiliationChangedSuccessful(jid);
4024 } else {
4025 Log.d(Config.LOGTAG, "changed affiliation of " + user + " to " + affiliation);
4026 }
4027 } else if (callback != null) {
4028 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
4029 } else {
4030 Log.d(Config.LOGTAG, "unable to change affiliation");
4031 }
4032 });
4033 }
4034
4035 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
4036 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
4037 sendIqPacket(conference.getAccount(), request, (account, packet) -> {
4038 if (packet.getType() != IqPacket.TYPE.RESULT) {
4039 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " unable to change role of " + nick);
4040 }
4041 });
4042 }
4043
4044 public void moderateMessage(final Account account, final Message m, final String reason) {
4045 IqPacket request = this.mIqGenerator.moderateMessage(account, m, reason);
4046 sendIqPacket(account, request, (a, packet) -> {
4047 if (packet.getType() != IqPacket.TYPE.RESULT) {
4048 showErrorToastInUi(R.string.unable_to_moderate);
4049 Log.d(Config.LOGTAG, a.getJid().asBareJid() + " unable to moderate: " + packet);
4050 }
4051 });
4052 }
4053
4054 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
4055 IqPacket request = new IqPacket(IqPacket.TYPE.SET);
4056 request.setTo(conversation.getJid().asBareJid());
4057 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
4058 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
4059 @Override
4060 public void onIqPacketReceived(Account account, IqPacket packet) {
4061 if (packet.getType() == IqPacket.TYPE.RESULT) {
4062 if (callback != null) {
4063 callback.onRoomDestroySucceeded();
4064 }
4065 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
4066 if (callback != null) {
4067 callback.onRoomDestroyFailed();
4068 }
4069 }
4070 }
4071 });
4072 }
4073
4074 private void disconnect(final Account account, boolean force) {
4075 final XmppConnection connection = account.getXmppConnection();
4076 if (connection == null) {
4077 return;
4078 }
4079 if (!force) {
4080 final List<Conversation> conversations = getConversations();
4081 for (Conversation conversation : conversations) {
4082 if (conversation.getAccount() == account) {
4083 if (conversation.getMode() == Conversation.MODE_MULTI) {
4084 leaveMuc(conversation, true);
4085 }
4086 }
4087 }
4088 sendOfflinePresence(account);
4089 }
4090 connection.disconnect(force);
4091 }
4092
4093 @Override
4094 public IBinder onBind(Intent intent) {
4095 return mBinder;
4096 }
4097
4098 public void updateMessage(Message message) {
4099 updateMessage(message, true);
4100 }
4101
4102 public void updateMessage(Message message, boolean includeBody) {
4103 databaseBackend.updateMessage(message, includeBody);
4104 updateConversationUi();
4105 }
4106
4107 public void createMessageAsync(final Message message) {
4108 mDatabaseWriterExecutor.execute(() -> databaseBackend.createMessage(message));
4109 }
4110
4111 public void updateMessage(Message message, String uuid) {
4112 if (!databaseBackend.updateMessage(message, uuid)) {
4113 Log.e(Config.LOGTAG, "error updated message in DB after edit");
4114 }
4115 updateConversationUi();
4116 }
4117
4118 protected void syncDirtyContacts(Account account) {
4119 for (Contact contact : account.getRoster().getContacts()) {
4120 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
4121 pushContactToServer(contact);
4122 }
4123 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
4124 deleteContactOnServer(contact);
4125 }
4126 }
4127 }
4128
4129 protected void unregisterPhoneAccounts(final Account account) {
4130 for (final Contact contact : account.getRoster().getContacts()) {
4131 if (!contact.showInRoster()) {
4132 contact.unregisterAsPhoneAccount(this);
4133 }
4134 }
4135 }
4136
4137 public void createContact(final Contact contact, final boolean autoGrant) {
4138 createContact(contact, autoGrant, null);
4139 }
4140
4141 public void createContact(final Contact contact, final boolean autoGrant, final String preAuth) {
4142 if (autoGrant) {
4143 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
4144 contact.setOption(Contact.Options.ASKING);
4145 }
4146 pushContactToServer(contact, preAuth);
4147 }
4148
4149 public void pushContactToServer(final Contact contact) {
4150 pushContactToServer(contact, null);
4151 }
4152
4153 private void pushContactToServer(final Contact contact, final String preAuth) {
4154 contact.resetOption(Contact.Options.DIRTY_DELETE);
4155 contact.setOption(Contact.Options.DIRTY_PUSH);
4156 final Account account = contact.getAccount();
4157 if (account.getStatus() == Account.State.ONLINE) {
4158 final boolean ask = contact.getOption(Contact.Options.ASKING);
4159 final boolean sendUpdates = contact
4160 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
4161 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
4162 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
4163 iq.query(Namespace.ROSTER).addChild(contact.asElement());
4164 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4165 if (sendUpdates) {
4166 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
4167 }
4168 if (ask) {
4169 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact, preAuth));
4170 }
4171 } else {
4172 syncRoster(contact.getAccount());
4173 }
4174 }
4175
4176 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
4177 new Thread(() -> {
4178 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4179 final int size = Config.AVATAR_SIZE;
4180 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4181 if (avatar != null) {
4182 if (!getFileBackend().save(avatar)) {
4183 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4184 return;
4185 }
4186 avatar.owner = conversation.getJid().asBareJid();
4187 publishMucAvatar(conversation, avatar, callback);
4188 } else {
4189 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4190 }
4191 }).start();
4192 }
4193
4194 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
4195 new Thread(() -> {
4196 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
4197 final int size = Config.AVATAR_SIZE;
4198 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
4199 if (avatar != null) {
4200 if (!getFileBackend().save(avatar)) {
4201 Log.d(Config.LOGTAG, "unable to save vcard");
4202 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
4203 return;
4204 }
4205 publishAvatar(account, avatar, callback);
4206 } else {
4207 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
4208 }
4209 }).start();
4210
4211 }
4212
4213 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
4214 final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
4215 sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
4216 boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
4217 if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
4218 Element vcard = response.findChild("vCard", "vcard-temp");
4219 if (vcard == null) {
4220 vcard = new Element("vCard", "vcard-temp");
4221 }
4222 Element photo = vcard.findChild("PHOTO");
4223 if (photo == null) {
4224 photo = vcard.addChild("PHOTO");
4225 }
4226 photo.clearChildren();
4227 photo.addChild("TYPE").setContent(avatar.type);
4228 photo.addChild("BINVAL").setContent(avatar.image);
4229 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
4230 publication.setTo(conversation.getJid().asBareJid());
4231 publication.addChild(vcard);
4232 sendIqPacket(account, publication, (a1, publicationResponse) -> {
4233 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
4234 callback.onAvatarPublicationSucceeded();
4235 } else {
4236 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getErrorCondition());
4237 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4238 }
4239 });
4240 } else {
4241 Log.d(Config.LOGTAG, "failed to request vcard " + response);
4242 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
4243 }
4244 });
4245 }
4246
4247 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
4248 final Bundle options;
4249 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
4250 options = PublishOptions.openAccess();
4251 } else {
4252 options = null;
4253 }
4254 publishAvatar(account, avatar, options, true, callback);
4255 }
4256
4257 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
4258 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": publishing avatar. options=" + options);
4259 IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
4260 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4261
4262 @Override
4263 public void onIqPacketReceived(Account account, IqPacket result) {
4264 if (result.getType() == IqPacket.TYPE.RESULT) {
4265 publishAvatarMetadata(account, avatar, options, true, callback);
4266 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4267 pushNodeConfiguration(account, Namespace.AVATAR_DATA, options, new OnConfigurationPushed() {
4268 @Override
4269 public void onPushSucceeded() {
4270 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar node");
4271 publishAvatar(account, avatar, options, false, callback);
4272 }
4273
4274 @Override
4275 public void onPushFailed() {
4276 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar node");
4277 publishAvatar(account, avatar, null, false, callback);
4278 }
4279 });
4280 } else {
4281 Element error = result.findChild("error");
4282 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
4283 if (callback != null) {
4284 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4285 }
4286 }
4287 }
4288 });
4289 }
4290
4291 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
4292 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
4293 sendIqPacket(account, packet, new OnIqPacketReceived() {
4294 @Override
4295 public void onIqPacketReceived(Account account, IqPacket result) {
4296 if (result.getType() == IqPacket.TYPE.RESULT) {
4297 if (account.setAvatar(avatar.getFilename())) {
4298 getAvatarService().clear(account);
4299 databaseBackend.updateAccount(account);
4300 notifyAccountAvatarHasChanged(account);
4301 }
4302 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
4303 if (callback != null) {
4304 callback.onAvatarPublicationSucceeded();
4305 }
4306 } else if (retry && PublishOptions.preconditionNotMet(result)) {
4307 pushNodeConfiguration(account, Namespace.AVATAR_METADATA, options, new OnConfigurationPushed() {
4308 @Override
4309 public void onPushSucceeded() {
4310 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": changed node configuration for avatar meta data node");
4311 publishAvatarMetadata(account, avatar, options, false, callback);
4312 }
4313
4314 @Override
4315 public void onPushFailed() {
4316 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to change node configuration for avatar meta data node");
4317 publishAvatarMetadata(account, avatar, null, false, callback);
4318 }
4319 });
4320 } else {
4321 if (callback != null) {
4322 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
4323 }
4324 }
4325 }
4326 });
4327 }
4328
4329 public void republishAvatarIfNeeded(Account account) {
4330 if (account.getAxolotlService().isPepBroken()) {
4331 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
4332 return;
4333 }
4334 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4335 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4336
4337 private Avatar parseAvatar(IqPacket packet) {
4338 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4339 if (pubsub != null) {
4340 Element items = pubsub.findChild("items");
4341 if (items != null) {
4342 return Avatar.parseMetadata(items);
4343 }
4344 }
4345 return null;
4346 }
4347
4348 private boolean errorIsItemNotFound(IqPacket packet) {
4349 Element error = packet.findChild("error");
4350 return packet.getType() == IqPacket.TYPE.ERROR
4351 && error != null
4352 && error.hasChild("item-not-found");
4353 }
4354
4355 @Override
4356 public void onIqPacketReceived(Account account, IqPacket packet) {
4357 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
4358 Avatar serverAvatar = parseAvatar(packet);
4359 if (serverAvatar == null && account.getAvatar() != null) {
4360 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
4361 if (avatar != null) {
4362 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
4363 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
4364 } else {
4365 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
4366 }
4367 }
4368 }
4369 }
4370 });
4371 }
4372
4373 public void fetchAvatar(Account account, Avatar avatar) {
4374 fetchAvatar(account, avatar, null);
4375 }
4376
4377 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4378 if (databaseBackend.isBlockedMedia(avatar.cid())) {
4379 if (callback != null) callback.error(0, null);
4380 return;
4381 }
4382
4383 final String KEY = generateFetchKey(account, avatar);
4384 synchronized (this.mInProgressAvatarFetches) {
4385 if (mInProgressAvatarFetches.add(KEY)) {
4386 switch (avatar.origin) {
4387 case PEP:
4388 this.mInProgressAvatarFetches.add(KEY);
4389 fetchAvatarPep(account, avatar, callback);
4390 break;
4391 case VCARD:
4392 this.mInProgressAvatarFetches.add(KEY);
4393 fetchAvatarVcard(account, avatar, callback);
4394 break;
4395 }
4396 } else if (avatar.origin == Avatar.Origin.PEP) {
4397 mOmittedPepAvatarFetches.add(KEY);
4398 } else {
4399 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": already fetching " + avatar.origin + " avatar for " + avatar.owner);
4400 }
4401 }
4402 }
4403
4404 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4405 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
4406 sendIqPacket(account, packet, (a, result) -> {
4407 synchronized (mInProgressAvatarFetches) {
4408 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
4409 }
4410 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
4411 if (result.getType() == IqPacket.TYPE.RESULT) {
4412 avatar.image = mIqParser.avatarData(result);
4413 if (avatar.image != null) {
4414 if (getFileBackend().save(avatar)) {
4415 if (a.getJid().asBareJid().equals(avatar.owner)) {
4416 if (a.setAvatar(avatar.getFilename())) {
4417 databaseBackend.updateAccount(a);
4418 }
4419 getAvatarService().clear(a);
4420 updateConversationUi();
4421 updateAccountUi();
4422 } else {
4423 final Contact contact = a.getRoster().getContact(avatar.owner);
4424 contact.setAvatar(avatar);
4425 syncRoster(account);
4426 getAvatarService().clear(contact);
4427 updateConversationUi();
4428 updateRosterUi();
4429 }
4430 if (callback != null) {
4431 callback.success(avatar);
4432 }
4433 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": successfully fetched pep avatar for " + avatar.owner);
4434 return;
4435 }
4436 } else {
4437
4438 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
4439 }
4440 } else {
4441 Element error = result.findChild("error");
4442 if (error == null) {
4443 Log.d(Config.LOGTAG, ERROR + "(server error)");
4444 } else {
4445 Log.d(Config.LOGTAG, ERROR + error.toString());
4446 }
4447 }
4448 if (callback != null) {
4449 callback.error(0, null);
4450 }
4451
4452 });
4453 }
4454
4455 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
4456 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
4457 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4458 @Override
4459 public void onIqPacketReceived(Account account, IqPacket packet) {
4460 final boolean previouslyOmittedPepFetch;
4461 synchronized (mInProgressAvatarFetches) {
4462 final String KEY = generateFetchKey(account, avatar);
4463 mInProgressAvatarFetches.remove(KEY);
4464 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
4465 }
4466 if (packet.getType() == IqPacket.TYPE.RESULT) {
4467 Element vCard = packet.findChild("vCard", "vcard-temp");
4468 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
4469 String image = photo != null ? photo.findChildContent("BINVAL") : null;
4470 if (image != null) {
4471 avatar.image = image;
4472 if (getFileBackend().save(avatar)) {
4473 Log.d(Config.LOGTAG, account.getJid().asBareJid()
4474 + ": successfully fetched vCard avatar for " + avatar.owner + " omittedPep=" + previouslyOmittedPepFetch);
4475 if (avatar.owner.isBareJid()) {
4476 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
4477 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
4478 account.setAvatar(avatar.getFilename());
4479 databaseBackend.updateAccount(account);
4480 getAvatarService().clear(account);
4481 updateAccountUi();
4482 } else {
4483 final Contact contact = account.getRoster().getContact(avatar.owner);
4484 contact.setAvatar(avatar, previouslyOmittedPepFetch);
4485 syncRoster(account);
4486 getAvatarService().clear(contact);
4487 updateRosterUi();
4488 }
4489 updateConversationUi();
4490 } else {
4491 Conversation conversation = find(account, avatar.owner.asBareJid());
4492 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
4493 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
4494 if (user != null) {
4495 if (user.setAvatar(avatar)) {
4496 getAvatarService().clear(user);
4497 updateConversationUi();
4498 updateMucRosterUi();
4499 }
4500 if (user.getRealJid() != null) {
4501 Contact contact = account.getRoster().getContact(user.getRealJid());
4502 contact.setAvatar(avatar);
4503 syncRoster(account);
4504 getAvatarService().clear(contact);
4505 updateRosterUi();
4506 }
4507 }
4508 }
4509 }
4510 }
4511 }
4512 }
4513 }
4514 });
4515 }
4516
4517 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
4518 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
4519 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
4520
4521 @Override
4522 public void onIqPacketReceived(Account account, IqPacket packet) {
4523 if (packet.getType() == IqPacket.TYPE.RESULT) {
4524 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
4525 if (pubsub != null) {
4526 Element items = pubsub.findChild("items");
4527 if (items != null) {
4528 Avatar avatar = Avatar.parseMetadata(items);
4529 if (avatar != null) {
4530 avatar.owner = account.getJid().asBareJid();
4531 if (fileBackend.isAvatarCached(avatar)) {
4532 if (account.setAvatar(avatar.getFilename())) {
4533 databaseBackend.updateAccount(account);
4534 }
4535 getAvatarService().clear(account);
4536 callback.success(avatar);
4537 } else {
4538 fetchAvatarPep(account, avatar, callback);
4539 }
4540 return;
4541 }
4542 }
4543 }
4544 }
4545 callback.error(0, null);
4546 }
4547 });
4548 }
4549
4550 public void notifyAccountAvatarHasChanged(final Account account) {
4551 final XmppConnection connection = account.getXmppConnection();
4552 if (connection != null && connection.getFeatures().bookmarksConversion()) {
4553 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar changed. resending presence to online group chats");
4554 for (Conversation conversation : conversations) {
4555 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
4556 presenceToMuc(conversation);
4557 }
4558 }
4559 }
4560 }
4561
4562 public void fetchVcard4(Account account, final Contact contact, final Consumer<Element> callback) {
4563 IqPacket packet = this.mIqGenerator.retrieveVcard4(contact.getJid());
4564 sendIqPacket(account, packet, (a, result) -> {
4565 if (result.getType() == IqPacket.TYPE.RESULT) {
4566 final Element item = mIqParser.getItem(result);
4567 if (item != null) {
4568 final Element vcard4 = item.findChild("vcard", Namespace.VCARD4);
4569 if (vcard4 != null) {
4570 if (callback != null) {
4571 callback.accept(vcard4);
4572 }
4573 return;
4574 }
4575 }
4576 } else {
4577 Element error = result.findChild("error");
4578 if (error == null) {
4579 Log.d(Config.LOGTAG, "fetchVcard4 (server error)");
4580 } else {
4581 Log.d(Config.LOGTAG, "fetchVcard4 " + error.toString());
4582 }
4583 }
4584 if (callback != null) {
4585 callback.accept(null);
4586 }
4587
4588 });
4589 }
4590
4591 public void deleteContactOnServer(Contact contact) {
4592 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
4593 contact.resetOption(Contact.Options.DIRTY_PUSH);
4594 contact.setOption(Contact.Options.DIRTY_DELETE);
4595 Account account = contact.getAccount();
4596 if (account.getStatus() == Account.State.ONLINE) {
4597 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
4598 Element item = iq.query(Namespace.ROSTER).addChild("item");
4599 item.setAttribute("jid", contact.getJid());
4600 item.setAttribute("subscription", "remove");
4601 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
4602 }
4603 }
4604
4605 public void updateConversation(final Conversation conversation) {
4606 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
4607 }
4608
4609 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
4610 synchronized (account) {
4611 final XmppConnection existingConnection = account.getXmppConnection();
4612 final XmppConnection connection;
4613 if (existingConnection != null) {
4614 connection = existingConnection;
4615 } else if (account.isConnectionEnabled()) {
4616 connection = createConnection(account);
4617 account.setXmppConnection(connection);
4618 } else {
4619 return;
4620 }
4621 final boolean hasInternet = hasInternetConnection();
4622 if (account.isConnectionEnabled() && hasInternet) {
4623 if (!force) {
4624 disconnect(account, false);
4625 }
4626 Thread thread = new Thread(connection);
4627 connection.setInteractive(interactive);
4628 connection.prepareNewConnection();
4629 connection.interrupt();
4630 thread.start();
4631 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
4632 } else {
4633 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
4634 account.getRoster().clearPresences();
4635 connection.resetEverything();
4636 final AxolotlService axolotlService = account.getAxolotlService();
4637 if (axolotlService != null) {
4638 axolotlService.resetBrokenness();
4639 }
4640 if (!hasInternet) {
4641 account.setStatus(Account.State.NO_INTERNET);
4642 }
4643 }
4644 }
4645 }
4646
4647 public void reconnectAccountInBackground(final Account account) {
4648 new Thread(() -> reconnectAccount(account, false, true)).start();
4649 }
4650
4651 public void invite(final Conversation conversation, final Jid contact) {
4652 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
4653 final MucOptions.User user = conversation.getMucOptions().findUserByRealJid(contact.asBareJid());
4654 if (user == null || user.getAffiliation() == MucOptions.Affiliation.OUTCAST) {
4655 changeAffiliationInConference(conversation, contact, MucOptions.Affiliation.NONE, null);
4656 }
4657 final MessagePacket packet = mMessageGenerator.invite(conversation, contact);
4658 sendMessagePacket(conversation.getAccount(), packet);
4659 }
4660
4661 public void directInvite(Conversation conversation, Jid jid) {
4662 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
4663 sendMessagePacket(conversation.getAccount(), packet);
4664 }
4665
4666 public void resetSendingToWaiting(Account account) {
4667 for (Conversation conversation : getConversations()) {
4668 if (conversation.getAccount() == account) {
4669 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
4670 }
4671 }
4672 }
4673
4674 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
4675 return markMessage(account, recipient, uuid, status, null);
4676 }
4677
4678 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
4679 if (uuid == null) {
4680 return null;
4681 }
4682 for (Conversation conversation : getConversations()) {
4683 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
4684 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
4685 if (message != null) {
4686 markMessage(message, status, errorMessage);
4687 }
4688 return message;
4689 }
4690 }
4691 return null;
4692 }
4693
4694 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId) {
4695 return markMessage(conversation, uuid, status, serverMessageId, null, null);
4696 }
4697
4698 public boolean markMessage(final Conversation conversation, final String uuid, final int status, final String serverMessageId, final LocalizedContent body, final Element html) {
4699 if (uuid == null) {
4700 return false;
4701 } else {
4702 final Message message = conversation.findSentMessageWithUuid(uuid);
4703 if (message != null) {
4704 if (message.getServerMsgId() == null) {
4705 message.setServerMsgId(serverMessageId);
4706 }
4707 if (message.getEncryption() == Message.ENCRYPTION_NONE
4708 && message.isTypeText()
4709 && isBodyModified(message, body)) {
4710 message.setBody(body.content);
4711 message.setHtml(html);
4712 if (body.count > 1) {
4713 message.setBodyLanguage(body.language);
4714 }
4715 markMessage(message, status, null, true);
4716 } else {
4717 markMessage(message, status);
4718 }
4719 return true;
4720 } else {
4721 return false;
4722 }
4723 }
4724 }
4725
4726 private static boolean isBodyModified(final Message message, final LocalizedContent body) {
4727 if (body == null || body.content == null) {
4728 return false;
4729 }
4730 return !body.content.equals(message.getBody());
4731 }
4732
4733 public void markMessage(Message message, int status) {
4734 markMessage(message, status, null);
4735 }
4736
4737
4738 public void markMessage(final Message message, final int status, final String errorMessage) {
4739 markMessage(message, status, errorMessage, false);
4740 }
4741
4742 public void markMessage(final Message message, final int status, final String errorMessage, final boolean includeBody) {
4743 final int oldStatus = message.getStatus();
4744 if (status == Message.STATUS_SEND_FAILED && (oldStatus == Message.STATUS_SEND_RECEIVED || oldStatus == Message.STATUS_SEND_DISPLAYED)) {
4745 return;
4746 }
4747 if (status == Message.STATUS_SEND_RECEIVED && oldStatus == Message.STATUS_SEND_DISPLAYED) {
4748 return;
4749 }
4750 message.setErrorMessage(errorMessage);
4751 message.setStatus(status);
4752 databaseBackend.updateMessage(message, includeBody);
4753 updateConversationUi();
4754 if (oldStatus != status && status == Message.STATUS_SEND_FAILED) {
4755 mNotificationService.pushFailedDelivery(message);
4756 }
4757 }
4758
4759 public SharedPreferences getPreferences() {
4760 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
4761 }
4762
4763 public long getAutomaticMessageDeletionDate() {
4764 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
4765 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
4766 }
4767
4768 public long getLongPreference(String name, @IntegerRes int res) {
4769 long defaultValue = getResources().getInteger(res);
4770 try {
4771 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
4772 } catch (NumberFormatException e) {
4773 return defaultValue;
4774 }
4775 }
4776
4777 public boolean getBooleanPreference(String name, @BoolRes int res) {
4778 return getPreferences().getBoolean(name, getResources().getBoolean(res));
4779 }
4780
4781 public boolean confirmMessages() {
4782 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
4783 }
4784
4785 public boolean allowMessageCorrection() {
4786 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
4787 }
4788
4789 public boolean sendChatStates() {
4790 return getBooleanPreference("chat_states", R.bool.chat_states);
4791 }
4792
4793 private boolean synchronizeWithBookmarks() {
4794 return getBooleanPreference("autojoin", R.bool.autojoin);
4795 }
4796
4797 public boolean useTorToConnect() {
4798 return getBooleanPreference("use_tor", R.bool.use_tor);
4799 }
4800
4801 public boolean showExtendedConnectionOptions() {
4802 return getBooleanPreference("show_connection_options", R.bool.show_connection_options);
4803 }
4804
4805 public boolean broadcastLastActivity() {
4806 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
4807 }
4808
4809 public int unreadCount() {
4810 int count = 0;
4811 for (Conversation conversation : getConversations()) {
4812 count += conversation.unreadCount();
4813 }
4814 return count;
4815 }
4816
4817
4818 private <T> List<T> threadSafeList(Set<T> set) {
4819 synchronized (LISTENER_LOCK) {
4820 return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
4821 }
4822 }
4823
4824 public void showErrorToastInUi(int resId) {
4825 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
4826 listener.onShowErrorToast(resId);
4827 }
4828 }
4829
4830 public void updateConversationUi() {
4831 updateConversationUi(false);
4832 }
4833
4834 public void updateConversationUi(boolean newCaps) {
4835 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
4836 listener.onConversationUpdate(newCaps);
4837 }
4838 }
4839
4840 public void notifyJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state) {
4841 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4842 listener.onJingleRtpConnectionUpdate(account, with, sessionId, state);
4843 }
4844 }
4845
4846 public void notifyJingleRtpConnectionUpdate(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices) {
4847 for (OnJingleRtpConnectionUpdate listener : threadSafeList(this.onJingleRtpConnectionUpdate)) {
4848 listener.onAudioDeviceChanged(selectedAudioDevice, availableAudioDevices);
4849 }
4850 }
4851
4852 public void updateAccountUi() {
4853 for (final OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
4854 listener.onAccountUpdate();
4855 }
4856 }
4857
4858 public void updateRosterUi() {
4859 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
4860 listener.onRosterUpdate();
4861 }
4862 }
4863
4864 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
4865 if (mOnCaptchaRequested.size() > 0) {
4866 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
4867 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
4868 (int) (captcha.getHeight() * metrics.scaledDensity), false);
4869 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
4870 listener.onCaptchaRequested(account, id, data, scaled);
4871 }
4872 return true;
4873 }
4874 return false;
4875 }
4876
4877 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
4878 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
4879 listener.OnUpdateBlocklist(status);
4880 }
4881 }
4882
4883 public void updateMucRosterUi() {
4884 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
4885 listener.onMucRosterUpdate();
4886 }
4887 }
4888
4889 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
4890 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
4891 listener.onKeyStatusUpdated(report);
4892 }
4893 }
4894
4895 public Account findAccountByJid(final Jid jid) {
4896 for (final Account account : this.accounts) {
4897 if (account.getJid().asBareJid().equals(jid.asBareJid())) {
4898 return account;
4899 }
4900 }
4901 return null;
4902 }
4903
4904 public Account findAccountByUuid(final String uuid) {
4905 for (Account account : this.accounts) {
4906 if (account.getUuid().equals(uuid)) {
4907 return account;
4908 }
4909 }
4910 return null;
4911 }
4912
4913 public Conversation findConversationByUuid(String uuid) {
4914 for (Conversation conversation : getConversations()) {
4915 if (conversation.getUuid().equals(uuid)) {
4916 return conversation;
4917 }
4918 }
4919 return null;
4920 }
4921
4922 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
4923 List<Conversation> findings = new ArrayList<>();
4924 for (Conversation c : getConversations()) {
4925 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid().asBareJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
4926 findings.add(c);
4927 }
4928 }
4929 return findings.size() == 1 ? findings.get(0) : null;
4930 }
4931
4932 public boolean markRead(final Conversation conversation, boolean dismiss) {
4933 return markRead(conversation, null, dismiss).size() > 0;
4934 }
4935
4936 public void markRead(final Conversation conversation) {
4937 markRead(conversation, null, true);
4938 }
4939
4940 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
4941 if (dismiss) {
4942 mNotificationService.clear(conversation);
4943 }
4944 final List<Message> readMessages = conversation.markRead(upToUuid);
4945 if (readMessages.size() > 0) {
4946 Runnable runnable = () -> {
4947 for (Message message : readMessages) {
4948 databaseBackend.updateMessage(message, false);
4949 }
4950 };
4951 mDatabaseWriterExecutor.execute(runnable);
4952 updateConversationUi();
4953 updateUnreadCountBadge();
4954 return readMessages;
4955 } else {
4956 return readMessages;
4957 }
4958 }
4959
4960 public synchronized void updateUnreadCountBadge() {
4961 int count = unreadCount();
4962 if (unreadCount != count) {
4963 Log.d(Config.LOGTAG, "update unread count to " + count);
4964 if (count > 0) {
4965 ShortcutBadger.applyCount(getApplicationContext(), count);
4966 } else {
4967 ShortcutBadger.removeCount(getApplicationContext());
4968 }
4969 unreadCount = count;
4970 }
4971 }
4972
4973 public void sendReadMarker(final Conversation conversation, String upToUuid) {
4974 final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
4975 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
4976 if (readMessages.size() > 0) {
4977 updateConversationUi();
4978 }
4979 final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
4980 if (confirmMessages()
4981 && markable != null
4982 && (markable.trusted() || isPrivateAndNonAnonymousMuc)
4983 && markable.getRemoteMsgId() != null) {
4984 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
4985 final Account account = conversation.getAccount();
4986 final MessagePacket packet = mMessageGenerator.confirm(markable);
4987 this.sendMessagePacket(account, packet);
4988 }
4989 }
4990
4991 public MemorizingTrustManager getMemorizingTrustManager() {
4992 return this.mMemorizingTrustManager;
4993 }
4994
4995 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
4996 this.mMemorizingTrustManager = trustManager;
4997 }
4998
4999 public void updateMemorizingTrustmanager() {
5000 final MemorizingTrustManager tm;
5001 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
5002 if (dontTrustSystemCAs) {
5003 tm = new MemorizingTrustManager(getApplicationContext(), null);
5004 } else {
5005 tm = new MemorizingTrustManager(getApplicationContext());
5006 }
5007 setMemorizingTrustManager(tm);
5008 }
5009
5010 public LruCache<String, Drawable> getDrawableCache() {
5011 return this.mDrawableCache;
5012 }
5013
5014 public Collection<String> getKnownHosts() {
5015 final Set<String> hosts = new HashSet<>();
5016 for (final Account account : getAccounts()) {
5017 hosts.add(account.getServer());
5018 for (final Contact contact : account.getRoster().getContacts()) {
5019 if (contact.showInRoster()) {
5020 final String server = contact.getServer();
5021 if (server != null) {
5022 hosts.add(server);
5023 }
5024 }
5025 }
5026 }
5027 if (Config.QUICKSY_DOMAIN != null) {
5028 hosts.remove(Config.QUICKSY_DOMAIN.toEscapedString()); //we only want to show this when we type a e164 number
5029 }
5030 if (Config.DOMAIN_LOCK != null) {
5031 hosts.add(Config.DOMAIN_LOCK);
5032 }
5033 if (Config.MAGIC_CREATE_DOMAIN != null) {
5034 hosts.add(Config.MAGIC_CREATE_DOMAIN);
5035 }
5036 hosts.add("chat.above.im");
5037 return hosts;
5038 }
5039
5040 public Collection<String> getKnownConferenceHosts() {
5041 final Set<String> mucServers = new HashSet<>();
5042 for (final Account account : accounts) {
5043 if (account.getXmppConnection() != null) {
5044 mucServers.addAll(account.getXmppConnection().getMucServers());
5045 for (final Bookmark bookmark : account.getBookmarks()) {
5046 final Jid jid = bookmark.getJid();
5047 final String s = jid == null ? null : jid.getDomain().toEscapedString();
5048 if (s != null) {
5049 mucServers.add(s);
5050 }
5051 }
5052 }
5053 }
5054 return mucServers;
5055 }
5056
5057 public void sendMessagePacket(Account account, MessagePacket packet) {
5058 final XmppConnection connection = account.getXmppConnection();
5059 if (connection != null) {
5060 connection.sendMessagePacket(packet);
5061 }
5062 }
5063
5064 public void sendPresencePacket(Account account, PresencePacket packet) {
5065 XmppConnection connection = account.getXmppConnection();
5066 if (connection != null) {
5067 connection.sendPresencePacket(packet);
5068 }
5069 }
5070
5071 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
5072 final XmppConnection connection = account.getXmppConnection();
5073 if (connection != null) {
5074 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
5075 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
5076 }
5077 }
5078
5079 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
5080 sendIqPacket(account, packet, callback, null);
5081 }
5082
5083 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback, Long timeout) {
5084 final XmppConnection connection = account.getXmppConnection();
5085 if (connection != null) {
5086 connection.sendIqPacket(packet, callback, timeout);
5087 } else if (callback != null) {
5088 callback.onIqPacketReceived(account, new IqPacket(IqPacket.TYPE.TIMEOUT));
5089 }
5090 }
5091
5092 public void sendPresence(final Account account) {
5093 sendPresence(account, checkListeners() && broadcastLastActivity());
5094 }
5095
5096 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
5097 final Presence.Status status;
5098 if (manuallyChangePresence()) {
5099 status = account.getPresenceStatus();
5100 } else {
5101 status = getTargetPresence();
5102 }
5103 final PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
5104 if (mLastActivity > 0 && includeIdleTimestamp) {
5105 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
5106 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
5107 }
5108 sendPresencePacket(account, packet);
5109 }
5110
5111 private void deactivateGracePeriod() {
5112 for (Account account : getAccounts()) {
5113 account.deactivateGracePeriod();
5114 }
5115 }
5116
5117 public void refreshAllPresences() {
5118 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
5119 for (Account account : getAccounts()) {
5120 if (account.isConnectionEnabled()) {
5121 sendPresence(account, includeIdleTimestamp);
5122 }
5123 }
5124 }
5125
5126 private void refreshAllFcmTokens() {
5127 for (Account account : getAccounts()) {
5128 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
5129 mPushManagementService.registerPushTokenOnServer(account);
5130 }
5131 }
5132 }
5133
5134
5135
5136 private void sendOfflinePresence(final Account account) {
5137 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
5138 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
5139 }
5140
5141 public MessageGenerator getMessageGenerator() {
5142 return this.mMessageGenerator;
5143 }
5144
5145 public PresenceGenerator getPresenceGenerator() {
5146 return this.mPresenceGenerator;
5147 }
5148
5149 public IqGenerator getIqGenerator() {
5150 return this.mIqGenerator;
5151 }
5152
5153 public IqParser getIqParser() {
5154 return this.mIqParser;
5155 }
5156
5157 public JingleConnectionManager getJingleConnectionManager() {
5158 return this.mJingleConnectionManager;
5159 }
5160
5161 private boolean hasJingleRtpConnection(final Account account) {
5162 return this.mJingleConnectionManager.hasJingleRtpConnection(account);
5163 }
5164
5165 public MessageArchiveService getMessageArchiveService() {
5166 return this.mMessageArchiveService;
5167 }
5168
5169 public QuickConversationsService getQuickConversationsService() {
5170 return this.mQuickConversationsService;
5171 }
5172
5173 public List<Contact> findContacts(Jid jid, String accountJid) {
5174 ArrayList<Contact> contacts = new ArrayList<>();
5175 for (Account account : getAccounts()) {
5176 if ((account.isEnabled() || accountJid != null)
5177 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
5178 Contact contact = account.getRoster().getContactFromContactList(jid);
5179 if (contact != null) {
5180 contacts.add(contact);
5181 }
5182 }
5183 }
5184 return contacts;
5185 }
5186
5187 public Conversation findFirstMuc(Jid jid) {
5188 return findFirstMuc(jid, null);
5189 }
5190
5191 public Conversation findFirstMuc(Jid jid, String accountJid) {
5192 for (Conversation conversation : getConversations()) {
5193 if ((conversation.getAccount().isEnabled() || accountJid != null)
5194 && (accountJid == null || accountJid.equals(conversation.getAccount().getJid().asBareJid().toString()))
5195 && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
5196 return conversation;
5197 }
5198 }
5199 return null;
5200 }
5201
5202 public NotificationService getNotificationService() {
5203 return this.mNotificationService;
5204 }
5205
5206 public HttpConnectionManager getHttpConnectionManager() {
5207 return this.mHttpConnectionManager;
5208 }
5209
5210 public void resendFailedMessages(final Message message) {
5211 final Collection<Message> messages = new ArrayList<>();
5212 Message current = message;
5213 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
5214 messages.add(current);
5215 if (current.mergeable(current.next())) {
5216 current = current.next();
5217 } else {
5218 break;
5219 }
5220 }
5221 for (final Message msg : messages) {
5222 msg.setTime(System.currentTimeMillis());
5223 markMessage(msg, Message.STATUS_WAITING);
5224 this.resendMessage(msg, false);
5225 }
5226 if (message.getConversation() instanceof Conversation) {
5227 ((Conversation) message.getConversation()).sort();
5228 }
5229 updateConversationUi();
5230 }
5231
5232 public void clearConversationHistory(final Conversation conversation) {
5233 final long clearDate;
5234 final String reference;
5235 if (conversation.countMessages() > 0) {
5236 Message latestMessage = conversation.getLatestMessage();
5237 clearDate = latestMessage.getTimeSent() + 1000;
5238 reference = latestMessage.getServerMsgId();
5239 } else {
5240 clearDate = System.currentTimeMillis();
5241 reference = null;
5242 }
5243 conversation.clearMessages();
5244 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
5245 conversation.setLastClearHistory(clearDate, reference);
5246 Runnable runnable = () -> {
5247 databaseBackend.deleteMessagesInConversation(conversation);
5248 databaseBackend.updateConversation(conversation);
5249 };
5250 mDatabaseWriterExecutor.execute(runnable);
5251 }
5252
5253 public boolean sendBlockRequest(final Blockable blockable, final boolean reportSpam, final String serverMsgId) {
5254 if (blockable != null && blockable.getBlockedJid() != null) {
5255 final Jid jid = blockable.getBlockedJid();
5256 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam, serverMsgId), (a, response) -> {
5257 if (response.getType() == IqPacket.TYPE.RESULT) {
5258 a.getBlocklist().add(jid);
5259 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
5260 }
5261 });
5262 if (blockable.getBlockedJid().isFullJid()) {
5263 return false;
5264 } else if (removeBlockedConversations(blockable.getAccount(), jid)) {
5265 updateConversationUi();
5266 return true;
5267 } else {
5268 return false;
5269 }
5270 } else {
5271 return false;
5272 }
5273 }
5274
5275 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
5276 boolean removed = false;
5277 synchronized (this.conversations) {
5278 boolean domainJid = blockedJid.getLocal() == null;
5279 for (Conversation conversation : this.conversations) {
5280 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
5281 || blockedJid.equals(conversation.getJid().asBareJid());
5282 if (conversation.getAccount() == account
5283 && conversation.getMode() == Conversation.MODE_SINGLE
5284 && jidMatches) {
5285 this.conversations.remove(conversation);
5286 markRead(conversation);
5287 conversation.setStatus(Conversation.STATUS_ARCHIVED);
5288 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
5289 updateConversation(conversation);
5290 removed = true;
5291 }
5292 }
5293 }
5294 return removed;
5295 }
5296
5297 public void sendUnblockRequest(final Blockable blockable) {
5298 if (blockable != null && blockable.getJid() != null) {
5299 final Jid jid = blockable.getBlockedJid();
5300 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
5301 @Override
5302 public void onIqPacketReceived(final Account account, final IqPacket packet) {
5303 if (packet.getType() == IqPacket.TYPE.RESULT) {
5304 account.getBlocklist().remove(jid);
5305 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
5306 }
5307 }
5308 });
5309 }
5310 }
5311
5312 public void publishDisplayName(Account account) {
5313 String displayName = account.getDisplayName();
5314 final IqPacket request;
5315 if (TextUtils.isEmpty(displayName)) {
5316 request = mIqGenerator.deleteNode(Namespace.NICK);
5317 } else {
5318 request = mIqGenerator.publishNick(displayName);
5319 }
5320 mAvatarService.clear(account);
5321 sendIqPacket(account, request, (account1, packet) -> {
5322 if (packet.getType() == IqPacket.TYPE.ERROR) {
5323 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name " + packet);
5324 }
5325 });
5326 }
5327
5328 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
5329 ServiceDiscoveryResult result = discoCache.get(key);
5330 if (result != null) {
5331 return result;
5332 } else {
5333 if (key.first == null || key.second == null) return null;
5334 result = databaseBackend.findDiscoveryResult(key.first, key.second);
5335 if (result != null) {
5336 discoCache.put(key, result);
5337 }
5338 return result;
5339 }
5340 }
5341
5342 public void fetchFromGateway(Account account, final Jid jid, final String input, final OnGatewayResult callback) {
5343 IqPacket request = new IqPacket(input == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
5344 request.setTo(jid);
5345 Element query = request.query("jabber:iq:gateway");
5346 if (input != null) {
5347 Element prompt = query.addChild("prompt");
5348 prompt.setContent(input);
5349 }
5350 sendIqPacket(account, request, (Account acct, IqPacket packet) -> {
5351 if (packet.getType() == IqPacket.TYPE.RESULT) {
5352 callback.onGatewayResult(packet.query().findChildContent(input == null ? "prompt" : "jid"), null);
5353 } else {
5354 Element error = packet.findChild("error");
5355 callback.onGatewayResult(null, error == null ? null : error.findChildContent("text"));
5356 }
5357 });
5358 }
5359
5360 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
5361 fetchCaps(account, jid, presence, null);
5362 }
5363
5364 public void fetchCaps(Account account, final Jid jid, final Presence presence, Runnable cb) {
5365 final Pair<String, String> key = presence == null ? null : new Pair<>(presence.getHash(), presence.getVer());
5366 final ServiceDiscoveryResult disco = key == null ? null : getCachedServiceDiscoveryResult(key);
5367
5368 if (disco != null) {
5369 presence.setServiceDiscoveryResult(disco);
5370 final Contact contact = account.getRoster().getContact(jid);
5371 if (contact.refreshRtpCapability()) {
5372 syncRoster(account);
5373 }
5374 if (disco.hasIdentity("gateway", "pstn")) {
5375 contact.registerAsPhoneAccount(this);
5376 mQuickConversationsService.considerSyncBackground(false);
5377 }
5378 updateConversationUi(true);
5379 } else {
5380 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
5381 request.setTo(jid);
5382 final String node = presence == null ? null : presence.getNode();
5383 final String ver = presence == null ? null : presence.getVer();
5384 final Element query = request.query(Namespace.DISCO_INFO);
5385 if (node != null && ver != null) {
5386 query.setAttribute("node", node + "#" + ver);
5387 }
5388 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + (key == null ? "" : key.second) + " to " + jid);
5389 sendIqPacket(account, request, (a, response) -> {
5390 if (response.getType() == IqPacket.TYPE.RESULT) {
5391 final ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
5392 if (presence == null || presence.getVer() == null || presence.getVer().equals(discoveryResult.getVer())) {
5393 databaseBackend.insertDiscoveryResult(discoveryResult);
5394 injectServiceDiscoveryResult(a.getRoster(), presence == null ? null : presence.getHash(), presence == null ? null : presence.getVer(), jid.getResource(), discoveryResult);
5395 if (discoveryResult.hasIdentity("gateway", "pstn")) {
5396 final Contact contact = account.getRoster().getContact(jid);
5397 contact.registerAsPhoneAccount(this);
5398 mQuickConversationsService.considerSyncBackground(false);
5399 }
5400 updateConversationUi(true);
5401 if (cb != null) cb.run();
5402 } else {
5403 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
5404 }
5405 } else {
5406 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to fetch caps from " + jid);
5407 }
5408 });
5409 }
5410 }
5411
5412 public void fetchCommands(Account account, final Jid jid, OnIqPacketReceived callback) {
5413 final IqPacket request = mIqGenerator.queryDiscoItems(jid, "http://jabber.org/protocol/commands");
5414 sendIqPacket(account, request, callback);
5415 }
5416
5417 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, String resource, ServiceDiscoveryResult disco) {
5418 boolean rosterNeedsSync = false;
5419 for (final Contact contact : roster.getContacts()) {
5420 boolean serviceDiscoverySet = false;
5421 Presence onePresence = contact.getPresences().get(resource == null ? "" : resource);
5422 if (onePresence != null) {
5423 onePresence.setServiceDiscoveryResult(disco);
5424 serviceDiscoverySet = true;
5425 } else if (resource == null && hash == null && ver == null) {
5426 Presence p = new Presence(Presence.Status.OFFLINE, null, null, null, "");
5427 p.setServiceDiscoveryResult(disco);
5428 contact.updatePresence("", p);
5429 serviceDiscoverySet = true;
5430 }
5431 if (hash != null && ver != null) {
5432 for (final Presence presence : contact.getPresences().getPresences()) {
5433 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
5434 presence.setServiceDiscoveryResult(disco);
5435 serviceDiscoverySet = true;
5436 }
5437 }
5438 }
5439 if (serviceDiscoverySet) {
5440 rosterNeedsSync |= contact.refreshRtpCapability();
5441 }
5442 }
5443 if (rosterNeedsSync) {
5444 syncRoster(roster.getAccount());
5445 }
5446 }
5447
5448 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
5449 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
5450 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
5451 request.addChild("prefs", version.namespace);
5452 sendIqPacket(account, request, (account1, packet) -> {
5453 Element prefs = packet.findChild("prefs", version.namespace);
5454 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
5455 callback.onPreferencesFetched(prefs);
5456 } else {
5457 callback.onPreferencesFetchFailed();
5458 }
5459 });
5460 }
5461
5462 public PushManagementService getPushManagementService() {
5463 return mPushManagementService;
5464 }
5465
5466 public void changeStatus(Account account, PresenceTemplate template, String signature) {
5467 if (!template.getStatusMessage().isEmpty()) {
5468 databaseBackend.insertPresenceTemplate(template);
5469 }
5470 account.setPgpSignature(signature);
5471 account.setPresenceStatus(template.getStatus());
5472 account.setPresenceStatusMessage(template.getStatusMessage());
5473 databaseBackend.updateAccount(account);
5474 sendPresence(account);
5475 }
5476
5477 public List<PresenceTemplate> getPresenceTemplates(Account account) {
5478 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
5479 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
5480 if (!templates.contains(template)) {
5481 templates.add(0, template);
5482 }
5483 }
5484 return templates;
5485 }
5486
5487 public void saveConversationAsBookmark(Conversation conversation, String name) {
5488 final Account account = conversation.getAccount();
5489 final Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
5490 String nick = conversation.getMucOptions().getActualNick();
5491 if (nick == null) nick = conversation.getJid().getResource();
5492 if (nick != null && !nick.isEmpty() && !nick.equals(MucOptions.defaultNick(account))) {
5493 bookmark.setNick(nick);
5494 }
5495 if (!TextUtils.isEmpty(name)) {
5496 bookmark.setBookmarkName(name);
5497 }
5498 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
5499 createBookmark(account, bookmark);
5500 bookmark.setConversation(conversation);
5501 }
5502
5503 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
5504 boolean performedVerification = false;
5505 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
5506 for (XmppUri.Fingerprint fp : fingerprints) {
5507 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5508 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5509 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5510 if (fingerprintStatus != null) {
5511 if (!fingerprintStatus.isVerified()) {
5512 performedVerification = true;
5513 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5514 }
5515 } else {
5516 axolotlService.preVerifyFingerprint(contact, fingerprint);
5517 }
5518 }
5519 }
5520 return performedVerification;
5521 }
5522
5523 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
5524 final AxolotlService axolotlService = account.getAxolotlService();
5525 boolean verifiedSomething = false;
5526 for (XmppUri.Fingerprint fp : fingerprints) {
5527 if (fp.type == XmppUri.FingerprintType.OMEMO) {
5528 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
5529 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
5530 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
5531 if (fingerprintStatus != null) {
5532 if (!fingerprintStatus.isVerified()) {
5533 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
5534 verifiedSomething = true;
5535 }
5536 } else {
5537 axolotlService.preVerifyFingerprint(account, fingerprint);
5538 verifiedSomething = true;
5539 }
5540 }
5541 }
5542 return verifiedSomething;
5543 }
5544
5545 public boolean blindTrustBeforeVerification() {
5546 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
5547 }
5548
5549 public ShortcutService getShortcutService() {
5550 return mShortcutService;
5551 }
5552
5553 public void pushMamPreferences(Account account, Element prefs) {
5554 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
5555 set.addChild(prefs);
5556 sendIqPacket(account, set, null);
5557 }
5558
5559 public void evictPreview(File f) {
5560 if (mDrawableCache.remove(f.getAbsolutePath()) != null) {
5561 Log.d(Config.LOGTAG, "deleted cached preview");
5562 }
5563 }
5564
5565 public void evictPreview(String uuid) {
5566 if (mDrawableCache.remove(uuid) != null) {
5567 Log.d(Config.LOGTAG, "deleted cached preview");
5568 }
5569 }
5570
5571 public interface OnMamPreferencesFetched {
5572 void onPreferencesFetched(Element prefs);
5573
5574 void onPreferencesFetchFailed();
5575 }
5576
5577 public interface OnAccountCreated {
5578 void onAccountCreated(Account account);
5579
5580 void informUser(int r);
5581 }
5582
5583 public interface OnMoreMessagesLoaded {
5584 void onMoreMessagesLoaded(int count, Conversation conversation);
5585
5586 void informUser(int r);
5587 }
5588
5589 public interface OnAccountPasswordChanged {
5590 void onPasswordChangeSucceeded();
5591
5592 void onPasswordChangeFailed();
5593 }
5594
5595 public interface OnRoomDestroy {
5596 void onRoomDestroySucceeded();
5597
5598 void onRoomDestroyFailed();
5599 }
5600
5601 public interface OnAffiliationChanged {
5602 void onAffiliationChangedSuccessful(Jid jid);
5603
5604 void onAffiliationChangeFailed(Jid jid, int resId);
5605 }
5606
5607 public interface OnConversationUpdate {
5608 default void onConversationUpdate() { onConversationUpdate(false); }
5609 default void onConversationUpdate(boolean newCaps) { onConversationUpdate(); }
5610 }
5611
5612 public interface OnJingleRtpConnectionUpdate {
5613 void onJingleRtpConnectionUpdate(final Account account, final Jid with, final String sessionId, final RtpEndUserState state);
5614
5615 void onAudioDeviceChanged(AppRTCAudioManager.AudioDevice selectedAudioDevice, Set<AppRTCAudioManager.AudioDevice> availableAudioDevices);
5616 }
5617
5618 public interface OnAccountUpdate {
5619 void onAccountUpdate();
5620 }
5621
5622 public interface OnCaptchaRequested {
5623 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
5624 }
5625
5626 public interface OnRosterUpdate {
5627 void onRosterUpdate();
5628 }
5629
5630 public interface OnMucRosterUpdate {
5631 void onMucRosterUpdate();
5632 }
5633
5634 public interface OnConferenceConfigurationFetched {
5635 void onConferenceConfigurationFetched(Conversation conversation);
5636
5637 void onFetchFailed(Conversation conversation, String errorCondition);
5638 }
5639
5640 public interface OnConferenceJoined {
5641 void onConferenceJoined(Conversation conversation);
5642 }
5643
5644 public interface OnConfigurationPushed {
5645 void onPushSucceeded();
5646
5647 void onPushFailed();
5648 }
5649
5650 public interface OnShowErrorToast {
5651 void onShowErrorToast(int resId);
5652 }
5653
5654 public class XmppConnectionBinder extends Binder {
5655 public XmppConnectionService getService() {
5656 return XmppConnectionService.this;
5657 }
5658 }
5659
5660 private class InternalEventReceiver extends BroadcastReceiver {
5661
5662 @Override
5663 public void onReceive(final Context context, final Intent intent) {
5664 onStartCommand(intent, 0, 0);
5665 }
5666 }
5667
5668 private class RestrictedEventReceiver extends BroadcastReceiver {
5669
5670 private final Collection<String> allowedActions;
5671
5672 private RestrictedEventReceiver(final Collection<String> allowedActions) {
5673 this.allowedActions = allowedActions;
5674 }
5675
5676 @Override
5677 public void onReceive(final Context context, final Intent intent) {
5678 final String action = intent == null ? null : intent.getAction();
5679 if (allowedActions.contains(action)) {
5680 onStartCommand(intent,0,0);
5681 } else {
5682 Log.e(Config.LOGTAG,"restricting broadcast of event "+action);
5683 }
5684 }
5685 }
5686
5687 public static class OngoingCall {
5688 public final AbstractJingleConnection.Id id;
5689 public final Set<Media> media;
5690 public final boolean reconnecting;
5691
5692 public OngoingCall(AbstractJingleConnection.Id id, Set<Media> media, final boolean reconnecting) {
5693 this.id = id;
5694 this.media = media;
5695 this.reconnecting = reconnecting;
5696 }
5697
5698 @Override
5699 public boolean equals(Object o) {
5700 if (this == o) return true;
5701 if (o == null || getClass() != o.getClass()) return false;
5702 OngoingCall that = (OngoingCall) o;
5703 return reconnecting == that.reconnecting && Objects.equal(id, that.id) && Objects.equal(media, that.media);
5704 }
5705
5706 @Override
5707 public int hashCode() {
5708 return Objects.hashCode(id, media, reconnecting);
5709 }
5710 }
5711
5712 public static void toggleForegroundService(final XmppConnectionService service) {
5713 if (service == null) {
5714 return;
5715 }
5716 service.toggleForegroundService();
5717 }
5718
5719 public static void toggleForegroundService(final ConversationsActivity activity) {
5720 if (activity == null) {
5721 return;
5722 }
5723 toggleForegroundService(activity.xmppConnectionService);
5724 }
5725
5726 public static class BlockedMediaException extends Exception { }
5727}