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