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
1828 } else {
1829 account.pendingConferenceJoins.add(conversation);
1830 }
1831 }
1832
1833 public void providePasswordForMuc(Conversation conversation, String password) {
1834 if (conversation.getMode() == Conversation.MODE_MULTI) {
1835 conversation.getMucOptions().setPassword(password);
1836 if (conversation.getBookmark() != null) {
1837 if (respectAutojoin()) {
1838 conversation.getBookmark().setAutojoin(true);
1839 }
1840 pushBookmarks(conversation.getAccount());
1841 }
1842 databaseBackend.updateConversation(conversation);
1843 joinMuc(conversation);
1844 }
1845 }
1846
1847 public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1848 final MucOptions options = conversation.getMucOptions();
1849 final Jid joinJid = options.createJoinJid(nick);
1850 if (options.online()) {
1851 Account account = conversation.getAccount();
1852 options.setOnRenameListener(new OnRenameListener() {
1853
1854 @Override
1855 public void onSuccess() {
1856 conversation.setContactJid(joinJid);
1857 databaseBackend.updateConversation(conversation);
1858 Bookmark bookmark = conversation.getBookmark();
1859 if (bookmark != null) {
1860 bookmark.setNick(nick);
1861 pushBookmarks(bookmark.getAccount());
1862 }
1863 callback.success(conversation);
1864 }
1865
1866 @Override
1867 public void onFailure() {
1868 callback.error(R.string.nick_in_use, conversation);
1869 }
1870 });
1871
1872 PresencePacket packet = new PresencePacket();
1873 packet.setTo(joinJid);
1874 packet.setFrom(conversation.getAccount().getJid());
1875
1876 String sig = account.getPgpSignature();
1877 if (sig != null) {
1878 packet.addChild("status").setContent("online");
1879 packet.addChild("x", "jabber:x:signed").setContent(sig);
1880 }
1881 sendPresencePacket(account, packet);
1882 } else {
1883 conversation.setContactJid(joinJid);
1884 databaseBackend.updateConversation(conversation);
1885 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1886 Bookmark bookmark = conversation.getBookmark();
1887 if (bookmark != null) {
1888 bookmark.setNick(nick);
1889 pushBookmarks(bookmark.getAccount());
1890 }
1891 joinMuc(conversation);
1892 }
1893 }
1894 }
1895
1896 public void leaveMuc(Conversation conversation) {
1897 leaveMuc(conversation, false);
1898 }
1899
1900 private void leaveMuc(Conversation conversation, boolean now) {
1901 Account account = conversation.getAccount();
1902 account.pendingConferenceJoins.remove(conversation);
1903 account.pendingConferenceLeaves.remove(conversation);
1904 if (account.getStatus() == Account.State.ONLINE || now) {
1905 PresencePacket packet = new PresencePacket();
1906 packet.setTo(conversation.getJid());
1907 packet.setFrom(conversation.getAccount().getJid());
1908 packet.setAttribute("type", "unavailable");
1909 sendPresencePacket(conversation.getAccount(), packet);
1910 conversation.getMucOptions().setOffline();
1911 conversation.deregisterWithBookmark();
1912 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1913 + ": leaving muc " + conversation.getJid());
1914 } else {
1915 account.pendingConferenceLeaves.add(conversation);
1916 }
1917 }
1918
1919 private String findConferenceServer(final Account account) {
1920 String server;
1921 if (account.getXmppConnection() != null) {
1922 server = account.getXmppConnection().getMucServer();
1923 if (server != null) {
1924 return server;
1925 }
1926 }
1927 for (Account other : getAccounts()) {
1928 if (other != account && other.getXmppConnection() != null) {
1929 server = other.getXmppConnection().getMucServer();
1930 if (server != null) {
1931 return server;
1932 }
1933 }
1934 }
1935 return null;
1936 }
1937
1938 public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1939 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1940 if (account.getStatus() == Account.State.ONLINE) {
1941 try {
1942 String server = findConferenceServer(account);
1943 if (server == null) {
1944 if (callback != null) {
1945 callback.error(R.string.no_conference_server_found, null);
1946 }
1947 return;
1948 }
1949 String name = new BigInteger(75, getRNG()).toString(32);
1950 Jid jid = Jid.fromParts(name, server, null);
1951 final Conversation conversation = findOrCreateConversation(account, jid, true);
1952 joinMuc(conversation, new OnConferenceJoined() {
1953 @Override
1954 public void onConferenceJoined(final Conversation conversation) {
1955 Bundle options = new Bundle();
1956 options.putString("muc#roomconfig_persistentroom", "1");
1957 options.putString("muc#roomconfig_membersonly", "1");
1958 options.putString("muc#roomconfig_publicroom", "0");
1959 options.putString("muc#roomconfig_whois", "anyone");
1960 pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1961 @Override
1962 public void onPushSucceeded() {
1963 for (Jid invite : jids) {
1964 invite(conversation, invite);
1965 }
1966 if (account.countPresences() > 1) {
1967 directInvite(conversation, account.getJid().toBareJid());
1968 }
1969 if (callback != null) {
1970 callback.success(conversation);
1971 }
1972 }
1973
1974 @Override
1975 public void onPushFailed() {
1976 if (callback != null) {
1977 callback.error(R.string.conference_creation_failed, conversation);
1978 }
1979 }
1980 });
1981 }
1982 });
1983 } catch (InvalidJidException e) {
1984 if (callback != null) {
1985 callback.error(R.string.conference_creation_failed, null);
1986 }
1987 }
1988 } else {
1989 if (callback != null) {
1990 callback.error(R.string.not_connected_try_again, null);
1991 }
1992 }
1993 }
1994
1995 public void fetchConferenceConfiguration(final Conversation conversation) {
1996 fetchConferenceConfiguration(conversation, null);
1997 }
1998
1999 public void fetchConferenceConfiguration(final Conversation conversation, final OnConferenceConfigurationFetched callback) {
2000 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2001 request.setTo(conversation.getJid().toBareJid());
2002 request.query("http://jabber.org/protocol/disco#info");
2003 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2004 @Override
2005 public void onIqPacketReceived(Account account, IqPacket packet) {
2006 if (packet.getType() == IqPacket.TYPE.RESULT) {
2007 ArrayList<String> features = new ArrayList<>();
2008 Element query = packet.query();
2009 for (Element child : query.getChildren()) {
2010 if (child != null && child.getName().equals("feature")) {
2011 String var = child.getAttribute("var");
2012 if (var != null) {
2013 features.add(var);
2014 }
2015 }
2016 }
2017 Element form = query.findChild("x", "jabber:x:data");
2018 if (form != null) {
2019 conversation.getMucOptions().updateFormData(Data.parse(form));
2020 }
2021 conversation.getMucOptions().updateFeatures(features);
2022 if (callback != null) {
2023 callback.onConferenceConfigurationFetched(conversation);
2024 }
2025 updateConversationUi();
2026 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2027 if (callback != null) {
2028 callback.onFetchFailed(conversation, packet.getError());
2029 }
2030 }
2031 }
2032 });
2033 }
2034
2035 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
2036 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2037 request.setTo(conversation.getJid().toBareJid());
2038 request.query("http://jabber.org/protocol/muc#owner");
2039 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
2040 @Override
2041 public void onIqPacketReceived(Account account, IqPacket packet) {
2042 if (packet.getType() == IqPacket.TYPE.RESULT) {
2043 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
2044 for (Field field : data.getFields()) {
2045 if (options.containsKey(field.getFieldName())) {
2046 field.setValue(options.getString(field.getFieldName()));
2047 }
2048 }
2049 data.submit();
2050 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
2051 set.setTo(conversation.getJid().toBareJid());
2052 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
2053 sendIqPacket(account, set, new OnIqPacketReceived() {
2054 @Override
2055 public void onIqPacketReceived(Account account, IqPacket packet) {
2056 if (callback != null) {
2057 if (packet.getType() == IqPacket.TYPE.RESULT) {
2058 callback.onPushSucceeded();
2059 } else {
2060 callback.onPushFailed();
2061 }
2062 }
2063 }
2064 });
2065 } else {
2066 if (callback != null) {
2067 callback.onPushFailed();
2068 }
2069 }
2070 }
2071 });
2072 }
2073
2074 public void pushSubjectToConference(final Conversation conference, final String subject) {
2075 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
2076 this.sendMessagePacket(conference.getAccount(), packet);
2077 final MucOptions mucOptions = conference.getMucOptions();
2078 final MucOptions.User self = mucOptions.getSelf();
2079 if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
2080 Bundle options = new Bundle();
2081 options.putString("muc#roomconfig_persistentroom", "1");
2082 this.pushConferenceConfiguration(conference, options, null);
2083 }
2084 }
2085
2086 public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
2087 final Jid jid = user.toBareJid();
2088 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
2089 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2090 @Override
2091 public void onIqPacketReceived(Account account, IqPacket packet) {
2092 if (packet.getType() == IqPacket.TYPE.RESULT) {
2093 callback.onAffiliationChangedSuccessful(jid);
2094 } else {
2095 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
2096 }
2097 }
2098 });
2099 }
2100
2101 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
2102 List<Jid> jids = new ArrayList<>();
2103 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
2104 if (user.getAffiliation() == before && user.getJid() != null) {
2105 jids.add(user.getJid());
2106 }
2107 }
2108 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
2109 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
2110 }
2111
2112 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
2113 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
2114 Log.d(Config.LOGTAG, request.toString());
2115 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
2116 @Override
2117 public void onIqPacketReceived(Account account, IqPacket packet) {
2118 Log.d(Config.LOGTAG, packet.toString());
2119 if (packet.getType() == IqPacket.TYPE.RESULT) {
2120 callback.onRoleChangedSuccessful(nick);
2121 } else {
2122 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
2123 }
2124 }
2125 });
2126 }
2127
2128 private void disconnect(Account account, boolean force) {
2129 if ((account.getStatus() == Account.State.ONLINE)
2130 || (account.getStatus() == Account.State.DISABLED)) {
2131 if (!force) {
2132 List<Conversation> conversations = getConversations();
2133 for (Conversation conversation : conversations) {
2134 if (conversation.getAccount() == account) {
2135 if (conversation.getMode() == Conversation.MODE_MULTI) {
2136 leaveMuc(conversation, true);
2137 } else {
2138 if (conversation.endOtrIfNeeded()) {
2139 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2140 + ": ended otr session with "
2141 + conversation.getJid());
2142 }
2143 }
2144 }
2145 }
2146 sendOfflinePresence(account);
2147 }
2148 account.getXmppConnection().disconnect(force);
2149 }
2150 }
2151
2152 @Override
2153 public IBinder onBind(Intent intent) {
2154 return mBinder;
2155 }
2156
2157 public void updateMessage(Message message) {
2158 databaseBackend.updateMessage(message);
2159 updateConversationUi();
2160 }
2161
2162 public void updateMessage(Message message, String uuid) {
2163 databaseBackend.updateMessage(message, uuid);
2164 updateConversationUi();
2165 }
2166
2167 protected void syncDirtyContacts(Account account) {
2168 for (Contact contact : account.getRoster().getContacts()) {
2169 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
2170 pushContactToServer(contact);
2171 }
2172 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
2173 deleteContactOnServer(contact);
2174 }
2175 }
2176 }
2177
2178 public void createContact(Contact contact) {
2179 boolean autoGrant = getPreferences().getBoolean("grant_new_contacts", true);
2180 if (autoGrant) {
2181 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
2182 contact.setOption(Contact.Options.ASKING);
2183 }
2184 pushContactToServer(contact);
2185 }
2186
2187 public void onOtrSessionEstablished(Conversation conversation) {
2188 final Account account = conversation.getAccount();
2189 final Session otrSession = conversation.getOtrSession();
2190 Log.d(Config.LOGTAG,
2191 account.getJid().toBareJid() + " otr session established with "
2192 + conversation.getJid() + "/"
2193 + otrSession.getSessionID().getUserID());
2194 conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() {
2195
2196 @Override
2197 public void onMessageFound(Message message) {
2198 SessionID id = otrSession.getSessionID();
2199 try {
2200 message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
2201 } catch (InvalidJidException e) {
2202 return;
2203 }
2204 if (message.needsUploading()) {
2205 mJingleConnectionManager.createNewConnection(message);
2206 } else {
2207 MessagePacket outPacket = mMessageGenerator.generateOtrChat(message);
2208 if (outPacket != null) {
2209 mMessageGenerator.addDelay(outPacket, message.getTimeSent());
2210 message.setStatus(Message.STATUS_SEND);
2211 databaseBackend.updateMessage(message);
2212 sendMessagePacket(account, outPacket);
2213 }
2214 }
2215 updateConversationUi();
2216 }
2217 });
2218 }
2219
2220 public boolean renewSymmetricKey(Conversation conversation) {
2221 Account account = conversation.getAccount();
2222 byte[] symmetricKey = new byte[32];
2223 this.mRandom.nextBytes(symmetricKey);
2224 Session otrSession = conversation.getOtrSession();
2225 if (otrSession != null) {
2226 MessagePacket packet = new MessagePacket();
2227 packet.setType(MessagePacket.TYPE_CHAT);
2228 packet.setFrom(account.getJid());
2229 MessageGenerator.addMessageHints(packet);
2230 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
2231 + otrSession.getSessionID().getUserID());
2232 try {
2233 packet.setBody(otrSession
2234 .transformSending(CryptoHelper.FILETRANSFER
2235 + CryptoHelper.bytesToHex(symmetricKey))[0]);
2236 sendMessagePacket(account, packet);
2237 conversation.setSymmetricKey(symmetricKey);
2238 return true;
2239 } catch (OtrException e) {
2240 return false;
2241 }
2242 }
2243 return false;
2244 }
2245
2246 public void pushContactToServer(final Contact contact) {
2247 contact.resetOption(Contact.Options.DIRTY_DELETE);
2248 contact.setOption(Contact.Options.DIRTY_PUSH);
2249 final Account account = contact.getAccount();
2250 if (account.getStatus() == Account.State.ONLINE) {
2251 final boolean ask = contact.getOption(Contact.Options.ASKING);
2252 final boolean sendUpdates = contact
2253 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
2254 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
2255 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2256 iq.query(Xmlns.ROSTER).addChild(contact.asElement());
2257 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2258 if (sendUpdates) {
2259 sendPresencePacket(account,
2260 mPresenceGenerator.sendPresenceUpdatesTo(contact));
2261 }
2262 if (ask) {
2263 sendPresencePacket(account,
2264 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
2265 }
2266 }
2267 }
2268
2269 public void publishAvatar(final Account account,
2270 final Uri image,
2271 final UiCallback<Avatar> callback) {
2272 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
2273 final int size = Config.AVATAR_SIZE;
2274 final Avatar avatar = getFileBackend().getPepAvatar(image, size, format);
2275 if (avatar != null) {
2276 avatar.height = size;
2277 avatar.width = size;
2278 if (format.equals(Bitmap.CompressFormat.WEBP)) {
2279 avatar.type = "image/webp";
2280 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
2281 avatar.type = "image/jpeg";
2282 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
2283 avatar.type = "image/png";
2284 }
2285 if (!getFileBackend().save(avatar)) {
2286 callback.error(R.string.error_saving_avatar, avatar);
2287 return;
2288 }
2289 final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
2290 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2291
2292 @Override
2293 public void onIqPacketReceived(Account account, IqPacket result) {
2294 if (result.getType() == IqPacket.TYPE.RESULT) {
2295 final IqPacket packet = XmppConnectionService.this.mIqGenerator
2296 .publishAvatarMetadata(avatar);
2297 sendIqPacket(account, packet, new OnIqPacketReceived() {
2298 @Override
2299 public void onIqPacketReceived(Account account, IqPacket result) {
2300 if (result.getType() == IqPacket.TYPE.RESULT) {
2301 if (account.setAvatar(avatar.getFilename())) {
2302 getAvatarService().clear(account);
2303 databaseBackend.updateAccount(account);
2304 }
2305 callback.success(avatar);
2306 } else {
2307 callback.error(
2308 R.string.error_publish_avatar_server_reject,
2309 avatar);
2310 }
2311 }
2312 });
2313 } else {
2314 callback.error(
2315 R.string.error_publish_avatar_server_reject,
2316 avatar);
2317 }
2318 }
2319 });
2320 } else {
2321 callback.error(R.string.error_publish_avatar_converting, null);
2322 }
2323 }
2324
2325 public void fetchAvatar(Account account, Avatar avatar) {
2326 fetchAvatar(account, avatar, null);
2327 }
2328
2329 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2330 final String KEY = generateFetchKey(account, avatar);
2331 synchronized (this.mInProgressAvatarFetches) {
2332 if (this.mInProgressAvatarFetches.contains(KEY)) {
2333 return;
2334 } else {
2335 switch (avatar.origin) {
2336 case PEP:
2337 this.mInProgressAvatarFetches.add(KEY);
2338 fetchAvatarPep(account, avatar, callback);
2339 break;
2340 case VCARD:
2341 this.mInProgressAvatarFetches.add(KEY);
2342 fetchAvatarVcard(account, avatar, callback);
2343 break;
2344 }
2345 }
2346 }
2347 }
2348
2349 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2350 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
2351 sendIqPacket(account, packet, new OnIqPacketReceived() {
2352
2353 @Override
2354 public void onIqPacketReceived(Account account, IqPacket result) {
2355 synchronized (mInProgressAvatarFetches) {
2356 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2357 }
2358 final String ERROR = account.getJid().toBareJid()
2359 + ": fetching avatar for " + avatar.owner + " failed ";
2360 if (result.getType() == IqPacket.TYPE.RESULT) {
2361 avatar.image = mIqParser.avatarData(result);
2362 if (avatar.image != null) {
2363 if (getFileBackend().save(avatar)) {
2364 if (account.getJid().toBareJid().equals(avatar.owner)) {
2365 if (account.setAvatar(avatar.getFilename())) {
2366 databaseBackend.updateAccount(account);
2367 }
2368 getAvatarService().clear(account);
2369 updateConversationUi();
2370 updateAccountUi();
2371 } else {
2372 Contact contact = account.getRoster()
2373 .getContact(avatar.owner);
2374 contact.setAvatar(avatar);
2375 getAvatarService().clear(contact);
2376 updateConversationUi();
2377 updateRosterUi();
2378 }
2379 if (callback != null) {
2380 callback.success(avatar);
2381 }
2382 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2383 + ": succesfuly fetched pep avatar for " + avatar.owner);
2384 return;
2385 }
2386 } else {
2387
2388 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2389 }
2390 } else {
2391 Element error = result.findChild("error");
2392 if (error == null) {
2393 Log.d(Config.LOGTAG, ERROR + "(server error)");
2394 } else {
2395 Log.d(Config.LOGTAG, ERROR + error.toString());
2396 }
2397 }
2398 if (callback != null) {
2399 callback.error(0, null);
2400 }
2401
2402 }
2403 });
2404 }
2405
2406 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2407 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2408 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2409 @Override
2410 public void onIqPacketReceived(Account account, IqPacket packet) {
2411 synchronized (mInProgressAvatarFetches) {
2412 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2413 }
2414 if (packet.getType() == IqPacket.TYPE.RESULT) {
2415 Element vCard = packet.findChild("vCard", "vcard-temp");
2416 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2417 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2418 if (image != null) {
2419 avatar.image = image;
2420 if (getFileBackend().save(avatar)) {
2421 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2422 + ": successfully fetched vCard avatar for " + avatar.owner);
2423 if (avatar.owner.isBareJid()) {
2424 Contact contact = account.getRoster()
2425 .getContact(avatar.owner);
2426 contact.setAvatar(avatar);
2427 getAvatarService().clear(contact);
2428 updateConversationUi();
2429 updateRosterUi();
2430 } else {
2431 Conversation conversation = find(account, avatar.owner.toBareJid());
2432 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
2433 MucOptions.User user = conversation.getMucOptions().findUser(avatar.owner.getResourcepart());
2434 if (user != null) {
2435 if (user.setAvatar(avatar)) {
2436 getAvatarService().clear(user);
2437 updateConversationUi();
2438 updateMucRosterUi();
2439 }
2440 }
2441 }
2442 }
2443 }
2444 }
2445 }
2446 }
2447 });
2448 }
2449
2450 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2451 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2452 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2453
2454 @Override
2455 public void onIqPacketReceived(Account account, IqPacket packet) {
2456 if (packet.getType() == IqPacket.TYPE.RESULT) {
2457 Element pubsub = packet.findChild("pubsub",
2458 "http://jabber.org/protocol/pubsub");
2459 if (pubsub != null) {
2460 Element items = pubsub.findChild("items");
2461 if (items != null) {
2462 Avatar avatar = Avatar.parseMetadata(items);
2463 if (avatar != null) {
2464 avatar.owner = account.getJid().toBareJid();
2465 if (fileBackend.isAvatarCached(avatar)) {
2466 if (account.setAvatar(avatar.getFilename())) {
2467 databaseBackend.updateAccount(account);
2468 }
2469 getAvatarService().clear(account);
2470 callback.success(avatar);
2471 } else {
2472 fetchAvatarPep(account, avatar, callback);
2473 }
2474 return;
2475 }
2476 }
2477 }
2478 }
2479 callback.error(0, null);
2480 }
2481 });
2482 }
2483
2484 public void deleteContactOnServer(Contact contact) {
2485 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2486 contact.resetOption(Contact.Options.DIRTY_PUSH);
2487 contact.setOption(Contact.Options.DIRTY_DELETE);
2488 Account account = contact.getAccount();
2489 if (account.getStatus() == Account.State.ONLINE) {
2490 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2491 Element item = iq.query(Xmlns.ROSTER).addChild("item");
2492 item.setAttribute("jid", contact.getJid().toString());
2493 item.setAttribute("subscription", "remove");
2494 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2495 }
2496 }
2497
2498 public void updateConversation(Conversation conversation) {
2499 this.databaseBackend.updateConversation(conversation);
2500 }
2501
2502 private void reconnectAccount(final Account account, final boolean force, final boolean interactive) {
2503 synchronized (account) {
2504 XmppConnection connection = account.getXmppConnection();
2505 if (connection != null) {
2506 disconnect(account, force);
2507 } else {
2508 connection = createConnection(account);
2509 account.setXmppConnection(connection);
2510 }
2511 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2512 synchronized (this.mInProgressAvatarFetches) {
2513 for (Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) {
2514 final String KEY = iterator.next();
2515 if (KEY.startsWith(account.getJid().toBareJid() + "_")) {
2516 iterator.remove();
2517 }
2518 }
2519 }
2520 if (!force) {
2521 try {
2522 Log.d(Config.LOGTAG, "wait for disconnect");
2523 Thread.sleep(500); //sleep wait for disconnect
2524 } catch (InterruptedException e) {
2525 //ignored
2526 }
2527 }
2528 Thread thread = new Thread(connection);
2529 connection.setInteractive(interactive);
2530 thread.start();
2531 scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2532 } else {
2533 account.getRoster().clearPresences();
2534 connection.resetEverything();
2535 }
2536 }
2537 }
2538
2539 public void reconnectAccountInBackground(final Account account) {
2540 new Thread(new Runnable() {
2541 @Override
2542 public void run() {
2543 reconnectAccount(account, false, true);
2544 }
2545 }).start();
2546 }
2547
2548 public void invite(Conversation conversation, Jid contact) {
2549 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid());
2550 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2551 sendMessagePacket(conversation.getAccount(), packet);
2552 }
2553
2554 public void directInvite(Conversation conversation, Jid jid) {
2555 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2556 sendMessagePacket(conversation.getAccount(), packet);
2557 }
2558
2559 public void resetSendingToWaiting(Account account) {
2560 for (Conversation conversation : getConversations()) {
2561 if (conversation.getAccount() == account) {
2562 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2563
2564 @Override
2565 public void onMessageFound(Message message) {
2566 markMessage(message, Message.STATUS_WAITING);
2567 }
2568 });
2569 }
2570 }
2571 }
2572
2573 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2574 if (uuid == null) {
2575 return null;
2576 }
2577 for (Conversation conversation : getConversations()) {
2578 if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2579 final Message message = conversation.findSentMessageWithUuidOrRemoteId(uuid);
2580 if (message != null) {
2581 markMessage(message, status);
2582 }
2583 return message;
2584 }
2585 }
2586 return null;
2587 }
2588
2589 public boolean markMessage(Conversation conversation, String uuid, int status) {
2590 if (uuid == null) {
2591 return false;
2592 } else {
2593 Message message = conversation.findSentMessageWithUuid(uuid);
2594 if (message != null) {
2595 markMessage(message, status);
2596 return true;
2597 } else {
2598 return false;
2599 }
2600 }
2601 }
2602
2603 public void markMessage(Message message, int status) {
2604 if (status == Message.STATUS_SEND_FAILED
2605 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2606 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2607 return;
2608 }
2609 message.setStatus(status);
2610 databaseBackend.updateMessage(message);
2611 updateConversationUi();
2612 }
2613
2614 public SharedPreferences getPreferences() {
2615 return PreferenceManager
2616 .getDefaultSharedPreferences(getApplicationContext());
2617 }
2618
2619 public boolean confirmMessages() {
2620 return getPreferences().getBoolean("confirm_messages", true);
2621 }
2622
2623 public boolean allowMessageCorrection() {
2624 return getPreferences().getBoolean("allow_message_correction", true);
2625 }
2626
2627 public boolean sendChatStates() {
2628 return getPreferences().getBoolean("chat_states", false);
2629 }
2630
2631 public boolean saveEncryptedMessages() {
2632 return !getPreferences().getBoolean("dont_save_encrypted", false);
2633 }
2634
2635 private boolean respectAutojoin() {
2636 return getPreferences().getBoolean("autojoin", true);
2637 }
2638
2639 public boolean indicateReceived() {
2640 return getPreferences().getBoolean("indicate_received", false);
2641 }
2642
2643 public boolean useTorToConnect() {
2644 return Config.FORCE_ORBOT || getPreferences().getBoolean("use_tor", false);
2645 }
2646
2647 public boolean showExtendedConnectionOptions() {
2648 return getPreferences().getBoolean("show_connection_options", false);
2649 }
2650
2651 public int unreadCount() {
2652 int count = 0;
2653 for (Conversation conversation : getConversations()) {
2654 count += conversation.unreadCount();
2655 }
2656 return count;
2657 }
2658
2659
2660 public void showErrorToastInUi(int resId) {
2661 if (mOnShowErrorToast != null) {
2662 mOnShowErrorToast.onShowErrorToast(resId);
2663 }
2664 }
2665
2666 public void updateConversationUi() {
2667 if (mOnConversationUpdate != null) {
2668 mOnConversationUpdate.onConversationUpdate();
2669 }
2670 }
2671
2672 public void updateAccountUi() {
2673 if (mOnAccountUpdate != null) {
2674 mOnAccountUpdate.onAccountUpdate();
2675 }
2676 }
2677
2678 public void updateRosterUi() {
2679 if (mOnRosterUpdate != null) {
2680 mOnRosterUpdate.onRosterUpdate();
2681 }
2682 }
2683
2684 public boolean displayCaptchaRequest(Account account, String id, Data data, Bitmap captcha) {
2685 boolean rc = false;
2686 if (mOnCaptchaRequested != null) {
2687 DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics();
2688 Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity),
2689 (int) (captcha.getHeight() * metrics.scaledDensity), false);
2690
2691 mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled);
2692 rc = true;
2693 }
2694
2695 return rc;
2696 }
2697
2698 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2699 if (mOnUpdateBlocklist != null) {
2700 mOnUpdateBlocklist.OnUpdateBlocklist(status);
2701 }
2702 }
2703
2704 public void updateMucRosterUi() {
2705 if (mOnMucRosterUpdate != null) {
2706 mOnMucRosterUpdate.onMucRosterUpdate();
2707 }
2708 }
2709
2710 public void keyStatusUpdated(AxolotlService.FetchStatus report) {
2711 if (mOnKeyStatusUpdated != null) {
2712 mOnKeyStatusUpdated.onKeyStatusUpdated(report);
2713 }
2714 }
2715
2716 public Account findAccountByJid(final Jid accountJid) {
2717 for (Account account : this.accounts) {
2718 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2719 return account;
2720 }
2721 }
2722 return null;
2723 }
2724
2725 public Conversation findConversationByUuid(String uuid) {
2726 for (Conversation conversation : getConversations()) {
2727 if (conversation.getUuid().equals(uuid)) {
2728 return conversation;
2729 }
2730 }
2731 return null;
2732 }
2733
2734 public boolean markRead(final Conversation conversation) {
2735 mNotificationService.clear(conversation);
2736 final List<Message> readMessages = conversation.markRead();
2737 if (readMessages.size() > 0) {
2738 Runnable runnable = new Runnable() {
2739 @Override
2740 public void run() {
2741 for (Message message : readMessages) {
2742 databaseBackend.updateMessage(message);
2743 }
2744 }
2745 };
2746 mDatabaseExecutor.execute(runnable);
2747 updateUnreadCountBadge();
2748 return true;
2749 } else {
2750 return false;
2751 }
2752 }
2753
2754 public synchronized void updateUnreadCountBadge() {
2755 int count = unreadCount();
2756 if (unreadCount != count) {
2757 Log.d(Config.LOGTAG, "update unread count to " + count);
2758 if (count > 0) {
2759 ShortcutBadger.with(getApplicationContext()).count(count);
2760 } else {
2761 ShortcutBadger.with(getApplicationContext()).remove();
2762 }
2763 unreadCount = count;
2764 }
2765 }
2766
2767 public void sendReadMarker(final Conversation conversation) {
2768 final Message markable = conversation.getLatestMarkableMessage();
2769 if (this.markRead(conversation)) {
2770 updateConversationUi();
2771 }
2772 if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2773 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2774 Account account = conversation.getAccount();
2775 final Jid to = markable.getCounterpart();
2776 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2777 this.sendMessagePacket(conversation.getAccount(), packet);
2778 }
2779 }
2780
2781 public SecureRandom getRNG() {
2782 return this.mRandom;
2783 }
2784
2785 public MemorizingTrustManager getMemorizingTrustManager() {
2786 return this.mMemorizingTrustManager;
2787 }
2788
2789 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2790 this.mMemorizingTrustManager = trustManager;
2791 }
2792
2793 public void updateMemorizingTrustmanager() {
2794 final MemorizingTrustManager tm;
2795 final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2796 if (dontTrustSystemCAs) {
2797 tm = new MemorizingTrustManager(getApplicationContext(), null);
2798 } else {
2799 tm = new MemorizingTrustManager(getApplicationContext());
2800 }
2801 setMemorizingTrustManager(tm);
2802 }
2803
2804 public PowerManager getPowerManager() {
2805 return this.pm;
2806 }
2807
2808 public LruCache<String, Bitmap> getBitmapCache() {
2809 return this.mBitmapCache;
2810 }
2811
2812 public void syncRosterToDisk(final Account account) {
2813 Runnable runnable = new Runnable() {
2814
2815 @Override
2816 public void run() {
2817 databaseBackend.writeRoster(account.getRoster());
2818 }
2819 };
2820 mDatabaseExecutor.execute(runnable);
2821
2822 }
2823
2824 public List<String> getKnownHosts() {
2825 final List<String> hosts = new ArrayList<>();
2826 for (final Account account : getAccounts()) {
2827 if (!hosts.contains(account.getServer().toString())) {
2828 hosts.add(account.getServer().toString());
2829 }
2830 for (final Contact contact : account.getRoster().getContacts()) {
2831 if (contact.showInRoster()) {
2832 final String server = contact.getServer().toString();
2833 if (server != null && !hosts.contains(server)) {
2834 hosts.add(server);
2835 }
2836 }
2837 }
2838 }
2839 return hosts;
2840 }
2841
2842 public List<String> getKnownConferenceHosts() {
2843 final ArrayList<String> mucServers = new ArrayList<>();
2844 for (final Account account : accounts) {
2845 if (account.getXmppConnection() != null) {
2846 final String server = account.getXmppConnection().getMucServer();
2847 if (server != null && !mucServers.contains(server)) {
2848 mucServers.add(server);
2849 }
2850 }
2851 }
2852 return mucServers;
2853 }
2854
2855 public void sendMessagePacket(Account account, MessagePacket packet) {
2856 XmppConnection connection = account.getXmppConnection();
2857 if (connection != null) {
2858 connection.sendMessagePacket(packet);
2859 }
2860 }
2861
2862 public void sendPresencePacket(Account account, PresencePacket packet) {
2863 XmppConnection connection = account.getXmppConnection();
2864 if (connection != null) {
2865 connection.sendPresencePacket(packet);
2866 }
2867 }
2868
2869 public void sendCreateAccountWithCaptchaPacket(Account account, String id, Data data) {
2870 XmppConnection connection = account.getXmppConnection();
2871 if (connection != null) {
2872 connection.sendCaptchaRegistryRequest(id, data);
2873 }
2874 }
2875
2876 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2877 final XmppConnection connection = account.getXmppConnection();
2878 if (connection != null) {
2879 connection.sendIqPacket(packet, callback);
2880 }
2881 }
2882
2883 public void sendPresence(final Account account) {
2884 sendPresencePacket(account, mPresenceGenerator.selfPresence(account, getTargetPresence()));
2885 }
2886
2887 public void refreshAllPresences() {
2888 for (Account account : getAccounts()) {
2889 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2890 sendPresence(account);
2891 }
2892 }
2893 }
2894
2895 private void refreshAllGcmTokens() {
2896 for(Account account : getAccounts()) {
2897 if (account.isOnlineAndConnected() && mPushManagementService.available(account)) {
2898 mPushManagementService.registerPushTokenOnServer(account);
2899 }
2900 }
2901 }
2902
2903 public void sendOfflinePresence(final Account account) {
2904 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2905 }
2906
2907 public MessageGenerator getMessageGenerator() {
2908 return this.mMessageGenerator;
2909 }
2910
2911 public PresenceGenerator getPresenceGenerator() {
2912 return this.mPresenceGenerator;
2913 }
2914
2915 public IqGenerator getIqGenerator() {
2916 return this.mIqGenerator;
2917 }
2918
2919 public IqParser getIqParser() {
2920 return this.mIqParser;
2921 }
2922
2923 public JingleConnectionManager getJingleConnectionManager() {
2924 return this.mJingleConnectionManager;
2925 }
2926
2927 public MessageArchiveService getMessageArchiveService() {
2928 return this.mMessageArchiveService;
2929 }
2930
2931 public List<Contact> findContacts(Jid jid) {
2932 ArrayList<Contact> contacts = new ArrayList<>();
2933 for (Account account : getAccounts()) {
2934 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2935 Contact contact = account.getRoster().getContactFromRoster(jid);
2936 if (contact != null) {
2937 contacts.add(contact);
2938 }
2939 }
2940 }
2941 return contacts;
2942 }
2943
2944 public NotificationService getNotificationService() {
2945 return this.mNotificationService;
2946 }
2947
2948 public HttpConnectionManager getHttpConnectionManager() {
2949 return this.mHttpConnectionManager;
2950 }
2951
2952 public void resendFailedMessages(final Message message) {
2953 final Collection<Message> messages = new ArrayList<>();
2954 Message current = message;
2955 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2956 messages.add(current);
2957 if (current.mergeable(current.next())) {
2958 current = current.next();
2959 } else {
2960 break;
2961 }
2962 }
2963 for (final Message msg : messages) {
2964 msg.setTime(System.currentTimeMillis());
2965 markMessage(msg, Message.STATUS_WAITING);
2966 this.resendMessage(msg, false);
2967 }
2968 }
2969
2970 public void clearConversationHistory(final Conversation conversation) {
2971 conversation.clearMessages();
2972 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2973 conversation.setLastClearHistory(System.currentTimeMillis());
2974 Runnable runnable = new Runnable() {
2975 @Override
2976 public void run() {
2977 databaseBackend.deleteMessagesInConversation(conversation);
2978 }
2979 };
2980 mDatabaseExecutor.execute(runnable);
2981 }
2982
2983 public void sendBlockRequest(final Blockable blockable) {
2984 if (blockable != null && blockable.getBlockedJid() != null) {
2985 final Jid jid = blockable.getBlockedJid();
2986 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2987
2988 @Override
2989 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2990 if (packet.getType() == IqPacket.TYPE.RESULT) {
2991 account.getBlocklist().add(jid);
2992 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2993 }
2994 }
2995 });
2996 }
2997 }
2998
2999 public void sendUnblockRequest(final Blockable blockable) {
3000 if (blockable != null && blockable.getJid() != null) {
3001 final Jid jid = blockable.getBlockedJid();
3002 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
3003 @Override
3004 public void onIqPacketReceived(final Account account, final IqPacket packet) {
3005 if (packet.getType() == IqPacket.TYPE.RESULT) {
3006 account.getBlocklist().remove(jid);
3007 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
3008 }
3009 }
3010 });
3011 }
3012 }
3013
3014 public void publishDisplayName(Account account) {
3015 String displayName = account.getDisplayName();
3016 if (displayName != null && !displayName.isEmpty()) {
3017 IqPacket publish = mIqGenerator.publishNick(displayName);
3018 sendIqPacket(account, publish, new OnIqPacketReceived() {
3019 @Override
3020 public void onIqPacketReceived(Account account, IqPacket packet) {
3021 if (packet.getType() == IqPacket.TYPE.ERROR) {
3022 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not publish nick");
3023 }
3024 }
3025 });
3026 }
3027 }
3028
3029 private ServiceDiscoveryResult getCachedServiceDiscoveryResult(Pair<String,String> key) {
3030 ServiceDiscoveryResult result = discoCache.get(key);
3031 if (result != null) {
3032 return result;
3033 } else {
3034 result = databaseBackend.findDiscoveryResult(key.first, key.second);
3035 if (result != null) {
3036 discoCache.put(key, result);
3037 }
3038 return result;
3039 }
3040 }
3041
3042 public void fetchCaps(Account account, final Jid jid, final Presence presence) {
3043 final Pair<String,String> key = new Pair<>(presence.getHash(), presence.getVer());
3044 ServiceDiscoveryResult disco = getCachedServiceDiscoveryResult(key);
3045 if (disco != null) {
3046 presence.setServiceDiscoveryResult(disco);
3047 } else {
3048 if (!account.inProgressDiscoFetches.contains(key)) {
3049 account.inProgressDiscoFetches.add(key);
3050 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3051 request.setTo(jid);
3052 request.query("http://jabber.org/protocol/disco#info");
3053 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": making disco request for "+key.second+" to "+jid);
3054 sendIqPacket(account, request, new OnIqPacketReceived() {
3055 @Override
3056 public void onIqPacketReceived(Account account, IqPacket discoPacket) {
3057 if (discoPacket.getType() == IqPacket.TYPE.RESULT) {
3058 ServiceDiscoveryResult disco = new ServiceDiscoveryResult(discoPacket);
3059 if (presence.getVer().equals(disco.getVer())) {
3060 databaseBackend.insertDiscoveryResult(disco);
3061 injectServiceDiscorveryResult(account.getRoster(), presence.getHash(), presence.getVer(), disco);
3062 } else {
3063 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": mismatch in caps for contact " + jid + " " + presence.getVer() + " vs " + disco.getVer());
3064 }
3065 }
3066 account.inProgressDiscoFetches.remove(key);
3067 }
3068 });
3069 }
3070 }
3071 }
3072
3073 private void injectServiceDiscorveryResult(Roster roster, String hash, String ver, ServiceDiscoveryResult disco) {
3074 for(Contact contact : roster.getContacts()) {
3075 for(Presence presence : contact.getPresences().getPresences().values()) {
3076 if (hash.equals(presence.getHash()) && ver.equals(presence.getVer())) {
3077 presence.setServiceDiscoveryResult(disco);
3078 }
3079 }
3080 }
3081 }
3082
3083 public void fetchMamPreferences(Account account, final OnMamPreferencesFetched callback) {
3084 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
3085 request.addChild("prefs","urn:xmpp:mam:0");
3086 sendIqPacket(account, request, new OnIqPacketReceived() {
3087 @Override
3088 public void onIqPacketReceived(Account account, IqPacket packet) {
3089 Element prefs = packet.findChild("prefs","urn:xmpp:mam:0");
3090 if (packet.getType() == IqPacket.TYPE.RESULT && prefs != null) {
3091 callback.onPreferencesFetched(prefs);
3092 } else {
3093 callback.onPreferencesFetchFailed();
3094 }
3095 }
3096 });
3097 }
3098
3099 public PushManagementService getPushManagementService() {
3100 return mPushManagementService;
3101 }
3102
3103 public interface OnMamPreferencesFetched {
3104 void onPreferencesFetched(Element prefs);
3105 void onPreferencesFetchFailed();
3106 }
3107
3108 public void pushMamPreferences(Account account, Element prefs) {
3109 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
3110 set.addChild(prefs);
3111 sendIqPacket(account, set, null);
3112 }
3113
3114 public interface OnAccountCreated {
3115 void onAccountCreated(Account account);
3116
3117 void informUser(int r);
3118 }
3119
3120 public interface OnMoreMessagesLoaded {
3121 void onMoreMessagesLoaded(int count, Conversation conversation);
3122
3123 void informUser(int r);
3124 }
3125
3126 public interface OnAccountPasswordChanged {
3127 void onPasswordChangeSucceeded();
3128
3129 void onPasswordChangeFailed();
3130 }
3131
3132 public interface OnAffiliationChanged {
3133 void onAffiliationChangedSuccessful(Jid jid);
3134
3135 void onAffiliationChangeFailed(Jid jid, int resId);
3136 }
3137
3138 public interface OnRoleChanged {
3139 void onRoleChangedSuccessful(String nick);
3140
3141 void onRoleChangeFailed(String nick, int resid);
3142 }
3143
3144 public interface OnConversationUpdate {
3145 void onConversationUpdate();
3146 }
3147
3148 public interface OnAccountUpdate {
3149 void onAccountUpdate();
3150 }
3151
3152 public interface OnCaptchaRequested {
3153 void onCaptchaRequested(Account account,
3154 String id,
3155 Data data,
3156 Bitmap captcha);
3157 }
3158
3159 public interface OnRosterUpdate {
3160 void onRosterUpdate();
3161 }
3162
3163 public interface OnMucRosterUpdate {
3164 void onMucRosterUpdate();
3165 }
3166
3167 public interface OnConferenceConfigurationFetched {
3168 void onConferenceConfigurationFetched(Conversation conversation);
3169
3170 void onFetchFailed(Conversation conversation, Element error);
3171 }
3172
3173 public interface OnConferenceJoined {
3174 void onConferenceJoined(Conversation conversation);
3175 }
3176
3177 public interface OnConferenceOptionsPushed {
3178 void onPushSucceeded();
3179
3180 void onPushFailed();
3181 }
3182
3183 public interface OnShowErrorToast {
3184 void onShowErrorToast(int resId);
3185 }
3186
3187 public class XmppConnectionBinder extends Binder {
3188 public XmppConnectionService getService() {
3189 return XmppConnectionService.this;
3190 }
3191 }
3192}