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