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