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