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