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