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 for (final Account account : accounts) {
973 if (account.getStatus() != Account.State.DISABLED) {
974 activeAccounts++;
975 }
976 databaseBackend.writeRoster(account.getRoster());
977 if (account.getXmppConnection() != null) {
978 new Thread(new Runnable() {
979 @Override
980 public void run() {
981 disconnect(account, false);
982 }
983 }).start();
984 }
985 }
986 if (stop || activeAccounts == 0) {
987 Log.d(Config.LOGTAG, "good bye");
988 stopSelf();
989 }
990 }
991
992 private void cancelWakeUpCall(int requestCode) {
993 final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
994 final Intent intent = new Intent(this, EventReceiver.class);
995 intent.setAction("ping");
996 alarmManager.cancel(PendingIntent.getBroadcast(this, requestCode, intent, 0));
997 }
998
999 public void scheduleWakeUpCall(int seconds, int requestCode) {
1000 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
1001 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1002 Intent intent = new Intent(this, EventReceiver.class);
1003 intent.setAction("ping");
1004 PendingIntent alarmIntent = PendingIntent.getBroadcast(this, requestCode, intent, 0);
1005 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
1006 }
1007
1008 @TargetApi(Build.VERSION_CODES.M)
1009 private void scheduleNextIdlePing() {
1010 Log.d(Config.LOGTAG,"schedule next idle ping");
1011 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
1012 Intent intent = new Intent(this, EventReceiver.class);
1013 intent.setAction(ACTION_IDLE_PING);
1014 alarmManager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
1015 SystemClock.elapsedRealtime()+(Config.IDLE_PING_INTERVAL * 1000),
1016 PendingIntent.getBroadcast(this,0,intent,0)
1017 );
1018 }
1019
1020 public XmppConnection createConnection(final Account account) {
1021 final SharedPreferences sharedPref = getPreferences();
1022 String resource;
1023 try {
1024 resource = sharedPref.getString("resource", getString(R.string.default_resource)).toLowerCase(Locale.ENGLISH);
1025 if (resource.trim().isEmpty()) {
1026 throw new Exception();
1027 }
1028 } catch (Exception e) {
1029 resource = "conversations";
1030 }
1031 account.setResource(resource);
1032 final XmppConnection connection = new XmppConnection(account, this);
1033 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
1034 connection.setOnStatusChangedListener(this.statusListener);
1035 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
1036 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
1037 connection.setOnJinglePacketReceivedListener(this.jingleListener);
1038 connection.setOnBindListener(this.mOnBindListener);
1039 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
1040 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
1041 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mAvatarService);
1042 AxolotlService axolotlService = account.getAxolotlService();
1043 if (axolotlService != null) {
1044 connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService);
1045 }
1046 return connection;
1047 }
1048
1049 public void sendChatState(Conversation conversation) {
1050 if (sendChatStates()) {
1051 MessagePacket packet = mMessageGenerator.generateChatState(conversation);
1052 sendMessagePacket(conversation.getAccount(), packet);
1053 }
1054 }
1055
1056 private void sendFileMessage(final Message message, final boolean delay) {
1057 Log.d(Config.LOGTAG, "send file message");
1058 final Account account = message.getConversation().getAccount();
1059 if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())) {
1060 mHttpConnectionManager.createNewUploadConnection(message, delay);
1061 } else {
1062 mJingleConnectionManager.createNewConnection(message);
1063 }
1064 }
1065
1066 public void sendMessage(final Message message) {
1067 sendMessage(message, false, false);
1068 }
1069
1070 private void sendMessage(final Message message, final boolean resend, final boolean delay) {
1071 final Account account = message.getConversation().getAccount();
1072 if (account.setShowErrorNotification(true)) {
1073 databaseBackend.updateAccount(account);
1074 mNotificationService.updateErrorNotification();
1075 }
1076 final Conversation conversation = message.getConversation();
1077 account.deactivateGracePeriod();
1078 MessagePacket packet = null;
1079 final boolean addToConversation = (conversation.getMode() != Conversation.MODE_MULTI
1080 || account.getServerIdentity() != XmppConnection.Identity.SLACK)
1081 && !message.edited();
1082 boolean saveInDb = addToConversation;
1083 message.setStatus(Message.STATUS_WAITING);
1084
1085 if (!resend && message.getEncryption() != Message.ENCRYPTION_OTR) {
1086 message.getConversation().endOtrIfNeeded();
1087 message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR,
1088 new Conversation.OnMessageFound() {
1089 @Override
1090 public void onMessageFound(Message message) {
1091 markMessage(message, Message.STATUS_SEND_FAILED);
1092 }
1093 });
1094 }
1095
1096 if (account.isOnlineAndConnected()) {
1097 switch (message.getEncryption()) {
1098 case Message.ENCRYPTION_NONE:
1099 if (message.needsUploading()) {
1100 if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1101 || message.fixCounterpart()) {
1102 this.sendFileMessage(message, delay);
1103 } else {
1104 break;
1105 }
1106 } else {
1107 packet = mMessageGenerator.generateChat(message);
1108 }
1109 break;
1110 case Message.ENCRYPTION_PGP:
1111 case Message.ENCRYPTION_DECRYPTED:
1112 if (message.needsUploading()) {
1113 if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1114 || message.fixCounterpart()) {
1115 this.sendFileMessage(message, delay);
1116 } else {
1117 break;
1118 }
1119 } else {
1120 packet = mMessageGenerator.generatePgpChat(message);
1121 }
1122 break;
1123 case Message.ENCRYPTION_OTR:
1124 SessionImpl otrSession = conversation.getOtrSession();
1125 if (otrSession != null && otrSession.getSessionStatus() == SessionStatus.ENCRYPTED) {
1126 try {
1127 message.setCounterpart(Jid.fromSessionID(otrSession.getSessionID()));
1128 } catch (InvalidJidException e) {
1129 break;
1130 }
1131 if (message.needsUploading()) {
1132 mJingleConnectionManager.createNewConnection(message);
1133 } else {
1134 packet = mMessageGenerator.generateOtrChat(message);
1135 }
1136 } else if (otrSession == null) {
1137 if (message.fixCounterpart()) {
1138 conversation.startOtrSession(message.getCounterpart().getResourcepart(), true);
1139 } else {
1140 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not fix counterpart for OTR message to contact "+message.getContact().getJid());
1141 break;
1142 }
1143 } else {
1144 Log.d(Config.LOGTAG,account.getJid().toBareJid()+" OTR session with "+message.getContact()+" is in wrong state: "+otrSession.getSessionStatus().toString());
1145 }
1146 break;
1147 case Message.ENCRYPTION_AXOLOTL:
1148 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1149 if (message.needsUploading()) {
1150 if (account.httpUploadAvailable(fileBackend.getFile(message,false).getSize())
1151 || message.fixCounterpart()) {
1152 this.sendFileMessage(message, delay);
1153 } else {
1154 break;
1155 }
1156 } else {
1157 XmppAxolotlMessage axolotlMessage = account.getAxolotlService().fetchAxolotlMessageFromCache(message);
1158 if (axolotlMessage == null) {
1159 account.getAxolotlService().preparePayloadMessage(message, delay);
1160 } else {
1161 packet = mMessageGenerator.generateAxolotlChat(message, axolotlMessage);
1162 }
1163 }
1164 break;
1165
1166 }
1167 if (packet != null) {
1168 if (account.getXmppConnection().getFeatures().sm()
1169 || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1170 message.setStatus(Message.STATUS_UNSEND);
1171 } else {
1172 message.setStatus(Message.STATUS_SEND);
1173 }
1174 }
1175 } else {
1176 switch (message.getEncryption()) {
1177 case Message.ENCRYPTION_DECRYPTED:
1178 if (!message.needsUploading()) {
1179 String pgpBody = message.getEncryptedBody();
1180 String decryptedBody = message.getBody();
1181 message.setBody(pgpBody);
1182 message.setEncryption(Message.ENCRYPTION_PGP);
1183 if (message.edited()) {
1184 message.setBody(decryptedBody);
1185 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1186 databaseBackend.updateMessage(message, message.getEditedId());
1187 updateConversationUi();
1188 return;
1189 } else {
1190 databaseBackend.createMessage(message);
1191 saveInDb = false;
1192 message.setBody(decryptedBody);
1193 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1194 }
1195 }
1196 break;
1197 case Message.ENCRYPTION_OTR:
1198 if (!conversation.hasValidOtrSession() && message.getCounterpart() != null) {
1199 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": create otr session without starting for "+message.getContact().getJid());
1200 conversation.startOtrSession(message.getCounterpart().getResourcepart(), false);
1201 }
1202 break;
1203 case Message.ENCRYPTION_AXOLOTL:
1204 message.setFingerprint(account.getAxolotlService().getOwnFingerprint());
1205 break;
1206 }
1207 }
1208
1209 if (resend) {
1210 if (packet != null && addToConversation) {
1211 if (account.getXmppConnection().getFeatures().sm()
1212 || (conversation.getMode() == Conversation.MODE_MULTI && message.getCounterpart().isBareJid())) {
1213 markMessage(message, Message.STATUS_UNSEND);
1214 } else {
1215 markMessage(message, Message.STATUS_SEND);
1216 }
1217 }
1218 } else {
1219 if (addToConversation) {
1220 conversation.add(message);
1221 }
1222 if (message.getEncryption() == Message.ENCRYPTION_NONE || saveEncryptedMessages()) {
1223 if (saveInDb) {
1224 databaseBackend.createMessage(message);
1225 } else if (message.edited()) {
1226 databaseBackend.updateMessage(message, message.getEditedId());
1227 }
1228 }
1229 updateConversationUi();
1230 }
1231 if (packet != null) {
1232 if (delay) {
1233 mMessageGenerator.addDelay(packet, message.getTimeSent());
1234 }
1235 if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1236 if (this.sendChatStates()) {
1237 packet.addChild(ChatState.toElement(conversation.getOutgoingChatState()));
1238 }
1239 }
1240 sendMessagePacket(account, packet);
1241 }
1242 }
1243
1244 private void sendUnsentMessages(final Conversation conversation) {
1245 conversation.findWaitingMessages(new Conversation.OnMessageFound() {
1246
1247 @Override
1248 public void onMessageFound(Message message) {
1249 resendMessage(message, true);
1250 }
1251 });
1252 }
1253
1254 public void resendMessage(final Message message, final boolean delay) {
1255 sendMessage(message, true, delay);
1256 }
1257
1258 public void fetchRosterFromServer(final Account account) {
1259 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1260 if (!"".equals(account.getRosterVersion())) {
1261 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1262 + ": fetching roster version " + account.getRosterVersion());
1263 } else {
1264 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
1265 }
1266 iqPacket.query(Xmlns.ROSTER).setAttribute("ver", account.getRosterVersion());
1267 sendIqPacket(account, iqPacket, mIqParser);
1268 }
1269
1270 public void fetchBookmarks(final Account account) {
1271 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
1272 final Element query = iqPacket.query("jabber:iq:private");
1273 query.addChild("storage", "storage:bookmarks");
1274 final OnIqPacketReceived callback = new OnIqPacketReceived() {
1275
1276 @Override
1277 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1278 if (packet.getType() == IqPacket.TYPE.RESULT) {
1279 final Element query = packet.query();
1280 final HashMap<Jid, Bookmark> bookmarks = new HashMap<>();
1281 final Element storage = query.findChild("storage", "storage:bookmarks");
1282 final boolean autojoin = respectAutojoin();
1283 if (storage != null) {
1284 for (final Element item : storage.getChildren()) {
1285 if (item.getName().equals("conference")) {
1286 final Bookmark bookmark = Bookmark.parse(item, account);
1287 Bookmark old = bookmarks.put(bookmark.getJid(), bookmark);
1288 if (old != null && old.getBookmarkName() != null && bookmark.getBookmarkName() == null) {
1289 bookmark.setBookmarkName(old.getBookmarkName());
1290 }
1291 Conversation conversation = find(bookmark);
1292 if (conversation != null) {
1293 conversation.setBookmark(bookmark);
1294 } else if (bookmark.autojoin() && bookmark.getJid() != null && autojoin) {
1295 conversation = findOrCreateConversation(
1296 account, bookmark.getJid(), true);
1297 conversation.setBookmark(bookmark);
1298 joinMuc(conversation);
1299 }
1300 }
1301 }
1302 }
1303 account.setBookmarks(new ArrayList<>(bookmarks.values()));
1304 } else {
1305 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks");
1306 }
1307 }
1308 };
1309 sendIqPacket(account, iqPacket, callback);
1310 }
1311
1312 public void pushBookmarks(Account account) {
1313 Log.d(Config.LOGTAG, account.getJid().toBareJid()+": pushing bookmarks");
1314 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
1315 Element query = iqPacket.query("jabber:iq:private");
1316 Element storage = query.addChild("storage", "storage:bookmarks");
1317 for (Bookmark bookmark : account.getBookmarks()) {
1318 storage.addChild(bookmark);
1319 }
1320 sendIqPacket(account, iqPacket, mDefaultIqHandler);
1321 }
1322
1323 private void restoreFromDatabase() {
1324 synchronized (this.conversations) {
1325 final Map<String, Account> accountLookupTable = new Hashtable<>();
1326 for (Account account : this.accounts) {
1327 accountLookupTable.put(account.getUuid(), account);
1328 }
1329 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
1330 for (Conversation conversation : this.conversations) {
1331 Account account = accountLookupTable.get(conversation.getAccountUuid());
1332 conversation.setAccount(account);
1333 }
1334 Runnable runnable = new Runnable() {
1335 @Override
1336 public void run() {
1337 Log.d(Config.LOGTAG, "restoring roster");
1338 for (Account account : accounts) {
1339 databaseBackend.readRoster(account.getRoster());
1340 account.initAccountServices(XmppConnectionService.this); //roster needs to be loaded at this stage
1341 }
1342 getBitmapCache().evictAll();
1343 loadPhoneContacts();
1344 Log.d(Config.LOGTAG, "restoring messages");
1345 for (Conversation conversation : conversations) {
1346 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1347 checkDeletedFiles(conversation);
1348 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
1349
1350 @Override
1351 public void onMessageFound(Message message) {
1352 markMessage(message, Message.STATUS_WAITING);
1353 }
1354 });
1355 conversation.findUnreadMessages(new Conversation.OnMessageFound() {
1356 @Override
1357 public void onMessageFound(Message message) {
1358 mNotificationService.pushFromBacklog(message);
1359 }
1360 });
1361 }
1362 mNotificationService.finishBacklog(false);
1363 mRestoredFromDatabase = true;
1364 Log.d(Config.LOGTAG, "restored all messages");
1365 updateConversationUi();
1366 }
1367 };
1368 mDatabaseExecutor.execute(runnable);
1369 }
1370 }
1371
1372 public void loadPhoneContacts() {
1373 mContactMergerExecutor.execute(new Runnable() {
1374 @Override
1375 public void run() {
1376 PhoneHelper.loadPhoneContacts(XmppConnectionService.this, new OnPhoneContactsLoadedListener() {
1377 @Override
1378 public void onPhoneContactsLoaded(List<Bundle> phoneContacts) {
1379 Log.d(Config.LOGTAG, "start merging phone contacts with roster");
1380 for (Account account : accounts) {
1381 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
1382 for (Bundle phoneContact : phoneContacts) {
1383 Jid jid;
1384 try {
1385 jid = Jid.fromString(phoneContact.getString("jid"));
1386 } catch (final InvalidJidException e) {
1387 continue;
1388 }
1389 final Contact contact = account.getRoster().getContact(jid);
1390 String systemAccount = phoneContact.getInt("phoneid")
1391 + "#"
1392 + phoneContact.getString("lookup");
1393 contact.setSystemAccount(systemAccount);
1394 if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
1395 getAvatarService().clear(contact);
1396 }
1397 contact.setSystemName(phoneContact.getString("displayname"));
1398 withSystemAccounts.remove(contact);
1399 }
1400 for (Contact contact : withSystemAccounts) {
1401 contact.setSystemAccount(null);
1402 contact.setSystemName(null);
1403 if (contact.setPhotoUri(null)) {
1404 getAvatarService().clear(contact);
1405 }
1406 }
1407 }
1408 Log.d(Config.LOGTAG, "finished merging phone contacts");
1409 updateAccountUi();
1410 }
1411 });
1412 }
1413 });
1414 }
1415
1416 public List<Conversation> getConversations() {
1417 return this.conversations;
1418 }
1419
1420 private void checkDeletedFiles(Conversation conversation) {
1421 conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1422
1423 @Override
1424 public void onMessageFound(Message message) {
1425 if (!getFileBackend().isFileAvailable(message)) {
1426 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1427 final int s = message.getStatus();
1428 if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1429 markMessage(message, Message.STATUS_SEND_FAILED);
1430 }
1431 }
1432 }
1433 });
1434 }
1435
1436 private void markFileDeleted(final String path) {
1437 Log.d(Config.LOGTAG,"deleted file "+path);
1438 for (Conversation conversation : getConversations()) {
1439 conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1440 @Override
1441 public void onMessageFound(Message message) {
1442 DownloadableFile file = fileBackend.getFile(message);
1443 if (file.getAbsolutePath().equals(path)) {
1444 if (!file.exists()) {
1445 message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED));
1446 final int s = message.getStatus();
1447 if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) {
1448 markMessage(message, Message.STATUS_SEND_FAILED);
1449 } else {
1450 updateConversationUi();
1451 }
1452 } else {
1453 Log.d(Config.LOGTAG,"found matching message for file "+path+" but file still exists");
1454 }
1455 }
1456 }
1457 });
1458 }
1459 }
1460
1461 public void populateWithOrderedConversations(final List<Conversation> list) {
1462 populateWithOrderedConversations(list, true);
1463 }
1464
1465 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeNoFileUpload) {
1466 list.clear();
1467 if (includeNoFileUpload) {
1468 list.addAll(getConversations());
1469 } else {
1470 for (Conversation conversation : getConversations()) {
1471 if (conversation.getMode() == Conversation.MODE_SINGLE
1472 || conversation.getAccount().httpUploadAvailable()) {
1473 list.add(conversation);
1474 }
1475 }
1476 }
1477 try {
1478 Collections.sort(list);
1479 } catch (IllegalArgumentException e) {
1480 //ignore
1481 }
1482 }
1483
1484 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1485 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) {
1486 return;
1487 } else if (timestamp == 0) {
1488 return;
1489 }
1490 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1491 Runnable runnable = new Runnable() {
1492 @Override
1493 public void run() {
1494 final Account account = conversation.getAccount();
1495 List<Message> messages = databaseBackend.getMessages(conversation, 50, timestamp);
1496 if (messages.size() > 0) {
1497 conversation.addAll(0, messages);
1498 checkDeletedFiles(conversation);
1499 callback.onMoreMessagesLoaded(messages.size(), conversation);
1500 } else if (conversation.hasMessagesLeftOnServer()
1501 && account.isOnlineAndConnected()
1502 && conversation.getLastClearHistory() == 0) {
1503 if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam())
1504 || (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) {
1505 MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp);
1506 if (query != null) {
1507 query.setCallback(callback);
1508 }
1509 callback.informUser(R.string.fetching_history_from_server);
1510 }
1511 }
1512 }
1513 };
1514 mDatabaseExecutor.execute(runnable);
1515 }
1516
1517 public List<Account> getAccounts() {
1518 return this.accounts;
1519 }
1520
1521 public List<Conversation> findAllConferencesWith(Contact contact) {
1522 ArrayList<Conversation> results = new ArrayList<>();
1523 for(Conversation conversation : conversations) {
1524 if (conversation.getMode() == Conversation.MODE_MULTI
1525 && conversation.getMucOptions().isContactInRoom(contact)) {
1526 results.add(conversation);
1527 }
1528 }
1529 return results;
1530 }
1531
1532 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1533 for (final Conversation conversation : haystack) {
1534 if (conversation.getContact() == contact) {
1535 return conversation;
1536 }
1537 }
1538 return null;
1539 }
1540
1541 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1542 if (jid == null) {
1543 return null;
1544 }
1545 for (final Conversation conversation : haystack) {
1546 if ((account == null || conversation.getAccount() == account)
1547 && (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1548 return conversation;
1549 }
1550 }
1551 return null;
1552 }
1553
1554 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1555 return this.findOrCreateConversation(account, jid, muc, null);
1556 }
1557
1558 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1559 synchronized (this.conversations) {
1560 Conversation conversation = find(account, jid);
1561 if (conversation != null) {
1562 return conversation;
1563 }
1564 conversation = databaseBackend.findConversation(account, jid);
1565 if (conversation != null) {
1566 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1567 conversation.setAccount(account);
1568 if (muc) {
1569 conversation.setMode(Conversation.MODE_MULTI);
1570 conversation.setContactJid(jid);
1571 } else {
1572 conversation.setMode(Conversation.MODE_SINGLE);
1573 conversation.setContactJid(jid.toBareJid());
1574 }
1575 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1576 this.databaseBackend.updateConversation(conversation);
1577 } else {
1578 String conversationName;
1579 Contact contact = account.getRoster().getContact(jid);
1580 if (contact != null) {
1581 conversationName = contact.getDisplayName();
1582 } else {
1583 conversationName = jid.getLocalpart();
1584 }
1585 if (muc) {
1586 conversation = new Conversation(conversationName, account, jid,
1587 Conversation.MODE_MULTI);
1588 } else {
1589 conversation = new Conversation(conversationName, account, jid.toBareJid(),
1590 Conversation.MODE_SINGLE);
1591 }
1592 this.databaseBackend.createConversation(conversation);
1593 }
1594 if (account.getXmppConnection() != null
1595 && account.getXmppConnection().getFeatures().mam()
1596 && !muc) {
1597 if (query == null) {
1598 this.mMessageArchiveService.query(conversation);
1599 } else {
1600 if (query.getConversation() == null) {
1601 this.mMessageArchiveService.query(conversation, query.getStart());
1602 }
1603 }
1604 }
1605 checkDeletedFiles(conversation);
1606 this.conversations.add(conversation);
1607 updateConversationUi();
1608 return conversation;
1609 }
1610 }
1611
1612 public void archiveConversation(Conversation conversation) {
1613 getNotificationService().clear(conversation);
1614 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1615 synchronized (this.conversations) {
1616 if (conversation.getMode() == Conversation.MODE_MULTI) {
1617 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1618 Bookmark bookmark = conversation.getBookmark();
1619 if (bookmark != null && bookmark.autojoin() && respectAutojoin()) {
1620 bookmark.setAutojoin(false);
1621 pushBookmarks(bookmark.getAccount());
1622 }
1623 }
1624 leaveMuc(conversation);
1625 } else {
1626 conversation.endOtrIfNeeded();
1627 if (conversation.getContact().getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
1628 Log.d(Config.LOGTAG, "Canceling presence request from " + conversation.getJid().toString());
1629 sendPresencePacket(
1630 conversation.getAccount(),
1631 mPresenceGenerator.stopPresenceUpdatesTo(conversation.getContact())
1632 );
1633 }
1634 }
1635 updateConversation(conversation);
1636 this.conversations.remove(conversation);
1637 updateConversationUi();
1638 }
1639 }
1640
1641 public void createAccount(final Account account) {
1642 account.initAccountServices(this);
1643 databaseBackend.createAccount(account);
1644 this.accounts.add(account);
1645 this.reconnectAccountInBackground(account);
1646 updateAccountUi();
1647 }
1648
1649 public void createAccountFromKey(final String alias, final OnAccountCreated callback) {
1650 new Thread(new Runnable() {
1651 @Override
1652 public void run() {
1653 try {
1654 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1655 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1656 if (findAccountByJid(info.first) == null) {
1657 Account account = new Account(info.first, "");
1658 account.setPrivateKeyAlias(alias);
1659 account.setOption(Account.OPTION_DISABLED, true);
1660 account.setDisplayName(info.second);
1661 createAccount(account);
1662 callback.onAccountCreated(account);
1663 if (Config.X509_VERIFICATION) {
1664 try {
1665 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1666 } catch (CertificateException e) {
1667 callback.informUser(R.string.certificate_chain_is_not_trusted);
1668 }
1669 }
1670 } else {
1671 callback.informUser(R.string.account_already_exists);
1672 }
1673 } catch (Exception e) {
1674 e.printStackTrace();
1675 callback.informUser(R.string.unable_to_parse_certificate);
1676 }
1677 }
1678 }).start();
1679
1680 }
1681
1682 public void updateKeyInAccount(final Account account, final String alias) {
1683 Log.d(Config.LOGTAG, "update key in account " + alias);
1684 try {
1685 X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias);
1686 Pair<Jid, String> info = CryptoHelper.extractJidAndName(chain[0]);
1687 if (account.getJid().toBareJid().equals(info.first)) {
1688 account.setPrivateKeyAlias(alias);
1689 account.setDisplayName(info.second);
1690 databaseBackend.updateAccount(account);
1691 if (Config.X509_VERIFICATION) {
1692 try {
1693 getMemorizingTrustManager().getNonInteractive().checkClientTrusted(chain, "RSA");
1694 } catch (CertificateException e) {
1695 showErrorToastInUi(R.string.certificate_chain_is_not_trusted);
1696 }
1697 account.getAxolotlService().regenerateKeys(true);
1698 }
1699 } else {
1700 showErrorToastInUi(R.string.jid_does_not_match_certificate);
1701 }
1702 } catch (Exception e) {
1703 e.printStackTrace();
1704 }
1705 }
1706
1707 public boolean updateAccount(final Account account) {
1708 if (databaseBackend.updateAccount(account)) {
1709 account.setShowErrorNotification(true);
1710 this.statusListener.onStatusChanged(account);
1711 databaseBackend.updateAccount(account);
1712 reconnectAccountInBackground(account);
1713 updateAccountUi();
1714 getNotificationService().updateErrorNotification();
1715 return true;
1716 } else {
1717 return false;
1718 }
1719 }
1720
1721 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1722 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1723 sendIqPacket(account, iq, new OnIqPacketReceived() {
1724 @Override
1725 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1726 if (packet.getType() == IqPacket.TYPE.RESULT) {
1727 account.setPassword(newPassword);
1728 account.setOption(Account.OPTION_MAGIC_CREATE, false);
1729 databaseBackend.updateAccount(account);
1730 callback.onPasswordChangeSucceeded();
1731 } else {
1732 callback.onPasswordChangeFailed();
1733 }
1734 }
1735 });
1736 }
1737
1738 public void deleteAccount(final Account account) {
1739 synchronized (this.conversations) {
1740 for (final Conversation conversation : conversations) {
1741 if (conversation.getAccount() == account) {
1742 if (conversation.getMode() == Conversation.MODE_MULTI) {
1743 leaveMuc(conversation);
1744 } else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1745 conversation.endOtrIfNeeded();
1746 }
1747 conversations.remove(conversation);
1748 }
1749 }
1750 if (account.getXmppConnection() != null) {
1751 new Thread(new Runnable() {
1752 @Override
1753 public void run() {
1754 disconnect(account, true);
1755 }
1756 }).start();
1757 }
1758 Runnable runnable = new Runnable() {
1759 @Override
1760 public void run() {
1761 if (!databaseBackend.deleteAccount(account)) {
1762 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": unable to delete account");
1763 }
1764 }
1765 };
1766 mDatabaseExecutor.execute(runnable);
1767 this.accounts.remove(account);
1768 updateAccountUi();
1769 getNotificationService().updateErrorNotification();
1770 }
1771 }
1772
1773 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1774 synchronized (this) {
1775 this.mLastActivity = System.currentTimeMillis();
1776 if (checkListeners()) {
1777 switchToForeground();
1778 }
1779 this.mOnConversationUpdate = listener;
1780 this.mNotificationService.setIsInForeground(true);
1781 if (this.convChangedListenerCount < 2) {
1782 this.convChangedListenerCount++;
1783 }
1784 }
1785 }
1786
1787 public void removeOnConversationListChangedListener() {
1788 synchronized (this) {
1789 this.convChangedListenerCount--;
1790 if (this.convChangedListenerCount <= 0) {
1791 this.convChangedListenerCount = 0;
1792 this.mOnConversationUpdate = null;
1793 this.mNotificationService.setIsInForeground(false);
1794 if (checkListeners()) {
1795 switchToBackground();
1796 }
1797 }
1798 }
1799 }
1800
1801 public void setOnShowErrorToastListener(OnShowErrorToast onShowErrorToast) {
1802 synchronized (this) {
1803 if (checkListeners()) {
1804 switchToForeground();
1805 }
1806 this.mOnShowErrorToast = onShowErrorToast;
1807 if (this.showErrorToastListenerCount < 2) {
1808 this.showErrorToastListenerCount++;
1809 }
1810 }
1811 this.mOnShowErrorToast = onShowErrorToast;
1812 }
1813
1814 public void removeOnShowErrorToastListener() {
1815 synchronized (this) {
1816 this.showErrorToastListenerCount--;
1817 if (this.showErrorToastListenerCount <= 0) {
1818 this.showErrorToastListenerCount = 0;
1819 this.mOnShowErrorToast = null;
1820 if (checkListeners()) {
1821 switchToBackground();
1822 }
1823 }
1824 }
1825 }
1826
1827 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1828 synchronized (this) {
1829 if (checkListeners()) {
1830 switchToForeground();
1831 }
1832 this.mOnAccountUpdate = listener;
1833 if (this.accountChangedListenerCount < 2) {
1834 this.accountChangedListenerCount++;
1835 }
1836 }
1837 }
1838
1839 public void removeOnAccountListChangedListener() {
1840 synchronized (this) {
1841 this.accountChangedListenerCount--;
1842 if (this.accountChangedListenerCount <= 0) {
1843 this.mOnAccountUpdate = null;
1844 this.accountChangedListenerCount = 0;
1845 if (checkListeners()) {
1846 switchToBackground();
1847 }
1848 }
1849 }
1850 }
1851
1852 public void setOnCaptchaRequestedListener(OnCaptchaRequested listener) {
1853 synchronized (this) {
1854 if (checkListeners()) {
1855 switchToForeground();
1856 }
1857 this.mOnCaptchaRequested = listener;
1858 if (this.captchaRequestedListenerCount < 2) {
1859 this.captchaRequestedListenerCount++;
1860 }
1861 }
1862 }
1863
1864 public void removeOnCaptchaRequestedListener() {
1865 synchronized (this) {
1866 this.captchaRequestedListenerCount--;
1867 if (this.captchaRequestedListenerCount <= 0) {
1868 this.mOnCaptchaRequested = null;
1869 this.captchaRequestedListenerCount = 0;
1870 if (checkListeners()) {
1871 switchToBackground();
1872 }
1873 }
1874 }
1875 }
1876
1877 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1878 synchronized (this) {
1879 if (checkListeners()) {
1880 switchToForeground();
1881 }
1882 this.mOnRosterUpdate = listener;
1883 if (this.rosterChangedListenerCount < 2) {
1884 this.rosterChangedListenerCount++;
1885 }
1886 }
1887 }
1888
1889 public void removeOnRosterUpdateListener() {
1890 synchronized (this) {
1891 this.rosterChangedListenerCount--;
1892 if (this.rosterChangedListenerCount <= 0) {
1893 this.rosterChangedListenerCount = 0;
1894 this.mOnRosterUpdate = null;
1895 if (checkListeners()) {
1896 switchToBackground();
1897 }
1898 }
1899 }
1900 }
1901
1902 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1903 synchronized (this) {
1904 if (checkListeners()) {
1905 switchToForeground();
1906 }
1907 this.mOnUpdateBlocklist = listener;
1908 if (this.updateBlocklistListenerCount < 2) {
1909 this.updateBlocklistListenerCount++;
1910 }
1911 }
1912 }
1913
1914 public void removeOnUpdateBlocklistListener() {
1915 synchronized (this) {
1916 this.updateBlocklistListenerCount--;
1917 if (this.updateBlocklistListenerCount <= 0) {
1918 this.updateBlocklistListenerCount = 0;
1919 this.mOnUpdateBlocklist = null;
1920 if (checkListeners()) {
1921 switchToBackground();
1922 }
1923 }
1924 }
1925 }
1926
1927 public void setOnKeyStatusUpdatedListener(final OnKeyStatusUpdated listener) {
1928 synchronized (this) {
1929 if (checkListeners()) {
1930 switchToForeground();
1931 }
1932 this.mOnKeyStatusUpdated = listener;
1933 if (this.keyStatusUpdatedListenerCount < 2) {
1934 this.keyStatusUpdatedListenerCount++;
1935 }
1936 }
1937 }
1938
1939 public void removeOnNewKeysAvailableListener() {
1940 synchronized (this) {
1941 this.keyStatusUpdatedListenerCount--;
1942 if (this.keyStatusUpdatedListenerCount <= 0) {
1943 this.keyStatusUpdatedListenerCount = 0;
1944 this.mOnKeyStatusUpdated = null;
1945 if (checkListeners()) {
1946 switchToBackground();
1947 }
1948 }
1949 }
1950 }
1951
1952 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1953 synchronized (this) {
1954 if (checkListeners()) {
1955 switchToForeground();
1956 }
1957 this.mOnMucRosterUpdate = listener;
1958 if (this.mucRosterChangedListenerCount < 2) {
1959 this.mucRosterChangedListenerCount++;
1960 }
1961 }
1962 }
1963
1964 public void removeOnMucRosterUpdateListener() {
1965 synchronized (this) {
1966 this.mucRosterChangedListenerCount--;
1967 if (this.mucRosterChangedListenerCount <= 0) {
1968 this.mucRosterChangedListenerCount = 0;
1969 this.mOnMucRosterUpdate = null;
1970 if (checkListeners()) {
1971 switchToBackground();
1972 }
1973 }
1974 }
1975 }
1976
1977 public boolean checkListeners() {
1978 return (this.mOnAccountUpdate == null
1979 && this.mOnConversationUpdate == null
1980 && this.mOnRosterUpdate == null
1981 && this.mOnCaptchaRequested == null
1982 && this.mOnUpdateBlocklist == null
1983 && this.mOnShowErrorToast == null
1984 && this.mOnKeyStatusUpdated == null);
1985 }
1986
1987 private void switchToForeground() {
1988 final boolean broadcastLastActivity = broadcastLastActivity();
1989 for (Conversation conversation : getConversations()) {
1990 conversation.setIncomingChatState(ChatState.ACTIVE);
1991 }
1992 for (Account account : getAccounts()) {
1993 if (account.getStatus() == Account.State.ONLINE) {
1994 account.deactivateGracePeriod();
1995 final XmppConnection connection = account.getXmppConnection();
1996 if (connection != null ) {
1997 if (connection.getFeatures().csi()) {
1998 connection.sendActive();
1999 }
2000 if (broadcastLastActivity) {
2001 sendPresence(account, false); //send new presence but don't include idle because we are not
2002 }
2003 }
2004 }
2005 }
2006 Log.d(Config.LOGTAG, "app switched into foreground");
2007 }
2008
2009 private void switchToBackground() {
2010 final boolean broadcastLastActivity = broadcastLastActivity();
2011 for (Account account : getAccounts()) {
2012 if (account.getStatus() == Account.State.ONLINE) {
2013 XmppConnection connection = account.getXmppConnection();
2014 if (connection != null) {
2015 if (broadcastLastActivity) {
2016 sendPresence(account, broadcastLastActivity);
2017 }
2018 if (connection.getFeatures().csi()) {
2019 connection.sendInactive();
2020 }
2021 }
2022 }
2023 }
2024 this.mNotificationService.setIsInForeground(false);
2025 Log.d(Config.LOGTAG, "app switched into background");
2026 }
2027
2028 private void connectMultiModeConversations(Account account) {
2029 List<Conversation> conversations = getConversations();
2030 for (Conversation conversation : conversations) {
2031 if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) {
2032 joinMuc(conversation);
2033 }
2034 }
2035 }
2036
2037 public void joinMuc(Conversation conversation) {
2038 joinMuc(conversation, null);
2039 }
2040
2041 private void joinMuc(Conversation conversation, final OnConferenceJoined onConferenceJoined) {
2042 Account account = conversation.getAccount();
2043 account.pendingConferenceJoins.remove(conversation);
2044 account.pendingConferenceLeaves.remove(conversation);
2045 if (account.getStatus() == Account.State.ONLINE) {
2046 conversation.resetMucOptions();
2047 if (onConferenceJoined != null) {
2048 conversation.getMucOptions().flagNoAutoPushConfiguration();
2049 }
2050 conversation.setHasMessagesLeftOnServer(false);
2051 fetchConferenceConfiguration(conversation, new OnConferenceConfigurationFetched() {
2052
2053 private void join(Conversation conversation) {
2054 Account account = conversation.getAccount();
2055 final MucOptions mucOptions = conversation.getMucOptions();
2056 final Jid joinJid = mucOptions.getSelf().getFullJid();
2057 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
2058 PresencePacket packet = mPresenceGenerator.selfPresence(account, Presence.Status.ONLINE, mucOptions.nonanonymous());
2059 packet.setTo(joinJid);
2060 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
2061 if (conversation.getMucOptions().getPassword() != null) {
2062 x.addChild("password").setContent(mucOptions.getPassword());
2063 }
2064
2065 if (mucOptions.mamSupport()) {
2066 // Use MAM instead of the limited muc history to get history
2067 x.addChild("history").setAttribute("maxchars", "0");
2068 } else {
2069 // Fallback to muc history
2070 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
2071 }
2072 sendPresencePacket(account, packet);
2073 if (onConferenceJoined != null) {
2074 onConferenceJoined.onConferenceJoined(conversation);
2075 }
2076 if (!joinJid.equals(conversation.getJid())) {
2077 conversation.setContactJid(joinJid);
2078 databaseBackend.updateConversation(conversation);
2079 }
2080
2081 if (mucOptions.mamSupport()) {
2082 getMessageArchiveService().catchupMUC(conversation);
2083 }
2084 if (mucOptions.membersOnly() && mucOptions.nonanonymous()) {
2085 fetchConferenceMembers(conversation);
2086 }
2087 sendUnsentMessages(conversation);
2088 }
2089
2090 @Override
2091 public void onConferenceConfigurationFetched(Conversation conversation) {
2092 join(conversation);
2093 }
2094
2095 @Override
2096 public void onFetchFailed(final Conversation conversation, Element error) {
2097 if (error != null && "remote-server-not-found".equals(error.getName())) {
2098 conversation.getMucOptions().setError(MucOptions.Error.SERVER_NOT_FOUND);
2099 } else {
2100 join(conversation);
2101 fetchConferenceConfiguration(conversation);
2102 }
2103 }
2104 });
2105 updateConversationUi();
2106 } else {
2107 account.pendingConferenceJoins.add(conversation);
2108 conversation.resetMucOptions();
2109 conversation.setHasMessagesLeftOnServer(false);
2110 updateConversationUi();
2111 }
2112 }
2113
2114 private void fetchConferenceMembers(final Conversation conversation) {
2115 final Account account = conversation.getAccount();
2116 final String[] affiliations = {"member","admin","owner"};
2117 OnIqPacketReceived callback = new OnIqPacketReceived() {
2118
2119 private int i = 0;
2120
2121 @Override
2122 public void onIqPacketReceived(Account account, IqPacket packet) {
2123
2124 Element query = packet.query("http://jabber.org/protocol/muc#admin");
2125 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2126 for(Element child : query.getChildren()) {
2127 if ("item".equals(child.getName())) {
2128 MucOptions.User user = AbstractParser.parseItem(conversation,child);
2129 if (!user.realJidMatchesAccount()) {
2130 conversation.getMucOptions().addUser(user);
2131 }
2132 }
2133 }
2134 } else {
2135 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not request affiliation "+affiliations[i]+" in "+conversation.getJid().toBareJid());
2136 }
2137 ++i;
2138 if (i >= affiliations.length) {
2139 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved members for "+conversation.getJid().toBareJid()+": "+conversation.getMucOptions().getMembers());
2140 getAvatarService().clear(conversation);
2141 updateMucRosterUi();
2142 updateConversationUi();
2143 }
2144 }
2145 };
2146 for(String affiliation : affiliations) {
2147 sendIqPacket(account, mIqGenerator.queryAffiliation(conversation, affiliation), callback);
2148 }
2149 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetching members for "+conversation.getName());
2150 }
2151
2152 public void providePasswordForMuc(Conversation conversation, String password) {
2153 if (conversation.getMode() == Conversation.MODE_MULTI) {
2154 conversation.getMucOptions().setPassword(password);
2155 if (conversation.getBookmark() != null) {
2156 if (respectAutojoin()) {
2157 conversation.getBookmark().setAutojoin(true);
2158 }
2159 pushBookmarks(conversation.getAccount());
2160 }
2161 updateConversation(conversation);
2162 joinMuc(conversation);
2163 }
2164 }
2165
2166 public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
2167 final MucOptions options = conversation.getMucOptions();
2168 final Jid joinJid = options.createJoinJid(nick);
2169 if (options.online()) {
2170 Account account = conversation.getAccount();
2171 options.setOnRenameListener(new OnRenameListener() {
2172
2173 @Override
2174 public void onSuccess() {
2175 conversation.setContactJid(joinJid);
2176 databaseBackend.updateConversation(conversation);
2177 Bookmark bookmark = conversation.getBookmark();
2178 if (bookmark != null) {
2179 bookmark.setNick(nick);
2180 pushBookmarks(bookmark.getAccount());
2181 }
2182 callback.success(conversation);
2183 }
2184
2185 @Override
2186 public void onFailure() {
2187 callback.error(R.string.nick_in_use, conversation);
2188 }
2189 });
2190
2191 PresencePacket packet = new PresencePacket();
2192 packet.setTo(joinJid);
2193 packet.setFrom(conversation.getAccount().getJid());
2194
2195 String sig = account.getPgpSignature();
2196 if (sig != null) {
2197 packet.addChild("status").setContent("online");
2198 packet.addChild("x", "jabber:x:signed").setContent(sig);
2199 }
2200 sendPresencePacket(account, packet);
2201 } else {
2202 conversation.setContactJid(joinJid);
2203 databaseBackend.updateConversation(conversation);
2204 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
2205 Bookmark bookmark = conversation.getBookmark();
2206 if (bookmark != null) {
2207 bookmark.setNick(nick);
2208 pushBookmarks(bookmark.getAccount());
2209 }
2210 joinMuc(conversation);
2211 }
2212 }
2213 }
2214
2215 public void leaveMuc(Conversation conversation) {
2216 leaveMuc(conversation, false);
2217 }
2218
2219 private void leaveMuc(Conversation conversation, boolean now) {
2220 Account account = conversation.getAccount();
2221 account.pendingConferenceJoins.remove(conversation);
2222 account.pendingConferenceLeaves.remove(conversation);
2223 if (account.getStatus() == Account.State.ONLINE || now) {
2224 PresencePacket packet = new PresencePacket();
2225 packet.setTo(conversation.getMucOptions().getSelf().getFullJid());
2226 packet.setFrom(conversation.getAccount().getJid());
2227 packet.setAttribute("type", "unavailable");
2228 sendPresencePacket(conversation.getAccount(), packet);
2229 conversation.getMucOptions().setOffline();
2230 conversation.deregisterWithBookmark();
2231 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
2232 + ": leaving muc " + conversation.getJid());
2233 } else {
2234 account.pendingConferenceLeaves.add(conversation);
2235 }
2236 }
2237
2238 private String findConferenceServer(final Account account) {
2239 String server;
2240 if (account.getXmppConnection() != null) {
2241 server = account.getXmppConnection().getMucServer();
2242 if (server != null) {
2243 return server;
2244 }
2245 }
2246 for (Account other : getAccounts()) {
2247 if (other != account && other.getXmppConnection() != null) {
2248 server = other.getXmppConnection().getMucServer();
2249 if (server != null) {
2250 return server;
2251 }
2252 }
2253 }
2254 return null;
2255 }
2256
2257 public void createAdhocConference(final Account account,
2258 final String subject,
2259 final Iterable<Jid> jids,
2260 final UiCallback<Conversation> callback) {
2261 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
2262 if (account.getStatus() == Account.State.ONLINE) {
2263 try {
2264 String server = findConferenceServer(account);
2265 if (server == null) {
2266 if (callback != null) {
2267 callback.error(R.string.no_conference_server_found, null);
2268 }
2269 return;
2270 }
2271 final Jid jid = Jid.fromParts(new BigInteger(64, getRNG()).toString(Character.MAX_RADIX), server, null);
2272 final Conversation conversation = findOrCreateConversation(account, jid, true);
2273 joinMuc(conversation, new OnConferenceJoined() {
2274 @Override
2275 public void onConferenceJoined(final Conversation conversation) {
2276 pushConferenceConfiguration(conversation, IqGenerator.defaultRoomConfiguration(), new OnConferenceOptionsPushed() {
2277 @Override
2278 public void onPushSucceeded() {
2279 if (subject != null && !subject.trim().isEmpty()) {
2280 pushSubjectToConference(conversation, subject.trim());
2281 }
2282 for (Jid invite : jids) {
2283 invite(conversation, invite);
2284 }
2285 if (account.countPresences() > 1) {
2286 directInvite(conversation, account.getJid().toBareJid());
2287 }
2288 saveConversationAsBookmark(conversation, subject);
2289 if (callback != null) {
2290 callback.success(conversation);
2291 }
2292 }
2293
2294 @Override
2295 public void onPushFailed() {
2296 archiveConversation(conversation);
2297 if (callback != null) {
2298 callback.error(R.string.conference_creation_failed, conversation);
2299 }
2300 }
2301 });
2302 }
2303 });
2304 } catch (InvalidJidException e) {
2305 if (callback != null) {
2306 callback.error(R.string.conference_creation_failed, null);
2307 }
2308 }
2309 } else {
2310 if (callback != null) {
2311 callback.error(R.string.not_connected_try_again, null);
2312 }
2313 }
2314 }
2315
2316 public void fetchConferenceConfiguration(final Conversation conversation) {
2317 fetchConferenceConfiguration(conversation, null);
2318 }
2319
2320 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2321 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2322 request.setTo(conversation.getJid().toBareJid());
2323 request.query("http://jabber.org/protocol/disco#info");
2324 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2325 @Override
2326 public void onIqPacketReceived(Account account, IqPacket packet) {
2327 Element query = packet.findChild("query","http://jabber.org/protocol/disco#info");
2328 if (packet.getType() == IqPacket.TYPE.RESULT && query != null) {
2329 ArrayList<String> features = new ArrayList<>();
2330 for (Element child : query.getChildren()) {
2331 if (child != null && child.getName().equals("feature")) {
2332 String var = child.getAttribute("var");
2333 if (var != null) {
2334 features.add(var);
2335 }
2336 }
2337 }
2338 Element form = query.findChild("x", "jabber:x:data");
2339 if (form != null) {
2340 conversation.getMucOptions().updateFormData(Data.parse(form));
2341 }
2342 conversation.getMucOptions().updateFeatures(features);
2343 if (callback != null) {
2344 callback.onConferenceConfigurationFetched(conversation);
2345 }
2346 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": fetched muc configuration for "+conversation.getJid().toBareJid()+" - "+features.toString());
2347 updateConversationUi();
2348 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2349 if (callback != null) {
2350 callback.onFetchFailed(conversation, packet.getError());
2351 }
2352 }
2353 }
2354 });
2355 }
2356
2357 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2358 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2359 request.setTo(conversation.getJid().toBareJid());
2360 request.query("http://jabber.org/protocol/muc#owner");
2361 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2362 @Override
2363 public void onIqPacketReceived(Account account, IqPacket packet) {
2364 if (packet.getType() == IqPacket.TYPE.RESULT) {
2365 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2366 for (Field field : data.getFields()) {
2367 if (options.containsKey(field.getFieldName())) {
2368 field.setValue(options.getString(field.getFieldName()));
2369 }
2370 }
2371 data.submit();
2372 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2373 set.setTo(conversation.getJid().toBareJid());
2374 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2375 sendIqPacket(account, set, new OnIqPacketReceived() {
2376 @Override
2377 public void onIqPacketReceived(Account account, IqPacket packet) {
2378 if (callback != null) {
2379 if (packet.getType() == IqPacket.TYPE.RESULT) {
2380 callback.onPushSucceeded();
2381 } else {
2382 callback.onPushFailed();
2383 }
2384 }
2385 }
2386 });
2387 } else {
2388 if (callback != null) {
2389 callback.onPushFailed();
2390 }
2391 }
2392 }
2393 });
2394 }
2395
2396 public void pushSubjectToConference(final Conversation conference, final String subject) {
2397 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2398 this.sendMessagePacket(conference.getAccount(), packet);
2399 final MucOptions mucOptions = conference.getMucOptions();
2400 final MucOptions.User self = mucOptions.getSelf();
2401 if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2402 Bundle options = new Bundle();
2403 options.putString("muc#roomconfig_persistentroom", "1");
2404 this.pushConferenceConfiguration(conference, options, null);
2405 }
2406 }
2407
2408 public void changeAffiliationInConference(final Conversation conference, Jid user, final MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2409 final Jid jid = user.toBareJid();
2410 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2411 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2412 @Override
2413 public void onIqPacketReceived(Account account, IqPacket packet) {
2414 if (packet.getType() == IqPacket.TYPE.RESULT) {
2415 conference.getMucOptions().changeAffiliation(jid, affiliation);
2416 getAvatarService().clear(conference);
2417 callback.onAffiliationChangedSuccessful(jid);
2418 } else {
2419 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2420 }
2421 }
2422 });
2423 }
2424
2425 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2426 List<Jid> jids = new ArrayList<>();
2427 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2428 if (user.getAffiliation() == before && user.getRealJid() != null) {
2429 jids.add(user.getRealJid());
2430 }
2431 }
2432 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2433 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2434 }
2435
2436 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2437 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2438 Log.d(Config.LOGTAG, request.toString());
2439 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2440 @Override
2441 public void onIqPacketReceived(Account account, IqPacket packet) {
2442 Log.d(Config.LOGTAG, packet.toString());
2443 if (packet.getType() == IqPacket.TYPE.RESULT) {
2444 callback.onRoleChangedSuccessful(nick);
2445 } else {
2446 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2447 }
2448 }
2449 });
2450 }
2451
2452 private void disconnect(Account account, boolean force) {
2453 if ((account.getStatus() == Account.State.ONLINE)
2454 || (account.getStatus() == Account.State.DISABLED)) {
2455 final XmppConnection connection = account.getXmppConnection();
2456 if (!force) {
2457 List<Conversation> conversations = getConversations();
2458 for (Conversation conversation : conversations) {
2459 if (conversation.getAccount() == account) {
2460 if (conversation.getMode() == Conversation.MODE_MULTI) {
2461 leaveMuc(conversation, true);
2462 } else {
2463 if (conversation.endOtrIfNeeded()) {
2464 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2465 + ": ended otr session with "
2466 + conversation.getJid());
2467 }
2468 }
2469 }
2470 }
2471 sendOfflinePresence(account);
2472 }
2473 connection.disconnect(force);
2474 }
2475 }
2476
2477 @Override
2478 public IBinder onBind(Intent intent) {
2479 return mBinder;
2480 }
2481
2482 public void updateMessage(Message message) {
2483 databaseBackend.updateMessage(message);
2484 updateConversationUi();
2485 }
2486
2487 public void updateMessage(Message message, String uuid) {
2488 databaseBackend.updateMessage(message, uuid);
2489 updateConversationUi();
2490 }
2491
2492 protected void syncDirtyContacts(Account account) {
2493 for (Contact contact : account.getRoster().getContacts()) {
2494 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2495 pushContactToServer(contact);
2496 }
2497 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2498 deleteContactOnServer(contact);
2499 }
2500 }
2501 }
2502
2503 public void createContact(Contact contact) {
2504 boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2505 if (autoGrant) {
2506 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2507 contact.setOption(Contact.Options.ASKING);
2508 }
2509 pushContactToServer(contact);
2510 }
2511
2512 public void onOtrSessionEstablished(Conversation conversation) {
2513 final Account account = conversation.getAccount();
2514 final Session otrSession = conversation.getOtrSession();
2515 Log.d(Config.LOGTAG,
2516 account.getJid().toBareJid() + " otr session established with "
2517 + conversation.getJid() + "/"
2518 + otrSession.getSessionID().getUserID());
2519 conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2520
2521 @Override
2522 public void onMessageFound(Message message) {
2523 SessionID id = otrSession.getSessionID();
2524 try {
2525 message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2526 } catch (InvalidJidException e) {
2527 return;
2528 }
2529 if (message.needsUploading()) {
2530 mJingleConnectionManager.createNewConnection(message);
2531 } else {
2532 MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2533 if (outPacket != null) {
2534 mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2535 message.setStatus(Message.STATUS_SEND);
2536 databaseBackend.updateMessage(message);
2537 sendMessagePacket(account, outPacket);
2538 }
2539 }
2540 updateConversationUi();
2541 }
2542 });
2543 }
2544
2545 public boolean renewSymmetricKey(Conversation conversation) {
2546 Account account = conversation.getAccount();
2547 byte[] symmetricKey = new byte[32];
2548 this.mRandom.nextBytes(symmetricKey);
2549 Session otrSession = conversation.getOtrSession();
2550 if (otrSession != null) {
2551 MessagePacket packet = new MessagePacket();
2552 packet.setType(MessagePacket.TYPE_CHAT);
2553 packet.setFrom(account.getJid());
2554 MessageGenerator.addMessageHints(packet);
2555 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2556 + otrSession.getSessionID().getUserID());
2557 try {
2558 packet.setBody(otrSession
2559 .transformSending(CryptoHelper.FILETRANSFER
2560 + CryptoHelper.bytesToHex(symmetricKey))[0]);
2561 sendMessagePacket(account, packet);
2562 conversation.setSymmetricKey(symmetricKey);
2563 return true;
2564 } catch (OtrException e) {
2565 return false;
2566 }
2567 }
2568 return false;
2569 }
2570
2571 public void pushContactToServer(final Contact contact) {
2572 contact.resetOption(Contact.Options.DIRTY_DELETE);
2573 contact.setOption(Contact.Options.DIRTY_PUSH);
2574 final Account account = contact.getAccount();
2575 if (account.getStatus() == Account.State.ONLINE) {
2576 final boolean ask = contact.getOption(Contact.Options.ASKING);
2577 final boolean sendUpdates = contact
2578 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2579 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2580 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2581 iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2582 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2583 if (sendUpdates) {
2584 sendPresencePacket(account,
2585 mPresenceGenerator.sendPresenceUpdatesTo(contact));
2586 }
2587 if (ask) {
2588 sendPresencePacket(account,
2589 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2590 }
2591 }
2592 }
2593
2594 public void publishAvatar(Account account, Uri image, UiCallback<Avatar> callback) {
2595 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2596 final int size = Config.AVATAR_SIZE;
2597 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2598 if (avatar != null) {
2599 avatar.height = size;
2600 avatar.width = size;
2601 if (format.equals(Bitmap.CompressFormat.WEBP)) {
2602 avatar.type = "image/webp";
2603 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2604 avatar.type = "image/jpeg";
2605 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
2606 avatar.type = "image/png";
2607 }
2608 if (!getFileBackend().save(avatar)) {
2609 callback.error(R.string.error_saving_avatar, avatar);
2610 return;
2611 }
2612 publishAvatar(account, avatar, callback);
2613 } else {
2614 callback.error(R.string.error_publish_avatar_converting, null);
2615 }
2616 }
2617
2618 public void publishAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2619 final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2620 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2621
2622 @Override
2623 public void onIqPacketReceived(Account account, IqPacket result) {
2624 if (result.getType() == IqPacket.TYPE.RESULT) {
2625 final IqPacket packet = XmppConnectionService.this.mIqGenerator
2626 .publishAvatarMetadata(avatar);
2627 sendIqPacket(account, packet, new OnIqPacketReceived() {
2628 @Override
2629 public void onIqPacketReceived(Account account, IqPacket result) {
2630 if (result.getType() == IqPacket.TYPE.RESULT) {
2631 if (account.setAvatar(avatar.getFilename())) {
2632 getAvatarService().clear(account);
2633 databaseBackend.updateAccount(account);
2634 }
2635 if (callback != null) {
2636 callback.success(avatar);
2637 } else {
2638 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": published avatar");
2639 }
2640 } else {
2641 if (callback != null) {
2642 callback.error(
2643 R.string.error_publish_avatar_server_reject,
2644 avatar);
2645 }
2646 }
2647 }
2648 });
2649 } else {
2650 if (callback != null) {
2651 callback.error(
2652 R.string.error_publish_avatar_server_reject,
2653 avatar);
2654 }
2655 }
2656 }
2657 });
2658 }
2659
2660 public void republishAvatarIfNeeded(Account account) {
2661 if (account.getAxolotlService().isPepBroken()) {
2662 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping republication of avatar because pep is broken");
2663 return;
2664 }
2665 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2666 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2667
2668 private Avatar parseAvatar(IqPacket packet) {
2669 Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub");
2670 if (pubsub != null) {
2671 Element items = pubsub.findChild("items");
2672 if (items != null) {
2673 return Avatar.parseMetadata(items);
2674 }
2675 }
2676 return null;
2677 }
2678
2679 private boolean errorIsItemNotFound(IqPacket packet) {
2680 Element error = packet.findChild("error");
2681 return packet.getType() == IqPacket.TYPE.ERROR
2682 && error != null
2683 && error.hasChild("item-not-found");
2684 }
2685
2686 @Override
2687 public void onIqPacketReceived(Account account, IqPacket packet) {
2688 if (packet.getType() == IqPacket.TYPE.RESULT || errorIsItemNotFound(packet)) {
2689 Avatar serverAvatar = parseAvatar(packet);
2690 if (serverAvatar == null && account.getAvatar() != null) {
2691 Avatar avatar = fileBackend.getStoredPepAvatar(account.getAvatar());
2692 if (avatar != null) {
2693 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": avatar on server was null. republishing");
2694 publishAvatar(account, fileBackend.getStoredPepAvatar(account.getAvatar()), null);
2695 } else {
2696 Log.e(Config.LOGTAG, account.getJid().toBareJid()+": error rereading avatar");
2697 }
2698 }
2699 }
2700 }
2701 });
2702 }
2703
2704 public void fetchAvatar(Account account, Avatar avatar) {
2705 fetchAvatar(account, avatar, null);
2706 }
2707
2708 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2709 final String KEY = generateFetchKey(account, avatar);
2710 synchronized (this.mInProgressAvatarFetches) {
2711 if (!this.mInProgressAvatarFetches.contains(KEY)) {
2712 switch (avatar.origin) {
2713 case PEP:
2714 this.mInProgressAvatarFetches.add(KEY);
2715 fetchAvatarPep(account, avatar, callback);
2716 break;
2717 case VCARD:
2718 this.mInProgressAvatarFetches.add(KEY);
2719 fetchAvatarVcard(account, avatar, callback);
2720 break;
2721 }
2722 }
2723 }
2724 }
2725
2726 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2727 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2728 sendIqPacket(account, packet, new OnIqPacketReceived() {
2729
2730 @Override
2731 public void onIqPacketReceived(Account account, IqPacket result) {
2732 synchronized (mInProgressAvatarFetches) {
2733 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2734 }
2735 final String ERROR = account.getJid().toBareJid()
2736 + ": fetching avatar for " + avatar.owner + " failed ";
2737 if (result.getType() == IqPacket.TYPE.RESULT) {
2738 avatar.image = mIqParser.avatarData(result);
2739 if (avatar.image != null) {
2740 if (getFileBackend().save(avatar)) {
2741 if (account.getJid().toBareJid().equals(avatar.owner)) {
2742 if (account.setAvatar(avatar.getFilename())) {
2743 databaseBackend.updateAccount(account);
2744 }
2745 getAvatarService().clear(account);
2746 updateConversationUi();
2747 updateAccountUi();
2748 } else {
2749 Contact contact = account.getRoster()
2750 .getContact(avatar.owner);
2751 contact.setAvatar(avatar);
2752 getAvatarService().clear(contact);
2753 updateConversationUi();
2754 updateRosterUi();
2755 }
2756 if (callback != null) {
2757 callback.success(avatar);
2758 }
2759 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2760 + ": successfully fetched pep avatar for " + avatar.owner);
2761 return;
2762 }
2763 } else {
2764
2765 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2766 }
2767 } else {
2768 Element error = result.findChild("error");
2769 if (error == null) {
2770 Log.d(Config.LOGTAG, ERROR + "(server error)");
2771 } else {
2772 Log.d(Config.LOGTAG, ERROR + error.toString());
2773 }
2774 }
2775 if (callback != null) {
2776 callback.error(0, null);
2777 }
2778
2779 }
2780 });
2781 }
2782
2783 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2784 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2785 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2786 @Override
2787 public void onIqPacketReceived(Account account, IqPacket packet) {
2788 synchronized (mInProgressAvatarFetches) {
2789 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2790 }
2791 if (packet.getType() == IqPacket.TYPE.RESULT) {
2792 Element vCard = packet.findChild("vCard", "vcard-temp");
2793 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2794 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2795 if (image != null) {
2796 avatar.image = image;
2797 if (getFileBackend().save(avatar)) {
2798 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2799 + ": successfully fetched vCard avatar for " + avatar.owner);
2800 if (avatar.owner.isBareJid()) {
2801 if (account.getJid().toBareJid().equals(avatar.owner) && account.getAvatar() == null) {
2802 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": had no avatar. replacing with vcard");
2803 account.setAvatar(avatar.getFilename());
2804 databaseBackend.updateAccount(account);
2805 getAvatarService().clear(account);
2806 updateAccountUi();
2807 } else {
2808 Contact contact = account.getRoster().getContact(avatar.owner);
2809 contact.setAvatar(avatar);
2810 getAvatarService().clear(contact);
2811 updateRosterUi();
2812 }
2813 updateConversationUi();
2814 } else {
2815 Conversation conversation = find(account, avatar.owner.toBareJid());
2816 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2817 MucOptions.User user = conversation.getMucOptions().findUserByFullJid(avatar.owner);
2818 if (user != null) {
2819 if (user.setAvatar(avatar)) {
2820 getAvatarService().clear(user);
2821 updateConversationUi();
2822 updateMucRosterUi();
2823 }
2824 }
2825 }
2826 }
2827 }
2828 }
2829 }
2830 }
2831 });
2832 }
2833
2834 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2835 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2836 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2837
2838 @Override
2839 public void onIqPacketReceived(Account account, IqPacket packet) {
2840 if (packet.getType() == IqPacket.TYPE.RESULT) {
2841 Element pubsub = packet.findChild("pubsub","http://jabber.org/protocol/pubsub");
2842 if (pubsub != null) {
2843 Element items = pubsub.findChild("items");
2844 if (items != null) {
2845 Avatar avatar = Avatar.parseMetadata(items);
2846 if (avatar != null) {
2847 avatar.owner = account.getJid().toBareJid();
2848 if (fileBackend.isAvatarCached(avatar)) {
2849 if (account.setAvatar(avatar.getFilename())) {
2850 databaseBackend.updateAccount(account);
2851 }
2852 getAvatarService().clear(account);
2853 callback.success(avatar);
2854 } else {
2855 fetchAvatarPep(account, avatar, callback);
2856 }
2857 return;
2858 }
2859 }
2860 }
2861 }
2862 callback.error(0, null);
2863 }
2864 });
2865 }
2866
2867 public void deleteContactOnServer(Contact contact) {
2868 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2869 contact.resetOption(Contact.Options.DIRTY_PUSH);
2870 contact.setOption(Contact.Options.DIRTY_DELETE);
2871 Account account = contact.getAccount();
2872 if (account.getStatus() == Account.State.ONLINE) {
2873 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2874 Element item = iq.query(Xmlns.ROSTER).addChild("item");
2875 item.setAttribute("jid", contact.getJid().toString());
2876 item.setAttribute("subscription", "remove");
2877 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2878 }
2879 }
2880
2881 public void updateConversation(final Conversation conversation) {
2882 mDatabaseExecutor.execute(new Runnable() {
2883 @Override
2884 public void run() {
2885 databaseBackend.updateConversation(conversation);
2886 }
2887 });
2888 }
2889
2890 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2891 synchronized (account) {
2892 XmppConnection connection = account.getXmppConnection();
2893 if (connection == null) {
2894 connection = createConnection(account);
2895 account.setXmppConnection(connection);
2896 } else {
2897 connection.interrupt();
2898 }
2899 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2900 if (!force) {
2901 disconnect(account, false);
2902 }
2903 Thread thread = new Thread(connection);
2904 connection.setInteractive(interactive);
2905 connection.prepareNewConnection();
2906 thread.start();
2907 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2908 } else {
2909 disconnect(account, force);
2910 account.getRoster().clearPresences();
2911 connection.resetEverything();
2912 account.getAxolotlService().resetBrokenness();
2913 }
2914 }
2915 }
2916
2917 public void reconnectAccountInBackground(final Account account) {
2918 new Thread(new Runnable() {
2919 @Override
2920 public void run() {
2921 reconnectAccount(account, false, true);
2922 }
2923 }).start();
2924 }
2925
2926 public void invite(Conversation conversation, Jid contact) {
2927 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2928 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2929 sendMessagePacket(conversation.getAccount(), packet);
2930 }
2931
2932 public void directInvite(Conversation conversation, Jid jid) {
2933 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2934 sendMessagePacket(conversation.getAccount(), packet);
2935 }
2936
2937 public void resetSendingToWaiting(Account account) {
2938 for (Conversation conversation : getConversations()) {
2939 if (conversation.getAccount() == account) {
2940 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2941
2942 @Override
2943 public void onMessageFound(Message message) {
2944 markMessage(message, Message.STATUS_WAITING);
2945 }
2946 });
2947 }
2948 }
2949 }
2950
2951 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2952 return markMessage(account, recipient, uuid, status, null);
2953 }
2954
2955 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status, String errorMessage) {
2956 if (uuid == null) {
2957 return null;
2958 }
2959 for (Conversation conversation : getConversations()) {
2960 if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2961 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2962 if (message != null) {
2963 markMessage(message, status, errorMessage);
2964 }
2965 return message;
2966 }
2967 }
2968 return null;
2969 }
2970
2971 public boolean markMessage(Conversation conversation, String uuid, int status) {
2972 if (uuid == null) {
2973 return false;
2974 } else {
2975 Message message = conversation.findSentMessageWithUuid(uuid);
2976 if (message != null) {
2977 markMessage(message, status);
2978 return true;
2979 } else {
2980 return false;
2981 }
2982 }
2983 }
2984
2985 public void markMessage(Message message, int status) {
2986 markMessage(message, status, null);
2987 }
2988
2989
2990 public void markMessage(Message message, int status, String errorMessage) {
2991 if (status == Message.STATUS_SEND_FAILED
2992 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2993 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2994 return;
2995 }
2996 message.setErrorMessage(errorMessage);
2997 message.setStatus(status);
2998 databaseBackend.updateMessage(message);
2999 updateConversationUi();
3000 }
3001
3002 public SharedPreferences getPreferences() {
3003 return PreferenceManager
3004 .getDefaultSharedPreferences(getApplicationContext());
3005 }
3006
3007 public boolean confirmMessages() {
3008 return getPreferences().getBoolean("confirm_messages", true);
3009 }
3010
3011 public boolean allowMessageCorrection() {
3012 return getPreferences().getBoolean("allow_message_correction", true);
3013 }
3014
3015 public boolean sendChatStates() {
3016 return getPreferences().getBoolean("chat_states", false);
3017 }
3018
3019 public boolean saveEncryptedMessages() {
3020 return !getPreferences().getBoolean("dont_save_encrypted", false);
3021 }
3022
3023 private boolean respectAutojoin() {
3024 return getPreferences().getBoolean("autojoin", true);
3025 }
3026
3027 public boolean indicateReceived() {
3028 return getPreferences().getBoolean("indicate_received", false);
3029 }
3030
3031 public boolean useTorToConnect() {
3032 return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
3033 }
3034
3035 public boolean showExtendedConnectionOptions() {
3036 return getPreferences().getBoolean("show_connection_options", false);
3037 }
3038
3039 public boolean broadcastLastActivity() {
3040 return getPreferences().getBoolean("last_activity", false);
3041 }
3042
3043 public int unreadCount() {
3044 int count = 0;
3045 for (Conversation conversation : getConversations()) {
3046 count += conversation.unreadCount();
3047 }
3048 return count;
3049 }
3050
3051
3052 public void showErrorToastInUi(int resId) {
3053 if (mOnShowErrorToast != null) {
3054 mOnShowErrorToast.onShowErrorToast(resId);
3055 }
3056 }
3057
3058 public void updateConversationUi() {
3059 if (mOnConversationUpdate != null) {
3060 mOnConversationUpdate.onConversationUpdate();
3061 }
3062 }
3063
3064 public void updateAccountUi() {
3065 if (mOnAccountUpdate != null) {
3066 mOnAccountUpdate.onAccountUpdate();
3067 }
3068 }
3069
3070 public void updateRosterUi() {
3071 if (mOnRosterUpdate != null) {
3072 mOnRosterUpdate.onRosterUpdate();
3073 }
3074 }
3075
3076 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
3077 if (mOnCaptchaRequested != null) {
3078 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
3079 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
3080 (int) (captcha.getHeight() * metrics.scaledDensity), false);
3081
3082 mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
3083 return true;
3084 }
3085 return false;
3086 }
3087
3088 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
3089 if (mOnUpdateBlocklist != null) {
3090 mOnUpdateBlocklist.OnUpdateBlocklist(status);
3091 }
3092 }
3093
3094 public void updateMucRosterUi() {
3095 if (mOnMucRosterUpdate != null) {
3096 mOnMucRosterUpdate.onMucRosterUpdate();
3097 }
3098 }
3099
3100 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
3101 if (mOnKeyStatusUpdated != null) {
3102 mOnKeyStatusUpdated.onKeyStatusUpdated(report);
3103 }
3104 }
3105
3106 public Account findAccountByJid(final Jid accountJid) {
3107 for (Account account : this.accounts) {
3108 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
3109 return account;
3110 }
3111 }
3112 return null;
3113 }
3114
3115 public Conversation findConversationByUuid(String uuid) {
3116 for (Conversation conversation : getConversations()) {
3117 if (conversation.getUuid().equals(uuid)) {
3118 return conversation;
3119 }
3120 }
3121 return null;
3122 }
3123
3124 public boolean markRead(final Conversation conversation) {
3125 return markRead(conversation,true);
3126 }
3127
3128 public boolean markRead(final Conversation conversation, boolean clear) {
3129 if (clear) {
3130 mNotificationService.clear(conversation);
3131 }
3132 final List<Message> readMessages = conversation.markRead();
3133 if (readMessages.size() > 0) {
3134 Runnable runnable = new Runnable() {
3135 @Override
3136 public void run() {
3137 for (Message message : readMessages) {
3138 databaseBackend.updateMessage(message);
3139 }
3140 }
3141 };
3142 mDatabaseExecutor.execute(runnable);
3143 updateUnreadCountBadge();
3144 return true;
3145 } else {
3146 return false;
3147 }
3148 }
3149
3150 public synchronized void updateUnreadCountBadge() {
3151 int count = unreadCount();
3152 if (unreadCount != count) {
3153 Log.d(Config.LOGTAG, "update unread count to " + count);
3154 if (count > 0) {
3155 ShortcutBadger.applyCount(getApplicationContext(), count);
3156 } else {
3157 ShortcutBadger.removeCount(getApplicationContext());
3158 }
3159 unreadCount = count;
3160 }
3161 }
3162
3163 public void sendReadMarker(final Conversation conversation) {
3164 final Message markable = conversation.getLatestMarkableMessage();
3165 if (this.markRead(conversation)) {
3166 updateConversationUi();
3167 }
3168 if (confirmMessages()
3169 && markable != null
3170 && markable.trusted()
3171 && markable.getRemoteMsgId() != null) {
3172 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
3173 Account account = conversation.getAccount();
3174 final Jid to = markable.getCounterpart();
3175 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
3176 this.sendMessagePacket(conversation.getAccount(), packet);
3177 }
3178 }
3179
3180 public SecureRandom getRNG() {
3181 return this.mRandom;
3182 }
3183
3184 public MemorizingTrustManager getMemorizingTrustManager() {
3185 return this.mMemorizingTrustManager;
3186 }
3187
3188 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
3189 this.mMemorizingTrustManager = trustManager;
3190 }
3191
3192 public void updateMemorizingTrustmanager() {
3193 final MemorizingTrustManager tm;
3194 final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
3195 if (dontTrustSystemCAs) {
3196 tm = new MemorizingTrustManager(getApplicationContext(), null);
3197 } else {
3198 tm = new MemorizingTrustManager(getApplicationContext());
3199 }
3200 setMemorizingTrustManager(tm);
3201 }
3202
3203 public PowerManager getPowerManager() {
3204 return this.pm;
3205 }
3206
3207 public LruCache<String, Bitmap> getBitmapCache() {
3208 return this.mBitmapCache;
3209 }
3210
3211 public void syncRosterToDisk(final Account account) {
3212 Runnable runnable = new Runnable() {
3213
3214 @Override
3215 public void run() {
3216 databaseBackend.writeRoster(account.getRoster());
3217 }
3218 };
3219 mDatabaseExecutor.execute(runnable);
3220
3221 }
3222
3223 public List<String> getKnownHosts() {
3224 final List<String> hosts = new ArrayList<>();
3225 for (final Account account : getAccounts()) {
3226 if (!hosts.contains(account.getServer().toString())) {
3227 hosts.add(account.getServer().toString());
3228 }
3229 for (final Contact contact : account.getRoster().getContacts()) {
3230 if (contact.showInRoster()) {
3231 final String server = contact.getServer().toString();
3232 if (server != null && !hosts.contains(server)) {
3233 hosts.add(server);
3234 }
3235 }
3236 }
3237 }
3238 if(Config.DOMAIN_LOCK != null && !hosts.contains(Config.DOMAIN_LOCK)) {
3239 hosts.add(Config.DOMAIN_LOCK);
3240 }
3241 if(Config.MAGIC_CREATE_DOMAIN != null && !hosts.contains(Config.MAGIC_CREATE_DOMAIN)) {
3242 hosts.add(Config.MAGIC_CREATE_DOMAIN);
3243 }
3244 return hosts;
3245 }
3246
3247 public List<String> getKnownConferenceHosts() {
3248 final ArrayList<String> mucServers = new ArrayList<>();
3249 for (final Account account : accounts) {
3250 if (account.getXmppConnection() != null) {
3251 final String server = account.getXmppConnection().getMucServer();
3252 if (server != null && !mucServers.contains(server)) {
3253 mucServers.add(server);
3254 }
3255 }
3256 }
3257 return mucServers;
3258 }
3259
3260 public void sendMessagePacket(Account account, MessagePacket packet) {
3261 XmppConnection connection = account.getXmppConnection();
3262 if (connection != null) {
3263 connection.sendMessagePacket(packet);
3264 }
3265 }
3266
3267 public void sendPresencePacket(Account account, PresencePacket packet) {
3268 XmppConnection connection = account.getXmppConnection();
3269 if (connection != null) {
3270 connection.sendPresencePacket(packet);
3271 }
3272 }
3273
3274 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
3275 final XmppConnection connection = account.getXmppConnection();
3276 if (connection != null) {
3277 IqPacket request = mIqGenerator.generateCreateAccountWithCaptcha(account, id, data);
3278 connection.sendUnmodifiedIqPacket(request, connection.registrationResponseListener);
3279 }
3280 }
3281
3282 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
3283 final XmppConnection connection = account.getXmppConnection();
3284 if (connection != null) {
3285 connection.sendIqPacket(packet, callback);
3286 }
3287 }
3288
3289 public void sendPresence(final Account account) {
3290 sendPresence(account, checkListeners() && broadcastLastActivity());
3291 }
3292
3293 private void sendPresence(final Account account, final boolean includeIdleTimestamp) {
3294 PresencePacket packet;
3295 if (manuallyChangePresence()) {
3296 packet = mPresenceGenerator.selfPresence(account, account.getPresenceStatus());
3297 String message = account.getPresenceStatusMessage();
3298 if (message != null && !message.isEmpty()) {
3299 packet.addChild(new Element("status").setContent(message));
3300 }
3301 } else {
3302 packet = mPresenceGenerator.selfPresence(account, getTargetPresence());
3303 }
3304 if (mLastActivity > 0 && includeIdleTimestamp) {
3305 long since = Math.min(mLastActivity, System.currentTimeMillis()); //don't send future dates
3306 packet.addChild("idle","urn:xmpp:idle:1").setAttribute("since", AbstractGenerator.getTimestamp(since));
3307 }
3308 sendPresencePacket(account, packet);
3309 }
3310
3311 private void deactivateGracePeriod() {
3312 for(Account account : getAccounts()) {
3313 account.deactivateGracePeriod();
3314 }
3315 }
3316
3317 public void refreshAllPresences() {
3318 boolean includeIdleTimestamp = checkListeners() && broadcastLastActivity();
3319 for (Account account : getAccounts()) {
3320 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3321 sendPresence(account, includeIdleTimestamp);
3322 }
3323 }
3324 }
3325
3326 private void refreshAllGcmTokens() {
3327 for(Account account : getAccounts()) {
3328 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
3329 mPushManagementService.registerPushTokenOnServer(account);
3330 }
3331 }
3332 }
3333
3334 private void sendOfflinePresence(final Account account) {
3335 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending offline presence");
3336 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
3337 }
3338
3339 public MessageGenerator getMessageGenerator() {
3340 return this.mMessageGenerator;
3341 }
3342
3343 public PresenceGenerator getPresenceGenerator() {
3344 return this.mPresenceGenerator;
3345 }
3346
3347 public IqGenerator getIqGenerator() {
3348 return this.mIqGenerator;
3349 }
3350
3351 public IqParser getIqParser() {
3352 return this.mIqParser;
3353 }
3354
3355 public JingleConnectionManager getJingleConnectionManager() {
3356 return this.mJingleConnectionManager;
3357 }
3358
3359 public MessageArchiveService getMessageArchiveService() {
3360 return this.mMessageArchiveService;
3361 }
3362
3363 public List<Contact> findContacts(Jid jid) {
3364 ArrayList<Contact> contacts = new ArrayList<>();
3365 for (Account account : getAccounts()) {
3366 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
3367 Contact contact = account.getRoster().getContactFromRoster(jid);
3368 if (contact != null) {
3369 contacts.add(contact);
3370 }
3371 }
3372 }
3373 return contacts;
3374 }
3375
3376 public Conversation findFirstMuc(Jid jid) {
3377 for(Conversation conversation : getConversations()) {
3378 if (conversation.getJid().toBareJid().equals(jid.toBareJid())
3379 && conversation.getMode() == Conversation.MODE_MULTI) {
3380 return conversation;
3381 }
3382 }
3383 return null;
3384 }
3385
3386 public NotificationService getNotificationService() {
3387 return this.mNotificationService;
3388 }
3389
3390 public HttpConnectionManager getHttpConnectionManager() {
3391 return this.mHttpConnectionManager;
3392 }
3393
3394 public void resendFailedMessages(final Message message) {
3395 final Collection<Message> messages = new ArrayList<>();
3396 Message current = message;
3397 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
3398 messages.add(current);
3399 if (current.mergeable(current.next())) {
3400 current = current.next();
3401 } else {
3402 break;
3403 }
3404 }
3405 for (final Message msg : messages) {
3406 msg.setTime(System.currentTimeMillis());
3407 markMessage(msg, Message.STATUS_WAITING);
3408 this.resendMessage(msg, false);
3409 }
3410 }
3411
3412 public void clearConversationHistory(final Conversation conversation) {
3413 conversation.clearMessages();
3414 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
3415 conversation.setLastClearHistory(System.currentTimeMillis());
3416 Runnable runnable = new Runnable() {
3417 @Override
3418 public void run() {
3419 databaseBackend.deleteMessagesInConversation(conversation);
3420 databaseBackend.updateConversation(conversation);
3421 }
3422 };
3423 mDatabaseExecutor.execute(runnable);
3424 }
3425
3426 public void sendBlockRequest(final Blockable blockable, boolean reportSpam) {
3427 if (blockable != null && blockable.getBlockedJid() != null) {
3428 final Jid jid = blockable.getBlockedJid();
3429 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid, reportSpam), new OnIqPacketReceived() {
3430
3431 @Override
3432 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3433 if (packet.getType() == IqPacket.TYPE.RESULT) {
3434 account.getBlocklist().add(jid);
3435 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
3436 }
3437 }
3438 });
3439 }
3440 }
3441
3442 public void sendUnblockRequest(final Blockable blockable) {
3443 if (blockable != null && blockable.getJid() != null) {
3444 final Jid jid = blockable.getBlockedJid();
3445 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3446 @Override
3447 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3448 if (packet.getType() == IqPacket.TYPE.RESULT) {
3449 account.getBlocklist().remove(jid);
3450 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3451 }
3452 }
3453 });
3454 }
3455 }
3456
3457 public void publishDisplayName(Account account) {
3458 String displayName = account.getDisplayName();
3459 if (displayName != null && !displayName.isEmpty()) {
3460 IqPacket publish = mIqGenerator.publishNick(displayName);
3461 sendIqPacket(account, publish, new OnIqPacketReceived() {
3462 @Override
3463 public void onIqPacketReceived(Account account, IqPacket packet) {
3464 if (packet.getType() == IqPacket.TYPE.ERROR) {
3465 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3466 }
3467 }
3468 });
3469 }
3470 }
3471
3472 public ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String, String> key) {
3473 ServiceDiscoveryResult result = discoCache.get(key);
3474 if (result != null) {
3475 return result;
3476 } else {
3477 result = databaseBackend.findDiscoveryResult(key.first, key.second);
3478 if (result != null) {
3479 discoCache.put(key, result);
3480 }
3481 return result;
3482 }
3483 }
3484
3485 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3486 final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3487 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3488 if (disco != null) {
3489 presence.setServiceDiscoveryResult(disco);
3490 } else {
3491 if (!account.inProgressDiscoFetches.contains(key)) {
3492 account.inProgressDiscoFetches.add(key);
3493 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3494 request.setTo(jid);
3495 request.query("http://jabber.org/protocol/disco#info");
3496 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3497 sendIqPacket(account, request, new OnIqPacketReceived() {
3498 @Override
3499 public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3500 if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3501 ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3502 if (presence.getVer().equals(disco.getVer())) {
3503 databaseBackend.insertDiscoveryResult(disco);
3504 injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3505 } else {
3506 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3507 }
3508 }
3509 account.inProgressDiscoFetches.remove(key);
3510 }
3511 });
3512 }
3513 }
3514 }
3515
3516 private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3517 for(Contact contact : roster.getContacts()) {
3518 for(Presence presence : contact.getPresences().getPresences().values()) {
3519 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3520 presence.setServiceDiscoveryResult(disco);
3521 }
3522 }
3523 }
3524 }
3525
3526 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3527 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3528 request.addChild("prefs","urn:xmpp:mam:0");
3529 sendIqPacket(account, request, new OnIqPacketReceived() {
3530 @Override
3531 public void onIqPacketReceived(Account account, IqPacket packet) {
3532 Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3533 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3534 callback.onPreferencesFetched(prefs);
3535 } else {
3536 callback.onPreferencesFetchFailed();
3537 }
3538 }
3539 });
3540 }
3541
3542 public PushManagementService getPushManagementService() {
3543 return mPushManagementService;
3544 }
3545
3546 public Account getPendingAccount() {
3547 Account pending = null;
3548 for(Account account : getAccounts()) {
3549 if (account.isOptionSet(Account.OPTION_REGISTER)) {
3550 pending = account;
3551 } else {
3552 return null;
3553 }
3554 }
3555 return pending;
3556 }
3557
3558 public void changeStatus(Account account, Presence.Status status, String statusMessage, boolean send) {
3559 if (!statusMessage.isEmpty()) {
3560 databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3561 }
3562 changeStatusReal(account, status, statusMessage, send);
3563 }
3564
3565 private void changeStatusReal(Account account, Presence.Status status, String statusMessage, boolean send) {
3566 account.setPresenceStatus(status);
3567 account.setPresenceStatusMessage(statusMessage);
3568 databaseBackend.updateAccount(account);
3569 if (!account.isOptionSet(Account.OPTION_DISABLED) && send) {
3570 sendPresence(account);
3571 }
3572 }
3573
3574 public void changeStatus(Presence.Status status, String statusMessage) {
3575 if (!statusMessage.isEmpty()) {
3576 databaseBackend.insertPresenceTemplate(new PresenceTemplate(status, statusMessage));
3577 }
3578 for(Account account : getAccounts()) {
3579 changeStatusReal(account, status, statusMessage, true);
3580 }
3581 }
3582
3583 public List<PresenceTemplate> getPresenceTemplates(Account account) {
3584 List<PresenceTemplate> templates = databaseBackend.getPresenceTemplates();
3585 for(PresenceTemplate template : account.getSelfContact().getPresences().asTemplates()) {
3586 if (!templates.contains(template)) {
3587 templates.add(0, template);
3588 }
3589 }
3590 return templates;
3591 }
3592
3593 public void saveConversationAsBookmark(Conversation conversation, String name) {
3594 Account account = conversation.getAccount();
3595 Bookmark bookmark = new Bookmark(account, conversation.getJid().toBareJid());
3596 if (!conversation.getJid().isBareJid()) {
3597 bookmark.setNick(conversation.getJid().getResourcepart());
3598 }
3599 if (name != null && !name.trim().isEmpty()) {
3600 bookmark.setBookmarkName(name.trim());
3601 }
3602 bookmark.setAutojoin(getPreferences().getBoolean("autojoin",true));
3603 account.getBookmarks().add(bookmark);
3604 pushBookmarks(account);
3605 conversation.setBookmark(bookmark);
3606 }
3607
3608 public void clearStartTimeCounter() {
3609 mDatabaseExecutor.execute(new Runnable() {
3610 @Override
3611 public void run() {
3612 databaseBackend.clearStartTimeCounter();
3613 }
3614 });
3615 }
3616
3617 public interface OnMamPreferencesFetched {
3618 void onPreferencesFetched(Element prefs);
3619 void onPreferencesFetchFailed();
3620 }
3621
3622 public void pushMamPreferences(Account account, Element prefs) {
3623 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3624 set.addChild(prefs);
3625 sendIqPacket(account, set, null);
3626 }
3627
3628 public interface OnAccountCreated {
3629 void onAccountCreated(Account account);
3630
3631 void informUser(int r);
3632 }
3633
3634 public interface OnMoreMessagesLoaded {
3635 void onMoreMessagesLoaded(int count, Conversation conversation);
3636
3637 void informUser(int r);
3638 }
3639
3640 public interface OnAccountPasswordChanged {
3641 void onPasswordChangeSucceeded();
3642
3643 void onPasswordChangeFailed();
3644 }
3645
3646 public interface OnAffiliationChanged {
3647 void onAffiliationChangedSuccessful(Jid jid);
3648
3649 void onAffiliationChangeFailed(Jid jid, int resId);
3650 }
3651
3652 public interface OnRoleChanged {
3653 void onRoleChangedSuccessful(String nick);
3654
3655 void onRoleChangeFailed(String nick, int resid);
3656 }
3657
3658 public interface OnConversationUpdate {
3659 void onConversationUpdate();
3660 }
3661
3662 public interface OnAccountUpdate {
3663 void onAccountUpdate();
3664 }
3665
3666 public interface OnCaptchaRequested {
3667 void onCaptchaRequested(Account account,
3668 String id,
3669 Data data,
3670 Bitmap captcha);
3671 }
3672
3673 public interface OnRosterUpdate {
3674 void onRosterUpdate();
3675 }
3676
3677 public interface OnMucRosterUpdate {
3678 void onMucRosterUpdate();
3679 }
3680
3681 public interface OnConferenceConfigurationFetched {
3682 void onConferenceConfigurationFetched(Conversation conversation);
3683
3684 void onFetchFailed(Conversation conversation, Element error);
3685 }
3686
3687 public interface OnConferenceJoined {
3688 void onConferenceJoined(Conversation conversation);
3689 }
3690
3691 public interface OnConferenceOptionsPushed {
3692 void onPushSucceeded();
3693
3694 void onPushFailed();
3695 }
3696
3697 public interface OnShowErrorToast {
3698 void onShowErrorToast(int resId);
3699 }
3700
3701 public class XmppConnectionBinder extends Binder {
3702 public XmppConnectionService getService() {
3703 return XmppConnectionService.this;
3704 }
3705 }
3706}