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