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