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