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