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