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 public boolean foregroundNotificationNeedsUpdatingWhenErrorStateChanges() {
1109 return !mForceForegroundService.get() && Compatibility.keepForegroundService(this) && hasEnabledAccounts();
1110 }
1111
1112 @Override
1113 public void onTaskRemoved(final Intent rootIntent) {
1114 super.onTaskRemoved(rootIntent);
1115 if ((Compatibility.keepForegroundService(this) && hasEnabledAccounts()) || mForceForegroundService.get()) {
1116 Log.d(Config.LOGTAG, "ignoring onTaskRemoved because foreground service is activated");
1117 } else {
1118 this.logoutAndSave(false);
1119 }
1120 }
1121
1122 private void logoutAndSave(boolean stop) {
1123 int activeAccounts = 0;
1124 for (final Account account : accounts) {
1125 if (account.getStatus() != Account.State.DISABLED) {
1126 databaseBackend.writeRoster(account.getRoster());
1127 activeAccounts++;
1128 }
1129 if (account.getXmppConnection() != null) {
1130 new Thread(() -> disconnect(account, false)).start();
1131 }
1132 }
1133 if (stop || activeAccounts == 0) {
1134 Log.d(Config.LOGTAG, "good bye");
1135 stopSelf();
1136 }
1137 }
1138
1139 public void scheduleWakeUpCall(int seconds, int requestCode) {
1140 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
1141 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1142 if (alarmManager == null) {
1143 return;
1144 }
1145 final Intent intent = new Intent(this, EventReceiver.class);
1146 intent.setAction("ping");
1147 try {
1148 PendingIntent pendingIntent = PendingIntent.getBroadcast(this, requestCode, intent, 0);
1149 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1150 } catch (RuntimeException e) {
1151 Log.e(Config.LOGTAG, "unable to schedule alarm for ping", e);
1152 }
1153 }
1154
1155 @TargetApi(Build.VERSION_CODES.M)
1156 private void scheduleNextIdlePing() {
1157 final long timeToWake = SystemClock.elapsedRealtime() + (Config.IDLE_PING_INTERVAL * 1000);
1158 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1159 if (alarmManager == null) {
1160 return;
1161 }
1162 final Intent intent = new Intent(this, EventReceiver.class);
1163 intent.setAction(ACTION_IDLE_PING);
1164 try {
1165 PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
1166 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, pendingIntent);
1167 } catch (RuntimeException e) {
1168 Log.d(Config.LOGTAG, "unable to schedule alarm for idle ping", e);
1169 }
1170 }
1171
1172 public XmppConnection createConnection(final Account account) {
1173 final XmppConnection connection = new XmppConnection(account, this);
1174 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1175 connection.setOnStatusChangedListener(this.statusListener);
1176 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1177 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1178 connection.setOnJinglePacketReceivedListener(this.jingleListener);
1179 connection.setOnBindListener(this.mOnBindListener);
1180 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1181 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1182 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1183 AxolotlService axolotlService = account.getAxolotlService();
1184 if (axolotlService != null) {
1185 connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1186 }
1187 return connection;
1188 }
1189
1190 public void sendChatState(Conversation conversation) {
1191 if (sendChatStates()) {
1192 MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1193 sendMessagePacket(conversation.getAccount(), packet);
1194 }
1195 }
1196
1197 private void sendFileMessage(final Message message, final boolean delay) {
1198 Log.d(Config.LOGTAG, "send file message");
1199 final Account account = message.getConversation().getAccount();
1200 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1201 || message.getConversation().getMode() == Conversation.MODE_MULTI) {
1202 mHttpConnectionManager.createNewUploadConnection(message, delay);
1203 } else {
1204 mJingleConnectionManager.createNewConnection(message);
1205 }
1206 }
1207
1208 public void sendMessage(final Message message) {
1209 sendMessage(message, false, false);
1210 }
1211
1212 private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1213 final Account account = message.getConversation().getAccount();
1214 if (account.setShowErrorNotification(true)) {
1215 databaseBackend.updateAccount(account);
1216 mNotificationService.updateErrorNotification();
1217 }
1218 final Conversation conversation = (Conversation) message.getConversation();
1219 account.deactivateGracePeriod();
1220
1221
1222 if (QuickConversationsService.isQuicksy() && conversation.getMode() == Conversation.MODE_SINGLE) {
1223 final Contact contact = conversation.getContact();
1224 if (!contact.showInRoster() && contact.getOption(Contact.Options.SYNCED_VIA_OTHER)) {
1225 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": adding "+contact.getJid()+" on sending message");
1226 createContact(contact, true);
1227 }
1228 }
1229
1230 MessagePacket packet = null;
1231 final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1232 || !Patches.BAD_MUC_REFLECTION.contains(account.getServerIdentity()))
1233 && !message.edited();
1234 boolean saveInDb = addToConversation;
1235 message.setStatus(Message.STATUS_WAITING);
1236
1237 if (account.isOnlineAndConnected()) {
1238 switch (message.getEncryption()) {
1239 case Message.ENCRYPTION_NONE:
1240 if (message.needsUploading()) {
1241 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1242 || conversation.getMode() == Conversation.MODE_MULTI
1243 || message.fixCounterpart()) {
1244 this.sendFileMessage(message, delay);
1245 } else {
1246 break;
1247 }
1248 } else {
1249 packet = mMessageGenerator.generateChat(message);
1250 }
1251 break;
1252 case Message.ENCRYPTION_PGP:
1253 case Message.ENCRYPTION_DECRYPTED:
1254 if (message.needsUploading()) {
1255 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1256 || conversation.getMode() == Conversation.MODE_MULTI
1257 || message.fixCounterpart()) {
1258 this.sendFileMessage(message, delay);
1259 } else {
1260 break;
1261 }
1262 } else {
1263 packet = mMessageGenerator.generatePgpChat(message);
1264 }
1265 break;
1266 case Message.ENCRYPTION_AXOLOTL:
1267 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1268 if (message.needsUploading()) {
1269 if (account.httpUploadAvailable(fileBackend.getFile(message, false).getSize())
1270 || conversation.getMode() == Conversation.MODE_MULTI
1271 || message.fixCounterpart()) {
1272 this.sendFileMessage(message, delay);
1273 } else {
1274 break;
1275 }
1276 } else {
1277 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1278 if (axolotlMessage == null) {
1279 account.getAxolotlService().preparePayloadMessage(message, delay);
1280 } else {
1281 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1282 }
1283 }
1284 break;
1285
1286 }
1287 if (packet != null) {
1288 if (account.getXmppConnection().getFeatures().sm()
1289 || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1290 message.setStatus(Message.STATUS_UNSEND);
1291 } else {
1292 message.setStatus(Message.STATUS_SEND);
1293 }
1294 }
1295 } else {
1296 switch (message.getEncryption()) {
1297 case Message.ENCRYPTION_DECRYPTED:
1298 if (!message.needsUploading()) {
1299 String pgpBody = message.getEncryptedBody();
1300 String decryptedBody = message.getBody();
1301 message.setBody(pgpBody); //TODO might throw NPE
1302 message.setEncryption(Message.ENCRYPTION_PGP);
1303 if (message.edited()) {
1304 message.setBody(decryptedBody);
1305 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1306 databaseBackend.updateMessage(message, message.getEditedId());
1307 updateConversationUi();
1308 return;
1309 } else {
1310 databaseBackend.createMessage(message);
1311 saveInDb = false;
1312 message.setBody(decryptedBody);
1313 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1314 }
1315 }
1316 break;
1317 case Message.ENCRYPTION_AXOLOTL:
1318 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1319 break;
1320 }
1321 }
1322
1323
1324 boolean mucMessage = conversation.getMode() == Conversation.MODE_MULTI && message.getType() != Message.TYPE_PRIVATE;
1325 if (mucMessage) {
1326 message.setCounterpart(conversation.getMucOptions().getSelf().getFullJid());
1327 }
1328
1329 if (resend) {
1330 if (packet != null && addToConversation) {
1331 if (account.getXmppConnection().getFeatures().sm() || mucMessage) {
1332 markMessage(message, Message.STATUS_UNSEND);
1333 } else {
1334 markMessage(message, Message.STATUS_SEND);
1335 }
1336 }
1337 } else {
1338 if (addToConversation) {
1339 conversation.add(message);
1340 }
1341 if (saveInDb) {
1342 databaseBackend.createMessage(message);
1343 } else if (message.edited()) {
1344 databaseBackend.updateMessage(message, message.getEditedId());
1345 }
1346 updateConversationUi();
1347 }
1348 if (packet != null) {
1349 if (delay) {
1350 mMessageGenerator.addDelay(packet, message.getTimeSent());
1351 }
1352 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1353 if (this.sendChatStates()) {
1354 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1355 }
1356 }
1357 sendMessagePacket(account, packet);
1358 }
1359 }
1360
1361 private void sendUnsentMessages(final Conversation conversation) {
1362 conversation.findWaitingMessages(message -> resendMessage(message, true));
1363 }
1364
1365 public void resendMessage(final Message message, final boolean delay) {
1366 sendMessage(message, true, delay);
1367 }
1368
1369 public void fetchRosterFromServer(final Account account) {
1370 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1371 if (!"".equals(account.getRosterVersion())) {
1372 Log.d(Config.LOGTAG, account.getJid().asBareJid()
1373 + ": fetching roster version " + account.getRosterVersion());
1374 } else {
1375 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
1376 }
1377 iqPacket.query(Namespace.ROSTER).setAttribute("ver", account.getRosterVersion());
1378 sendIqPacket(account, iqPacket, mIqParser);
1379 }
1380
1381 public void fetchBookmarks(final Account account) {
1382 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1383 final Element query = iqPacket.query("jabber:iq:private");
1384 query.addChild("storage", Namespace.BOOKMARKS);
1385 final OnIqPacketReceived callback = (a, response) -> {
1386 if (response.getType() == IqPacket.TYPE.RESULT) {
1387 final Element query1 = response.query();
1388 final Element storage = query1.findChild("storage", "storage:bookmarks");
1389 processBookmarks(a, storage);
1390 } else {
1391 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": could not fetch bookmarks");
1392 }
1393 };
1394 sendIqPacket(account, iqPacket, callback);
1395 }
1396
1397 public void processBookmarks(Account account, Element storage) {
1398 final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1399 final boolean autojoin = respectAutojoin();
1400 if (storage != null) {
1401 for (final Element item : storage.getChildren()) {
1402 if (item.getName().equals("conference")) {
1403 final Bookmark bookmark = Bookmark.parse(item, account);
1404 Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1405 if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1406 bookmark.setBookmarkName(old.getBookmarkName());
1407 }
1408 Conversation conversation = find(bookmark);
1409 if (conversation != null) {
1410 bookmark.setConversation(conversation);
1411 } else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1412 conversation = findOrCreateConversation(account, bookmark.getFullJid(), true, true, false);
1413 bookmark.setConversation(conversation);
1414 }
1415 }
1416 }
1417 }
1418 account.setBookmarks(new CopyOnWriteArrayList<>(bookmarks.values()));
1419 }
1420
1421 public void pushBookmarks(Account account) {
1422 if (account.getXmppConnection().getFeatures().bookmarksConversion()) {
1423 pushBookmarksPep(account);
1424 } else {
1425 pushBookmarksPrivateXml(account);
1426 }
1427 }
1428
1429 private void pushBookmarksPrivateXml(Account account) {
1430 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via private xml");
1431 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1432 Element query = iqPacket.query("jabber:iq:private");
1433 Element storage = query.addChild("storage", "storage:bookmarks");
1434 for (Bookmark bookmark : account.getBookmarks()) {
1435 storage.addChild(bookmark);
1436 }
1437 sendIqPacket(account, iqPacket, mDefaultIqHandler);
1438 }
1439
1440 private void pushBookmarksPep(Account account) {
1441 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": pushing bookmarks via pep");
1442 Element storage = new Element("storage", "storage:bookmarks");
1443 for (Bookmark bookmark : account.getBookmarks()) {
1444 storage.addChild(bookmark);
1445 }
1446 pushNodeAndEnforcePublishOptions(account,Namespace.BOOKMARKS,storage, PublishOptions.persistentWhitelistAccess());
1447
1448 }
1449
1450
1451 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final Bundle options) {
1452 pushNodeAndEnforcePublishOptions(account, node, element, options, true);
1453
1454 }
1455
1456 private void pushNodeAndEnforcePublishOptions(final Account account, final String node, final Element element, final Bundle options, final boolean retry) {
1457 IqPacket packet = mIqGenerator.publishElement(node, element, options);
1458 Log.d(Config.LOGTAG,packet.toString());
1459 sendIqPacket(account, packet, (a, response) -> {
1460 if (response.getType() == IqPacket.TYPE.RESULT) {
1461 return;
1462 }
1463 final Element error = response.getType() == IqPacket.TYPE.ERROR ? response.findChild("error") : null;
1464 final boolean preconditionNotMet = error != null && error.hasChild("precondition-not-met", Namespace.PUBSUB_ERROR);
1465 if (retry && preconditionNotMet) {
1466 pushNodeConfiguration(account, node, options, new OnConfigurationPushed() {
1467 @Override
1468 public void onPushSucceeded() {
1469 pushNodeAndEnforcePublishOptions(account, node, element, options, false);
1470 }
1471
1472 @Override
1473 public void onPushFailed() {
1474 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to push node configuration ("+node+")");
1475 }
1476 });
1477 } else {
1478 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": error publishing bookmarks (retry="+Boolean.toString(retry)+") "+response);
1479 }
1480 });
1481 }
1482
1483 private void restoreFromDatabase() {
1484 synchronized (this.conversations) {
1485 final Map<String, Account> accountLookupTable = new Hashtable<>();
1486 for (Account account : this.accounts) {
1487 accountLookupTable.put(account.getUuid(), account);
1488 }
1489 Log.d(Config.LOGTAG, "restoring conversations...");
1490 final long startTimeConversationsRestore = SystemClock.elapsedRealtime();
1491 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1492 for (Iterator<Conversation> iterator = conversations.listIterator(); iterator.hasNext(); ) {
1493 Conversation conversation = iterator.next();
1494 Account account = accountLookupTable.get(conversation.getAccountUuid());
1495 if (account != null) {
1496 conversation.setAccount(account);
1497 } else {
1498 Log.e(Config.LOGTAG, "unable to restore Conversations with " + conversation.getJid());
1499 iterator.remove();
1500 }
1501 }
1502 long diffConversationsRestore = SystemClock.elapsedRealtime() - startTimeConversationsRestore;
1503 Log.d(Config.LOGTAG, "finished restoring conversations in " + diffConversationsRestore + "ms");
1504 Runnable runnable = () -> {
1505 long deletionDate = getAutomaticMessageDeletionDate();
1506 mLastExpiryRun.set(SystemClock.elapsedRealtime());
1507 if (deletionDate > 0) {
1508 Log.d(Config.LOGTAG, "deleting messages that are older than " + AbstractGenerator.getTimestamp(deletionDate));
1509 databaseBackend.expireOldMessages(deletionDate);
1510 }
1511 Log.d(Config.LOGTAG, "restoring roster...");
1512 for (Account account : accounts) {
1513 databaseBackend.readRoster(account.getRoster());
1514 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1515 }
1516 getBitmapCache().evictAll();
1517 loadPhoneContacts();
1518 Log.d(Config.LOGTAG, "restoring messages...");
1519 final long startMessageRestore = SystemClock.elapsedRealtime();
1520 final Conversation quickLoad = QuickLoader.get(this.conversations);
1521 if (quickLoad != null) {
1522 restoreMessages(quickLoad);
1523 updateConversationUi();
1524 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1525 Log.d(Config.LOGTAG,"quickly restored "+quickLoad.getName()+" after " + diffMessageRestore + "ms");
1526 }
1527 for (Conversation conversation : this.conversations) {
1528 if (quickLoad != conversation) {
1529 restoreMessages(conversation);
1530 }
1531 }
1532 mNotificationService.finishBacklog(false);
1533 restoredFromDatabaseLatch.countDown();
1534 final long diffMessageRestore = SystemClock.elapsedRealtime() - startMessageRestore;
1535 Log.d(Config.LOGTAG, "finished restoring messages in " + diffMessageRestore + "ms");
1536 updateConversationUi();
1537 };
1538 mDatabaseReaderExecutor.execute(runnable); //will contain one write command (expiry) but that's fine
1539 }
1540 }
1541
1542 private void restoreMessages(Conversation conversation) {
1543 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1544 checkDeletedFiles(conversation);
1545 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
1546 conversation.findUnreadMessages(message -> mNotificationService.pushFromBacklog(message));
1547 }
1548
1549 public void loadPhoneContacts() {
1550 mContactMergerExecutor.execute(() -> {
1551 Map<Jid, JabberIdContact> contacts = JabberIdContact.load(this);
1552 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1553 for (Account account : accounts) {
1554 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts(JabberIdContact.class);
1555 for (JabberIdContact jidContact : contacts.values()) {
1556 final Contact contact = account.getRoster().getContact(jidContact.getJid());
1557 boolean needsCacheClean = contact.setPhoneContact(jidContact);
1558 if (needsCacheClean) {
1559 getAvatarService().clear(contact);
1560 }
1561 withSystemAccounts.remove(contact);
1562 }
1563 for (Contact contact : withSystemAccounts) {
1564 boolean needsCacheClean = contact.unsetPhoneContact(JabberIdContact.class);
1565 if (needsCacheClean) {
1566 getAvatarService().clear(contact);
1567 }
1568 }
1569 }
1570 Log.d(Config.LOGTAG, "finished merging phone contacts");
1571 mShortcutService.refresh(mInitialAddressbookSyncCompleted.compareAndSet(false, true));
1572 updateRosterUi();
1573 mQuickConversationsService.considerSync();
1574 });
1575 }
1576
1577
1578 public void syncRoster(final Account account) {
1579 mRosterSyncTaskManager.execute(account, () -> databaseBackend.writeRoster(account.getRoster()));
1580 }
1581
1582 public List<Conversation> getConversations() {
1583 return this.conversations;
1584 }
1585
1586 private void checkDeletedFiles(Conversation conversation) {
1587 conversation.findMessagesWithFiles(message -> {
1588 if (!getFileBackend().isFileAvailable(message)) {
1589 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1590 final int s = message.getStatus();
1591 if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1592 markMessage(message, Message.STATUS_SEND_FAILED);
1593 }
1594 }
1595 });
1596 }
1597
1598 private void markFileDeleted(final String path) {
1599 Log.d(Config.LOGTAG, "deleted file " + path);
1600 for (Conversation conversation : getConversations()) {
1601 conversation.findMessagesWithFiles(message -> {
1602 DownloadableFile file = fileBackend.getFile(message);
1603 if (file.getAbsolutePath().equals(path)) {
1604 if (!file.exists()) {
1605 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1606 final int s = message.getStatus();
1607 if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1608 markMessage(message, Message.STATUS_SEND_FAILED);
1609 } else {
1610 updateConversationUi();
1611 }
1612 } else {
1613 Log.d(Config.LOGTAG, "found matching message for file " + path + " but file still exists");
1614 }
1615 }
1616 });
1617 }
1618 }
1619
1620 public void populateWithOrderedConversations(final List<Conversation> list) {
1621 populateWithOrderedConversations(list, true);
1622 }
1623
1624 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1625 list.clear();
1626 if (includeNoFileUpload) {
1627 list.addAll(getConversations());
1628 } else {
1629 for (Conversation conversation : getConversations()) {
1630 if (conversation.getMode() == Conversation.MODE_SINGLE
1631 || (conversation.getAccount().httpUploadAvailable() && conversation.getMucOptions().participating())) {
1632 list.add(conversation);
1633 }
1634 }
1635 }
1636 try {
1637 Collections.sort(list);
1638 } catch (IllegalArgumentException e) {
1639 //ignore
1640 }
1641 }
1642
1643 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1644 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1645 return;
1646 } else if (timestamp == 0) {
1647 return;
1648 }
1649 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1650 final Runnable runnable = () -> {
1651 final Account account = conversation.getAccount();
1652 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1653 if (messages.size() > 0) {
1654 conversation.addAll(0, messages);
1655 checkDeletedFiles(conversation);
1656 callback.onMoreMessagesLoaded(messages.size(), conversation);
1657 } else if (conversation.hasMessagesLeftOnServer()
1658 && account.isOnlineAndConnected()
1659 && conversation.getLastClearHistory().getTimestamp() == 0) {
1660 final boolean mamAvailable;
1661 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1662 mamAvailable = account.getXmppConnection().getFeatures().mam() && !conversation.getContact().isBlocked();
1663 } else {
1664 mamAvailable = conversation.getMucOptions().mamSupport();
1665 }
1666 if (mamAvailable) {
1667 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, new MamReference(0), timestamp, false);
1668 if (query != null) {
1669 query.setCallback(callback);
1670 callback.informUser(R.string.fetching_history_from_server);
1671 } else {
1672 callback.informUser(R.string.not_fetching_history_retention_period);
1673 }
1674
1675 }
1676 }
1677 };
1678 mDatabaseReaderExecutor.execute(runnable);
1679 }
1680
1681 public List<Account> getAccounts() {
1682 return this.accounts;
1683 }
1684
1685 public List<Conversation> findAllConferencesWith(Contact contact) {
1686 ArrayList<Conversation> results = new ArrayList<>();
1687 for (final Conversation c : conversations) {
1688 if (c.getMode() == Conversation.MODE_MULTI && c.getMucOptions().isContactInRoom(contact)) {
1689 results.add(c);
1690 }
1691 }
1692 return results;
1693 }
1694
1695 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1696 for (final Conversation conversation : haystack) {
1697 if (conversation.getContact() == contact) {
1698 return conversation;
1699 }
1700 }
1701 return null;
1702 }
1703
1704 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1705 if (jid == null) {
1706 return null;
1707 }
1708 for (final Conversation conversation : haystack) {
1709 if ((account == null || conversation.getAccount() == account)
1710 && (conversation.getJid().asBareJid().equals(jid.asBareJid()))) {
1711 return conversation;
1712 }
1713 }
1714 return null;
1715 }
1716
1717 public boolean isConversationsListEmpty(final Conversation ignore) {
1718 synchronized (this.conversations) {
1719 final int size = this.conversations.size();
1720 return size == 0 || size == 1 && this.conversations.get(0) == ignore;
1721 }
1722 }
1723
1724 public boolean isConversationStillOpen(final Conversation conversation) {
1725 synchronized (this.conversations) {
1726 for (Conversation current : this.conversations) {
1727 if (current == conversation) {
1728 return true;
1729 }
1730 }
1731 }
1732 return false;
1733 }
1734
1735 public Conversation findOrCreateConversation(Account account, Jid jid, boolean muc, final boolean async) {
1736 return this.findOrCreateConversation(account, jid, muc, false, async);
1737 }
1738
1739 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final boolean async) {
1740 return this.findOrCreateConversation(account, jid, muc, joinAfterCreate, null, async);
1741 }
1742
1743 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final boolean joinAfterCreate, final MessageArchiveService.Query query, final boolean async) {
1744 synchronized (this.conversations) {
1745 Conversation conversation = find(account, jid);
1746 if (conversation != null) {
1747 return conversation;
1748 }
1749 conversation = databaseBackend.findConversation(account, jid);
1750 final boolean loadMessagesFromDb;
1751 if (conversation != null) {
1752 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1753 conversation.setAccount(account);
1754 if (muc) {
1755 conversation.setMode(Conversation.MODE_MULTI);
1756 conversation.setContactJid(jid);
1757 } else {
1758 conversation.setMode(Conversation.MODE_SINGLE);
1759 conversation.setContactJid(jid.asBareJid());
1760 }
1761 databaseBackend.updateConversation(conversation);
1762 loadMessagesFromDb = conversation.messagesLoaded.compareAndSet(true, false);
1763 } else {
1764 String conversationName;
1765 Contact contact = account.getRoster().getContact(jid);
1766 if (contact != null) {
1767 conversationName = contact.getDisplayName();
1768 } else {
1769 conversationName = jid.getLocal();
1770 }
1771 if (muc) {
1772 conversation = new Conversation(conversationName, account, jid,
1773 Conversation.MODE_MULTI);
1774 } else {
1775 conversation = new Conversation(conversationName, account, jid.asBareJid(),
1776 Conversation.MODE_SINGLE);
1777 }
1778 this.databaseBackend.createConversation(conversation);
1779 loadMessagesFromDb = false;
1780 }
1781 final Conversation c = conversation;
1782 final Runnable runnable = () -> {
1783 if (loadMessagesFromDb) {
1784 c.addAll(0, databaseBackend.getMessages(c, Config.PAGE_SIZE));
1785 updateConversationUi();
1786 c.messagesLoaded.set(true);
1787 }
1788 if (account.getXmppConnection() != null
1789 && !c.getContact().isBlocked()
1790 && account.getXmppConnection().getFeatures().mam()
1791 && !muc) {
1792 if (query == null) {
1793 mMessageArchiveService.query(c);
1794 } else {
1795 if (query.getConversation() == null) {
1796 mMessageArchiveService.query(c, query.getStart(), query.isCatchup());
1797 }
1798 }
1799 }
1800 checkDeletedFiles(c);
1801 if (joinAfterCreate) {
1802 joinMuc(c);
1803 }
1804 };
1805 if (async) {
1806 mDatabaseReaderExecutor.execute(runnable);
1807 } else {
1808 runnable.run();
1809 }
1810 this.conversations.add(conversation);
1811 updateConversationUi();
1812 return conversation;
1813 }
1814 }
1815
1816 public void archiveConversation(Conversation conversation) {
1817 getNotificationService().clear(conversation);
1818 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1819 conversation.setNextMessage(null);
1820 synchronized (this.conversations) {
1821 getMessageArchiveService().kill(conversation);
1822 if (conversation.getMode() == Conversation.MODE_MULTI) {
1823 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1824 Bookmark bookmark = conversation.getBookmark();
1825 if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1826 bookmark.setAutojoin(false);
1827 pushBookmarks(bookmark.getAccount());
1828 }
1829 }
1830 leaveMuc(conversation);
1831 } else {
1832 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1833 Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1834 sendPresencePacket(
1835 conversation.getAccount(),
1836 mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1837 );
1838 }
1839 }
1840 updateConversation(conversation);
1841 this.conversations.remove(conversation);
1842 updateConversationUi();
1843 }
1844 }
1845
1846 public void createAccount(final Account account) {
1847 account.initAccountServices(this);
1848 databaseBackend.createAccount(account);
1849 this.accounts.add(account);
1850 this.reconnectAccountInBackground(account);
1851 updateAccountUi();
1852 syncEnabledAccountSetting();
1853 toggleForegroundService();
1854 }
1855
1856 private void syncEnabledAccountSetting() {
1857 getPreferences().edit().putBoolean(EventReceiver.SETTING_ENABLED_ACCOUNTS, hasEnabledAccounts()).apply();
1858 }
1859
1860 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1861 new Thread(() -> {
1862 try {
1863 final X509Certificate[] chain = KeyChain.getCertificateChain(this, alias);
1864 final X509Certificate cert = chain != null && chain.length > 0 ? chain[0] : null;
1865 if (cert == null) {
1866 callback.informUser(R.string.unable_to_parse_certificate);
1867 return;
1868 }
1869 Pair<Jid, String> info = CryptoHelper.extractJidAndName(cert);
1870 if (info == null) {
1871 callback.informUser(R.string.certificate_does_not_contain_jid);
1872 return;
1873 }
1874 if (findAccountByJid(info.first) == null) {
1875 Account account = new Account(info.first, "");
1876 account.setPrivateKeyAlias(alias);
1877 account.setOption(Account.OPTION_DISABLED, true);
1878 account.setDisplayName(info.second);
1879 createAccount(account);
1880 callback.onAccountCreated(account);
1881 if (Config.X509_VERIFICATION) {
1882 try {
1883 getMemorizingTrustManager().getNonInteractive(account.getJid().getDomain()).checkClientTrusted(chain, "RSA");
1884 } catch (CertificateException e) {
1885 callback.informUser(R.string.certificate_chain_is_not_trusted);
1886 }
1887 }
1888 } else {
1889 callback.informUser(R.string.account_already_exists);
1890 }
1891 } catch (Exception e) {
1892 e.printStackTrace();
1893 callback.informUser(R.string.unable_to_parse_certificate);
1894 }
1895 }).start();
1896
1897 }
1898
1899 public void updateKeyInAccount(final Account account, final String alias) {
1900 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": update key in account " + alias);
1901 try {
1902 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1903 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " loaded certificate chain");
1904 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1905 if (info == null) {
1906 showErrorToastInUi(R.string.certificate_does_not_contain_jid);
1907 return;
1908 }
1909 if (account.getJid().asBareJid().equals(info.first)) {
1910 account.setPrivateKeyAlias(alias);
1911 account.setDisplayName(info.second);
1912 databaseBackend.updateAccount(account);
1913 if (Config.X509_VERIFICATION) {
1914 try {
1915 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1916 } catch (CertificateException e) {
1917 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1918 }
1919 account.getAxolotlService().regenerateKeys(true);
1920 }
1921 } else {
1922 showErrorToastInUi(R.string.jid_does_not_match_certificate);
1923 }
1924 } catch (Exception e) {
1925 e.printStackTrace();
1926 }
1927 }
1928
1929 public boolean updateAccount(final Account account) {
1930 if (databaseBackend.updateAccount(account)) {
1931 account.setShowErrorNotification(true);
1932 this.statusListener.onStatusChanged(account);
1933 databaseBackend.updateAccount(account);
1934 reconnectAccountInBackground(account);
1935 updateAccountUi();
1936 getNotificationService().updateErrorNotification();
1937 toggleForegroundService();
1938 syncEnabledAccountSetting();
1939 return true;
1940 } else {
1941 return false;
1942 }
1943 }
1944
1945 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1946 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1947 sendIqPacket(account, iq, (a, packet) -> {
1948 if (packet.getType() == IqPacket.TYPE.RESULT) {
1949 a.setPassword(newPassword);
1950 a.setOption(Account.OPTION_MAGIC_CREATE, false);
1951 databaseBackend.updateAccount(a);
1952 callback.onPasswordChangeSucceeded();
1953 } else {
1954 callback.onPasswordChangeFailed();
1955 }
1956 });
1957 }
1958
1959 public void deleteAccount(final Account account) {
1960 synchronized (this.conversations) {
1961 for (final Conversation conversation : conversations) {
1962 if (conversation.getAccount() == account) {
1963 if (conversation.getMode() == Conversation.MODE_MULTI) {
1964 leaveMuc(conversation);
1965 }
1966 conversations.remove(conversation);
1967 }
1968 }
1969 if (account.getXmppConnection() != null) {
1970 new Thread(() -> disconnect(account, true)).start();
1971 }
1972 final Runnable runnable = () -> {
1973 if (!databaseBackend.deleteAccount(account)) {
1974 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to delete account");
1975 }
1976 };
1977 mDatabaseWriterExecutor.execute(runnable);
1978 this.accounts.remove(account);
1979 this.mRosterSyncTaskManager.clear(account);
1980 updateAccountUi();
1981 getNotificationService().updateErrorNotification();
1982 syncEnabledAccountSetting();
1983 toggleForegroundService();
1984 }
1985 }
1986
1987 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1988 final boolean remainingListeners;
1989 synchronized (LISTENER_LOCK) {
1990 remainingListeners = checkListeners();
1991 if (!this.mOnConversationUpdates.add(listener)) {
1992 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as ConversationListChangedListener");
1993 }
1994 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
1995 }
1996 if (remainingListeners) {
1997 switchToForeground();
1998 }
1999 }
2000
2001 public void removeOnConversationListChangedListener(OnConversationUpdate listener) {
2002 final boolean remainingListeners;
2003 synchronized (LISTENER_LOCK) {
2004 this.mOnConversationUpdates.remove(listener);
2005 this.mNotificationService.setIsInForeground(this.mOnConversationUpdates.size() > 0);
2006 remainingListeners = checkListeners();
2007 }
2008 if (remainingListeners) {
2009 switchToBackground();
2010 }
2011 }
2012
2013 public void setOnShowErrorToastListener(OnShowErrorToast listener) {
2014 final boolean remainingListeners;
2015 synchronized (LISTENER_LOCK) {
2016 remainingListeners = checkListeners();
2017 if (!this.mOnShowErrorToasts.add(listener)) {
2018 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnShowErrorToastListener");
2019 }
2020 }
2021 if (remainingListeners) {
2022 switchToForeground();
2023 }
2024 }
2025
2026 public void removeOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
2027 final boolean remainingListeners;
2028 synchronized (LISTENER_LOCK) {
2029 this.mOnShowErrorToasts.remove(onShowErrorToast);
2030 remainingListeners = checkListeners();
2031 }
2032 if (remainingListeners) {
2033 switchToBackground();
2034 }
2035 }
2036
2037 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
2038 final boolean remainingListeners;
2039 synchronized (LISTENER_LOCK) {
2040 remainingListeners = checkListeners();
2041 if (!this.mOnAccountUpdates.add(listener)) {
2042 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnAccountListChangedtListener");
2043 }
2044 }
2045 if (remainingListeners) {
2046 switchToForeground();
2047 }
2048 }
2049
2050 public void removeOnAccountListChangedListener(OnAccountUpdate listener) {
2051 final boolean remainingListeners;
2052 synchronized (LISTENER_LOCK) {
2053 this.mOnAccountUpdates.remove(listener);
2054 remainingListeners = checkListeners();
2055 }
2056 if (remainingListeners) {
2057 switchToBackground();
2058 }
2059 }
2060
2061 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2062 final boolean remainingListeners;
2063 synchronized (LISTENER_LOCK) {
2064 remainingListeners = checkListeners();
2065 if (!this.mOnCaptchaRequested.add(listener)) {
2066 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnCaptchaRequestListener");
2067 }
2068 }
2069 if (remainingListeners) {
2070 switchToForeground();
2071 }
2072 }
2073
2074 public void removeOnCaptchaRequestedListener(OnCaptchaRequested listener) {
2075 final boolean remainingListeners;
2076 synchronized (LISTENER_LOCK) {
2077 this.mOnCaptchaRequested.remove(listener);
2078 remainingListeners = checkListeners();
2079 }
2080 if (remainingListeners) {
2081 switchToBackground();
2082 }
2083 }
2084
2085 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
2086 final boolean remainingListeners;
2087 synchronized (LISTENER_LOCK) {
2088 remainingListeners = checkListeners();
2089 if (!this.mOnRosterUpdates.add(listener)) {
2090 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnRosterUpdateListener");
2091 }
2092 }
2093 if (remainingListeners) {
2094 switchToForeground();
2095 }
2096 }
2097
2098 public void removeOnRosterUpdateListener(final OnRosterUpdate listener) {
2099 final boolean remainingListeners;
2100 synchronized (LISTENER_LOCK) {
2101 this.mOnRosterUpdates.remove(listener);
2102 remainingListeners = checkListeners();
2103 }
2104 if (remainingListeners) {
2105 switchToBackground();
2106 }
2107 }
2108
2109 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2110 final boolean remainingListeners;
2111 synchronized (LISTENER_LOCK) {
2112 remainingListeners = checkListeners();
2113 if (!this.mOnUpdateBlocklist.add(listener)) {
2114 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnUpdateBlocklistListener");
2115 }
2116 }
2117 if (remainingListeners) {
2118 switchToForeground();
2119 }
2120 }
2121
2122 public void removeOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
2123 final boolean remainingListeners;
2124 synchronized (LISTENER_LOCK) {
2125 this.mOnUpdateBlocklist.remove(listener);
2126 remainingListeners = checkListeners();
2127 }
2128 if (remainingListeners) {
2129 switchToBackground();
2130 }
2131 }
2132
2133 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
2134 final boolean remainingListeners;
2135 synchronized (LISTENER_LOCK) {
2136 remainingListeners = checkListeners();
2137 if (!this.mOnKeyStatusUpdated.add(listener)) {
2138 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnKeyStatusUpdateListener");
2139 }
2140 }
2141 if (remainingListeners) {
2142 switchToForeground();
2143 }
2144 }
2145
2146 public void removeOnNewKeysAvailableListener(final OnKeyStatusUpdated listener) {
2147 final boolean remainingListeners;
2148 synchronized (LISTENER_LOCK) {
2149 this.mOnKeyStatusUpdated.remove(listener);
2150 remainingListeners = checkListeners();
2151 }
2152 if (remainingListeners) {
2153 switchToBackground();
2154 }
2155 }
2156
2157 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
2158 final boolean remainingListeners;
2159 synchronized (LISTENER_LOCK) {
2160 remainingListeners = checkListeners();
2161 if (!this.mOnMucRosterUpdate.add(listener)) {
2162 Log.w(Config.LOGTAG,listener.getClass().getName()+" is already registered as OnMucRosterListener");
2163 }
2164 }
2165 if (remainingListeners) {
2166 switchToForeground();
2167 }
2168 }
2169
2170 public void removeOnMucRosterUpdateListener(final OnMucRosterUpdate listener) {
2171 final boolean remainingListeners;
2172 synchronized (LISTENER_LOCK) {
2173 this.mOnMucRosterUpdate.remove(listener);
2174 remainingListeners = checkListeners();
2175 }
2176 if (remainingListeners) {
2177 switchToBackground();
2178 }
2179 }
2180
2181 public boolean checkListeners() {
2182 return (this.mOnAccountUpdates.size() == 0
2183 && this.mOnConversationUpdates.size() == 0
2184 && this.mOnRosterUpdates.size() == 0
2185 && this.mOnCaptchaRequested.size() == 0
2186 && this.mOnMucRosterUpdate.size() == 0
2187 && this.mOnUpdateBlocklist.size() == 0
2188 && this.mOnShowErrorToasts.size() == 0
2189 && this.mOnKeyStatusUpdated.size() == 0);
2190 }
2191
2192 private void switchToForeground() {
2193 final boolean broadcastLastActivity = broadcastLastActivity();
2194 for (Conversation conversation : getConversations()) {
2195 if (conversation.getMode() == Conversation.MODE_MULTI) {
2196 conversation.getMucOptions().resetChatState();
2197 } else {
2198 conversation.setIncomingChatState(Config.DEFAULT_CHATSTATE);
2199 }
2200 }
2201 for (Account account : getAccounts()) {
2202 if (account.getStatus() == Account.State.ONLINE) {
2203 account.deactivateGracePeriod();
2204 final XmppConnection connection = account.getXmppConnection();
2205 if (connection != null) {
2206 if (connection.getFeatures().csi()) {
2207 connection.sendActive();
2208 }
2209 if (broadcastLastActivity) {
2210 sendPresence(account, false); //send new presence but don't include idle because we are not
2211 }
2212 }
2213 }
2214 }
2215 Log.d(Config.LOGTAG, "app switched into foreground");
2216 }
2217
2218 private void switchToBackground() {
2219 final boolean broadcastLastActivity = broadcastLastActivity();
2220 if (broadcastLastActivity) {
2221 mLastActivity = System.currentTimeMillis();
2222 final SharedPreferences.Editor editor = getPreferences().edit();
2223 editor.putLong(SETTING_LAST_ACTIVITY_TS, mLastActivity);
2224 editor.apply();
2225 }
2226 for (Account account : getAccounts()) {
2227 if (account.getStatus() == Account.State.ONLINE) {
2228 XmppConnection connection = account.getXmppConnection();
2229 if (connection != null) {
2230 if (broadcastLastActivity) {
2231 sendPresence(account, true);
2232 }
2233 if (connection.getFeatures().csi()) {
2234 connection.sendInactive();
2235 }
2236 }
2237 }
2238 }
2239 this.mNotificationService.setIsInForeground(false);
2240 Log.d(Config.LOGTAG, "app switched into background");
2241 }
2242
2243 private void connectMultiModeConversations(Account account) {
2244 List<Conversation> conversations = getConversations();
2245 for (Conversation conversation : conversations) {
2246 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2247 joinMuc(conversation);
2248 }
2249 }
2250 }
2251
2252 public void joinMuc(Conversation conversation) {
2253 joinMuc(conversation, null, false);
2254 }
2255
2256 public void joinMuc(Conversation conversation, boolean followedInvite) {
2257 joinMuc(conversation, null, followedInvite);
2258 }
2259
2260 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2261 joinMuc(conversation, onConferenceJoined, false);
2262 }
2263
2264 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined, final boolean followedInvite) {
2265 Account account = conversation.getAccount();
2266 account.pendingConferenceJoins.remove(conversation);
2267 account.pendingConferenceLeaves.remove(conversation);
2268 if (account.getStatus() == Account.State.ONLINE) {
2269 sendPresencePacket(account, mPresenceGenerator.leave(conversation.getMucOptions()));
2270 conversation.resetMucOptions();
2271 if (onConferenceJoined != null) {
2272 conversation.getMucOptions().flagNoAutoPushConfiguration();
2273 }
2274 conversation.setHasMessagesLeftOnServer(false);
2275 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2276
2277 private void join(Conversation conversation) {
2278 Account account = conversation.getAccount();
2279 final MucOptions mucOptions = conversation.getMucOptions();
2280 final Jid joinJid = mucOptions.getSelf().getFullJid();
2281 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": joining conversation " + joinJid.toString());
2282 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous() || onConferenceJoined != null);
2283 packet.setTo(joinJid);
2284 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2285 if (conversation.getMucOptions().getPassword() != null) {
2286 x.addChild("password").setContent(mucOptions.getPassword());
2287 }
2288
2289 if (mucOptions.mamSupport()) {
2290 // Use MAM instead of the limited muc history to get history
2291 x.addChild("history").setAttribute("maxchars", "0");
2292 } else {
2293 // Fallback to muc history
2294 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted().getTimestamp()));
2295 }
2296 sendPresencePacket(account, packet);
2297 if (onConferenceJoined != null) {
2298 onConferenceJoined.onConferenceJoined(conversation);
2299 }
2300 if (!joinJid.equals(conversation.getJid())) {
2301 conversation.setContactJid(joinJid);
2302 databaseBackend.updateConversation(conversation);
2303 }
2304
2305 if (mucOptions.mamSupport()) {
2306 getMessageArchiveService().catchupMUC(conversation);
2307 }
2308 if (mucOptions.isPrivateAndNonAnonymous()) {
2309 fetchConferenceMembers(conversation);
2310 if (followedInvite && conversation.getBookmark() == null) {
2311 saveConversationAsBookmark(conversation, null);
2312 }
2313 }
2314 sendUnsentMessages(conversation);
2315 }
2316
2317 @Override
2318 public void onConferenceConfigurationFetched(Conversation conversation) {
2319 join(conversation);
2320 }
2321
2322 @Override
2323 public void onFetchFailed(final Conversation conversation, Element error) {
2324 if (error != null && "remote-server-not-found".equals(error.getName())) {
2325 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2326 updateConversationUi();
2327 } else {
2328 join(conversation);
2329 fetchConferenceConfiguration(conversation);
2330 }
2331 }
2332 });
2333 updateConversationUi();
2334 } else {
2335 account.pendingConferenceJoins.add(conversation);
2336 conversation.resetMucOptions();
2337 conversation.setHasMessagesLeftOnServer(false);
2338 updateConversationUi();
2339 }
2340 }
2341
2342 private void fetchConferenceMembers(final Conversation conversation) {
2343 final Account account = conversation.getAccount();
2344 final AxolotlService axolotlService = account.getAxolotlService();
2345 final String[] affiliations = {"member", "admin", "owner"};
2346 OnIqPacketReceived callback = new OnIqPacketReceived() {
2347
2348 private int i = 0;
2349 private boolean success = true;
2350
2351 @Override
2352 public void onIqPacketReceived(Account account, IqPacket packet) {
2353 final boolean omemoEnabled = conversation.getNextEncryption() == Message.ENCRYPTION_AXOLOTL;
2354 Element query = packet.query("http://jabber.org/protocol/muc#admin");
2355 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2356 for (Element child : query.getChildren()) {
2357 if ("item".equals(child.getName())) {
2358 MucOptions.User user = AbstractParser.parseItem(conversation, child);
2359 if (!user.realJidMatchesAccount()) {
2360 boolean isNew = conversation.getMucOptions().updateUser(user);
2361 Contact contact = user.getContact();
2362 if (omemoEnabled
2363 && isNew
2364 && user.getRealJid() != null
2365 && (contact == null || !contact.mutualPresenceSubscription())
2366 && axolotlService.hasEmptyDeviceList(user.getRealJid())) {
2367 axolotlService.fetchDeviceIds(user.getRealJid());
2368 }
2369 }
2370 }
2371 }
2372 } else {
2373 success = false;
2374 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not request affiliation " + affiliations[i] + " in " + conversation.getJid().asBareJid());
2375 }
2376 ++i;
2377 if (i >= affiliations.length) {
2378 List<Jid> members = conversation.getMucOptions().getMembers(true);
2379 if (success) {
2380 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
2381 boolean changed = false;
2382 for (ListIterator<Jid> iterator = cryptoTargets.listIterator(); iterator.hasNext(); ) {
2383 Jid jid = iterator.next();
2384 if (!members.contains(jid) && !members.contains(Jid.ofDomain(jid.getDomain()))) {
2385 iterator.remove();
2386 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
2387 changed = true;
2388 }
2389 }
2390 if (changed) {
2391 conversation.setAcceptedCryptoTargets(cryptoTargets);
2392 updateConversation(conversation);
2393 }
2394 }
2395 getAvatarService().clear(conversation);
2396 updateMucRosterUi();
2397 updateConversationUi();
2398 }
2399 }
2400 };
2401 for (String affiliation : affiliations) {
2402 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2403 }
2404 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching members for " + conversation.getName());
2405 }
2406
2407 public void providePasswordForMuc(Conversation conversation, String password) {
2408 if (conversation.getMode() == Conversation.MODE_MULTI) {
2409 conversation.getMucOptions().setPassword(password);
2410 if (conversation.getBookmark() != null) {
2411 if (respectAutojoin()) {
2412 conversation.getBookmark().setAutojoin(true);
2413 }
2414 pushBookmarks(conversation.getAccount());
2415 }
2416 updateConversation(conversation);
2417 joinMuc(conversation);
2418 }
2419 }
2420
2421 private boolean hasEnabledAccounts() {
2422 for (Account account : this.accounts) {
2423 if (account.isEnabled()) {
2424 return true;
2425 }
2426 }
2427 return false;
2428 }
2429
2430
2431 public void getAttachments(final Conversation conversation, int limit, final OnMediaLoaded onMediaLoaded) {
2432 getAttachments(conversation.getAccount(), conversation.getJid().asBareJid(), limit, onMediaLoaded);
2433 }
2434
2435 public void getAttachments(final Account account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2436 getAttachments(account.getUuid(),jid.asBareJid(),limit, onMediaLoaded);
2437 }
2438
2439
2440 public void getAttachments(final String account, final Jid jid, final int limit, final OnMediaLoaded onMediaLoaded) {
2441 new Thread(() -> onMediaLoaded.onMediaLoaded(fileBackend.convertToAttachments(databaseBackend.getRelativeFilePaths(account, jid, limit)))).start();
2442 }
2443
2444 public void persistSelfNick(MucOptions.User self) {
2445 final Conversation conversation = self.getConversation();
2446 final boolean tookProposedNickFromBookmark = conversation.getMucOptions().isTookProposedNickFromBookmark();
2447 Jid full = self.getFullJid();
2448 if (!full.equals(conversation.getJid())) {
2449 Log.d(Config.LOGTAG, "nick changed. updating");
2450 conversation.setContactJid(full);
2451 databaseBackend.updateConversation(conversation);
2452 }
2453
2454 final Bookmark bookmark = conversation.getBookmark();
2455 final String bookmarkedNick = bookmark == null ? null : bookmark.getNick();
2456 if (bookmark != null && (tookProposedNickFromBookmark || TextUtils.isEmpty(bookmarkedNick)) && !full.getResource().equals(bookmarkedNick)) {
2457 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": persist nick '" + full.getResource() + "' into bookmark for " + conversation.getJid().asBareJid());
2458 bookmark.setNick(full.getResource());
2459 pushBookmarks(bookmark.getAccount());
2460 }
2461 }
2462
2463 public boolean renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2464 final MucOptions options = conversation.getMucOptions();
2465 final Jid joinJid = options.createJoinJid(nick);
2466 if (joinJid == null) {
2467 return false;
2468 }
2469 if (options.online()) {
2470 Account account = conversation.getAccount();
2471 options.setOnRenameListener(new OnRenameListener() {
2472
2473 @Override
2474 public void onSuccess() {
2475 callback.success(conversation);
2476 }
2477
2478 @Override
2479 public void onFailure() {
2480 callback.error(R.string.nick_in_use, conversation);
2481 }
2482 });
2483
2484 PresencePacket packet = new PresencePacket();
2485 packet.setTo(joinJid);
2486 packet.setFrom(conversation.getAccount().getJid());
2487
2488 String sig = account.getPgpSignature();
2489 if (sig != null) {
2490 packet.addChild("status").setContent("online");
2491 packet.addChild("x", "jabber:x:signed").setContent(sig);
2492 }
2493 sendPresencePacket(account, packet);
2494 } else {
2495 conversation.setContactJid(joinJid);
2496 databaseBackend.updateConversation(conversation);
2497 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2498 Bookmark bookmark = conversation.getBookmark();
2499 if (bookmark != null) {
2500 bookmark.setNick(nick);
2501 pushBookmarks(bookmark.getAccount());
2502 }
2503 joinMuc(conversation);
2504 }
2505 }
2506 return true;
2507 }
2508
2509 public void leaveMuc(Conversation conversation) {
2510 leaveMuc(conversation, false);
2511 }
2512
2513 private void leaveMuc(Conversation conversation, boolean now) {
2514 Account account = conversation.getAccount();
2515 account.pendingConferenceJoins.remove(conversation);
2516 account.pendingConferenceLeaves.remove(conversation);
2517 if (account.getStatus() == Account.State.ONLINE || now) {
2518 sendPresencePacket(conversation.getAccount(), mPresenceGenerator.leave(conversation.getMucOptions()));
2519 conversation.getMucOptions().setOffline();
2520 Bookmark bookmark = conversation.getBookmark();
2521 if (bookmark != null) {
2522 bookmark.setConversation(null);
2523 }
2524 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": leaving muc " + conversation.getJid());
2525 } else {
2526 account.pendingConferenceLeaves.add(conversation);
2527 }
2528 }
2529
2530 public String findConferenceServer(final Account account) {
2531 String server;
2532 if (account.getXmppConnection() != null) {
2533 server = account.getXmppConnection().getMucServer();
2534 if (server != null) {
2535 return server;
2536 }
2537 }
2538 for (Account other : getAccounts()) {
2539 if (other != account && other.getXmppConnection() != null) {
2540 server = other.getXmppConnection().getMucServer();
2541 if (server != null) {
2542 return server;
2543 }
2544 }
2545 }
2546 return null;
2547 }
2548
2549 public boolean createAdhocConference(final Account account,
2550 final String name,
2551 final Iterable<Jid> jids,
2552 final UiCallback<Conversation> callback) {
2553 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2554 if (account.getStatus() == Account.State.ONLINE) {
2555 try {
2556 String server = findConferenceServer(account);
2557 if (server == null) {
2558 if (callback != null) {
2559 callback.error(R.string.no_conference_server_found, null);
2560 }
2561 return false;
2562 }
2563 final Jid jid = Jid.of(CryptoHelper.pronounceable(getRNG()), server, null);
2564 final Conversation conversation = findOrCreateConversation(account, jid, true, false, true);
2565 joinMuc(conversation, new OnConferenceJoined() {
2566 @Override
2567 public void onConferenceJoined(final Conversation conversation) {
2568 final Bundle configuration = IqGenerator.defaultRoomConfiguration();
2569 if (!TextUtils.isEmpty(name)) {
2570 configuration.putString("muc#roomconfig_roomname", name);
2571 }
2572 pushConferenceConfiguration(conversation, configuration, new OnConfigurationPushed() {
2573 @Override
2574 public void onPushSucceeded() {
2575 for (Jid invite : jids) {
2576 invite(conversation, invite);
2577 }
2578 if (account.countPresences() > 1) {
2579 directInvite(conversation, account.getJid().asBareJid());
2580 }
2581 saveConversationAsBookmark(conversation, name);
2582 if (callback != null) {
2583 callback.success(conversation);
2584 }
2585 }
2586
2587 @Override
2588 public void onPushFailed() {
2589 archiveConversation(conversation);
2590 if (callback != null) {
2591 callback.error(R.string.conference_creation_failed, conversation);
2592 }
2593 }
2594 });
2595 }
2596 });
2597 return true;
2598 } catch (IllegalArgumentException e) {
2599 if (callback != null) {
2600 callback.error(R.string.conference_creation_failed, null);
2601 }
2602 return false;
2603 }
2604 } else {
2605 if (callback != null) {
2606 callback.error(R.string.not_connected_try_again, null);
2607 }
2608 return false;
2609 }
2610 }
2611
2612 public void fetchConferenceConfiguration(final Conversation conversation) {
2613 fetchConferenceConfiguration(conversation, null);
2614 }
2615
2616 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2617 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2618 request.setTo(conversation.getJid().asBareJid());
2619 request.query("http://jabber.org/protocol/disco#info");
2620 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2621 @Override
2622 public void onIqPacketReceived(Account account, IqPacket packet) {
2623 if (packet.getType() == IqPacket.TYPE.RESULT) {
2624
2625 final MucOptions mucOptions = conversation.getMucOptions();
2626 final Bookmark bookmark = conversation.getBookmark();
2627 final boolean sameBefore = StringUtils.equals(bookmark == null ? null : bookmark.getBookmarkName(), mucOptions.getName());
2628
2629 if (mucOptions.updateConfiguration(new ServiceDiscoveryResult(packet))) {
2630 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": muc configuration changed for " + conversation.getJid().asBareJid());
2631 updateConversation(conversation);
2632 }
2633
2634 if (bookmark != null && (sameBefore || bookmark.getBookmarkName() == null)) {
2635 if (bookmark.setBookmarkName(StringUtils.nullOnEmpty(mucOptions.getName()))) {
2636 pushBookmarks(account);
2637 }
2638 }
2639
2640
2641 if (callback != null) {
2642 callback.onConferenceConfigurationFetched(conversation);
2643 }
2644
2645
2646
2647 updateConversationUi();
2648 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2649 if (callback != null) {
2650 callback.onFetchFailed(conversation, packet.getError());
2651 }
2652 }
2653 }
2654 });
2655 }
2656
2657 public void pushNodeConfiguration(Account account, final String node, final Bundle options, final OnConfigurationPushed callback) {
2658 pushNodeConfiguration(account, account.getJid().asBareJid(), node, options, callback);
2659 }
2660
2661 public void pushNodeConfiguration(Account account, final Jid jid, final String node, final Bundle options, final OnConfigurationPushed callback) {
2662 Log.d(Config.LOGTAG,"pushing node configuration");
2663 sendIqPacket(account, mIqGenerator.requestPubsubConfiguration(jid, node), new OnIqPacketReceived() {
2664 @Override
2665 public void onIqPacketReceived(Account account, IqPacket packet) {
2666 if (packet.getType() == IqPacket.TYPE.RESULT) {
2667 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
2668 Element configuration = pubsub == null ? null : pubsub.findChild("configure");
2669 Element x = configuration == null ? null : configuration.findChild("x", Namespace.DATA);
2670 if (x != null) {
2671 Data data = Data.parse(x);
2672 data.submit(options);
2673 sendIqPacket(account, mIqGenerator.publishPubsubConfiguration(jid, node, data), new OnIqPacketReceived() {
2674 @Override
2675 public void onIqPacketReceived(Account account, IqPacket packet) {
2676 if (packet.getType() == IqPacket.TYPE.RESULT && callback != null) {
2677 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": successfully changed node configuration for node "+node);
2678 callback.onPushSucceeded();
2679 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2680 callback.onPushFailed();
2681 }
2682 }
2683 });
2684 } else if (callback != null) {
2685 callback.onPushFailed();
2686 }
2687 } else if (packet.getType() == IqPacket.TYPE.ERROR && callback != null) {
2688 callback.onPushFailed();
2689 }
2690 }
2691 });
2692 }
2693
2694 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConfigurationPushed callback) {
2695 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2696 request.setTo(conversation.getJid().asBareJid());
2697 request.query("http://jabber.org/protocol/muc#owner");
2698 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2699 @Override
2700 public void onIqPacketReceived(Account account, IqPacket packet) {
2701 if (packet.getType() == IqPacket.TYPE.RESULT) {
2702 Data data = Data.parse(packet.query().findChild("x", Namespace.DATA));
2703 data.submit(options);
2704 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2705 set.setTo(conversation.getJid().asBareJid());
2706 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2707 sendIqPacket(account, set, new OnIqPacketReceived() {
2708 @Override
2709 public void onIqPacketReceived(Account account, IqPacket packet) {
2710 if (callback != null) {
2711 if (packet.getType() == IqPacket.TYPE.RESULT) {
2712 callback.onPushSucceeded();
2713 } else {
2714 callback.onPushFailed();
2715 }
2716 }
2717 }
2718 });
2719 } else {
2720 if (callback != null) {
2721 callback.onPushFailed();
2722 }
2723 }
2724 }
2725 });
2726 }
2727
2728 public void pushSubjectToConference(final Conversation conference, final String subject) {
2729 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, StringUtils.nullOnEmpty(subject));
2730 this.sendMessagePacket(conference.getAccount(), packet);
2731 }
2732
2733 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2734 final Jid jid = user.asBareJid();
2735 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2736 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2737 @Override
2738 public void onIqPacketReceived(Account account, IqPacket packet) {
2739 if (packet.getType() == IqPacket.TYPE.RESULT) {
2740 conference.getMucOptions().changeAffiliation(jid, affiliation);
2741 getAvatarService().clear(conference);
2742 callback.onAffiliationChangedSuccessful(jid);
2743 } else {
2744 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2745 }
2746 }
2747 });
2748 }
2749
2750 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2751 List<Jid> jids = new ArrayList<>();
2752 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2753 if (user.getAffiliation() == before && user.getRealJid() != null) {
2754 jids.add(user.getRealJid());
2755 }
2756 }
2757 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2758 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2759 }
2760
2761 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2762 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2763 Log.d(Config.LOGTAG, request.toString());
2764 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2765 @Override
2766 public void onIqPacketReceived(Account account, IqPacket packet) {
2767 Log.d(Config.LOGTAG, packet.toString());
2768 if (packet.getType() == IqPacket.TYPE.RESULT) {
2769 callback.onRoleChangedSuccessful(nick);
2770 } else {
2771 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2772 }
2773 }
2774 });
2775 }
2776
2777 private void disconnect(Account account, boolean force) {
2778 if ((account.getStatus() == Account.State.ONLINE)
2779 || (account.getStatus() == Account.State.DISABLED)) {
2780 final XmppConnection connection = account.getXmppConnection();
2781 if (!force) {
2782 List<Conversation> conversations = getConversations();
2783 for (Conversation conversation : conversations) {
2784 if (conversation.getAccount() == account) {
2785 if (conversation.getMode() == Conversation.MODE_MULTI) {
2786 leaveMuc(conversation, true);
2787 }
2788 }
2789 }
2790 sendOfflinePresence(account);
2791 }
2792 connection.disconnect(force);
2793 }
2794 }
2795
2796 @Override
2797 public IBinder onBind(Intent intent) {
2798 return mBinder;
2799 }
2800
2801 public void updateMessage(Message message) {
2802 updateMessage(message, true);
2803 }
2804
2805 public void updateMessage(Message message, boolean includeBody) {
2806 databaseBackend.updateMessage(message, includeBody);
2807 updateConversationUi();
2808 }
2809
2810 public void updateMessage(Message message, String uuid) {
2811 databaseBackend.updateMessage(message, uuid);
2812 updateConversationUi();
2813 }
2814
2815 protected void syncDirtyContacts(Account account) {
2816 for (Contact contact : account.getRoster().getContacts()) {
2817 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2818 pushContactToServer(contact);
2819 }
2820 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2821 deleteContactOnServer(contact);
2822 }
2823 }
2824 }
2825
2826 public void createContact(Contact contact, boolean autoGrant) {
2827 if (autoGrant) {
2828 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2829 contact.setOption(Contact.Options.ASKING);
2830 }
2831 pushContactToServer(contact);
2832 }
2833
2834 public void pushContactToServer(final Contact contact) {
2835 contact.resetOption(Contact.Options.DIRTY_DELETE);
2836 contact.setOption(Contact.Options.DIRTY_PUSH);
2837 final Account account = contact.getAccount();
2838 if (account.getStatus() == Account.State.ONLINE) {
2839 final boolean ask = contact.getOption(Contact.Options.ASKING);
2840 final boolean sendUpdates = contact
2841 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2842 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2843 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2844 iq.query(Namespace.ROSTER).addChild(contact.asElement());
2845 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2846 if (sendUpdates) {
2847 sendPresencePacket(account, mPresenceGenerator.sendPresenceUpdatesTo(contact));
2848 }
2849 if (ask) {
2850 sendPresencePacket(account, mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2851 }
2852 } else {
2853 syncRoster(contact.getAccount());
2854 }
2855 }
2856
2857 public void publishMucAvatar(final Conversation conversation, final Uri image, final OnAvatarPublication callback) {
2858 new Thread(() -> {
2859 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2860 final int size = Config.AVATAR_SIZE;
2861 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2862 if (avatar != null) {
2863 if (!getFileBackend().save(avatar)) {
2864 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
2865 return;
2866 }
2867 avatar.owner = conversation.getJid().asBareJid();
2868 publishMucAvatar(conversation, avatar, callback);
2869 } else {
2870 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
2871 }
2872 }).start();
2873 }
2874
2875 public void publishAvatar(final Account account, final Uri image, final OnAvatarPublication callback) {
2876 new Thread(() -> {
2877 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2878 final int size = Config.AVATAR_SIZE;
2879 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2880 if (avatar != null) {
2881 if (!getFileBackend().save(avatar)) {
2882 Log.d(Config.LOGTAG,"unable to save vcard");
2883 callback.onAvatarPublicationFailed(R.string.error_saving_avatar);
2884 return;
2885 }
2886 publishAvatar(account, avatar, callback);
2887 } else {
2888 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_converting);
2889 }
2890 }).start();
2891
2892 }
2893
2894 private void publishMucAvatar(Conversation conversation, Avatar avatar, OnAvatarPublication callback) {
2895 final IqPacket retrieve = mIqGenerator.retrieveVcardAvatar(avatar);
2896 sendIqPacket(conversation.getAccount(), retrieve, (account, response) -> {
2897 boolean itemNotFound = response.getType() == IqPacket.TYPE.ERROR && response.hasChild("error") && response.findChild("error").hasChild("item-not-found");
2898 if (response.getType() == IqPacket.TYPE.RESULT || itemNotFound) {
2899 Element vcard = response.findChild("vCard", "vcard-temp");
2900 if (vcard == null) {
2901 vcard = new Element("vCard", "vcard-temp");
2902 }
2903 Element photo = vcard.findChild("PHOTO");
2904 if (photo == null) {
2905 photo = vcard.addChild("PHOTO");
2906 }
2907 photo.clearChildren();
2908 photo.addChild("TYPE").setContent(avatar.type);
2909 photo.addChild("BINVAL").setContent(avatar.image);
2910 IqPacket publication = new IqPacket(IqPacket.TYPE.SET);
2911 publication.setTo(conversation.getJid().asBareJid());
2912 publication.addChild(vcard);
2913 sendIqPacket(account, publication, (a1, publicationResponse) -> {
2914 if (publicationResponse.getType() == IqPacket.TYPE.RESULT) {
2915 callback.onAvatarPublicationSucceeded();
2916 } else {
2917 Log.d(Config.LOGTAG, "failed to publish vcard " + publicationResponse.getError());
2918 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2919 }
2920 });
2921 } else {
2922 Log.d(Config.LOGTAG, "failed to request vcard " + response.toString());
2923 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_no_server_support);
2924 }
2925 });
2926 }
2927
2928 public void publishAvatar(Account account, final Avatar avatar, final OnAvatarPublication callback) {
2929 IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2930 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2931
2932 @Override
2933 public void onIqPacketReceived(Account account, IqPacket result) {
2934 if (result.getType() == IqPacket.TYPE.RESULT) {
2935 final IqPacket packet = XmppConnectionService.this.mIqGenerator.publishAvatarMetadata(avatar);
2936 sendIqPacket(account, packet, new OnIqPacketReceived() {
2937 @Override
2938 public void onIqPacketReceived(Account account, IqPacket result) {
2939 if (result.getType() == IqPacket.TYPE.RESULT) {
2940 if (account.setAvatar(avatar.getFilename())) {
2941 getAvatarService().clear(account);
2942 databaseBackend.updateAccount(account);
2943 }
2944 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": published avatar " + (avatar.size / 1024) + "KiB");
2945 if (callback != null) {
2946 callback.onAvatarPublicationSucceeded();
2947 }
2948 } else {
2949 if (callback != null) {
2950 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2951 }
2952 }
2953 }
2954 });
2955 } else {
2956 Element error = result.findChild("error");
2957 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server rejected avatar " + (avatar.size / 1024) + "KiB " + (error != null ? error.toString() : ""));
2958 if (callback != null) {
2959 callback.onAvatarPublicationFailed(R.string.error_publish_avatar_server_reject);
2960 }
2961 }
2962 }
2963 });
2964 }
2965
2966 public void republishAvatarIfNeeded(Account account) {
2967 if (account.getAxolotlService().isPepBroken()) {
2968 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping republication of avatar because pep is broken");
2969 return;
2970 }
2971 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2972 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2973
2974 private Avatar parseAvatar(IqPacket packet) {
2975 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2976 if (pubsub != null) {
2977 Element items = pubsub.findChild("items");
2978 if (items != null) {
2979 return Avatar.parseMetadata(items);
2980 }
2981 }
2982 return null;
2983 }
2984
2985 private boolean errorIsItemNotFound(IqPacket packet) {
2986 Element error = packet.findChild("error");
2987 return packet.getType() == IqPacket.TYPE.ERROR
2988 && error != null
2989 && error.hasChild("item-not-found");
2990 }
2991
2992 @Override
2993 public void onIqPacketReceived(Account account, IqPacket packet) {
2994 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2995 Avatar serverAvatar = parseAvatar(packet);
2996 if (serverAvatar == null && account.getAvatar() != null) {
2997 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2998 if (avatar != null) {
2999 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": avatar on server was null. republishing");
3000 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
3001 } else {
3002 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": error rereading avatar");
3003 }
3004 }
3005 }
3006 }
3007 });
3008 }
3009
3010 public void fetchAvatar(Account account, Avatar avatar) {
3011 fetchAvatar(account, avatar, null);
3012 }
3013
3014 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3015 final String KEY = generateFetchKey(account, avatar);
3016 synchronized (this.mInProgressAvatarFetches) {
3017 if (!this.mInProgressAvatarFetches.contains(KEY)) {
3018 switch (avatar.origin) {
3019 case PEP:
3020 this.mInProgressAvatarFetches.add(KEY);
3021 fetchAvatarPep(account, avatar, callback);
3022 break;
3023 case VCARD:
3024 this.mInProgressAvatarFetches.add(KEY);
3025 fetchAvatarVcard(account, avatar, callback);
3026 break;
3027 }
3028 }
3029 }
3030 }
3031
3032 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3033 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
3034 sendIqPacket(account, packet, (a, result) -> {
3035 synchronized (mInProgressAvatarFetches) {
3036 mInProgressAvatarFetches.remove(generateFetchKey(a, avatar));
3037 }
3038 final String ERROR = a.getJid().asBareJid() + ": fetching avatar for " + avatar.owner + " failed ";
3039 if (result.getType() == IqPacket.TYPE.RESULT) {
3040 avatar.image = mIqParser.avatarData(result);
3041 if (avatar.image != null) {
3042 if (getFileBackend().save(avatar)) {
3043 if (a.getJid().asBareJid().equals(avatar.owner)) {
3044 if (a.setAvatar(avatar.getFilename())) {
3045 databaseBackend.updateAccount(a);
3046 }
3047 getAvatarService().clear(a);
3048 updateConversationUi();
3049 updateAccountUi();
3050 } else {
3051 Contact contact = a.getRoster().getContact(avatar.owner);
3052 if (contact.setAvatar(avatar)) {
3053 syncRoster(account);
3054 getAvatarService().clear(contact);
3055 updateConversationUi();
3056 updateRosterUi();
3057 }
3058 }
3059 if (callback != null) {
3060 callback.success(avatar);
3061 }
3062 Log.d(Config.LOGTAG, a.getJid().asBareJid()
3063 + ": successfully fetched pep avatar for " + avatar.owner);
3064 return;
3065 }
3066 } else {
3067
3068 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
3069 }
3070 } else {
3071 Element error = result.findChild("error");
3072 if (error == null) {
3073 Log.d(Config.LOGTAG, ERROR + "(server error)");
3074 } else {
3075 Log.d(Config.LOGTAG, ERROR + error.toString());
3076 }
3077 }
3078 if (callback != null) {
3079 callback.error(0, null);
3080 }
3081
3082 });
3083 }
3084
3085 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
3086 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
3087 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3088 @Override
3089 public void onIqPacketReceived(Account account, IqPacket packet) {
3090 synchronized (mInProgressAvatarFetches) {
3091 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
3092 }
3093 if (packet.getType() == IqPacket.TYPE.RESULT) {
3094 Element vCard = packet.findChild("vCard", "vcard-temp");
3095 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
3096 String image = photo != null ? photo.findChildContent("BINVAL") : null;
3097 if (image != null) {
3098 avatar.image = image;
3099 if (getFileBackend().save(avatar)) {
3100 Log.d(Config.LOGTAG, account.getJid().asBareJid()
3101 + ": successfully fetched vCard avatar for " + avatar.owner);
3102 if (avatar.owner.isBareJid()) {
3103 if (account.getJid().asBareJid().equals(avatar.owner) && account.getAvatar() == null) {
3104 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": had no avatar. replacing with vcard");
3105 account.setAvatar(avatar.getFilename());
3106 databaseBackend.updateAccount(account);
3107 getAvatarService().clear(account);
3108 updateAccountUi();
3109 } else {
3110 Contact contact = account.getRoster().getContact(avatar.owner);
3111 if (contact.setAvatar(avatar)) {
3112 syncRoster(account);
3113 getAvatarService().clear(contact);
3114 updateRosterUi();
3115 }
3116 }
3117 updateConversationUi();
3118 } else {
3119 Conversation conversation = find(account, avatar.owner.asBareJid());
3120 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
3121 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
3122 if (user != null) {
3123 if (user.setAvatar(avatar)) {
3124 getAvatarService().clear(user);
3125 updateConversationUi();
3126 updateMucRosterUi();
3127 }
3128 if (user.getRealJid() != null) {
3129 Contact contact = account.getRoster().getContact(user.getRealJid());
3130 if (contact.setAvatar(avatar)) {
3131 syncRoster(account);
3132 getAvatarService().clear(contact);
3133 updateRosterUi();
3134 }
3135 }
3136 }
3137 }
3138 }
3139 }
3140 }
3141 }
3142 }
3143 });
3144 }
3145
3146 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
3147 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
3148 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
3149
3150 @Override
3151 public void onIqPacketReceived(Account account, IqPacket packet) {
3152 if (packet.getType() == IqPacket.TYPE.RESULT) {
3153 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
3154 if (pubsub != null) {
3155 Element items = pubsub.findChild("items");
3156 if (items != null) {
3157 Avatar avatar = Avatar.parseMetadata(items);
3158 if (avatar != null) {
3159 avatar.owner = account.getJid().asBareJid();
3160 if (fileBackend.isAvatarCached(avatar)) {
3161 if (account.setAvatar(avatar.getFilename())) {
3162 databaseBackend.updateAccount(account);
3163 }
3164 getAvatarService().clear(account);
3165 callback.success(avatar);
3166 } else {
3167 fetchAvatarPep(account, avatar, callback);
3168 }
3169 return;
3170 }
3171 }
3172 }
3173 }
3174 callback.error(0, null);
3175 }
3176 });
3177 }
3178
3179 public void deleteContactOnServer(Contact contact) {
3180 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
3181 contact.resetOption(Contact.Options.DIRTY_PUSH);
3182 contact.setOption(Contact.Options.DIRTY_DELETE);
3183 Account account = contact.getAccount();
3184 if (account.getStatus() == Account.State.ONLINE) {
3185 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
3186 Element item = iq.query(Namespace.ROSTER).addChild("item");
3187 item.setAttribute("jid", contact.getJid().toString());
3188 item.setAttribute("subscription", "remove");
3189 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
3190 }
3191 }
3192
3193 public void updateConversation(final Conversation conversation) {
3194 mDatabaseWriterExecutor.execute(() -> databaseBackend.updateConversation(conversation));
3195 }
3196
3197 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
3198 synchronized (account) {
3199 XmppConnection connection = account.getXmppConnection();
3200 if (connection == null) {
3201 connection = createConnection(account);
3202 account.setXmppConnection(connection);
3203 }
3204 boolean hasInternet = hasInternetConnection();
3205 if (account.isEnabled() && hasInternet) {
3206 if (!force) {
3207 disconnect(account, false);
3208 }
3209 Thread thread = new Thread(connection);
3210 connection.setInteractive(interactive);
3211 connection.prepareNewConnection();
3212 connection.interrupt();
3213 thread.start();
3214 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
3215 } else {
3216 disconnect(account, force || account.getTrueStatus().isError() || !hasInternet);
3217 account.getRoster().clearPresences();
3218 connection.resetEverything();
3219 final AxolotlService axolotlService = account.getAxolotlService();
3220 if (axolotlService != null) {
3221 axolotlService.resetBrokenness();
3222 }
3223 if (!hasInternet) {
3224 account.setStatus(Account.State.NO_INTERNET);
3225 }
3226 }
3227 }
3228 }
3229
3230 public void reconnectAccountInBackground(final Account account) {
3231 new Thread(() -> reconnectAccount(account, false, true)).start();
3232 }
3233
3234 public void invite(Conversation conversation, Jid contact) {
3235 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": inviting " + contact + " to " + conversation.getJid().asBareJid());
3236 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
3237 sendMessagePacket(conversation.getAccount(), packet);
3238 }
3239
3240 public void directInvite(Conversation conversation, Jid jid) {
3241 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
3242 sendMessagePacket(conversation.getAccount(), packet);
3243 }
3244
3245 public void resetSendingToWaiting(Account account) {
3246 for (Conversation conversation : getConversations()) {
3247 if (conversation.getAccount() == account) {
3248 conversation.findUnsentTextMessages(message -> markMessage(message, Message.STATUS_WAITING));
3249 }
3250 }
3251 }
3252
3253 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
3254 return markMessage(account, recipient, uuid, status, null);
3255 }
3256
3257 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
3258 if (uuid == null) {
3259 return null;
3260 }
3261 for (Conversation conversation : getConversations()) {
3262 if (conversation.getJid().asBareJid().equals(recipient) && conversation.getAccount() == account) {
3263 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
3264 if (message != null) {
3265 markMessage(message, status, errorMessage);
3266 }
3267 return message;
3268 }
3269 }
3270 return null;
3271 }
3272
3273 public boolean markMessage(Conversation conversation, String uuid, int status, String serverMessageId) {
3274 if (uuid == null) {
3275 return false;
3276 } else {
3277 Message message = conversation.findSentMessageWithUuid(uuid);
3278 if (message != null) {
3279 if (message.getServerMsgId() == null) {
3280 message.setServerMsgId(serverMessageId);
3281 }
3282 markMessage(message, status);
3283 return true;
3284 } else {
3285 return false;
3286 }
3287 }
3288 }
3289
3290 public void markMessage(Message message, int status) {
3291 markMessage(message, status, null);
3292 }
3293
3294
3295 public void markMessage(Message message, int status, String errorMessage) {
3296 final int c = message.getStatus();
3297 if (status == Message.STATUS_SEND_FAILED && (c == Message.STATUS_SEND_RECEIVED || c == Message.STATUS_SEND_DISPLAYED)) {
3298 return;
3299 }
3300 if (status == Message.STATUS_SEND_RECEIVED && c == Message.STATUS_SEND_DISPLAYED) {
3301 return;
3302 }
3303 message.setErrorMessage(errorMessage);
3304 message.setStatus(status);
3305 databaseBackend.updateMessage(message, false);
3306 updateConversationUi();
3307 }
3308
3309 private SharedPreferences getPreferences() {
3310 return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
3311 }
3312
3313 public long getAutomaticMessageDeletionDate() {
3314 final long timeout = getLongPreference(SettingsActivity.AUTOMATIC_MESSAGE_DELETION, R.integer.automatic_message_deletion);
3315 return timeout == 0 ? timeout : (System.currentTimeMillis() - (timeout * 1000));
3316 }
3317
3318 public long getLongPreference(String name, @IntegerRes int res) {
3319 long defaultValue = getResources().getInteger(res);
3320 try {
3321 return Long.parseLong(getPreferences().getString(name, String.valueOf(defaultValue)));
3322 } catch (NumberFormatException e) {
3323 return defaultValue;
3324 }
3325 }
3326
3327 public boolean getBooleanPreference(String name, @BoolRes int res) {
3328 return getPreferences().getBoolean(name, getResources().getBoolean(res));
3329 }
3330
3331 public boolean confirmMessages() {
3332 return getBooleanPreference("confirm_messages", R.bool.confirm_messages);
3333 }
3334
3335 public boolean allowMessageCorrection() {
3336 return getBooleanPreference("allow_message_correction", R.bool.allow_message_correction);
3337 }
3338
3339 public boolean sendChatStates() {
3340 return getBooleanPreference("chat_states", R.bool.chat_states);
3341 }
3342
3343 private boolean respectAutojoin() {
3344 return getBooleanPreference("autojoin", R.bool.autojoin);
3345 }
3346
3347 public boolean indicateReceived() {
3348 return getBooleanPreference("indicate_received", R.bool.indicate_received);
3349 }
3350
3351 public boolean useTorToConnect() {
3352 return QuickConversationsService.isConversations() && getBooleanPreference("use_tor", R.bool.use_tor);
3353 }
3354
3355 public boolean showExtendedConnectionOptions() {
3356 return QuickConversationsService.isConversations() && getBooleanPreference("show_connection_options", R.bool.show_connection_options);
3357 }
3358
3359 public boolean broadcastLastActivity() {
3360 return getBooleanPreference(SettingsActivity.BROADCAST_LAST_ACTIVITY, R.bool.last_activity);
3361 }
3362
3363 public int unreadCount() {
3364 int count = 0;
3365 for (Conversation conversation : getConversations()) {
3366 count += conversation.unreadCount();
3367 }
3368 return count;
3369 }
3370
3371
3372 private <T> List<T> threadSafeList(Set<T> set) {
3373 synchronized (LISTENER_LOCK) {
3374 return set.size() == 0 ? Collections.emptyList() : new ArrayList<>(set);
3375 }
3376 }
3377
3378 public void showErrorToastInUi(int resId) {
3379 for (OnShowErrorToast listener : threadSafeList(this.mOnShowErrorToasts)) {
3380 listener.onShowErrorToast(resId);
3381 }
3382 }
3383
3384 public void updateConversationUi() {
3385 for (OnConversationUpdate listener : threadSafeList(this.mOnConversationUpdates)) {
3386 listener.onConversationUpdate();
3387 }
3388 }
3389
3390 public void updateAccountUi() {
3391 for (OnAccountUpdate listener : threadSafeList(this.mOnAccountUpdates)) {
3392 listener.onAccountUpdate();
3393 }
3394 }
3395
3396 public void updateRosterUi() {
3397 for (OnRosterUpdate listener : threadSafeList(this.mOnRosterUpdates)) {
3398 listener.onRosterUpdate();
3399 }
3400 }
3401
3402 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3403 if (mOnCaptchaRequested.size() > 0) {
3404 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3405 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3406 (int) (captcha.getHeight() * metrics.scaledDensity), false);
3407 for (OnCaptchaRequested listener : threadSafeList(this.mOnCaptchaRequested)) {
3408 listener.onCaptchaRequested(account, id, data, scaled);
3409 }
3410 return true;
3411 }
3412 return false;
3413 }
3414
3415 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3416 for (OnUpdateBlocklist listener : threadSafeList(this.mOnUpdateBlocklist)) {
3417 listener.OnUpdateBlocklist(status);
3418 }
3419 }
3420
3421 public void updateMucRosterUi() {
3422 for (OnMucRosterUpdate listener : threadSafeList(this.mOnMucRosterUpdate)) {
3423 listener.onMucRosterUpdate();
3424 }
3425 }
3426
3427 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3428 for (OnKeyStatusUpdated listener : threadSafeList(this.mOnKeyStatusUpdated)) {
3429 listener.onKeyStatusUpdated(report);
3430 }
3431 }
3432
3433 public Account findAccountByJid(final Jid accountJid) {
3434 for (Account account : this.accounts) {
3435 if (account.getJid().asBareJid().equals(accountJid.asBareJid())) {
3436 return account;
3437 }
3438 }
3439 return null;
3440 }
3441
3442 public Account findAccountByUuid(final String uuid) {
3443 for(Account account : this.accounts) {
3444 if (account.getUuid().equals(uuid)) {
3445 return account;
3446 }
3447 }
3448 return null;
3449 }
3450
3451 public Conversation findConversationByUuid(String uuid) {
3452 for (Conversation conversation : getConversations()) {
3453 if (conversation.getUuid().equals(uuid)) {
3454 return conversation;
3455 }
3456 }
3457 return null;
3458 }
3459
3460 public Conversation findUniqueConversationByJid(XmppUri xmppUri) {
3461 List<Conversation> findings = new ArrayList<>();
3462 for (Conversation c : getConversations()) {
3463 if (c.getAccount().isEnabled() && c.getJid().asBareJid().equals(xmppUri.getJid()) && ((c.getMode() == Conversational.MODE_MULTI) == xmppUri.isAction(XmppUri.ACTION_JOIN))) {
3464 findings.add(c);
3465 }
3466 }
3467 return findings.size() == 1 ? findings.get(0) : null;
3468 }
3469
3470 public boolean markRead(final Conversation conversation, boolean dismiss) {
3471 return markRead(conversation, null, dismiss).size() > 0;
3472 }
3473
3474 public void markRead(final Conversation conversation) {
3475 markRead(conversation, null, true);
3476 }
3477
3478 public List<Message> markRead(final Conversation conversation, String upToUuid, boolean dismiss) {
3479 if (dismiss) {
3480 mNotificationService.clear(conversation);
3481 }
3482 final List<Message> readMessages = conversation.markRead(upToUuid);
3483 if (readMessages.size() > 0) {
3484 Runnable runnable = () -> {
3485 for (Message message : readMessages) {
3486 databaseBackend.updateMessage(message, false);
3487 }
3488 };
3489 mDatabaseWriterExecutor.execute(runnable);
3490 updateUnreadCountBadge();
3491 return readMessages;
3492 } else {
3493 return readMessages;
3494 }
3495 }
3496
3497 public synchronized void updateUnreadCountBadge() {
3498 int count = unreadCount();
3499 if (unreadCount != count) {
3500 Log.d(Config.LOGTAG, "update unread count to " + count);
3501 if (count > 0) {
3502 ShortcutBadger.applyCount(getApplicationContext(), count);
3503 } else {
3504 ShortcutBadger.removeCount(getApplicationContext());
3505 }
3506 unreadCount = count;
3507 }
3508 }
3509
3510 public void sendReadMarker(final Conversation conversation, String upToUuid) {
3511 final boolean isPrivateAndNonAnonymousMuc = conversation.getMode() == Conversation.MODE_MULTI && conversation.isPrivateAndNonAnonymous();
3512 final List<Message> readMessages = this.markRead(conversation, upToUuid, true);
3513 if (readMessages.size() > 0) {
3514 updateConversationUi();
3515 }
3516 final Message markable = Conversation.getLatestMarkableMessage(readMessages, isPrivateAndNonAnonymousMuc);
3517 if (confirmMessages()
3518 && markable != null
3519 && (markable.trusted() || isPrivateAndNonAnonymousMuc)
3520 && markable.getRemoteMsgId() != null) {
3521 Log.d(Config.LOGTAG, conversation.getAccount().getJid().asBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3522 Account account = conversation.getAccount();
3523 final Jid to = markable.getCounterpart();
3524 final boolean groupChat = conversation.getMode() == Conversation.MODE_MULTI;
3525 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId(), markable.getCounterpart(), groupChat);
3526 this.sendMessagePacket(conversation.getAccount(), packet);
3527 }
3528 }
3529
3530 public SecureRandom getRNG() {
3531 return this.mRandom;
3532 }
3533
3534 public MemorizingTrustManager getMemorizingTrustManager() {
3535 return this.mMemorizingTrustManager;
3536 }
3537
3538 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3539 this.mMemorizingTrustManager = trustManager;
3540 }
3541
3542 public void updateMemorizingTrustmanager() {
3543 final MemorizingTrustManager tm;
3544 final boolean dontTrustSystemCAs = getBooleanPreference("dont_trust_system_cas", R.bool.dont_trust_system_cas);
3545 if (dontTrustSystemCAs) {
3546 tm = new MemorizingTrustManager(getApplicationContext(), null);
3547 } else {
3548 tm = new MemorizingTrustManager(getApplicationContext());
3549 }
3550 setMemorizingTrustManager(tm);
3551 }
3552
3553 public LruCache<String, Bitmap> getBitmapCache() {
3554 return this.mBitmapCache;
3555 }
3556
3557 public Collection<String> getKnownHosts() {
3558 final Set<String> hosts = new HashSet<>();
3559 for (final Account account : getAccounts()) {
3560 hosts.add(account.getServer());
3561 for (final Contact contact : account.getRoster().getContacts()) {
3562 if (contact.showInRoster()) {
3563 final String server = contact.getServer();
3564 if (server != null) {
3565 hosts.add(server);
3566 }
3567 }
3568 }
3569 }
3570 if (Config.QUICKSY_DOMAIN != null) {
3571 hosts.remove(Config.QUICKSY_DOMAIN); //we only want to show this when we type a e164 number
3572 }
3573 if (Config.DOMAIN_LOCK != null) {
3574 hosts.add(Config.DOMAIN_LOCK);
3575 }
3576 if (Config.MAGIC_CREATE_DOMAIN != null) {
3577 hosts.add(Config.MAGIC_CREATE_DOMAIN);
3578 }
3579 return hosts;
3580 }
3581
3582 public Collection<String> getKnownConferenceHosts() {
3583 final Set<String> mucServers = new HashSet<>();
3584 for (final Account account : accounts) {
3585 if (account.getXmppConnection() != null) {
3586 mucServers.addAll(account.getXmppConnection().getMucServers());
3587 for (Bookmark bookmark : account.getBookmarks()) {
3588 final Jid jid = bookmark.getJid();
3589 final String s = jid == null ? null : jid.getDomain();
3590 if (s != null) {
3591 mucServers.add(s);
3592 }
3593 }
3594 }
3595 }
3596 return mucServers;
3597 }
3598
3599 public void sendMessagePacket(Account account, MessagePacket packet) {
3600 XmppConnection connection = account.getXmppConnection();
3601 if (connection != null) {
3602 connection.sendMessagePacket(packet);
3603 }
3604 }
3605
3606 public void sendPresencePacket(Account account, PresencePacket packet) {
3607 XmppConnection connection = account.getXmppConnection();
3608 if (connection != null) {
3609 connection.sendPresencePacket(packet);
3610 }
3611 }
3612
3613 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3614 final XmppConnection connection = account.getXmppConnection();
3615 if (connection != null) {
3616 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3617 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener, true);
3618 }
3619 }
3620
3621 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3622 final XmppConnection connection = account.getXmppConnection();
3623 if (connection != null) {
3624 connection.sendIqPacket(packet, callback);
3625 } else if (callback != null) {
3626 callback.onIqPacketReceived(account,new IqPacket(IqPacket.TYPE.TIMEOUT));
3627 }
3628 }
3629
3630 public void sendPresence(final Account account) {
3631 sendPresence(account, checkListeners() && broadcastLastActivity());
3632 }
3633
3634 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3635 Presence.Status status;
3636 if (manuallyChangePresence()) {
3637 status = account.getPresenceStatus();
3638 } else {
3639 status = getTargetPresence();
3640 }
3641 PresencePacket packet = mPresenceGenerator.selfPresence(account, status);
3642 String message = account.getPresenceStatusMessage();
3643 if (message != null && !message.isEmpty()) {
3644 packet.addChild(new Element("status").setContent(message));
3645 }
3646 if (mLastActivity > 0 && includeIdleTimestamp) {
3647 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3648 packet.addChild("idle", Namespace.IDLE).setAttribute("since", AbstractGenerator.getTimestamp(since));
3649 }
3650 sendPresencePacket(account, packet);
3651 }
3652
3653 private void deactivateGracePeriod() {
3654 for (Account account : getAccounts()) {
3655 account.deactivateGracePeriod();
3656 }
3657 }
3658
3659 public void refreshAllPresences() {
3660 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3661 for (Account account : getAccounts()) {
3662 if (account.isEnabled()) {
3663 sendPresence(account, includeIdleTimestamp);
3664 }
3665 }
3666 }
3667
3668 private void refreshAllFcmTokens() {
3669 for (Account account : getAccounts()) {
3670 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3671 mPushManagementService.registerPushTokenOnServer(account);
3672 }
3673 }
3674 }
3675
3676 private void sendOfflinePresence(final Account account) {
3677 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending offline presence");
3678 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3679 }
3680
3681 public MessageGenerator getMessageGenerator() {
3682 return this.mMessageGenerator;
3683 }
3684
3685 public PresenceGenerator getPresenceGenerator() {
3686 return this.mPresenceGenerator;
3687 }
3688
3689 public IqGenerator getIqGenerator() {
3690 return this.mIqGenerator;
3691 }
3692
3693 public IqParser getIqParser() {
3694 return this.mIqParser;
3695 }
3696
3697 public JingleConnectionManager getJingleConnectionManager() {
3698 return this.mJingleConnectionManager;
3699 }
3700
3701 public MessageArchiveService getMessageArchiveService() {
3702 return this.mMessageArchiveService;
3703 }
3704
3705 public QuickConversationsService getQuickConversationsService() {
3706 return this.mQuickConversationsService;
3707 }
3708
3709 public List<Contact> findContacts(Jid jid, String accountJid) {
3710 ArrayList<Contact> contacts = new ArrayList<>();
3711 for (Account account : getAccounts()) {
3712 if ((account.isEnabled() || accountJid != null)
3713 && (accountJid == null || accountJid.equals(account.getJid().asBareJid().toString()))) {
3714 Contact contact = account.getRoster().getContactFromContactList(jid);
3715 if (contact != null) {
3716 contacts.add(contact);
3717 }
3718 }
3719 }
3720 return contacts;
3721 }
3722
3723 public Conversation findFirstMuc(Jid jid) {
3724 for (Conversation conversation : getConversations()) {
3725 if (conversation.getAccount().isEnabled() && conversation.getJid().asBareJid().equals(jid.asBareJid()) && conversation.getMode() == Conversation.MODE_MULTI) {
3726 return conversation;
3727 }
3728 }
3729 return null;
3730 }
3731
3732 public NotificationService getNotificationService() {
3733 return this.mNotificationService;
3734 }
3735
3736 public HttpConnectionManager getHttpConnectionManager() {
3737 return this.mHttpConnectionManager;
3738 }
3739
3740 public void resendFailedMessages(final Message message) {
3741 final Collection<Message> messages = new ArrayList<>();
3742 Message current = message;
3743 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3744 messages.add(current);
3745 if (current.mergeable(current.next())) {
3746 current = current.next();
3747 } else {
3748 break;
3749 }
3750 }
3751 for (final Message msg : messages) {
3752 msg.setTime(System.currentTimeMillis());
3753 markMessage(msg, Message.STATUS_WAITING);
3754 this.resendMessage(msg, false);
3755 }
3756 if (message.getConversation() instanceof Conversation) {
3757 ((Conversation) message.getConversation()).sort();
3758 }
3759 updateConversationUi();
3760 }
3761
3762 public void clearConversationHistory(final Conversation conversation) {
3763 final long clearDate;
3764 final String reference;
3765 if (conversation.countMessages() > 0) {
3766 Message latestMessage = conversation.getLatestMessage();
3767 clearDate = latestMessage.getTimeSent() + 1000;
3768 reference = latestMessage.getServerMsgId();
3769 } else {
3770 clearDate = System.currentTimeMillis();
3771 reference = null;
3772 }
3773 conversation.clearMessages();
3774 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3775 conversation.setLastClearHistory(clearDate, reference);
3776 Runnable runnable = () -> {
3777 databaseBackend.deleteMessagesInConversation(conversation);
3778 databaseBackend.updateConversation(conversation);
3779 };
3780 mDatabaseWriterExecutor.execute(runnable);
3781 }
3782
3783 public boolean sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3784 if (blockable != null && blockable.getBlockedJid() != null) {
3785 final Jid jid = blockable.getBlockedJid();
3786 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3787
3788 @Override
3789 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3790 if (packet.getType() == IqPacket.TYPE.RESULT) {
3791 account.getBlocklist().add(jid);
3792 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3793 }
3794 }
3795 });
3796 if (removeBlockedConversations(blockable.getAccount(), jid)) {
3797 updateConversationUi();
3798 return true;
3799 } else {
3800 return false;
3801 }
3802 } else {
3803 return false;
3804 }
3805 }
3806
3807 public boolean removeBlockedConversations(final Account account, final Jid blockedJid) {
3808 boolean removed = false;
3809 synchronized (this.conversations) {
3810 boolean domainJid = blockedJid.getLocal() == null;
3811 for (Conversation conversation : this.conversations) {
3812 boolean jidMatches = (domainJid && blockedJid.getDomain().equals(conversation.getJid().getDomain()))
3813 || blockedJid.equals(conversation.getJid().asBareJid());
3814 if (conversation.getAccount() == account
3815 && conversation.getMode() == Conversation.MODE_SINGLE
3816 && jidMatches) {
3817 this.conversations.remove(conversation);
3818 markRead(conversation);
3819 conversation.setStatus(Conversation.STATUS_ARCHIVED);
3820 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": archiving conversation " + conversation.getJid().asBareJid() + " because jid was blocked");
3821 updateConversation(conversation);
3822 removed = true;
3823 }
3824 }
3825 }
3826 return removed;
3827 }
3828
3829 public void sendUnblockRequest(final Blockable blockable) {
3830 if (blockable != null && blockable.getJid() != null) {
3831 final Jid jid = blockable.getBlockedJid();
3832 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3833 @Override
3834 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3835 if (packet.getType() == IqPacket.TYPE.RESULT) {
3836 account.getBlocklist().remove(jid);
3837 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3838 }
3839 }
3840 });
3841 }
3842 }
3843
3844 public void publishDisplayName(Account account) {
3845 String displayName = account.getDisplayName();
3846 final IqPacket request;
3847 if (TextUtils.isEmpty(displayName)) {
3848 request = mIqGenerator.deleteNode(Namespace.NICK);
3849 } else {
3850 request = mIqGenerator.publishNick(displayName);
3851 }
3852 mAvatarService.clear(account);
3853 sendIqPacket(account, request, (account1, packet) -> {
3854 if (packet.getType() == IqPacket.TYPE.ERROR) {
3855 Log.d(Config.LOGTAG, account1.getJid().asBareJid() + ": unable to modify nick name "+packet.toString());
3856 }
3857 });
3858 }
3859
3860 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3861 ServiceDiscoveryResult result = discoCache.get(key);
3862 if (result != null) {
3863 return result;
3864 } else {
3865 result = databaseBackend.findDiscoveryResult(key.first, key.second);
3866 if (result != null) {
3867 discoCache.put(key, result);
3868 }
3869 return result;
3870 }
3871 }
3872
3873 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3874 final Pair<String, String> key = new Pair<>(presence.getHash(), presence.getVer());
3875 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3876 if (disco != null) {
3877 presence.setServiceDiscoveryResult(disco);
3878 } else {
3879 if (!account.inProgressDiscoFetches.contains(key)) {
3880 account.inProgressDiscoFetches.add(key);
3881 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3882 request.setTo(jid);
3883 final String node = presence.getNode();
3884 final String ver = presence.getVer();
3885 final Element query = request.query("http://jabber.org/protocol/disco#info");
3886 if (node != null && ver != null) {
3887 query.setAttribute("node",node+"#"+ver);
3888 }
3889 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": making disco request for " + key.second + " to " + jid);
3890 sendIqPacket(account, request, (a, response) -> {
3891 if (response.getType() == IqPacket.TYPE.RESULT) {
3892 ServiceDiscoveryResult discoveryResult = new ServiceDiscoveryResult(response);
3893 if (presence.getVer().equals(discoveryResult.getVer())) {
3894 databaseBackend.insertDiscoveryResult(discoveryResult);
3895 injectServiceDiscoveryResult(a.getRoster(), presence.getHash(), presence.getVer(), discoveryResult);
3896 } else {
3897 Log.d(Config.LOGTAG, a.getJid().asBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + discoveryResult.getVer());
3898 }
3899 }
3900 a.inProgressDiscoFetches.remove(key);
3901 });
3902 }
3903 }
3904 }
3905
3906 private void injectServiceDiscoveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3907 for (Contact contact : roster.getContacts()) {
3908 for (Presence presence : contact.getPresences().getPresences().values()) {
3909 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3910 presence.setServiceDiscoveryResult(disco);
3911 }
3912 }
3913 }
3914 }
3915
3916 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3917 final MessageArchiveService.Version version = MessageArchiveService.Version.get(account);
3918 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3919 request.addChild("prefs", version.namespace);
3920 sendIqPacket(account, request, (account1, packet) -> {
3921 Element prefs = packet.findChild("prefs", version.namespace);
3922 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3923 callback.onPreferencesFetched(prefs);
3924 } else {
3925 callback.onPreferencesFetchFailed();
3926 }
3927 });
3928 }
3929
3930 public PushManagementService getPushManagementService() {
3931 return mPushManagementService;
3932 }
3933
3934 public void changeStatus(Account account, PresenceTemplate template, String signature) {
3935 if (!template.getStatusMessage().isEmpty()) {
3936 databaseBackend.insertPresenceTemplate(template);
3937 }
3938 account.setPgpSignature(signature);
3939 account.setPresenceStatus(template.getStatus());
3940 account.setPresenceStatusMessage(template.getStatusMessage());
3941 databaseBackend.updateAccount(account);
3942 sendPresence(account);
3943 }
3944
3945 public List<PresenceTemplate> getPresenceTemplates(Account account) {
3946 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3947 for (PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3948 if (!templates.contains(template)) {
3949 templates.add(0, template);
3950 }
3951 }
3952 return templates;
3953 }
3954
3955 public void saveConversationAsBookmark(Conversation conversation, String name) {
3956 Account account = conversation.getAccount();
3957 Bookmark bookmark = new Bookmark(account, conversation.getJid().asBareJid());
3958 if (!conversation.getJid().isBareJid()) {
3959 bookmark.setNick(conversation.getJid().getResource());
3960 }
3961 if (!TextUtils.isEmpty(name)) {
3962 bookmark.setBookmarkName(name);
3963 }
3964 bookmark.setAutojoin(getPreferences().getBoolean("autojoin", getResources().getBoolean(R.bool.autojoin)));
3965 account.getBookmarks().add(bookmark);
3966 pushBookmarks(account);
3967 bookmark.setConversation(conversation);
3968 }
3969
3970 public boolean verifyFingerprints(Contact contact, List<XmppUri.Fingerprint> fingerprints) {
3971 boolean performedVerification = false;
3972 final AxolotlService axolotlService = contact.getAccount().getAxolotlService();
3973 for (XmppUri.Fingerprint fp : fingerprints) {
3974 if (fp.type == XmppUri.FingerprintType.OMEMO) {
3975 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3976 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3977 if (fingerprintStatus != null) {
3978 if (!fingerprintStatus.isVerified()) {
3979 performedVerification = true;
3980 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
3981 }
3982 } else {
3983 axolotlService.preVerifyFingerprint(contact, fingerprint);
3984 }
3985 }
3986 }
3987 return performedVerification;
3988 }
3989
3990 public boolean verifyFingerprints(Account account, List<XmppUri.Fingerprint> fingerprints) {
3991 final AxolotlService axolotlService = account.getAxolotlService();
3992 boolean verifiedSomething = false;
3993 for (XmppUri.Fingerprint fp : fingerprints) {
3994 if (fp.type == XmppUri.FingerprintType.OMEMO) {
3995 String fingerprint = "05" + fp.fingerprint.replaceAll("\\s", "");
3996 Log.d(Config.LOGTAG, "trying to verify own fp=" + fingerprint);
3997 FingerprintStatus fingerprintStatus = axolotlService.getFingerprintTrust(fingerprint);
3998 if (fingerprintStatus != null) {
3999 if (!fingerprintStatus.isVerified()) {
4000 axolotlService.setFingerprintTrust(fingerprint, fingerprintStatus.toVerified());
4001 verifiedSomething = true;
4002 }
4003 } else {
4004 axolotlService.preVerifyFingerprint(account, fingerprint);
4005 verifiedSomething = true;
4006 }
4007 }
4008 }
4009 return verifiedSomething;
4010 }
4011
4012 public boolean blindTrustBeforeVerification() {
4013 return getBooleanPreference(SettingsActivity.BLIND_TRUST_BEFORE_VERIFICATION, R.bool.btbv);
4014 }
4015
4016 public ShortcutService getShortcutService() {
4017 return mShortcutService;
4018 }
4019
4020 public void pushMamPreferences(Account account, Element prefs) {
4021 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
4022 set.addChild(prefs);
4023 sendIqPacket(account, set, null);
4024 }
4025
4026 public interface OnMamPreferencesFetched {
4027 void onPreferencesFetched(Element prefs);
4028
4029 void onPreferencesFetchFailed();
4030 }
4031
4032 public interface OnAccountCreated {
4033 void onAccountCreated(Account account);
4034
4035 void informUser(int r);
4036 }
4037
4038 public interface OnMoreMessagesLoaded {
4039 void onMoreMessagesLoaded(int count, Conversation conversation);
4040
4041 void informUser(int r);
4042 }
4043
4044 public interface OnAccountPasswordChanged {
4045 void onPasswordChangeSucceeded();
4046
4047 void onPasswordChangeFailed();
4048 }
4049
4050 public interface OnAffiliationChanged {
4051 void onAffiliationChangedSuccessful(Jid jid);
4052
4053 void onAffiliationChangeFailed(Jid jid, int resId);
4054 }
4055
4056 public interface OnRoleChanged {
4057 void onRoleChangedSuccessful(String nick);
4058
4059 void onRoleChangeFailed(String nick, int resid);
4060 }
4061
4062 public interface OnConversationUpdate {
4063 void onConversationUpdate();
4064 }
4065
4066 public interface OnAccountUpdate {
4067 void onAccountUpdate();
4068 }
4069
4070 public interface OnCaptchaRequested {
4071 void onCaptchaRequested(Account account, String id, Data data, Bitmap captcha);
4072 }
4073
4074 public interface OnRosterUpdate {
4075 void onRosterUpdate();
4076 }
4077
4078 public interface OnMucRosterUpdate {
4079 void onMucRosterUpdate();
4080 }
4081
4082 public interface OnConferenceConfigurationFetched {
4083 void onConferenceConfigurationFetched(Conversation conversation);
4084
4085 void onFetchFailed(Conversation conversation, Element error);
4086 }
4087
4088 public interface OnConferenceJoined {
4089 void onConferenceJoined(Conversation conversation);
4090 }
4091
4092 public interface OnConfigurationPushed {
4093 void onPushSucceeded();
4094
4095 void onPushFailed();
4096 }
4097
4098 public interface OnShowErrorToast {
4099 void onShowErrorToast(int resId);
4100 }
4101
4102 public class XmppConnectionBinder extends Binder {
4103 public XmppConnectionService getService() {
4104 return XmppConnectionService.this;
4105 }
4106 }
4107
4108 private class InternalEventReceiver extends BroadcastReceiver {
4109
4110 @Override
4111 public void onReceive(Context context, Intent intent) {
4112 onStartCommand(intent,0,0);
4113 }
4114 }
4115}