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