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