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