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