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