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