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