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