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