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