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 final XmppConnection connection = account.getXmppConnection();
1563 if (connection != null && connection.getFeatures().bookmarksConversion()) {
1564 pushBookmarksPep(account);
1565 } else {
1566 pushBookmarksPrivateXml(account);
1567 }
1568 }
1569
1570 private void pushBookmarksPrivateXml(Account account) {
1571 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
1572 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1573 Element query = iqPacket.query("jabber:iq:private");
1574 Element storage = query.addChild("storage", "storage:bookmarks");
1575 for (Bookmark bookmark : account.getBookmarks()) {
1576 storage.addChild(bookmark);
1577 }
1578 sendIqPacket(account, iqPacket, mDefaultIqHandler);
1579 }
1580
1581 private void pushBookmarksPep(Account account) {
1582 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
1583 Element storage = new Element("storage", "storage:bookmarks");
1584 for (Bookmark bookmark : account.getBookmarks()) {
1585 storage.addChild(bookmark);
1586 }
1587 pushNodeAndEnforcePublishOptions(account,Namespace.BOOKMARKS,storage, PublishOptions.persistentWhitelistAccess());
1588
1589 }
1590
1591
1592 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final Bundle options) {
1593 pushNodeAndEnforcePublishOptions(account, node, element, options, true);
1594
1595 }
1596
1597 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final Bundle options, final boolean retry) {
1598 final IqPacket packet = mIqGenerator.publishElement(node, element, options);
1599 sendIqPacket(account, packet, (a, response) -> {
1600 if (response.getType() == IqPacket.TYPE.RESULT) {
1601 return;
1602 }
1603 if (retry && PublishOptions.preconditionNotMet(response)) {
1604 pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
1605 @Override
1606 public void onPushSucceeded() {
1607 pushNodeAndEnforcePublishOptions(account, node, element, options, false);
1608 }
1609
1610 @Override
1611 public void onPushFailed() {
1612 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to push node configuration ("+node+")");
1613 }
1614 });
1615 } else {
1616 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": error publishing bookmarks (retry="+Boolean.toString(retry)+") "+response);
1617 }
1618 });
1619 }
1620
1621 private void restoreFromDatabase() {
1622 synchronized (this.conversations) {
1623 final Map<String, Account> accountLookupTable = new Hashtable<>();
1624 for (Account account : this.accounts) {
1625 accountLookupTable.put(account.getUuid(), account);
1626 }
1627 Log.d(Config.LOGTAG, "restoring conversations...");
1628 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1629 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1630 for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1631 Conversation conversation = iterator.next();
1632 Account account = accountLookupTable.get(conversation.getAccountUuid());
1633 if (account != null) {
1634 conversation.setAccount(account);
1635 } else {
1636 Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1637 iterator.remove();
1638 }
1639 }
1640 long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1641 Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1642 Runnable runnable = () -> {
1643 long deletionDate = getAutomaticMessageDeletionDate();
1644 mLastExpiryRun.set(SystemClock.elapsedRealtime());
1645 if (deletionDate > 0) {
1646 Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1647 databaseBackend.expireOldMessages(deletionDate);
1648 }
1649 Log.d(Config.LOGTAG, "restoring roster...");
1650 for (Account account : accounts) {
1651 databaseBackend.readRoster(account.getRoster());
1652 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1653 }
1654 getBitmapCache().evictAll();
1655 loadPhoneContacts();
1656 Log.d(Config.LOGTAG, "restoring messages...");
1657 final long startMessageRestore = SystemClock.elapsedRealtime();
1658 final Conversation quickLoad = QuickLoader.get(this.conversations);
1659 if (quickLoad != null) {
1660 restoreMessages(quickLoad);
1661 updateConversationUi();
1662 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1663 Log.d(Config.LOGTAG,"quickly restored "+quickLoad.getName()+" after " + diffMessageRestore + "ms");
1664 }
1665 for (Conversation conversation : this.conversations) {
1666 if (quickLoad != conversation) {
1667 restoreMessages(conversation);
1668 }
1669 }
1670 mNotificationService.finishBacklog(false);
1671 restoredFromDatabaseLatch.countDown();
1672 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1673 Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
1674 updateConversationUi();
1675 };
1676 mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
1677 }
1678 }
1679
1680 private void restoreMessages(Conversation conversation) {
1681 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1682 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
1683 conversation.findUnreadMessages(message -> mNotificationService.pushFromBacklog(message));
1684 }
1685
1686 public void loadPhoneContacts() {
1687 mContactMergerExecutor.execute(() -> {
1688 Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
1689 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1690 for (Account account : accounts) {
1691 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
1692 for (JabberIdContact jidContact : contacts.values()) {
1693 final Contact contact = account.getRoster().getContact(jidContact.getJid());
1694 boolean needsCacheClean = contact.setPhoneContact(jidContact);
1695 if (needsCacheClean) {
1696 getAvatarService().clear(contact);
1697 }
1698 withSystemAccounts.remove(contact);
1699 }
1700 for (Contact contact : withSystemAccounts) {
1701 boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
1702 if (needsCacheClean) {
1703 getAvatarService().clear(contact);
1704 }
1705 }
1706 }
1707 Log.d(Config.LOGTAG, "finished merging phone contacts");
1708 mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
1709 updateRosterUi();
1710 mQuickConversationsService.considerSync();
1711 });
1712 }
1713
1714
1715 public void syncRoster(final Account account) {
1716 mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
1717 }
1718
1719 public List<Conversation> getConversations() {
1720 return this.conversations;
1721 }
1722
1723 private void markFileDeleted(final String path) {
1724 final File file = new File(path);
1725 final boolean isInternalFile = fileBackend.isInternalFile(file);
1726 final List<String> uuids = databaseBackend.markFileAsDeleted(file, isInternalFile);
1727 Log.d(Config.LOGTAG, "deleted file " + path+" internal="+isInternalFile+", database hits="+uuids.size());
1728 markUuidsAsDeletedFiles(uuids);
1729 }
1730
1731 private void markUuidsAsDeletedFiles(List<String> uuids) {
1732 boolean deleted = false;
1733 for (Conversation conversation : getConversations()) {
1734 deleted |= conversation.markAsDeleted(uuids);
1735 }
1736 if (deleted) {
1737 updateConversationUi();
1738 }
1739 }
1740
1741 private void markChangedFiles(List<DatabaseBackend.FilePathInfo> infos) {
1742 boolean changed = false;
1743 for (Conversation conversation : getConversations()) {
1744 changed |= conversation.markAsChanged(infos);
1745 }
1746 if (changed) {
1747 updateConversationUi();
1748 }
1749 }
1750
1751 public void populateWithOrderedConversations(final List<Conversation> list) {
1752 populateWithOrderedConversations(list, true, true);
1753 }
1754
1755 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload) {
1756 populateWithOrderedConversations(list, includeNoFileUpload, true);
1757 }
1758
1759 public void populateWithOrderedConversations(final List<Conversation> list, final boolean includeNoFileUpload, final boolean sort) {
1760 final List<String> orderedUuids;
1761 if (sort) {
1762 orderedUuids = null;
1763 } else {
1764 orderedUuids = new ArrayList<>();
1765 for(Conversation conversation : list) {
1766 orderedUuids.add(conversation.getUuid());
1767 }
1768 }
1769 list.clear();
1770 if (includeNoFileUpload) {
1771 list.addAll(getConversations());
1772 } else {
1773 for (Conversation conversation : getConversations()) {
1774 if (conversation.getMode() == Conversation.MODE_SINGLE
1775 || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
1776 list.add(conversation);
1777 }
1778 }
1779 }
1780 try {
1781 if (orderedUuids != null) {
1782 Collections.sort(list, (a, b) -> {
1783 final int indexA = orderedUuids.indexOf(a.getUuid());
1784 final int indexB = orderedUuids.indexOf(b.getUuid());
1785 if (indexA == -1 || indexB == -1 || indexA == indexB) {
1786 return a.compareTo(b);
1787 }
1788 return indexA - indexB;
1789 });
1790 } else {
1791 Collections.sort(list);
1792 }
1793 } catch (IllegalArgumentException e) {
1794 //ignore
1795 }
1796 }
1797
1798 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1799 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1800 return;
1801 } else if (timestamp == 0) {
1802 return;
1803 }
1804 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1805 final Runnable runnable = () -> {
1806 final Account account = conversation.getAccount();
1807 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1808 if (messages.size() > 0) {
1809 conversation.addAll(0, messages);
1810 callback.onMoreMessagesLoaded(messages.size(), conversation);
1811 } else if (conversation.hasMessagesLeftOnServer()
1812 && account.isOnlineAndConnected()
1813 && conversation.getLastClearHistory().getTimestamp() == 0) {
1814 final boolean mamAvailable;
1815 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1816 mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
1817 } else {
1818 mamAvailable = conversation.getMucOptions().mamSupport();
1819 }
1820 if (mamAvailable) {
1821 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
1822 if (query != null) {
1823 query.setCallback(callback);
1824 callback.informUser(R.string.fetching_history_from_server);
1825 } else {
1826 callback.informUser(R.string.not_fetching_history_retention_period);
1827 }
1828
1829 }
1830 }
1831 };
1832 mDatabaseReaderExecutor.execute(runnable);
1833 }
1834
1835 public List<Account> getAccounts() {
1836 return this.accounts;
1837 }
1838
1839
1840 /**
1841 * 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)
1842 */
1843 public List<Conversation> findAllConferencesWith(Contact contact) {
1844 ArrayList<Conversation> results = new ArrayList<>();
1845 for (final Conversation c : conversations) {
1846 if (c.getMode() == Conversation.MODE_MULTI && (c.getJid().asBareJid().equals(contact.getJid().asBareJid()) || c.getMucOptions().isContactInRoom(contact))) {
1847 results.add(c);
1848 }
1849 }
1850 return results;
1851 }
1852
1853 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1854 for (final Conversation conversation : haystack) {
1855 if (conversation.getContact() == contact) {
1856 return conversation;
1857 }
1858 }
1859 return null;
1860 }
1861
1862 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1863 if (jid == null) {
1864 return null;
1865 }
1866 for (final Conversation conversation : haystack) {
1867 if ((account == null || conversation.getAccount() == account)
1868 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
1869 return conversation;
1870 }
1871 }
1872 return null;
1873 }
1874
1875 public boolean isConversationsListEmpty(final Conversation ignore) {
1876 synchronized (this.conversations) {
1877 final int size = this.conversations.size();
1878 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
1879 }
1880 }
1881
1882 public boolean isConversationStillOpen(final Conversation conversation) {
1883 synchronized (this.conversations) {
1884 for (Conversation current : this.conversations) {
1885 if (current == conversation) {
1886 return true;
1887 }
1888 }
1889 }
1890 return false;
1891 }
1892
1893 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
1894 return this.findOrCreateConversation(account, jid, muc, false, async);
1895 }
1896
1897 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
1898 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
1899 }
1900
1901 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
1902 synchronized (this.conversations) {
1903 Conversation conversation = find(account, jid);
1904 if (conversation != null) {
1905 return conversation;
1906 }
1907 conversation = databaseBackend.findConversation(account, jid);
1908 final boolean loadMessagesFromDb;
1909 if (conversation != null) {
1910 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1911 conversation.setAccount(account);
1912 if (muc) {
1913 conversation.setMode(Conversation.MODE_MULTI);
1914 conversation.setContactJid(jid);
1915 } else {
1916 conversation.setMode(Conversation.MODE_SINGLE);
1917 conversation.setContactJid(jid.asBareJid());
1918 }
1919 databaseBackend.updateConversation(conversation);
1920 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
1921 } else {
1922 String conversationName;
1923 Contact contact = account.getRoster().getContact(jid);
1924 if (contact != null) {
1925 conversationName = contact.getDisplayName();
1926 } else {
1927 conversationName = jid.getLocal();
1928 }
1929 if (muc) {
1930 conversation = new Conversation(conversationName, account, jid,
1931 Conversation.MODE_MULTI);
1932 } else {
1933 conversation = new Conversation(conversationName, account, jid.asBareJid(),
1934 Conversation.MODE_SINGLE);
1935 }
1936 this.databaseBackend.createConversation(conversation);
1937 loadMessagesFromDb = false;
1938 }
1939 final Conversation c = conversation;
1940 final Runnable runnable = () -> {
1941 if (loadMessagesFromDb) {
1942 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
1943 updateConversationUi();
1944 c.messagesLoaded.set(true);
1945 }
1946 if (account.getXmppConnection() != null
1947 && !c.getContact().isBlocked()
1948 && account.getXmppConnection().getFeatures().mam()
1949 && !muc) {
1950 if (query == null) {
1951 mMessageArchiveService.query(c);
1952 } else {
1953 if (query.getConversation() == null) {
1954 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
1955 }
1956 }
1957 }
1958 if (joinAfterCreate) {
1959 joinMuc(c);
1960 }
1961 };
1962 if (async) {
1963 mDatabaseReaderExecutor.execute(runnable);
1964 } else {
1965 runnable.run();
1966 }
1967 this.conversations.add(conversation);
1968 updateConversationUi();
1969 return conversation;
1970 }
1971 }
1972
1973 public void archiveConversation(Conversation conversation) {
1974 archiveConversation(conversation, true);
1975 }
1976
1977 private void archiveConversation(Conversation conversation, final boolean maySynchronizeWithBookmarks) {
1978 getNotificationService().clear(conversation);
1979 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1980 conversation.setNextMessage(null);
1981 synchronized (this.conversations) {
1982 getMessageArchiveService().kill(conversation);
1983 if (conversation.getMode() == Conversation.MODE_MULTI) {
1984 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1985 Bookmark bookmark = conversation.getBookmark();
1986 if (maySynchronizeWithBookmarks && bookmark != null && synchronizeWithBookmarks()) {
1987 if (conversation.getMucOptions().getError() == MucOptions.Error.DESTROYED) {
1988 Account account = bookmark.getAccount();
1989 bookmark.setConversation(null);
1990 account.getBookmarks().remove(bookmark);
1991 pushBookmarks(account);
1992 } else if (bookmark.autojoin()) {
1993 bookmark.setAutojoin(false);
1994 pushBookmarks(bookmark.getAccount());
1995 }
1996 }
1997 }
1998 leaveMuc(conversation);
1999 } else {
2000 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
2001 stopPresenceUpdatesTo(conversation.getContact());
2002 }
2003 }
2004 updateConversation(conversation);
2005 this.conversations.remove(conversation);
2006 updateConversationUi();
2007 }
2008 }
2009
2010 public void stopPresenceUpdatesTo(Contact contact) {
2011 Log.d(Config.LOGTAG, "Canceling presence request from " + contact.getJid().toString());
2012 sendPresencePacket(contact.getAccount(), mPresenceGenerator.stopPresenceUpdatesTo(contact));
2013 contact.resetOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST);
2014 }
2015
2016 public void createAccount(final Account account) {
2017 account.initAccountServices(this);
2018 databaseBackend.createAccount(account);
2019 this.accounts.add(account);
2020 this.reconnectAccountInBackground(account);
2021 updateAccountUi();
2022 syncEnabledAccountSetting();
2023 toggleForegroundService();
2024 }
2025
2026 private void syncEnabledAccountSetting() {
2027 final boolean hasEnabledAccounts = hasEnabledAccounts();
2028 getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts).apply();
2029 toggleSetProfilePictureActivity(hasEnabledAccounts);
2030 }
2031
2032 private void toggleSetProfilePictureActivity(final boolean enabled) {
2033 try {
2034 final ComponentName name = new ComponentName(this, ChooseAccountForProfilePictureActivity.class);
2035 final int targetState = enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
2036 getPackageManager().setComponentEnabledSetting(name, targetState, PackageManager.DONT_KILL_APP);
2037 } catch (IllegalStateException e) {
2038 Log.d(Config.LOGTAG,"unable to toggle profile picture actvitiy");
2039 }
2040 }
2041
2042 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
2043 new Thread(() -> {
2044 try {
2045 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
2046 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
2047 if (cert == null) {
2048 callback.informUser(R.string.unable_to_parse_certificate);
2049 return;
2050 }
2051 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
2052 if (info == null) {
2053 callback.informUser(R.string.certificate_does_not_contain_jid);
2054 return;
2055 }
2056 if (findAccountByJid(info.first) == null) {
2057 Account account = new Account(info.first, "");
2058 account.setPrivateKeyAlias(alias);
2059 account.setOption(Account.OPTION_DISABLED, true);
2060 account.setDisplayName(info.second);
2061 createAccount(account);
2062 callback.onAccountCreated(account);
2063 if (Config.X509_VERIFICATION) {
2064 try {
2065 getMemorizingTrustManager().getNonInteractive(account.getJid().getDomain()).checkClientTrusted(chain, "RSA");
2066 } catch (CertificateException e) {
2067 callback.informUser(R.string.certificate_chain_is_not_trusted);
2068 }
2069 }
2070 } else {
2071 callback.informUser(R.string.account_already_exists);
2072 }
2073 } catch (Exception e) {
2074 e.printStackTrace();
2075 callback.informUser(R.string.unable_to_parse_certificate);
2076 }
2077 }).start();
2078
2079 }
2080
2081 public void updateKeyInAccount(final Account account, final String alias) {
2082 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
2083 try {
2084 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
2085 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
2086 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
2087 if (info == null) {
2088 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
2089 return;
2090 }
2091 if (account.getJid().asBareJid().equals(info.first)) {
2092 account.setPrivateKeyAlias(alias);
2093 account.setDisplayName(info.second);
2094 databaseBackend.updateAccount(account);
2095 if (Config.X509_VERIFICATION) {
2096 try {
2097 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
2098 } catch (CertificateException e) {
2099 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
2100 }
2101 account.getAxolotlService().regenerateKeys(true);
2102 }
2103 } else {
2104 showErrorToastInUi(R.string.jid_does_not_match_certificate);
2105 }
2106 } catch (Exception e) {
2107 e.printStackTrace();
2108 }
2109 }
2110
2111 public boolean updateAccount(final Account account) {
2112 if (databaseBackend.updateAccount(account)) {
2113 account.setShowErrorNotification(true);
2114 this.statusListener.onStatusChanged(account);
2115 databaseBackend.updateAccount(account);
2116 reconnectAccountInBackground(account);
2117 updateAccountUi();
2118 getNotificationService().updateErrorNotification();
2119 toggleForegroundService();
2120 syncEnabledAccountSetting();
2121 return true;
2122 } else {
2123 return false;
2124 }
2125 }
2126
2127 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
2128 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
2129 sendIqPacket(account, iq, (a, packet) -> {
2130 if (packet.getType() == IqPacket.TYPE.RESULT) {
2131 a.setPassword(newPassword);
2132 a.setOption(Account.OPTION_MAGIC_CREATE, false);
2133 databaseBackend.updateAccount(a);
2134 callback.onPasswordChangeSucceeded();
2135 } else {
2136 callback.onPasswordChangeFailed();
2137 }
2138 });
2139 }
2140
2141 public void deleteAccount(final Account account) {
2142 synchronized (this.conversations) {
2143 for (final Conversation conversation : conversations) {
2144 if (conversation.getAccount() == account) {
2145 if (conversation.getMode() == Conversation.MODE_MULTI) {
2146 leaveMuc(conversation);
2147 }
2148 conversations.remove(conversation);
2149 }
2150 }
2151 if (account.getXmppConnection() != null) {
2152 new Thread(() -> disconnect(account, true)).start();
2153 }
2154 final Runnable runnable = () -> {
2155 if (!databaseBackend.deleteAccount(account)) {
2156 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
2157 }
2158 };
2159 mDatabaseWriterExecutor.execute(runnable);
2160 this.accounts.remove(account);
2161 this.mRosterSyncTaskManager.clear(account);
2162 updateAccountUi();
2163 getNotificationService().updateErrorNotification();
2164 syncEnabledAccountSetting();
2165 toggleForegroundService();
2166 }
2167 }
2168
2169 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
2170 final boolean remainingListeners;
2171 synchronized (LISTENER_LOCK) {
2172 remainingListeners = checkListeners();
2173 if (!this.mOnConversationUpdates.add(listener)) {
2174 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as ConversationListChangedListener");
2175 }
2176 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2177 }
2178 if (remainingListeners) {
2179 switchToForeground();
2180 }
2181 }
2182
2183 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2184 final boolean remainingListeners;
2185 synchronized (LISTENER_LOCK) {
2186 this.mOnConversationUpdates.remove(listener);
2187 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2188 remainingListeners = checkListeners();
2189 }
2190 if (remainingListeners) {
2191 switchToBackground();
2192 }
2193 }
2194
2195 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2196 final boolean remainingListeners;
2197 synchronized (LISTENER_LOCK) {
2198 remainingListeners = checkListeners();
2199 if (!this.mOnShowErrorToasts.add(listener)) {
2200 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnShowErrorToastListener");
2201 }
2202 }
2203 if (remainingListeners) {
2204 switchToForeground();
2205 }
2206 }
2207
2208 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2209 final boolean remainingListeners;
2210 synchronized (LISTENER_LOCK) {
2211 this.mOnShowErrorToasts.remove(onShowErrorToast);
2212 remainingListeners = checkListeners();
2213 }
2214 if (remainingListeners) {
2215 switchToBackground();
2216 }
2217 }
2218
2219 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2220 final boolean remainingListeners;
2221 synchronized (LISTENER_LOCK) {
2222 remainingListeners = checkListeners();
2223 if (!this.mOnAccountUpdates.add(listener)) {
2224 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnAccountListChangedtListener");
2225 }
2226 }
2227 if (remainingListeners) {
2228 switchToForeground();
2229 }
2230 }
2231
2232 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2233 final boolean remainingListeners;
2234 synchronized (LISTENER_LOCK) {
2235 this.mOnAccountUpdates.remove(listener);
2236 remainingListeners = checkListeners();
2237 }
2238 if (remainingListeners) {
2239 switchToBackground();
2240 }
2241 }
2242
2243 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2244 final boolean remainingListeners;
2245 synchronized (LISTENER_LOCK) {
2246 remainingListeners = checkListeners();
2247 if (!this.mOnCaptchaRequested.add(listener)) {
2248 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnCaptchaRequestListener");
2249 }
2250 }
2251 if (remainingListeners) {
2252 switchToForeground();
2253 }
2254 }
2255
2256 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2257 final boolean remainingListeners;
2258 synchronized (LISTENER_LOCK) {
2259 this.mOnCaptchaRequested.remove(listener);
2260 remainingListeners = checkListeners();
2261 }
2262 if (remainingListeners) {
2263 switchToBackground();
2264 }
2265 }
2266
2267 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2268 final boolean remainingListeners;
2269 synchronized (LISTENER_LOCK) {
2270 remainingListeners = checkListeners();
2271 if (!this.mOnRosterUpdates.add(listener)) {
2272 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnRosterUpdateListener");
2273 }
2274 }
2275 if (remainingListeners) {
2276 switchToForeground();
2277 }
2278 }
2279
2280 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2281 final boolean remainingListeners;
2282 synchronized (LISTENER_LOCK) {
2283 this.mOnRosterUpdates.remove(listener);
2284 remainingListeners = checkListeners();
2285 }
2286 if (remainingListeners) {
2287 switchToBackground();
2288 }
2289 }
2290
2291 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2292 final boolean remainingListeners;
2293 synchronized (LISTENER_LOCK) {
2294 remainingListeners = checkListeners();
2295 if (!this.mOnUpdateBlocklist.add(listener)) {
2296 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnUpdateBlocklistListener");
2297 }
2298 }
2299 if (remainingListeners) {
2300 switchToForeground();
2301 }
2302 }
2303
2304 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2305 final boolean remainingListeners;
2306 synchronized (LISTENER_LOCK) {
2307 this.mOnUpdateBlocklist.remove(listener);
2308 remainingListeners = checkListeners();
2309 }
2310 if (remainingListeners) {
2311 switchToBackground();
2312 }
2313 }
2314
2315 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2316 final boolean remainingListeners;
2317 synchronized (LISTENER_LOCK) {
2318 remainingListeners = checkListeners();
2319 if (!this.mOnKeyStatusUpdated.add(listener)) {
2320 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnKeyStatusUpdateListener");
2321 }
2322 }
2323 if (remainingListeners) {
2324 switchToForeground();
2325 }
2326 }
2327
2328 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2329 final boolean remainingListeners;
2330 synchronized (LISTENER_LOCK) {
2331 this.mOnKeyStatusUpdated.remove(listener);
2332 remainingListeners = checkListeners();
2333 }
2334 if (remainingListeners) {
2335 switchToBackground();
2336 }
2337 }
2338
2339 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2340 final boolean remainingListeners;
2341 synchronized (LISTENER_LOCK) {
2342 remainingListeners = checkListeners();
2343 if (!this.mOnMucRosterUpdate.add(listener)) {
2344 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnMucRosterListener");
2345 }
2346 }
2347 if (remainingListeners) {
2348 switchToForeground();
2349 }
2350 }
2351
2352 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2353 final boolean remainingListeners;
2354 synchronized (LISTENER_LOCK) {
2355 this.mOnMucRosterUpdate.remove(listener);
2356 remainingListeners = checkListeners();
2357 }
2358 if (remainingListeners) {
2359 switchToBackground();
2360 }
2361 }
2362
2363 public boolean checkListeners() {
2364 return (this.mOnAccountUpdates.size() == 0
2365 && this.mOnConversationUpdates.size() == 0
2366 && this.mOnRosterUpdates.size() == 0
2367 && this.mOnCaptchaRequested.size() == 0
2368 && this.mOnMucRosterUpdate.size() == 0
2369 && this.mOnUpdateBlocklist.size() == 0
2370 && this.mOnShowErrorToasts.size() == 0
2371 && this.mOnKeyStatusUpdated.size() == 0);
2372 }
2373
2374 private void switchToForeground() {
2375 final boolean broadcastLastActivity = broadcastLastActivity();
2376 for (Conversation conversation : getConversations()) {
2377 if (conversation.getMode() == Conversation.MODE_MULTI) {
2378 conversation.getMucOptions().resetChatState();
2379 } else {
2380 conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
2381 }
2382 }
2383 for (Account account : getAccounts()) {
2384 if (account.getStatus() == Account.State.ONLINE) {
2385 account.deactivateGracePeriod();
2386 final XmppConnection connection = account.getXmppConnection();
2387 if (connection != null) {
2388 if (connection.getFeatures().csi()) {
2389 connection.sendActive();
2390 }
2391 if (broadcastLastActivity) {
2392 sendPresence(account, false); //send new presence but don't include idle because we are not
2393 }
2394 }
2395 }
2396 }
2397 Log.d(Config.LOGTAG, "app switched into foreground");
2398 }
2399
2400 private void switchToBackground() {
2401 final boolean broadcastLastActivity = broadcastLastActivity();
2402 if (broadcastLastActivity) {
2403 mLastActivity = System.currentTimeMillis();
2404 final SharedPreferences.Editor editor = getPreferences().edit();
2405 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2406 editor.apply();
2407 }
2408 for (Account account : getAccounts()) {
2409 if (account.getStatus() == Account.State.ONLINE) {
2410 XmppConnection connection = account.getXmppConnection();
2411 if (connection != null) {
2412 if (broadcastLastActivity) {
2413 sendPresence(account, true);
2414 }
2415 if (connection.getFeatures().csi()) {
2416 connection.sendInactive();
2417 }
2418 }
2419 }
2420 }
2421 this.mNotificationService.setIsInForeground(false);
2422 Log.d(Config.LOGTAG, "app switched into background");
2423 }
2424
2425 private void connectMultiModeConversations(Account account) {
2426 List<Conversation> conversations = getConversations();
2427 for (Conversation conversation : conversations) {
2428 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2429 joinMuc(conversation);
2430 }
2431 }
2432 }
2433
2434 public void mucSelfPingAndRejoin(final Conversation conversation) {
2435 final Jid self = conversation.getMucOptions().getSelf().getFullJid();
2436 final IqPacket ping = new IqPacket(IqPacket.TYPE.GET);
2437 ping.setTo(self);
2438 ping.addChild("ping", Namespace.PING);
2439 sendIqPacket(conversation.getAccount(), ping, (account, response) -> {
2440 if (response.getType() == IqPacket.TYPE.ERROR) {
2441 Element error = response.findChild("error");
2442 if (error == null || error.hasChild("service-unavailable") || error.hasChild("feature-not-implemented") || error.hasChild("item-not-found")) {
2443 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": ping to "+self+" came back as ignorable error");
2444 } else {
2445 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": ping to "+self+" failed. attempting rejoin");
2446 joinMuc(conversation);
2447 }
2448 } else if (response.getType() == IqPacket.TYPE.RESULT) {
2449 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": ping to "+self+" came back fine");
2450 }
2451 });
2452 }
2453
2454 public void joinMuc(Conversation conversation) {
2455 joinMuc(conversation, null, false);
2456 }
2457
2458 public void joinMuc(Conversation conversation, boolean followedInvite) {
2459 joinMuc(conversation, null, followedInvite);
2460 }
2461
2462 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2463 joinMuc(conversation, onConferenceJoined, false);
2464 }
2465
2466 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2467 Account account = conversation.getAccount();
2468 account.pendingConferenceJoins.remove(conversation);
2469 account.pendingConferenceLeaves.remove(conversation);
2470 if (account.getStatus() == Account.State.ONLINE) {
2471 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2472 conversation.resetMucOptions();
2473 if (onConferenceJoined != null) {
2474 conversation.getMucOptions().flagNoAutoPushConfiguration();
2475 }
2476 conversation.setHasMessagesLeftOnServer(false);
2477 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2478
2479 private void join(Conversation conversation) {
2480 Account account = conversation.getAccount();
2481 final MucOptions mucOptions = conversation.getMucOptions();
2482
2483 if (mucOptions.nonanonymous() && !mucOptions.membersOnly() && !conversation.getBooleanAttribute("accept_non_anonymous", false)) {
2484 mucOptions.setError(MucOptions.Error.NON_ANONYMOUS);
2485 updateConversationUi();
2486 if (onConferenceJoined != null) {
2487 onConferenceJoined.onConferenceJoined(conversation);
2488 }
2489 return;
2490 }
2491
2492 final Jid joinJid = mucOptions.getSelf().getFullJid();
2493 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2494 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2495 packet.setTo(joinJid);
2496 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2497 if (conversation.getMucOptions().getPassword() != null) {
2498 x.addChild("password").setContent(mucOptions.getPassword());
2499 }
2500
2501 if (mucOptions.mamSupport()) {
2502 // Use MAM instead of the limited muc history to get history
2503 x.addChild("history").setAttribute("maxchars", "0");
2504 } else {
2505 // Fallback to muc history
2506 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2507 }
2508 sendPresencePacket(account, packet);
2509 if (onConferenceJoined != null) {
2510 onConferenceJoined.onConferenceJoined(conversation);
2511 }
2512 if (!joinJid.equals(conversation.getJid())) {
2513 conversation.setContactJid(joinJid);
2514 databaseBackend.updateConversation(conversation);
2515 }
2516
2517 if (mucOptions.mamSupport()) {
2518 getMessageArchiveService().catchupMUC(conversation);
2519 }
2520 if (mucOptions.isPrivateAndNonAnonymous()) {
2521 fetchConferenceMembers(conversation);
2522 if (followedInvite && conversation.getBookmark() == null) {
2523 saveConversationAsBookmark(conversation, null);
2524 }
2525 }
2526 sendUnsentMessages(conversation);
2527 }
2528
2529 @Override
2530 public void onConferenceConfigurationFetched(Conversation conversation) {
2531 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2532 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": conversation ("+conversation.getJid()+") got archived before IQ result");
2533 return;
2534 }
2535 join(conversation);
2536 }
2537
2538 @Override
2539 public void onFetchFailed(final Conversation conversation, Element error) {
2540 if (conversation.getStatus() == Conversation.STATUS_ARCHIVED) {
2541 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": conversation ("+conversation.getJid()+") got archived before IQ result");
2542 return;
2543 }
2544 if (error != null && "remote-server-not-found".equals(error.getName())) {
2545 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2546 updateConversationUi();
2547 } else {
2548 join(conversation);
2549 fetchConferenceConfiguration(conversation);
2550 }
2551 }
2552 });
2553 updateConversationUi();
2554 } else {
2555 account.pendingConferenceJoins.add(conversation);
2556 conversation.resetMucOptions();
2557 conversation.setHasMessagesLeftOnServer(false);
2558 updateConversationUi();
2559 }
2560 }
2561
2562 private void fetchConferenceMembers(final Conversation conversation) {
2563 final Account account = conversation.getAccount();
2564 final AxolotlService axolotlService = account.getAxolotlService();
2565 final String[] affiliations = {"member", "admin", "owner"};
2566 OnIqPacketReceived callback = new OnIqPacketReceived() {
2567
2568 private int i = 0;
2569 private boolean success = true;
2570
2571 @Override
2572 public void onIqPacketReceived(Account account, IqPacket packet) {
2573 final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
2574 Element query = packet.query("http://jabber.org/protocol/muc#admin");
2575 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2576 for (Element child : query.getChildren()) {
2577 if ("item".equals(child.getName())) {
2578 MucOptions.User user = AbstractParser.parseItem(conversation, child);
2579 if (!user.realJidMatchesAccount()) {
2580 boolean isNew = conversation.getMucOptions().updateUser(user);
2581 Contact contact = user.getContact();
2582 if (omemoEnabled
2583 && isNew
2584 && user.getRealJid() != null
2585 && (contact == null || !contact.mutualPresenceSubscription())
2586 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2587 axolotlService.fetchDeviceIds(user.getRealJid());
2588 }
2589 }
2590 }
2591 }
2592 } else {
2593 success = false;
2594 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2595 }
2596 ++i;
2597 if (i >= affiliations.length) {
2598 List<Jid> members = conversation.getMucOptions().getMembers(true);
2599 if (success) {
2600 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2601 boolean changed = false;
2602 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2603 Jid jid = iterator.next();
2604 if (!members.contains(jid) && !members.contains(Jid.ofDomain(jid.getDomain()))) {
2605 iterator.remove();
2606 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2607 changed = true;
2608 }
2609 }
2610 if (changed) {
2611 conversation.setAcceptedCryptoTargets(cryptoTargets);
2612 updateConversation(conversation);
2613 }
2614 }
2615 getAvatarService().clear(conversation);
2616 updateMucRosterUi();
2617 updateConversationUi();
2618 }
2619 }
2620 };
2621 for (String affiliation : affiliations) {
2622 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2623 }
2624 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2625 }
2626
2627 public void providePasswordForMuc(Conversation conversation, String password) {
2628 if (conversation.getMode() == Conversation.MODE_MULTI) {
2629 conversation.getMucOptions().setPassword(password);
2630 if (conversation.getBookmark() != null) {
2631 if (synchronizeWithBookmarks()) {
2632 conversation.getBookmark().setAutojoin(true);
2633 }
2634 pushBookmarks(conversation.getAccount());
2635 }
2636 updateConversation(conversation);
2637 joinMuc(conversation);
2638 }
2639 }
2640
2641 private boolean hasEnabledAccounts() {
2642 if (this.accounts == null) {
2643 return false;
2644 }
2645 for (Account account : this.accounts) {
2646 if (account.isEnabled()) {
2647 return true;
2648 }
2649 }
2650 return false;
2651 }
2652
2653
2654 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
2655 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
2656 }
2657
2658 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2659 getAttachments(account.getUuid(),jid.asBareJid(),limit, onMediaLoaded);
2660 }
2661
2662
2663 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2664 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
2665 }
2666
2667 public void persistSelfNick(MucOptions.User self) {
2668 final Conversation conversation = self.getConversation();
2669 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
2670 Jid full = self.getFullJid();
2671 if (!full.equals(conversation.getJid())) {
2672 Log.d(Config.LOGTAG, "nick changed. updating");
2673 conversation.setContactJid(full);
2674 databaseBackend.updateConversation(conversation);
2675 }
2676
2677 final Bookmark bookmark = conversation.getBookmark();
2678 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
2679 if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
2680 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
2681 bookmark.setNick(full.getResource());
2682 pushBookmarks(bookmark.getAccount());
2683 }
2684 }
2685
2686 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2687 final MucOptions options = conversation.getMucOptions();
2688 final Jid joinJid = options.createJoinJid(nick);
2689 if (joinJid == null) {
2690 return false;
2691 }
2692 if (options.online()) {
2693 Account account = conversation.getAccount();
2694 options.setOnRenameListener(new OnRenameListener() {
2695
2696 @Override
2697 public void onSuccess() {
2698 callback.success(conversation);
2699 }
2700
2701 @Override
2702 public void onFailure() {
2703 callback.error(R.string.nick_in_use, conversation);
2704 }
2705 });
2706
2707 PresencePacket packet = new PresencePacket();
2708 packet.setTo(joinJid);
2709 packet.setFrom(conversation.getAccount().getJid());
2710
2711 String sig = account.getPgpSignature();
2712 if (sig != null) {
2713 packet.addChild("status").setContent("online");
2714 packet.addChild("x", "jabber:x:signed").setContent(sig);
2715 }
2716 sendPresencePacket(account, packet);
2717 } else {
2718 conversation.setContactJid(joinJid);
2719 databaseBackend.updateConversation(conversation);
2720 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2721 Bookmark bookmark = conversation.getBookmark();
2722 if (bookmark != null) {
2723 bookmark.setNick(nick);
2724 pushBookmarks(bookmark.getAccount());
2725 }
2726 joinMuc(conversation);
2727 }
2728 }
2729 return true;
2730 }
2731
2732 public void leaveMuc(Conversation conversation) {
2733 leaveMuc(conversation, false);
2734 }
2735
2736 private void leaveMuc(Conversation conversation, boolean now) {
2737 Account account = conversation.getAccount();
2738 account.pendingConferenceJoins.remove(conversation);
2739 account.pendingConferenceLeaves.remove(conversation);
2740 if (account.getStatus() == Account.State.ONLINE || now) {
2741 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2742 conversation.getMucOptions().setOffline();
2743 Bookmark bookmark = conversation.getBookmark();
2744 if (bookmark != null) {
2745 bookmark.setConversation(null);
2746 }
2747 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
2748 } else {
2749 account.pendingConferenceLeaves.add(conversation);
2750 }
2751 }
2752
2753 public String findConferenceServer(final Account account) {
2754 String server;
2755 if (account.getXmppConnection() != null) {
2756 server = account.getXmppConnection().getMucServer();
2757 if (server != null) {
2758 return server;
2759 }
2760 }
2761 for (Account other : getAccounts()) {
2762 if (other != account && other.getXmppConnection() != null) {
2763 server = other.getXmppConnection().getMucServer();
2764 if (server != null) {
2765 return server;
2766 }
2767 }
2768 }
2769 return null;
2770 }
2771
2772
2773 public void createPublicChannel(final Account account, final String name, final Jid address, final UiCallback<Conversation> callback) {
2774 joinMuc(findOrCreateConversation(account, address, true, false, true), conversation -> {
2775 final Bundle configuration = IqGenerator.defaultChannelConfiguration();
2776 if (!TextUtils.isEmpty(name)) {
2777 configuration.putString("muc#roomconfig_roomname", name);
2778 }
2779 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
2780 @Override
2781 public void onPushSucceeded() {
2782 saveConversationAsBookmark(conversation, name);
2783 callback.success(conversation);
2784 }
2785
2786 @Override
2787 public void onPushFailed() {
2788 if (conversation.getMucOptions().getSelf().getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2789 callback.error(R.string.unable_to_set_channel_configuration, conversation);
2790 } else {
2791 callback.error(R.string.joined_an_existing_channel, conversation);
2792 }
2793 }
2794 });
2795 });
2796 }
2797
2798 public boolean createAdhocConference(final Account account,
2799 final String name,
2800 final Iterable<Jid> jids,
2801 final UiCallback<Conversation> callback) {
2802 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2803 if (account.getStatus() == Account.State.ONLINE) {
2804 try {
2805 String server = findConferenceServer(account);
2806 if (server == null) {
2807 if (callback != null) {
2808 callback.error(R.string.no_conference_server_found, null);
2809 }
2810 return false;
2811 }
2812 final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
2813 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2814 joinMuc(conversation, new OnConferenceJoined() {
2815 @Override
2816 public void onConferenceJoined(final Conversation conversation) {
2817 final Bundle configuration = IqGenerator.defaultGroupChatConfiguration();
2818 if (!TextUtils.isEmpty(name)) {
2819 configuration.putString("muc#roomconfig_roomname", name);
2820 }
2821 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
2822 @Override
2823 public void onPushSucceeded() {
2824 for (Jid invite : jids) {
2825 invite(conversation, invite);
2826 }
2827 if (account.countPresences() > 1) {
2828 directInvite(conversation, account.getJid().asBareJid());
2829 }
2830 saveConversationAsBookmark(conversation, name);
2831 if (callback != null) {
2832 callback.success(conversation);
2833 }
2834 }
2835
2836 @Override
2837 public void onPushFailed() {
2838 archiveConversation(conversation);
2839 if (callback != null) {
2840 callback.error(R.string.conference_creation_failed, conversation);
2841 }
2842 }
2843 });
2844 }
2845 });
2846 return true;
2847 } catch (IllegalArgumentException e) {
2848 if (callback != null) {
2849 callback.error(R.string.conference_creation_failed, null);
2850 }
2851 return false;
2852 }
2853 } else {
2854 if (callback != null) {
2855 callback.error(R.string.not_connected_try_again, null);
2856 }
2857 return false;
2858 }
2859 }
2860
2861 public void fetchConferenceConfiguration(final Conversation conversation) {
2862 fetchConferenceConfiguration(conversation, null);
2863 }
2864
2865 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2866 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2867 request.setTo(conversation.getJid().asBareJid());
2868 request.query("http://jabber.org/protocol/disco#info");
2869 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2870 @Override
2871 public void onIqPacketReceived(Account account, IqPacket packet) {
2872 if (packet.getType() == IqPacket.TYPE.RESULT) {
2873
2874 final MucOptions mucOptions = conversation.getMucOptions();
2875 final Bookmark bookmark = conversation.getBookmark();
2876 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
2877
2878 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
2879 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
2880 updateConversation(conversation);
2881 }
2882
2883 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
2884 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
2885 pushBookmarks(account);
2886 }
2887 }
2888
2889
2890 if (callback != null) {
2891 callback.onConferenceConfigurationFetched(conversation);
2892 }
2893
2894
2895
2896 updateConversationUi();
2897 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2898 if (callback != null) {
2899 callback.onFetchFailed(conversation, packet.getError());
2900 }
2901 }
2902 }
2903 });
2904 }
2905
2906 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
2907 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
2908 }
2909
2910 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2911 Log.d(Config.LOGTAG,"pushing node configuration");
2912 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
2913 @Override
2914 public void onIqPacketReceived(Account account, IqPacket packet) {
2915 if (packet.getType() == IqPacket.TYPE.RESULT) {
2916 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
2917 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2918 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
2919 if (x != null) {
2920 Data data = Data.parse(x);
2921 data.submit(options);
2922 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2923 @Override
2924 public void onIqPacketReceived(Account account, IqPacket packet) {
2925 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
2926 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully changed node configuration for node "+node);
2927 callback.onPushSucceeded();
2928 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2929 callback.onPushFailed();
2930 }
2931 }
2932 });
2933 } else if (callback != null) {
2934 callback.onPushFailed();
2935 }
2936 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2937 callback.onPushFailed();
2938 }
2939 }
2940 });
2941 }
2942
2943 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2944 if (options.getString("muc#roomconfig_whois","moderators").equals("anyone")) {
2945 conversation.setAttribute("accept_non_anonymous",true);
2946 updateConversation(conversation);
2947 }
2948 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2949 request.setTo(conversation.getJid().asBareJid());
2950 request.query("http://jabber.org/protocol/muc#owner");
2951 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2952 @Override
2953 public void onIqPacketReceived(Account account, IqPacket packet) {
2954 if (packet.getType() == IqPacket.TYPE.RESULT) {
2955 Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
2956 data.submit(options);
2957 Log.d(Config.LOGTAG,data.toString());
2958 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2959 set.setTo(conversation.getJid().asBareJid());
2960 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2961 sendIqPacket(account, set, new OnIqPacketReceived() {
2962 @Override
2963 public void onIqPacketReceived(Account account, IqPacket packet) {
2964 if (callback != null) {
2965 if (packet.getType() == IqPacket.TYPE.RESULT) {
2966 callback.onPushSucceeded();
2967 } else {
2968 callback.onPushFailed();
2969 }
2970 }
2971 }
2972 });
2973 } else {
2974 if (callback != null) {
2975 callback.onPushFailed();
2976 }
2977 }
2978 }
2979 });
2980 }
2981
2982 public void pushSubjectToConference(final Conversation conference, final String subject) {
2983 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
2984 this.sendMessagePacket(conference.getAccount(), packet);
2985 }
2986
2987 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2988 final Jid jid = user.asBareJid();
2989 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2990 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2991 @Override
2992 public void onIqPacketReceived(Account account, IqPacket packet) {
2993 if (packet.getType() == IqPacket.TYPE.RESULT) {
2994 conference.getMucOptions().changeAffiliation(jid, affiliation);
2995 getAvatarService().clear(conference);
2996 callback.onAffiliationChangedSuccessful(jid);
2997 } else {
2998 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2999 }
3000 }
3001 });
3002 }
3003
3004 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
3005 List<Jid> jids = new ArrayList<>();
3006 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
3007 if (user.getAffiliation() == before && user.getRealJid() != null) {
3008 jids.add(user.getRealJid());
3009 }
3010 }
3011 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
3012 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
3013 }
3014
3015 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role) {
3016 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
3017 Log.d(Config.LOGTAG, request.toString());
3018 sendIqPacket(conference.getAccount(), request, (account, packet) -> {
3019 if (packet.getType() != IqPacket.TYPE.RESULT) {
3020 Log.d(Config.LOGTAG,account.getJid().asBareJid()+" unable to change role of "+nick);
3021 }
3022 });
3023 }
3024
3025 public void destroyRoom(final Conversation conversation, final OnRoomDestroy callback) {
3026 IqPacket request = new IqPacket(IqPacket.TYPE.SET);
3027 request.setTo(conversation.getJid().asBareJid());
3028 request.query("http://jabber.org/protocol/muc#owner").addChild("destroy");
3029 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
3030 @Override
3031 public void onIqPacketReceived(Account account, IqPacket packet) {
3032 if (packet.getType() == IqPacket.TYPE.RESULT) {
3033 if (callback != null) {
3034 callback.onRoomDestroySucceeded();
3035 }
3036 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
3037 if (callback != null) {
3038 callback.onRoomDestroyFailed();
3039 }
3040 }
3041 }
3042 });
3043 }
3044
3045 private void disconnect(Account account, boolean force) {
3046 if ((account.getStatus() == Account.State.ONLINE)
3047 || (account.getStatus() == Account.State.DISABLED)) {
3048 final XmppConnection connection = account.getXmppConnection();
3049 if (!force) {
3050 List<Conversation> conversations = getConversations();
3051 for (Conversation conversation : conversations) {
3052 if (conversation.getAccount() == account) {
3053 if (conversation.getMode() == Conversation.MODE_MULTI) {
3054 leaveMuc(conversation, true);
3055 }
3056 }
3057 }
3058 sendOfflinePresence(account);
3059 }
3060 connection.disconnect(force);
3061 }
3062 }
3063
3064 @Override
3065 public IBinder onBind(Intent intent) {
3066 return mBinder;
3067 }
3068
3069 public void updateMessage(Message message) {
3070 updateMessage(message, true);
3071 }
3072
3073 public void updateMessage(Message message, boolean includeBody) {
3074 databaseBackend.updateMessage(message, includeBody);
3075 updateConversationUi();
3076 }
3077
3078 public void updateMessage(Message message, String uuid) {
3079 if (!databaseBackend.updateMessage(message, uuid)) {
3080 Log.e(Config.LOGTAG,"error updated message in DB after edit");
3081 }
3082 updateConversationUi();
3083 }
3084
3085 protected void syncDirtyContacts(Account account) {
3086 for (Contact contact : account.getRoster().getContacts()) {
3087 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
3088 pushContactToServer(contact);
3089 }
3090 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
3091 deleteContactOnServer(contact);
3092 }
3093 }
3094 }
3095
3096 public void createContact(Contact contact, boolean autoGrant) {
3097 if (autoGrant) {
3098 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
3099 contact.setOption(Contact.Options.ASKING);
3100 }
3101 pushContactToServer(contact);
3102 }
3103
3104 public void pushContactToServer(final Contact contact) {
3105 contact.resetOption(Contact.Options.DIRTY_DELETE);
3106 contact.setOption(Contact.Options.DIRTY_PUSH);
3107 final Account account = contact.getAccount();
3108 if (account.getStatus() == Account.State.ONLINE) {
3109 final boolean ask = contact.getOption(Contact.Options.ASKING);
3110 final boolean sendUpdates = contact
3111 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
3112 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
3113 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3114 iq.query(Namespace.ROSTER).addChild(contact.asElement());
3115 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3116 if (sendUpdates) {
3117 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
3118 }
3119 if (ask) {
3120 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
3121 }
3122 } else {
3123 syncRoster(contact.getAccount());
3124 }
3125 }
3126
3127 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
3128 new Thread(() -> {
3129 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3130 final int size = Config.AVATAR_SIZE;
3131 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3132 if (avatar != null) {
3133 if (!getFileBackend().save(avatar)) {
3134 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3135 return;
3136 }
3137 avatar.owner = conversation.getJid().asBareJid();
3138 publishMucAvatar(conversation, avatar, callback);
3139 } else {
3140 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3141 }
3142 }).start();
3143 }
3144
3145 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
3146 new Thread(() -> {
3147 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
3148 final int size = Config.AVATAR_SIZE;
3149 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
3150 if (avatar != null) {
3151 if (!getFileBackend().save(avatar)) {
3152 Log.d(Config.LOGTAG,"unable to save vcard");
3153 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
3154 return;
3155 }
3156 publishAvatar(account, avatar, callback);
3157 } else {
3158 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
3159 }
3160 }).start();
3161
3162 }
3163
3164 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
3165 final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
3166 sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
3167 boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
3168 if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
3169 Element vcard = response.findChild("vCard", "vcard-temp");
3170 if (vcard == null) {
3171 vcard = new Element("vCard", "vcard-temp");
3172 }
3173 Element photo = vcard.findChild("PHOTO");
3174 if (photo == null) {
3175 photo = vcard.addChild("PHOTO");
3176 }
3177 photo.clearChildren();
3178 photo.addChild("TYPE").setContent(avatar.type);
3179 photo.addChild("BINVAL").setContent(avatar.image);
3180 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
3181 publication.setTo(conversation.getJid().asBareJid());
3182 publication.addChild(vcard);
3183 sendIqPacket(account, publication, (a1, publicationResponse) -> {
3184 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
3185 callback.onAvatarPublicationSucceeded();
3186 } else {
3187 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
3188 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3189 }
3190 });
3191 } else {
3192 Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
3193 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
3194 }
3195 });
3196 }
3197
3198 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
3199 final Bundle options;
3200 if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
3201 options = PublishOptions.openAccess();
3202 } else {
3203 options = null;
3204 }
3205 publishAvatar(account, avatar, options, true, callback);
3206 }
3207
3208 public void publishAvatar(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3209 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": publishing avatar. options="+options);
3210 IqPacket packet = this.mIqGenerator.publishAvatar(avatar, options);
3211 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3212
3213 @Override
3214 public void onIqPacketReceived(Account account, IqPacket result) {
3215 if (result.getType() == IqPacket.TYPE.RESULT) {
3216 publishAvatarMetadata(account, avatar, options,true, callback);
3217 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3218 pushNodeConfiguration(account, "urn:xmpp:avatar:data", options, new OnConfigurationPushed() {
3219 @Override
3220 public void onPushSucceeded() {
3221 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": changed node configuration for avatar node");
3222 publishAvatar(account, avatar, options, false, callback);
3223 }
3224
3225 @Override
3226 public void onPushFailed() {
3227 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to change node configuration for avatar node");
3228 publishAvatar(account, avatar, null, false, callback);
3229 }
3230 });
3231 } else {
3232 Element error = result.findChild("error");
3233 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
3234 if (callback != null) {
3235 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3236 }
3237 }
3238 }
3239 });
3240 }
3241
3242 public void publishAvatarMetadata(Account account, final Avatar avatar, final Bundle options, final boolean retry, final OnAvatarPublication callback) {
3243 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar, options);
3244 sendIqPacket(account, packet, new OnIqPacketReceived() {
3245 @Override
3246 public void onIqPacketReceived(Account account, IqPacket result) {
3247 if (result.getType() == IqPacket.TYPE.RESULT) {
3248 if (account.setAvatar(avatar.getFilename())) {
3249 getAvatarService().clear(account);
3250 databaseBackend.updateAccount(account);
3251 notifyAccountAvatarHasChanged(account);
3252 }
3253 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
3254 if (callback != null) {
3255 callback.onAvatarPublicationSucceeded();
3256 }
3257 } else if (retry && PublishOptions.preconditionNotMet(result)) {
3258 pushNodeConfiguration(account, "urn:xmpp:avatar:metadata", options, new OnConfigurationPushed() {
3259 @Override
3260 public void onPushSucceeded() {
3261 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": changed node configuration for avatar meta data node");
3262 publishAvatarMetadata(account, avatar, options,false, callback);
3263 }
3264
3265 @Override
3266 public void onPushFailed() {
3267 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to change node configuration for avatar meta data node");
3268 publishAvatarMetadata(account, avatar, null,false, callback);
3269 }
3270 });
3271 } else {
3272 if (callback != null) {
3273 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
3274 }
3275 }
3276 }
3277 });
3278 }
3279
3280 public void republishAvatarIfNeeded(Account account) {
3281 if (account.getAxolotlService().isPepBroken()) {
3282 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
3283 return;
3284 }
3285 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3286 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3287
3288 private Avatar parseAvatar(IqPacket packet) {
3289 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3290 if (pubsub != null) {
3291 Element items = pubsub.findChild("items");
3292 if (items != null) {
3293 return Avatar.parseMetadata(items);
3294 }
3295 }
3296 return null;
3297 }
3298
3299 private boolean errorIsItemNotFound(IqPacket packet) {
3300 Element error = packet.findChild("error");
3301 return packet.getType() == IqPacket.TYPE.ERROR
3302 && error != null
3303 && error.hasChild("item-not-found");
3304 }
3305
3306 @Override
3307 public void onIqPacketReceived(Account account, IqPacket packet) {
3308 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
3309 Avatar serverAvatar = parseAvatar(packet);
3310 if (serverAvatar == null && account.getAvatar() != null) {
3311 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
3312 if (avatar != null) {
3313 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3314 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3315 } else {
3316 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3317 }
3318 }
3319 }
3320 }
3321 });
3322 }
3323
3324 public void fetchAvatar(Account account, Avatar avatar) {
3325 fetchAvatar(account, avatar, null);
3326 }
3327
3328 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3329 final String KEY = generateFetchKey(account, avatar);
3330 synchronized (this.mInProgressAvatarFetches) {
3331 if (mInProgressAvatarFetches.add(KEY)) {
3332 switch (avatar.origin) {
3333 case PEP:
3334 this.mInProgressAvatarFetches.add(KEY);
3335 fetchAvatarPep(account, avatar, callback);
3336 break;
3337 case VCARD:
3338 this.mInProgressAvatarFetches.add(KEY);
3339 fetchAvatarVcard(account, avatar, callback);
3340 break;
3341 }
3342 } else if (avatar.origin == Avatar.Origin.PEP) {
3343 mOmittedPepAvatarFetches.add(KEY);
3344 } else {
3345 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": already fetching "+avatar.origin+" avatar for "+avatar.owner);
3346 }
3347 }
3348 }
3349
3350 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3351 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3352 sendIqPacket(account, packet, (a, result) -> {
3353 synchronized (mInProgressAvatarFetches) {
3354 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3355 }
3356 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3357 if (result.getType() == IqPacket.TYPE.RESULT) {
3358 avatar.image = mIqParser.avatarData(result);
3359 if (avatar.image != null) {
3360 if (getFileBackend().save(avatar)) {
3361 if (a.getJid().asBareJid().equals(avatar.owner)) {
3362 if (a.setAvatar(avatar.getFilename())) {
3363 databaseBackend.updateAccount(a);
3364 }
3365 getAvatarService().clear(a);
3366 updateConversationUi();
3367 updateAccountUi();
3368 } else {
3369 Contact contact = a.getRoster().getContact(avatar.owner);
3370 if (contact.setAvatar(avatar)) {
3371 syncRoster(account);
3372 getAvatarService().clear(contact);
3373 updateConversationUi();
3374 updateRosterUi();
3375 }
3376 }
3377 if (callback != null) {
3378 callback.success(avatar);
3379 }
3380 Log.d(Config.LOGTAG, a.getJid().asBareJid()
3381 + ": successfully fetched pep avatar for " + avatar.owner);
3382 return;
3383 }
3384 } else {
3385
3386 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3387 }
3388 } else {
3389 Element error = result.findChild("error");
3390 if (error == null) {
3391 Log.d(Config.LOGTAG, ERROR + "(server error)");
3392 } else {
3393 Log.d(Config.LOGTAG, ERROR + error.toString());
3394 }
3395 }
3396 if (callback != null) {
3397 callback.error(0, null);
3398 }
3399
3400 });
3401 }
3402
3403 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3404 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3405 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3406 @Override
3407 public void onIqPacketReceived(Account account, IqPacket packet) {
3408 final boolean previouslyOmittedPepFetch;
3409 synchronized (mInProgressAvatarFetches) {
3410 final String KEY = generateFetchKey(account, avatar);
3411 mInProgressAvatarFetches.remove(KEY);
3412 previouslyOmittedPepFetch = mOmittedPepAvatarFetches.remove(KEY);
3413 }
3414 if (packet.getType() == IqPacket.TYPE.RESULT) {
3415 Element vCard = packet.findChild("vCard", "vcard-temp");
3416 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3417 String image = photo != null ? photo.findChildContent("BINVAL") : null;
3418 if (image != null) {
3419 avatar.image = image;
3420 if (getFileBackend().save(avatar)) {
3421 Log.d(Config.LOGTAG, account.getJid().asBareJid()
3422 + ": successfully fetched vCard avatar for " + avatar.owner+" omittedPep="+previouslyOmittedPepFetch);
3423 if (avatar.owner.isBareJid()) {
3424 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3425 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3426 account.setAvatar(avatar.getFilename());
3427 databaseBackend.updateAccount(account);
3428 getAvatarService().clear(account);
3429 updateAccountUi();
3430 } else {
3431 Contact contact = account.getRoster().getContact(avatar.owner);
3432 if (contact.setAvatar(avatar, previouslyOmittedPepFetch)) {
3433 syncRoster(account);
3434 getAvatarService().clear(contact);
3435 updateRosterUi();
3436 }
3437 }
3438 updateConversationUi();
3439 } else {
3440 Conversation conversation = find(account, avatar.owner.asBareJid());
3441 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3442 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3443 if (user != null) {
3444 if (user.setAvatar(avatar)) {
3445 getAvatarService().clear(user);
3446 updateConversationUi();
3447 updateMucRosterUi();
3448 }
3449 if (user.getRealJid() != null) {
3450 Contact contact = account.getRoster().getContact(user.getRealJid());
3451 if (contact.setAvatar(avatar)) {
3452 syncRoster(account);
3453 getAvatarService().clear(contact);
3454 updateRosterUi();
3455 }
3456 }
3457 }
3458 }
3459 }
3460 }
3461 }
3462 }
3463 }
3464 });
3465 }
3466
3467 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3468 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3469 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3470
3471 @Override
3472 public void onIqPacketReceived(Account account, IqPacket packet) {
3473 if (packet.getType() == IqPacket.TYPE.RESULT) {
3474 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3475 if (pubsub != null) {
3476 Element items = pubsub.findChild("items");
3477 if (items != null) {
3478 Avatar avatar = Avatar.parseMetadata(items);
3479 if (avatar != null) {
3480 avatar.owner = account.getJid().asBareJid();
3481 if (fileBackend.isAvatarCached(avatar)) {
3482 if (account.setAvatar(avatar.getFilename())) {
3483 databaseBackend.updateAccount(account);
3484 }
3485 getAvatarService().clear(account);
3486 callback.success(avatar);
3487 } else {
3488 fetchAvatarPep(account, avatar, callback);
3489 }
3490 return;
3491 }
3492 }
3493 }
3494 }
3495 callback.error(0, null);
3496 }
3497 });
3498 }
3499
3500 public void notifyAccountAvatarHasChanged(final Account account) {
3501 final XmppConnection connection = account.getXmppConnection();
3502 if (connection != null && connection.getFeatures().bookmarksConversion()) {
3503 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": avatar changed. resending presence to online group chats");
3504 for(Conversation conversation : conversations) {
3505 if (conversation.getAccount() == account && conversation.getMode() == Conversational.MODE_MULTI) {
3506 final MucOptions mucOptions = conversation.getMucOptions();
3507 if (mucOptions.online()) {
3508 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
3509 packet.setTo(mucOptions.getSelf().getFullJid());
3510 connection.sendPresencePacket(packet);
3511 }
3512 }
3513 }
3514 }
3515 }
3516
3517 public void deleteContactOnServer(Contact contact) {
3518 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3519 contact.resetOption(Contact.Options.DIRTY_PUSH);
3520 contact.setOption(Contact.Options.DIRTY_DELETE);
3521 Account account = contact.getAccount();
3522 if (account.getStatus() == Account.State.ONLINE) {
3523 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3524 Element item = iq.query(Namespace.ROSTER).addChild("item");
3525 item.setAttribute("jid", contact.getJid().toString());
3526 item.setAttribute("subscription", "remove");
3527 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3528 }
3529 }
3530
3531 public void updateConversation(final Conversation conversation) {
3532 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3533 }
3534
3535 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3536 synchronized (account) {
3537 XmppConnection connection = account.getXmppConnection();
3538 if (connection == null) {
3539 connection = createConnection(account);
3540 account.setXmppConnection(connection);
3541 }
3542 boolean hasInternet = hasInternetConnection();
3543 if (account.isEnabled() && hasInternet) {
3544 if (!force) {
3545 disconnect(account, false);
3546 }
3547 Thread thread = new Thread(connection);
3548 connection.setInteractive(interactive);
3549 connection.prepareNewConnection();
3550 connection.interrupt();
3551 thread.start();
3552 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3553 } else {
3554 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3555 account.getRoster().clearPresences();
3556 connection.resetEverything();
3557 final AxolotlService axolotlService = account.getAxolotlService();
3558 if (axolotlService != null) {
3559 axolotlService.resetBrokenness();
3560 }
3561 if (!hasInternet) {
3562 account.setStatus(Account.State.NO_INTERNET);
3563 }
3564 }
3565 }
3566 }
3567
3568 public void reconnectAccountInBackground(final Account account) {
3569 new Thread(() -> reconnectAccount(account, false, true)).start();
3570 }
3571
3572 public void invite(Conversation conversation, Jid contact) {
3573 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3574 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3575 sendMessagePacket(conversation.getAccount(), packet);
3576 }
3577
3578 public void directInvite(Conversation conversation, Jid jid) {
3579 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3580 sendMessagePacket(conversation.getAccount(), packet);
3581 }
3582
3583 public void resetSendingToWaiting(Account account) {
3584 for (Conversation conversation : getConversations()) {
3585 if (conversation.getAccount() == account) {
3586 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
3587 }
3588 }
3589 }
3590
3591 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3592 return markMessage(account, recipient, uuid, status, null);
3593 }
3594
3595 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3596 if (uuid == null) {
3597 return null;
3598 }
3599 for (Conversation conversation : getConversations()) {
3600 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3601 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3602 if (message != null) {
3603 markMessage(message, status, errorMessage);
3604 }
3605 return message;
3606 }
3607 }
3608 return null;
3609 }
3610
3611 public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3612 if (uuid == null) {
3613 return false;
3614 } else {
3615 Message message = conversation.findSentMessageWithUuid(uuid);
3616 if (message != null) {
3617 if (message.getServerMsgId() == null) {
3618 message.setServerMsgId(serverMessageId);
3619 }
3620 markMessage(message, status);
3621 return true;
3622 } else {
3623 return false;
3624 }
3625 }
3626 }
3627
3628 public void markMessage(Message message, int status) {
3629 markMessage(message, status, null);
3630 }
3631
3632
3633 public void markMessage(Message message, int status, String errorMessage) {
3634 final int c = message.getStatus();
3635 if (status == Message.STATUS_SEND_FAILED && (c == Message.STATUS_SEND_RECEIVED || c == Message.STATUS_SEND_DISPLAYED)) {
3636 return;
3637 }
3638 if (status == Message.STATUS_SEND_RECEIVED && c == Message.STATUS_SEND_DISPLAYED) {
3639 return;
3640 }
3641 message.setErrorMessage(errorMessage);
3642 message.setStatus(status);
3643 databaseBackend.updateMessage(message, false);
3644 updateConversationUi();
3645 }
3646
3647 private SharedPreferences getPreferences() {
3648 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3649 }
3650
3651 public long getAutomaticMessageDeletionDate() {
3652 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3653 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3654 }
3655
3656 public long getLongPreference(String name, @IntegerRes int res) {
3657 long defaultValue = getResources().getInteger(res);
3658 try {
3659 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3660 } catch (NumberFormatException e) {
3661 return defaultValue;
3662 }
3663 }
3664
3665 public boolean getBooleanPreference(String name, @BoolRes int res) {
3666 return getPreferences().getBoolean(name, getResources().getBoolean(res));
3667 }
3668
3669 public boolean confirmMessages() {
3670 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3671 }
3672
3673 public boolean allowMessageCorrection() {
3674 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3675 }
3676
3677 public boolean sendChatStates() {
3678 return getBooleanPreference("chat_states", R.bool.chat_states);
3679 }
3680
3681 private boolean synchronizeWithBookmarks() {
3682 return getBooleanPreference("autojoin", R.bool.autojoin);
3683 }
3684
3685 public boolean indicateReceived() {
3686 return getBooleanPreference("indicate_received", R.bool.indicate_received);
3687 }
3688
3689 public boolean useTorToConnect() {
3690 return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
3691 }
3692
3693 public boolean showExtendedConnectionOptions() {
3694 return QuickConversationsService.isConversations() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3695 }
3696
3697 public boolean broadcastLastActivity() {
3698 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3699 }
3700
3701 public int unreadCount() {
3702 int count = 0;
3703 for (Conversation conversation : getConversations()) {
3704 count += conversation.unreadCount();
3705 }
3706 return count;
3707 }
3708
3709
3710 private <T> List<T> threadSafeList(Set<T> set) {
3711 synchronized (LISTENER_LOCK) {
3712 return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
3713 }
3714 }
3715
3716 public void showErrorToastInUi(int resId) {
3717 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
3718 listener.onShowErrorToast(resId);
3719 }
3720 }
3721
3722 public void updateConversationUi() {
3723 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
3724 listener.onConversationUpdate();
3725 }
3726 }
3727
3728 public void updateAccountUi() {
3729 for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
3730 listener.onAccountUpdate();
3731 }
3732 }
3733
3734 public void updateRosterUi() {
3735 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
3736 listener.onRosterUpdate();
3737 }
3738 }
3739
3740 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3741 if (mOnCaptchaRequested.size() > 0) {
3742 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3743 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3744 (int) (captcha.getHeight() * metrics.scaledDensity), false);
3745 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
3746 listener.onCaptchaRequested(account, id, data, scaled);
3747 }
3748 return true;
3749 }
3750 return false;
3751 }
3752
3753 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3754 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
3755 listener.OnUpdateBlocklist(status);
3756 }
3757 }
3758
3759 public void updateMucRosterUi() {
3760 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
3761 listener.onMucRosterUpdate();
3762 }
3763 }
3764
3765 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3766 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
3767 listener.onKeyStatusUpdated(report);
3768 }
3769 }
3770
3771 public Account findAccountByJid(final Jid accountJid) {
3772 for (Account account : this.accounts) {
3773 if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3774 return account;
3775 }
3776 }
3777 return null;
3778 }
3779
3780 public Account findAccountByUuid(final String uuid) {
3781 for(Account account : this.accounts) {
3782 if (account.getUuid().equals(uuid)) {
3783 return account;
3784 }
3785 }
3786 return null;
3787 }
3788
3789 public Conversation findConversationByUuid(String uuid) {
3790 for (Conversation conversation : getConversations()) {
3791 if (conversation.getUuid().equals(uuid)) {
3792 return conversation;
3793 }
3794 }
3795 return null;
3796 }
3797
3798 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
3799 List<Conversation> findings = new ArrayList<>();
3800 for (Conversation c : getConversations()) {
3801 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
3802 findings.add(c);
3803 }
3804 }
3805 return findings.size() == 1 ? findings.get(0) : null;
3806 }
3807
3808 public boolean markRead(final Conversation conversation, boolean dismiss) {
3809 return markRead(conversation, null, dismiss).size() > 0;
3810 }
3811
3812 public void markRead(final Conversation conversation) {
3813 markRead(conversation, null, true);
3814 }
3815
3816 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
3817 if (dismiss) {
3818 mNotificationService.clear(conversation);
3819 }
3820 final List<Message> readMessages = conversation.markRead(upToUuid);
3821 if (readMessages.size() > 0) {
3822 Runnable runnable = () -> {
3823 for (Message message : readMessages) {
3824 databaseBackend.updateMessage(message, false);
3825 }
3826 };
3827 mDatabaseWriterExecutor.execute(runnable);
3828 updateUnreadCountBadge();
3829 return readMessages;
3830 } else {
3831 return readMessages;
3832 }
3833 }
3834
3835 public synchronized void updateUnreadCountBadge() {
3836 int count = unreadCount();
3837 if (unreadCount != count) {
3838 Log.d(Config.LOGTAG, "update unread count to " + count);
3839 if (count > 0) {
3840 ShortcutBadger.applyCount(getApplicationContext(), count);
3841 } else {
3842 ShortcutBadger.removeCount(getApplicationContext());
3843 }
3844 unreadCount = count;
3845 }
3846 }
3847
3848 public void sendReadMarker(final Conversation conversation, String upToUuid) {
3849 final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
3850 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
3851 if (readMessages.size() > 0) {
3852 updateConversationUi();
3853 }
3854 final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
3855 if (confirmMessages()
3856 && markable != null
3857 && (markable.trusted() || isPrivateAndNonAnonymousMuc)
3858 && markable.getRemoteMsgId() != null) {
3859 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3860 Account account = conversation.getAccount();
3861 final Jid to = markable.getCounterpart();
3862 final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3863 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3864 this.sendMessagePacket(conversation.getAccount(), packet);
3865 }
3866 }
3867
3868 public SecureRandom getRNG() {
3869 return this.mRandom;
3870 }
3871
3872 public MemorizingTrustManager getMemorizingTrustManager() {
3873 return this.mMemorizingTrustManager;
3874 }
3875
3876 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3877 this.mMemorizingTrustManager = trustManager;
3878 }
3879
3880 public void updateMemorizingTrustmanager() {
3881 final MemorizingTrustManager tm;
3882 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3883 if (dontTrustSystemCAs) {
3884 tm = new MemorizingTrustManager(getApplicationContext(), null);
3885 } else {
3886 tm = new MemorizingTrustManager(getApplicationContext());
3887 }
3888 setMemorizingTrustManager(tm);
3889 }
3890
3891 public LruCache<String, Bitmap> getBitmapCache() {
3892 return this.mBitmapCache;
3893 }
3894
3895 public Collection<String> getKnownHosts() {
3896 final Set<String> hosts = new HashSet<>();
3897 for (final Account account : getAccounts()) {
3898 hosts.add(account.getServer());
3899 for (final Contact contact : account.getRoster().getContacts()) {
3900 if (contact.showInRoster()) {
3901 final String server = contact.getServer();
3902 if (server != null) {
3903 hosts.add(server);
3904 }
3905 }
3906 }
3907 }
3908 if (Config.QUICKSY_DOMAIN != null) {
3909 hosts.remove(Config.QUICKSY_DOMAIN); //we only want to show this when we type a e164 number
3910 }
3911 if (Config.DOMAIN_LOCK != null) {
3912 hosts.add(Config.DOMAIN_LOCK);
3913 }
3914 if (Config.MAGIC_CREATE_DOMAIN != null) {
3915 hosts.add(Config.MAGIC_CREATE_DOMAIN);
3916 }
3917 return hosts;
3918 }
3919
3920 public Collection<String> getKnownConferenceHosts() {
3921 final Set<String> mucServers = new HashSet<>();
3922 for (final Account account : accounts) {
3923 if (account.getXmppConnection() != null) {
3924 mucServers.addAll(account.getXmppConnection().getMucServers());
3925 for (Bookmark bookmark : account.getBookmarks()) {
3926 final Jid jid = bookmark.getJid();
3927 final String s = jid == null ? null : jid.getDomain();
3928 if (s != null) {
3929 mucServers.add(s);
3930 }
3931 }
3932 }
3933 }
3934 return mucServers;
3935 }
3936
3937 public void sendMessagePacket(Account account, MessagePacket packet) {
3938 XmppConnection connection = account.getXmppConnection();
3939 if (connection != null) {
3940 connection.sendMessagePacket(packet);
3941 }
3942 }
3943
3944 public void sendPresencePacket(Account account, PresencePacket packet) {
3945 XmppConnection connection = account.getXmppConnection();
3946 if (connection != null) {
3947 connection.sendPresencePacket(packet);
3948 }
3949 }
3950
3951 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3952 final XmppConnection connection = account.getXmppConnection();
3953 if (connection != null) {
3954 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3955 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
3956 }
3957 }
3958
3959 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3960 final XmppConnection connection = account.getXmppConnection();
3961 if (connection != null) {
3962 connection.sendIqPacket(packet, callback);
3963 } else if (callback != null) {
3964 callback.onIqPacketReceived(account,new IqPacket(IqPacket.TYPE.TIMEOUT));
3965 }
3966 }
3967
3968 public void sendPresence(final Account account) {
3969 sendPresence(account, checkListeners() && broadcastLastActivity());
3970 }
3971
3972 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3973 Presence.Status status;
3974 if (manuallyChangePresence()) {
3975 status = account.getPresenceStatus();
3976 } else {
3977 status = getTargetPresence();
3978 }
3979 PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
3980 String message = account.getPresenceStatusMessage();
3981 if (message != null && !message.isEmpty()) {
3982 packet.addChild(new Element("status").setContent(message));
3983 }
3984 if (mLastActivity > 0 && includeIdleTimestamp) {
3985 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3986 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3987 }
3988 sendPresencePacket(account, packet);
3989 }
3990
3991 private void deactivateGracePeriod() {
3992 for (Account account : getAccounts()) {
3993 account.deactivateGracePeriod();
3994 }
3995 }
3996
3997 public void refreshAllPresences() {
3998 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3999 for (Account account : getAccounts()) {
4000 if (account.isEnabled()) {
4001 sendPresence(account, includeIdleTimestamp);
4002 }
4003 }
4004 }
4005
4006 private void refreshAllFcmTokens() {
4007 for (Account account : getAccounts()) {
4008 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
4009 mPushManagementService.registerPushTokenOnServer(account);
4010 }
4011 }
4012 }
4013
4014 private void sendOfflinePresence(final Account account) {
4015 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
4016 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
4017 }
4018
4019 public MessageGenerator getMessageGenerator() {
4020 return this.mMessageGenerator;
4021 }
4022
4023 public PresenceGenerator getPresenceGenerator() {
4024 return this.mPresenceGenerator;
4025 }
4026
4027 public IqGenerator getIqGenerator() {
4028 return this.mIqGenerator;
4029 }
4030
4031 public IqParser getIqParser() {
4032 return this.mIqParser;
4033 }
4034
4035 public JingleConnectionManager getJingleConnectionManager() {
4036 return this.mJingleConnectionManager;
4037 }
4038
4039 public MessageArchiveService getMessageArchiveService() {
4040 return this.mMessageArchiveService;
4041 }
4042
4043 public QuickConversationsService getQuickConversationsService() {
4044 return this.mQuickConversationsService;
4045 }
4046
4047 public List<Contact> findContacts(Jid jid, String accountJid) {
4048 ArrayList<Contact> contacts = new ArrayList<>();
4049 for (Account account : getAccounts()) {
4050 if ((account.isEnabled() || accountJid != null)
4051 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
4052 Contact contact = account.getRoster().getContactFromContactList(jid);
4053 if (contact != null) {
4054 contacts.add(contact);
4055 }
4056 }
4057 }
4058 return contacts;
4059 }
4060
4061 public Conversation findFirstMuc(Jid jid) {
4062 for (Conversation conversation : getConversations()) {
4063 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
4064 return conversation;
4065 }
4066 }
4067 return null;
4068 }
4069
4070 public NotificationService getNotificationService() {
4071 return this.mNotificationService;
4072 }
4073
4074 public HttpConnectionManager getHttpConnectionManager() {
4075 return this.mHttpConnectionManager;
4076 }
4077
4078 public void resendFailedMessages(final Message message) {
4079 final Collection<Message> messages = new ArrayList<>();
4080 Message current = message;
4081 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
4082 messages.add(current);
4083 if (current.mergeable(current.next())) {
4084 current = current.next();
4085 } else {
4086 break;
4087 }
4088 }
4089 for (final Message msg : messages) {
4090 msg.setTime(System.currentTimeMillis());
4091 markMessage(msg, Message.STATUS_WAITING);
4092 this.resendMessage(msg, false);
4093 }
4094 if (message.getConversation() instanceof Conversation) {
4095 ((Conversation) message.getConversation()).sort();
4096 }
4097 updateConversationUi();
4098 }
4099
4100 public void clearConversationHistory(final Conversation conversation) {
4101 final long clearDate;
4102 final String reference;
4103 if (conversation.countMessages() > 0) {
4104 Message latestMessage = conversation.getLatestMessage();
4105 clearDate = latestMessage.getTimeSent() + 1000;
4106 reference = latestMessage.getServerMsgId();
4107 } else {
4108 clearDate = System.currentTimeMillis();
4109 reference = null;
4110 }
4111 conversation.clearMessages();
4112 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
4113 conversation.setLastClearHistory(clearDate, reference);
4114 Runnable runnable = () -> {
4115 databaseBackend.deleteMessagesInConversation(conversation);
4116 databaseBackend.updateConversation(conversation);
4117 };
4118 mDatabaseWriterExecutor.execute(runnable);
4119 }
4120
4121 public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
4122 if (blockable != null && blockable.getBlockedJid() != null) {
4123 final Jid jid = blockable.getBlockedJid();
4124 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
4125
4126 @Override
4127 public void onIqPacketReceived(final Account account, final IqPacket packet) {
4128 if (packet.getType() == IqPacket.TYPE.RESULT) {
4129 account.getBlocklist().add(jid);
4130 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
4131 }
4132 }
4133 });
4134 if (removeBlockedConversations(blockable.getAccount(), jid)) {
4135 updateConversationUi();
4136 return true;
4137 } else {
4138 return false;
4139 }
4140 } else {
4141 return false;
4142 }
4143 }
4144
4145 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
4146 boolean removed = false;
4147 synchronized (this.conversations) {
4148 boolean domainJid = blockedJid.getLocal() == null;
4149 for (Conversation conversation : this.conversations) {
4150 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
4151 || blockedJid.equals(conversation.getJid().asBareJid());
4152 if (conversation.getAccount() == account
4153 && conversation.getMode() == Conversation.MODE_SINGLE
4154 && jidMatches) {
4155 this.conversations.remove(conversation);
4156 markRead(conversation);
4157 conversation.setStatus(Conversation.STATUS_ARCHIVED);
4158 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
4159 updateConversation(conversation);
4160 removed = true;
4161 }
4162 }
4163 }
4164 return removed;
4165 }
4166
4167 public void sendUnblockRequest(final Blockable blockable) {
4168 if (blockable != null && blockable.getJid() != null) {
4169 final Jid jid = blockable.getBlockedJid();
4170 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
4171 @Override
4172 public void onIqPacketReceived(final Account account, final IqPacket packet) {
4173 if (packet.getType() == IqPacket.TYPE.RESULT) {
4174 account.getBlocklist().remove(jid);
4175 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
4176 }
4177 }
4178 });
4179 }
4180 }
4181
4182 public void publishDisplayName(Account account) {
4183 String displayName = account.getDisplayName();
4184 final IqPacket request;
4185 if (TextUtils.isEmpty(displayName)) {
4186 request = mIqGenerator.deleteNode(Namespace.NICK);
4187 } else {
4188 request = mIqGenerator.publishNick(displayName);
4189 }
4190 mAvatarService.clear(account);
4191 sendIqPacket(account, request, (account1, packet) -> {
4192 if (packet.getType() == IqPacket.TYPE.ERROR) {
4193 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name "+packet.toString());
4194 }
4195 });
4196 }
4197
4198 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
4199 ServiceDiscoveryResult result = discoCache.get(key);
4200 if (result != null) {
4201 return result;
4202 } else {
4203 result = databaseBackend.findDiscoveryResult(key.first, key.second);
4204 if (result != null) {
4205 discoCache.put(key, result);
4206 }
4207 return result;
4208 }
4209 }
4210
4211 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
4212 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
4213 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
4214 if (disco != null) {
4215 presence.setServiceDiscoveryResult(disco);
4216 } else {
4217 if (!account.inProgressDiscoFetches.contains(key)) {
4218 account.inProgressDiscoFetches.add(key);
4219 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4220 request.setTo(jid);
4221 final String node = presence.getNode();
4222 final String ver = presence.getVer();
4223 final Element query = request.query("http://jabber.org/protocol/disco#info");
4224 if (node != null && ver != null) {
4225 query.setAttribute("node",node+"#"+ver);
4226 }
4227 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
4228 sendIqPacket(account, request, (a, response) -> {
4229 if (response.getType() == IqPacket.TYPE.RESULT) {
4230 ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
4231 if (presence.getVer().equals(discoveryResult.getVer())) {
4232 databaseBackend.insertDiscoveryResult(discoveryResult);
4233 injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
4234 } else {
4235 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
4236 }
4237 }
4238 a.inProgressDiscoFetches.remove(key);
4239 });
4240 }
4241 }
4242 }
4243
4244 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
4245 for (Contact contact : roster.getContacts()) {
4246 for (Presence presence : contact.getPresences().getPresences().values()) {
4247 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
4248 presence.setServiceDiscoveryResult(disco);
4249 }
4250 }
4251 }
4252 }
4253
4254 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
4255 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
4256 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
4257 request.addChild("prefs", version.namespace);
4258 sendIqPacket(account, request, (account1, packet) -> {
4259 Element prefs = packet.findChild("prefs", version.namespace);
4260 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
4261 callback.onPreferencesFetched(prefs);
4262 } else {
4263 callback.onPreferencesFetchFailed();
4264 }
4265 });
4266 }
4267
4268 public PushManagementService getPushManagementService() {
4269 return mPushManagementService;
4270 }
4271
4272 public void changeStatus(Account account, PresenceTemplate template, String signature) {
4273 if (!template.getStatusMessage().isEmpty()) {
4274 databaseBackend.insertPresenceTemplate(template);
4275 }
4276 account.setPgpSignature(signature);
4277 account.setPresenceStatus(template.getStatus());
4278 account.setPresenceStatusMessage(template.getStatusMessage());
4279 databaseBackend.updateAccount(account);
4280 sendPresence(account);
4281 }
4282
4283 public List<PresenceTemplate> getPresenceTemplates(Account account) {
4284 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
4285 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
4286 if (!templates.contains(template)) {
4287 templates.add(0, template);
4288 }
4289 }
4290 return templates;
4291 }
4292
4293 public void saveConversationAsBookmark(Conversation conversation, String name) {
4294 Account account = conversation.getAccount();
4295 Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
4296 if (!conversation.getJid().isBareJid()) {
4297 bookmark.setNick(conversation.getJid().getResource());
4298 }
4299 if (!TextUtils.isEmpty(name)) {
4300 bookmark.setBookmarkName(name);
4301 }
4302 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
4303 account.getBookmarks().add(bookmark);
4304 pushBookmarks(account);
4305 bookmark.setConversation(conversation);
4306 }
4307
4308 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
4309 boolean performedVerification = false;
4310 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
4311 for (XmppUri.Fingerprint fp : fingerprints) {
4312 if (fp.type == XmppUri.FingerprintType.OMEMO) {
4313 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4314 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4315 if (fingerprintStatus != null) {
4316 if (!fingerprintStatus.isVerified()) {
4317 performedVerification = true;
4318 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4319 }
4320 } else {
4321 axolotlService.preVerifyFingerprint(contact, fingerprint);
4322 }
4323 }
4324 }
4325 return performedVerification;
4326 }
4327
4328 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
4329 final AxolotlService axolotlService = account.getAxolotlService();
4330 boolean verifiedSomething = false;
4331 for (XmppUri.Fingerprint fp : fingerprints) {
4332 if (fp.type == XmppUri.FingerprintType.OMEMO) {
4333 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
4334 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
4335 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
4336 if (fingerprintStatus != null) {
4337 if (!fingerprintStatus.isVerified()) {
4338 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4339 verifiedSomething = true;
4340 }
4341 } else {
4342 axolotlService.preVerifyFingerprint(account, fingerprint);
4343 verifiedSomething = true;
4344 }
4345 }
4346 }
4347 return verifiedSomething;
4348 }
4349
4350 public boolean blindTrustBeforeVerification() {
4351 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4352 }
4353
4354 public ShortcutService getShortcutService() {
4355 return mShortcutService;
4356 }
4357
4358 public void pushMamPreferences(Account account, Element prefs) {
4359 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4360 set.addChild(prefs);
4361 sendIqPacket(account, set, null);
4362 }
4363
4364 public interface OnMamPreferencesFetched {
4365 void onPreferencesFetched(Element prefs);
4366
4367 void onPreferencesFetchFailed();
4368 }
4369
4370 public interface OnAccountCreated {
4371 void onAccountCreated(Account account);
4372
4373 void informUser(int r);
4374 }
4375
4376 public interface OnMoreMessagesLoaded {
4377 void onMoreMessagesLoaded(int count, Conversation conversation);
4378
4379 void informUser(int r);
4380 }
4381
4382 public interface OnAccountPasswordChanged {
4383 void onPasswordChangeSucceeded();
4384
4385 void onPasswordChangeFailed();
4386 }
4387
4388 public interface OnRoomDestroy {
4389 void onRoomDestroySucceeded();
4390
4391 void onRoomDestroyFailed();
4392 }
4393
4394 public interface OnAffiliationChanged {
4395 void onAffiliationChangedSuccessful(Jid jid);
4396
4397 void onAffiliationChangeFailed(Jid jid, int resId);
4398 }
4399
4400 public interface OnConversationUpdate {
4401 void onConversationUpdate();
4402 }
4403
4404 public interface OnAccountUpdate {
4405 void onAccountUpdate();
4406 }
4407
4408 public interface OnCaptchaRequested {
4409 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4410 }
4411
4412 public interface OnRosterUpdate {
4413 void onRosterUpdate();
4414 }
4415
4416 public interface OnMucRosterUpdate {
4417 void onMucRosterUpdate();
4418 }
4419
4420 public interface OnConferenceConfigurationFetched {
4421 void onConferenceConfigurationFetched(Conversation conversation);
4422
4423 void onFetchFailed(Conversation conversation, Element error);
4424 }
4425
4426 public interface OnConferenceJoined {
4427 void onConferenceJoined(Conversation conversation);
4428 }
4429
4430 public interface OnConfigurationPushed {
4431 void onPushSucceeded();
4432
4433 void onPushFailed();
4434 }
4435
4436 public interface OnShowErrorToast {
4437 void onShowErrorToast(int resId);
4438 }
4439
4440 public class XmppConnectionBinder extends Binder {
4441 public XmppConnectionService getService() {
4442 return XmppConnectionService.this;
4443 }
4444 }
4445
4446 private class InternalEventReceiver extends BroadcastReceiver {
4447
4448 @Override
4449 public void onReceive(Context context, Intent intent) {
4450 onStartCommand(intent,0,0);
4451 }
4452 }
4453}