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