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