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