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