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