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