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