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