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