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