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