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.SharedPreferences;
10import android.database.ContentObserver;
11import android.graphics.Bitmap;
12import android.net.ConnectivityManager;
13import android.net.NetworkInfo;
14import android.net.Uri;
15import android.os.Binder;
16import android.os.Bundle;
17import android.os.FileObserver;
18import android.os.IBinder;
19import android.os.Looper;
20import android.os.PowerManager;
21import android.os.PowerManager.WakeLock;
22import android.os.SystemClock;
23import android.preference.PreferenceManager;
24import android.provider.ContactsContract;
25import android.util.Log;
26import android.util.LruCache;
27
28import net.java.otr4j.OtrException;
29import net.java.otr4j.session.Session;
30import net.java.otr4j.session.SessionID;
31import net.java.otr4j.session.SessionStatus;
32
33import org.openintents.openpgp.util.OpenPgpApi;
34import org.openintents.openpgp.util.OpenPgpServiceConnection;
35
36import java.math.BigInteger;
37import java.security.SecureRandom;
38import java.util.ArrayList;
39import java.util.Arrays;
40import java.util.Collection;
41import java.util.Collections;
42import java.util.Comparator;
43import java.util.Hashtable;
44import java.util.Iterator;
45import java.util.List;
46import java.util.Locale;
47import java.util.Map;
48import java.util.concurrent.CopyOnWriteArrayList;
49
50import de.duenndns.ssl.MemorizingTrustManager;
51import eu.siacs.conversations.Config;
52import eu.siacs.conversations.R;
53import eu.siacs.conversations.crypto.PgpEngine;
54import eu.siacs.conversations.entities.Account;
55import eu.siacs.conversations.entities.Blockable;
56import eu.siacs.conversations.entities.Bookmark;
57import eu.siacs.conversations.entities.Contact;
58import eu.siacs.conversations.entities.Conversation;
59import eu.siacs.conversations.entities.Downloadable;
60import eu.siacs.conversations.entities.DownloadablePlaceholder;
61import eu.siacs.conversations.entities.Message;
62import eu.siacs.conversations.entities.MucOptions;
63import eu.siacs.conversations.entities.MucOptions.OnRenameListener;
64import eu.siacs.conversations.entities.Presences;
65import eu.siacs.conversations.generator.IqGenerator;
66import eu.siacs.conversations.generator.MessageGenerator;
67import eu.siacs.conversations.generator.PresenceGenerator;
68import eu.siacs.conversations.http.HttpConnectionManager;
69import eu.siacs.conversations.parser.IqParser;
70import eu.siacs.conversations.parser.MessageParser;
71import eu.siacs.conversations.parser.PresenceParser;
72import eu.siacs.conversations.persistance.DatabaseBackend;
73import eu.siacs.conversations.persistance.FileBackend;
74import eu.siacs.conversations.ui.UiCallback;
75import eu.siacs.conversations.utils.CryptoHelper;
76import eu.siacs.conversations.utils.ExceptionHelper;
77import eu.siacs.conversations.utils.OnPhoneContactsLoadedListener;
78import eu.siacs.conversations.utils.PRNGFixes;
79import eu.siacs.conversations.utils.PhoneHelper;
80import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
81import eu.siacs.conversations.utils.Xmlns;
82import eu.siacs.conversations.xml.Element;
83import eu.siacs.conversations.xmpp.OnBindListener;
84import eu.siacs.conversations.xmpp.OnContactStatusChanged;
85import eu.siacs.conversations.xmpp.OnIqPacketReceived;
86import eu.siacs.conversations.xmpp.OnMessageAcknowledged;
87import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
88import eu.siacs.conversations.xmpp.OnPresencePacketReceived;
89import eu.siacs.conversations.xmpp.OnStatusChanged;
90import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
91import eu.siacs.conversations.xmpp.XmppConnection;
92import eu.siacs.conversations.xmpp.chatstate.ChatState;
93import eu.siacs.conversations.xmpp.forms.Data;
94import eu.siacs.conversations.xmpp.forms.Field;
95import eu.siacs.conversations.xmpp.jid.InvalidJidException;
96import eu.siacs.conversations.xmpp.jid.Jid;
97import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
98import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
99import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
100import eu.siacs.conversations.xmpp.pep.Avatar;
101import eu.siacs.conversations.xmpp.stanzas.IqPacket;
102import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
103import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
104import me.leolin.shortcutbadger.ShortcutBadger;
105
106public class XmppConnectionService extends Service implements OnPhoneContactsLoadedListener {
107
108 public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification";
109 public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground";
110 private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts";
111 public static final String ACTION_TRY_AGAIN = "try_again";
112 public static final String ACTION_DISABLE_ACCOUNT = "disable_account";
113 private ContentObserver contactObserver = new ContentObserver(null) {
114 @Override
115 public void onChange(boolean selfChange) {
116 super.onChange(selfChange);
117 Intent intent = new Intent(getApplicationContext(),
118 XmppConnectionService.class);
119 intent.setAction(ACTION_MERGE_PHONE_CONTACTS);
120 startService(intent);
121 }
122 };
123
124 private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor();
125 private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor();
126
127 private final IBinder mBinder = new XmppConnectionBinder();
128 private final List<Conversation> conversations = new CopyOnWriteArrayList<>();
129 private final FileObserver fileObserver = new FileObserver(
130 FileBackend.getConversationsImageDirectory()) {
131
132 @Override
133 public void onEvent(int event, String path) {
134 if (event == FileObserver.DELETE) {
135 markFileDeleted(path.split("\\.")[0]);
136 }
137 }
138 };
139 private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() {
140
141 @Override
142 public void onJinglePacketReceived(Account account, JinglePacket packet) {
143 mJingleConnectionManager.deliverPacket(account, packet);
144 }
145 };
146 private final OnBindListener mOnBindListener = new OnBindListener() {
147
148 @Override
149 public void onBind(final Account account) {
150 account.getRoster().clearPresences();
151 account.pendingConferenceJoins.clear();
152 account.pendingConferenceLeaves.clear();
153 fetchRosterFromServer(account);
154 fetchBookmarks(account);
155 sendPresence(account);
156 connectMultiModeConversations(account);
157 updateConversationUi();
158 }
159 };
160 private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() {
161
162 @Override
163 public void onMessageAcknowledged(Account account, String uuid) {
164 for (final Conversation conversation : getConversations()) {
165 if (conversation.getAccount() == account) {
166 Message message = conversation.findUnsentMessageWithUuid(uuid);
167 if (message != null) {
168 markMessage(message, Message.STATUS_SEND);
169 if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
170 databaseBackend.updateConversation(conversation);
171 }
172 }
173 }
174 }
175 }
176 };
177 private final IqGenerator mIqGenerator = new IqGenerator(this);
178 public DatabaseBackend databaseBackend;
179 public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() {
180
181 @Override
182 public void onContactStatusChanged(Contact contact, boolean online) {
183 Conversation conversation = find(getConversations(), contact);
184 if (conversation != null) {
185 if (online) {
186 conversation.endOtrIfNeeded();
187 if (contact.getPresences().size() == 1) {
188 sendUnsentMessages(conversation);
189 }
190 } else {
191 if (contact.getPresences().size() >= 1) {
192 if (conversation.hasValidOtrSession()) {
193 String otrResource = conversation.getOtrSession().getSessionID().getUserID();
194 if (!(Arrays.asList(contact.getPresences().asStringArray()).contains(otrResource))) {
195 conversation.endOtrIfNeeded();
196 }
197 }
198 } else {
199 conversation.endOtrIfNeeded();
200 }
201 }
202 }
203 }
204 };
205 private FileBackend fileBackend = new FileBackend(this);
206 private MemorizingTrustManager mMemorizingTrustManager;
207 private NotificationService mNotificationService = new NotificationService(
208 this);
209 private OnMessagePacketReceived mMessageParser = new MessageParser(this);
210 private OnPresencePacketReceived mPresenceParser = new PresenceParser(this);
211 private IqParser mIqParser = new IqParser(this);
212 private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() {
213 @Override
214 public void onIqPacketReceived(Account account, IqPacket packet) {
215 if (packet.getType() == IqPacket.TYPE.ERROR) {
216 Element error = packet.findChild("error");
217 String text = error != null ? error.findChildContent("text") : null;
218 if (text != null) {
219 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received iq error - "+text);
220 }
221 }
222 }
223 };
224 private MessageGenerator mMessageGenerator = new MessageGenerator(this);
225 private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this);
226 private List<Account> accounts;
227 private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
228 this);
229 private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager(
230 this);
231 private AvatarService mAvatarService = new AvatarService(this);
232 private final List<String> mInProgressAvatarFetches = new ArrayList<>();
233 private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this);
234 private OnConversationUpdate mOnConversationUpdate = null;
235 private int convChangedListenerCount = 0;
236 private int unreadCount = 0;
237 private OnAccountUpdate mOnAccountUpdate = null;
238 private OnStatusChanged statusListener = new OnStatusChanged() {
239
240 @Override
241 public void onStatusChanged(Account account) {
242 XmppConnection connection = account.getXmppConnection();
243 if (mOnAccountUpdate != null) {
244 mOnAccountUpdate.onAccountUpdate();
245 }
246 if (account.getStatus() == Account.State.ONLINE) {
247 for (Conversation conversation : account.pendingConferenceLeaves) {
248 leaveMuc(conversation);
249 }
250 for (Conversation conversation : account.pendingConferenceJoins) {
251 joinMuc(conversation);
252 }
253 mMessageArchiveService.executePendingQueries(account);
254 mJingleConnectionManager.cancelInTransmission();
255 List<Conversation> conversations = getConversations();
256 for (Conversation conversation : conversations) {
257 if (conversation.getAccount() == account) {
258 conversation.startOtrIfNeeded();
259 sendUnsentMessages(conversation);
260 }
261 }
262 if (connection != null && connection.getFeatures().csi()) {
263 if (checkListeners()) {
264 Log.d(Config.LOGTAG, account.getJid().toBareJid()
265 + " sending csi//inactive");
266 connection.sendInactive();
267 } else {
268 Log.d(Config.LOGTAG, account.getJid().toBareJid()
269 + " sending csi//active");
270 connection.sendActive();
271 }
272 }
273 syncDirtyContacts(account);
274 scheduleWakeUpCall(Config.PING_MAX_INTERVAL,account.getUuid().hashCode());
275 } else if (account.getStatus() == Account.State.OFFLINE) {
276 resetSendingToWaiting(account);
277 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
278 int timeToReconnect = mRandom.nextInt(50) + 10;
279 scheduleWakeUpCall(timeToReconnect,account.getUuid().hashCode());
280 }
281 } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) {
282 databaseBackend.updateAccount(account);
283 reconnectAccount(account, true);
284 } else if ((account.getStatus() != Account.State.CONNECTING)
285 && (account.getStatus() != Account.State.NO_INTERNET)) {
286 if (connection != null) {
287 int next = connection.getTimeToNextAttempt();
288 Log.d(Config.LOGTAG, account.getJid().toBareJid()
289 + ": error connecting account. try again in "
290 + next + "s for the "
291 + (connection.getAttempt() + 1) + " time");
292 scheduleWakeUpCall(next,account.getUuid().hashCode());
293 }
294 }
295 getNotificationService().updateErrorNotification();
296 }
297 };
298 private int accountChangedListenerCount = 0;
299 private OnRosterUpdate mOnRosterUpdate = null;
300 private OnUpdateBlocklist mOnUpdateBlocklist = null;
301 private int updateBlocklistListenerCount = 0;
302 private int rosterChangedListenerCount = 0;
303 private OnMucRosterUpdate mOnMucRosterUpdate = null;
304 private int mucRosterChangedListenerCount = 0;
305 private SecureRandom mRandom;
306 private OpenPgpServiceConnection pgpServiceConnection;
307 private PgpEngine mPgpEngine = null;
308 private WakeLock wakeLock;
309 private PowerManager pm;
310 private LruCache<String, Bitmap> mBitmapCache;
311 private Thread mPhoneContactMergerThread;
312
313 private boolean mRestoredFromDatabase = false;
314 public boolean areMessagesInitialized() {
315 return this.mRestoredFromDatabase;
316 }
317
318 public PgpEngine getPgpEngine() {
319 if (pgpServiceConnection.isBound()) {
320 if (this.mPgpEngine == null) {
321 this.mPgpEngine = new PgpEngine(new OpenPgpApi(
322 getApplicationContext(),
323 pgpServiceConnection.getService()), this);
324 }
325 return mPgpEngine;
326 } else {
327 return null;
328 }
329
330 }
331
332 public FileBackend getFileBackend() {
333 return this.fileBackend;
334 }
335
336 public AvatarService getAvatarService() {
337 return this.mAvatarService;
338 }
339
340 public void attachLocationToConversation(final Conversation conversation,
341 final Uri uri,
342 final UiCallback<Message> callback) {
343 int encryption = conversation.getNextEncryption(forceEncryption());
344 if (encryption == Message.ENCRYPTION_PGP) {
345 encryption = Message.ENCRYPTION_DECRYPTED;
346 }
347 Message message = new Message(conversation,uri.toString(),encryption);
348 if (conversation.getNextCounterpart() != null) {
349 message.setCounterpart(conversation.getNextCounterpart());
350 }
351 if (encryption == Message.ENCRYPTION_DECRYPTED) {
352 getPgpEngine().encrypt(message, callback);
353 } else {
354 callback.success(message);
355 }
356 }
357
358 public void attachFileToConversation(final Conversation conversation,
359 final Uri uri,
360 final UiCallback<Message> callback) {
361 final Message message;
362 if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
363 message = new Message(conversation, "",
364 Message.ENCRYPTION_DECRYPTED);
365 } else {
366 message = new Message(conversation, "",
367 conversation.getNextEncryption(forceEncryption()));
368 }
369 message.setCounterpart(conversation.getNextCounterpart());
370 message.setType(Message.TYPE_FILE);
371 String path = getFileBackend().getOriginalPath(uri);
372 if (path!=null) {
373 message.setRelativeFilePath(path);
374 getFileBackend().updateFileParams(message);
375 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
376 getPgpEngine().encrypt(message, callback);
377 } else {
378 callback.success(message);
379 }
380 } else {
381 mFileAddingExecutor.execute(new Runnable() {
382 @Override
383 public void run() {
384 try {
385 getFileBackend().copyFileToPrivateStorage(message, uri);
386 getFileBackend().updateFileParams(message);
387 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
388 getPgpEngine().encrypt(message, callback);
389 } else {
390 callback.success(message);
391 }
392 } catch (FileBackend.FileCopyException e) {
393 callback.error(e.getResId(), message);
394 }
395 }
396 });
397 }
398 }
399
400 public void attachImageToConversation(final Conversation conversation,
401 final Uri uri, final UiCallback<Message> callback) {
402 final Message message;
403 if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
404 message = new Message(conversation, "",
405 Message.ENCRYPTION_DECRYPTED);
406 } else {
407 message = new Message(conversation, "",
408 conversation.getNextEncryption(forceEncryption()));
409 }
410 message.setCounterpart(conversation.getNextCounterpart());
411 message.setType(Message.TYPE_IMAGE);
412 mFileAddingExecutor.execute(new Runnable() {
413
414 @Override
415 public void run() {
416 try {
417 getFileBackend().copyImageToPrivateStorage(message, uri);
418 if (conversation.getNextEncryption(forceEncryption()) == Message.ENCRYPTION_PGP) {
419 getPgpEngine().encrypt(message, callback);
420 } else {
421 callback.success(message);
422 }
423 } catch (final FileBackend.FileCopyException e) {
424 callback.error(e.getResId(), message);
425 }
426 }
427 });
428 }
429
430 public Conversation find(Bookmark bookmark) {
431 return find(bookmark.getAccount(), bookmark.getJid());
432 }
433
434 public Conversation find(final Account account, final Jid jid) {
435 return find(getConversations(), account, jid);
436 }
437
438 @Override
439 public int onStartCommand(Intent intent, int flags, int startId) {
440 final String action = intent == null ? null : intent.getAction();
441 if (action != null) {
442 switch (action) {
443 case ConnectivityManager.CONNECTIVITY_ACTION:
444 if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) {
445 resetAllAttemptCounts(true);
446 }
447 break;
448 case ACTION_MERGE_PHONE_CONTACTS:
449 if (mRestoredFromDatabase) {
450 PhoneHelper.loadPhoneContacts(getApplicationContext(),
451 new CopyOnWriteArrayList<Bundle>(),
452 this);
453 }
454 return START_STICKY;
455 case Intent.ACTION_SHUTDOWN:
456 logoutAndSave();
457 return START_NOT_STICKY;
458 case ACTION_CLEAR_NOTIFICATION:
459 mNotificationService.clear();
460 break;
461 case ACTION_DISABLE_FOREGROUND:
462 getPreferences().edit().putBoolean("keep_foreground_service",false).commit();
463 toggleForegroundService();
464 break;
465 case ACTION_TRY_AGAIN:
466 resetAllAttemptCounts(false);
467 break;
468 case ACTION_DISABLE_ACCOUNT:
469 try {
470 String jid = intent.getStringExtra("account");
471 Account account = jid == null ? null : findAccountByJid(Jid.fromString(jid));
472 if (account != null) {
473 account.setOption(Account.OPTION_DISABLED,true);
474 updateAccount(account);
475 }
476 } catch (final InvalidJidException ignored) {
477 break;
478 }
479 break;
480 }
481 }
482 this.wakeLock.acquire();
483
484 for (Account account : accounts) {
485 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
486 if (!hasInternetConnection()) {
487 account.setStatus(Account.State.NO_INTERNET);
488 if (statusListener != null) {
489 statusListener.onStatusChanged(account);
490 }
491 } else {
492 if (account.getStatus() == Account.State.NO_INTERNET) {
493 account.setStatus(Account.State.OFFLINE);
494 if (statusListener != null) {
495 statusListener.onStatusChanged(account);
496 }
497 }
498 if (account.getStatus() == Account.State.ONLINE) {
499 long lastReceived = account.getXmppConnection().getLastPacketReceived();
500 long lastSent = account.getXmppConnection().getLastPingSent();
501 long pingInterval = "ui".equals(action) ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000;
502 long msToNextPing = (Math.max(lastReceived,lastSent) + pingInterval) - SystemClock.elapsedRealtime();
503 long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime();
504 if (lastSent > lastReceived) {
505 if (pingTimeoutIn < 0) {
506 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ping timeout");
507 this.reconnectAccount(account, true);
508 } else {
509 int secs = (int) (pingTimeoutIn / 1000);
510 this.scheduleWakeUpCall(secs,account.getUuid().hashCode());
511 }
512 } else if (msToNextPing <= 0) {
513 account.getXmppConnection().sendPing();
514 Log.d(Config.LOGTAG, account.getJid().toBareJid()+" send ping");
515 this.scheduleWakeUpCall(Config.PING_TIMEOUT,account.getUuid().hashCode());
516 } else {
517 this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode());
518 }
519 } else if (account.getStatus() == Account.State.OFFLINE) {
520 reconnectAccount(account,true);
521 } else if (account.getStatus() == Account.State.CONNECTING) {
522 long timeout = Config.CONNECT_TIMEOUT - ((SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000);
523 if (timeout < 0) {
524 Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting");
525 reconnectAccount(account, true);
526 } else {
527 scheduleWakeUpCall((int) timeout,account.getUuid().hashCode());
528 }
529 } else {
530 if (account.getXmppConnection().getTimeToNextAttempt() <= 0) {
531 reconnectAccount(account, true);
532 }
533 }
534
535 }
536 if (mOnAccountUpdate != null) {
537 mOnAccountUpdate.onAccountUpdate();
538 }
539 }
540 }
541 /*PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
542 if (!pm.isScreenOn()) {
543 removeStaleListeners();
544 }*/
545 if (wakeLock.isHeld()) {
546 try {
547 wakeLock.release();
548 } catch (final RuntimeException ignored) {
549 }
550 }
551 return START_STICKY;
552 }
553
554 private void resetAllAttemptCounts(boolean reallyAll) {
555 Log.d(Config.LOGTAG,"resetting all attepmt counts");
556 for(Account account : accounts) {
557 if (account.hasErrorStatus() || reallyAll) {
558 final XmppConnection connection = account.getXmppConnection();
559 if (connection != null) {
560 connection.resetAttemptCount();
561 }
562 }
563 }
564 }
565
566 public boolean hasInternetConnection() {
567 ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
568 .getSystemService(Context.CONNECTIVITY_SERVICE);
569 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
570 return activeNetwork != null && activeNetwork.isConnected();
571 }
572
573 @SuppressLint("TrulyRandom")
574 @Override
575 public void onCreate() {
576 ExceptionHelper.init(getApplicationContext());
577 PRNGFixes.apply();
578 this.mRandom = new SecureRandom();
579 updateMemorizingTrustmanager();
580 final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
581 final int cacheSize = maxMemory / 8;
582 this.mBitmapCache = new LruCache<String, Bitmap>(cacheSize) {
583 @Override
584 protected int sizeOf(final String key, final Bitmap bitmap) {
585 return bitmap.getByteCount() / 1024;
586 }
587 };
588
589 this.databaseBackend = DatabaseBackend.getInstance(getApplicationContext());
590 this.accounts = databaseBackend.getAccounts();
591
592 for (final Account account : this.accounts) {
593 account.initAccountServices(this);
594 }
595 restoreFromDatabase();
596
597 getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, contactObserver);
598 this.fileObserver.startWatching();
599 this.pgpServiceConnection = new OpenPgpServiceConnection(getApplicationContext(), "org.sufficientlysecure.keychain");
600 this.pgpServiceConnection.bindToService();
601
602 this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
603 this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"XmppConnectionService");
604 toggleForegroundService();
605 }
606
607 public void toggleForegroundService() {
608 if (getPreferences().getBoolean("keep_foreground_service",false)) {
609 startForeground(NotificationService.FOREGROUND_NOTIFICATION_ID, this.mNotificationService.createForegroundNotification());
610 } else {
611 stopForeground(true);
612 }
613 }
614
615 @Override
616 public void onTaskRemoved(final Intent rootIntent) {
617 super.onTaskRemoved(rootIntent);
618 if (!getPreferences().getBoolean("keep_foreground_service",false)) {
619 this.logoutAndSave();
620 }
621 }
622
623 private void logoutAndSave() {
624 for (final Account account : accounts) {
625 databaseBackend.writeRoster(account.getRoster());
626 if (account.getXmppConnection() != null) {
627 disconnect(account, false);
628 }
629 }
630 Context context = getApplicationContext();
631 AlarmManager alarmManager = (AlarmManager) context
632 .getSystemService(Context.ALARM_SERVICE);
633 Intent intent = new Intent(context, EventReceiver.class);
634 alarmManager.cancel(PendingIntent.getBroadcast(context, 0, intent, 0));
635 Log.d(Config.LOGTAG, "good bye");
636 stopSelf();
637 }
638
639 protected void scheduleWakeUpCall(int seconds, int requestCode) {
640 final long timeToWake = SystemClock.elapsedRealtime() + (seconds < 0 ? 1 : seconds + 1) * 1000;
641
642 Context context = getApplicationContext();
643 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
644
645 Intent intent = new Intent(context, EventReceiver.class);
646 intent.setAction("ping");
647 PendingIntent alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);
648 alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeToWake, alarmIntent);
649 }
650
651 public XmppConnection createConnection(final Account account) {
652 final SharedPreferences sharedPref = getPreferences();
653 account.setResource(sharedPref.getString("resource", "mobile")
654 .toLowerCase(Locale.getDefault()));
655 final XmppConnection connection = new XmppConnection(account, this);
656 connection.setOnMessagePacketReceivedListener(this.mMessageParser);
657 connection.setOnStatusChangedListener(this.statusListener);
658 connection.setOnPresencePacketReceivedListener(this.mPresenceParser);
659 connection.setOnUnregisteredIqPacketReceivedListener(this.mIqParser);
660 connection.setOnJinglePacketReceivedListener(this.jingleListener);
661 connection.setOnBindListener(this.mOnBindListener);
662 connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener);
663 connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService);
664 return connection;
665 }
666
667 public void sendChatState(Conversation conversation) {
668 if (sendChatStates()) {
669 MessagePacket packet = mMessageGenerator.generateChatState(conversation);
670 sendMessagePacket(conversation.getAccount(), packet);
671 }
672 }
673
674 private void sendFileMessage(final Message message) {
675 Log.d(Config.LOGTAG, "send file message");
676 final Account account = message.getConversation().getAccount();
677 final XmppConnection connection = account.getXmppConnection();
678 if (connection != null && connection.getFeatures().httpUpload()) {
679 mHttpConnectionManager.createNewUploadConnection(message);
680 } else {
681 mJingleConnectionManager.createNewConnection(message);
682 }
683 }
684
685 public void sendMessage(final Message message) {
686 final Account account = message.getConversation().getAccount();
687 account.deactivateGracePeriod();
688 final Conversation conv = message.getConversation();
689 MessagePacket packet = null;
690 boolean saveInDb = true;
691 boolean send = false;
692 if (account.getStatus() == Account.State.ONLINE
693 && account.getXmppConnection() != null) {
694 if (message.needsUploading()) {
695 if (message.getCounterpart() != null) {
696 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
697 if (!conv.hasValidOtrSession()) {
698 conv.startOtrSession(message.getCounterpart().getResourcepart(),true);
699 message.setStatus(Message.STATUS_WAITING);
700 } else if (conv.hasValidOtrSession()
701 && conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
702 mJingleConnectionManager.createNewConnection(message);
703 }
704 } else {
705 this.sendFileMessage(message);
706
707 }
708 } else {
709 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
710 conv.startOtrIfNeeded();
711 }
712 message.setStatus(Message.STATUS_WAITING);
713 }
714 } else {
715 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
716 if (!conv.hasValidOtrSession() && (message.getCounterpart() != null)) {
717 conv.startOtrSession(message.getCounterpart().getResourcepart(), true);
718 message.setStatus(Message.STATUS_WAITING);
719 } else if (conv.hasValidOtrSession()) {
720 if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
721 packet = mMessageGenerator.generateOtrChat(message);
722 send = true;
723 } else {
724 message.setStatus(Message.STATUS_WAITING);
725 conv.startOtrIfNeeded();
726 }
727 } else {
728 message.setStatus(Message.STATUS_WAITING);
729 }
730 } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
731 message.getConversation().endOtrIfNeeded();
732 message.getConversation().findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
733 @Override
734 public void onMessageFound(Message message) {
735 markMessage(message,Message.STATUS_SEND_FAILED);
736 }
737 });
738 packet = mMessageGenerator.generatePgpChat(message);
739 send = true;
740 } else {
741 message.getConversation().endOtrIfNeeded();
742 message.getConversation().findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
743 @Override
744 public void onMessageFound(Message message) {
745 markMessage(message,Message.STATUS_SEND_FAILED);
746 }
747 });
748 packet = mMessageGenerator.generateChat(message);
749 send = true;
750 }
751 }
752 if (!account.getXmppConnection().getFeatures().sm()
753 && conv.getMode() != Conversation.MODE_MULTI) {
754 message.setStatus(Message.STATUS_SEND);
755 }
756 } else {
757 message.setStatus(Message.STATUS_WAITING);
758 if (message.getType() == Message.TYPE_TEXT) {
759 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
760 String pgpBody = message.getEncryptedBody();
761 String decryptedBody = message.getBody();
762 message.setBody(pgpBody);
763 message.setEncryption(Message.ENCRYPTION_PGP);
764 databaseBackend.createMessage(message);
765 saveInDb = false;
766 message.setBody(decryptedBody);
767 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
768 } else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
769 if (!conv.hasValidOtrSession()
770 && message.getCounterpart() != null) {
771 conv.startOtrSession(message.getCounterpart().getResourcepart(), false);
772 }
773 }
774 }
775
776 }
777 conv.add(message);
778 if (saveInDb) {
779 if (message.getEncryption() == Message.ENCRYPTION_NONE
780 || saveEncryptedMessages()) {
781 databaseBackend.createMessage(message);
782 }
783 }
784 if ((send) && (packet != null)) {
785 if (conv.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
786 if (this.sendChatStates()) {
787 packet.addChild(ChatState.toElement(conv.getOutgoingChatState()));
788 }
789 }
790 sendMessagePacket(account, packet);
791 }
792 updateConversationUi();
793 }
794
795 private void sendUnsentMessages(final Conversation conversation) {
796 conversation.findWaitingMessages(new Conversation.OnMessageFound() {
797
798 @Override
799 public void onMessageFound(Message message) {
800 resendMessage(message);
801 }
802 });
803 }
804
805 public void resendMessage(final Message message) {
806 Account account = message.getConversation().getAccount();
807 MessagePacket packet = null;
808 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
809 Presences presences = message.getConversation().getContact().getPresences();
810 if (!message.getConversation().hasValidOtrSession()) {
811 if ((message.getCounterpart() != null)
812 && (presences.has(message.getCounterpart().getResourcepart()))) {
813 message.getConversation().startOtrSession(message.getCounterpart().getResourcepart(), true);
814 } else {
815 if (presences.size() == 1) {
816 String presence = presences.asStringArray()[0];
817 message.getConversation().startOtrSession(presence, true);
818 }
819 }
820 } else {
821 if (message.getConversation().getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
822 try {
823 message.setCounterpart(Jid.fromSessionID(message.getConversation().getOtrSession().getSessionID()));
824 if (message.needsUploading()) {
825 mJingleConnectionManager.createNewConnection(message);
826 } else {
827 packet = mMessageGenerator.generateOtrChat(message, true);
828 }
829 } catch (final InvalidJidException ignored) {
830
831 }
832 }
833 }
834 } else if (message.needsUploading()) {
835 Contact contact = message.getConversation().getContact();
836 Presences presences = contact.getPresences();
837 if ((message.getCounterpart() != null)
838 && (presences.has(message.getCounterpart().getResourcepart()))) {
839 this.sendFileMessage(message);
840 } else {
841 if (presences.size() == 1) {
842 String presence = presences.asStringArray()[0];
843 try {
844 message.setCounterpart(Jid.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), presence));
845 } catch (InvalidJidException e) {
846 return;
847 }
848 this.sendFileMessage(message);
849 }
850 }
851 } else {
852 if (message.getEncryption() == Message.ENCRYPTION_NONE) {
853 packet = mMessageGenerator.generateChat(message, true);
854 } else if ((message.getEncryption() == Message.ENCRYPTION_DECRYPTED)
855 || (message.getEncryption() == Message.ENCRYPTION_PGP)) {
856 packet = mMessageGenerator.generatePgpChat(message, true);
857 }
858 }
859 if (packet != null) {
860 if (!account.getXmppConnection().getFeatures().sm()
861 && message.getConversation().getMode() != Conversation.MODE_MULTI) {
862 markMessage(message, Message.STATUS_SEND);
863 } else {
864 markMessage(message, Message.STATUS_UNSEND);
865 }
866 if (message.getConversation().setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
867 if (this.sendChatStates()) {
868 packet.addChild(ChatState.toElement(message.getConversation().getOutgoingChatState()));
869 }
870 }
871 sendMessagePacket(account, packet);
872 }
873 }
874
875 public void fetchRosterFromServer(final Account account) {
876 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
877 if (!"".equals(account.getRosterVersion())) {
878 Log.d(Config.LOGTAG, account.getJid().toBareJid()
879 + ": fetching roster version " + account.getRosterVersion());
880 } else {
881 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
882 }
883 iqPacket.query(Xmlns.ROSTER).setAttribute("ver",
884 account.getRosterVersion());
885 account.getXmppConnection().sendIqPacket(iqPacket, mIqParser);
886 }
887
888 public void fetchBookmarks(final Account account) {
889 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
890 final Element query = iqPacket.query("jabber:iq:private");
891 query.addChild("storage", "storage:bookmarks");
892 final OnIqPacketReceived callback = new OnIqPacketReceived() {
893
894 @Override
895 public void onIqPacketReceived(final Account account, final IqPacket packet) {
896 final Element query = packet.query();
897 final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
898 final Element storage = query.findChild("storage",
899 "storage:bookmarks");
900 if (storage != null) {
901 for (final Element item : storage.getChildren()) {
902 if (item.getName().equals("conference")) {
903 final Bookmark bookmark = Bookmark.parse(item, account);
904 bookmarks.add(bookmark);
905 Conversation conversation = find(bookmark);
906 if (conversation != null) {
907 conversation.setBookmark(bookmark);
908 } else if (bookmark.autojoin() && bookmark.getJid() != null) {
909 conversation = findOrCreateConversation(
910 account, bookmark.getJid(), true);
911 conversation.setBookmark(bookmark);
912 joinMuc(conversation);
913 }
914 }
915 }
916 }
917 account.setBookmarks(bookmarks);
918 }
919 };
920 sendIqPacket(account, iqPacket, callback);
921 }
922
923 public void pushBookmarks(Account account) {
924 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
925 Element query = iqPacket.query("jabber:iq:private");
926 Element storage = query.addChild("storage", "storage:bookmarks");
927 for (Bookmark bookmark : account.getBookmarks()) {
928 storage.addChild(bookmark);
929 }
930 sendIqPacket(account, iqPacket, mDefaultIqHandler);
931 }
932
933 public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
934 if (mPhoneContactMergerThread != null) {
935 mPhoneContactMergerThread.interrupt();
936 }
937 mPhoneContactMergerThread = new Thread(new Runnable() {
938 @Override
939 public void run() {
940 Log.d(Config.LOGTAG,"start merging phone contacts with roster");
941 for (Account account : accounts) {
942 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
943 for (Bundle phoneContact : phoneContacts) {
944 if (Thread.interrupted()) {
945 Log.d(Config.LOGTAG,"interrupted merging phone contacts");
946 return;
947 }
948 Jid jid;
949 try {
950 jid = Jid.fromString(phoneContact.getString("jid"));
951 } catch (final InvalidJidException e) {
952 continue;
953 }
954 final Contact contact = account.getRoster().getContact(jid);
955 String systemAccount = phoneContact.getInt("phoneid")
956 + "#"
957 + phoneContact.getString("lookup");
958 contact.setSystemAccount(systemAccount);
959 if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
960 getAvatarService().clear(contact);
961 }
962 contact.setSystemName(phoneContact.getString("displayname"));
963 withSystemAccounts.remove(contact);
964 }
965 for(Contact contact : withSystemAccounts) {
966 contact.setSystemAccount(null);
967 contact.setSystemName(null);
968 if (contact.setPhotoUri(null)) {
969 getAvatarService().clear(contact);
970 }
971 }
972 }
973 Log.d(Config.LOGTAG,"finished merging phone contacts");
974 updateAccountUi();
975 }
976 });
977 mPhoneContactMergerThread.start();
978 }
979
980 private void restoreFromDatabase() {
981 synchronized (this.conversations) {
982 final Map<String, Account> accountLookupTable = new Hashtable<>();
983 for (Account account : this.accounts) {
984 accountLookupTable.put(account.getUuid(), account);
985 }
986 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
987 for (Conversation conversation : this.conversations) {
988 Account account = accountLookupTable.get(conversation.getAccountUuid());
989 conversation.setAccount(account);
990 }
991 Runnable runnable =new Runnable() {
992 @Override
993 public void run() {
994 Log.d(Config.LOGTAG,"restoring roster");
995 for(Account account : accounts) {
996 databaseBackend.readRoster(account.getRoster());
997 }
998 getBitmapCache().evictAll();
999 Looper.prepare();
1000 PhoneHelper.loadPhoneContacts(getApplicationContext(),
1001 new CopyOnWriteArrayList<Bundle>(),
1002 XmppConnectionService.this);
1003 Log.d(Config.LOGTAG,"restoring messages");
1004 for (Conversation conversation : conversations) {
1005 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1006 checkDeletedFiles(conversation);
1007 }
1008 mRestoredFromDatabase = true;
1009 Log.d(Config.LOGTAG,"restored all messages");
1010 updateConversationUi();
1011 }
1012 };
1013 mDatabaseExecutor.execute(runnable);
1014 }
1015 }
1016
1017 public List<Conversation> getConversations() {
1018 return this.conversations;
1019 }
1020
1021 private void checkDeletedFiles(Conversation conversation) {
1022 conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1023
1024 @Override
1025 public void onMessageFound(Message message) {
1026 if (!getFileBackend().isFileAvailable(message)) {
1027 message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
1028 }
1029 }
1030 });
1031 }
1032
1033 private void markFileDeleted(String uuid) {
1034 for (Conversation conversation : getConversations()) {
1035 Message message = conversation.findMessageWithFileAndUuid(uuid);
1036 if (message != null) {
1037 if (!getFileBackend().isFileAvailable(message)) {
1038 message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
1039 updateConversationUi();
1040 }
1041 return;
1042 }
1043 }
1044 }
1045
1046 public void populateWithOrderedConversations(final List<Conversation> list) {
1047 populateWithOrderedConversations(list, true);
1048 }
1049
1050 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeConferences) {
1051 list.clear();
1052 if (includeConferences) {
1053 list.addAll(getConversations());
1054 } else {
1055 for (Conversation conversation : getConversations()) {
1056 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1057 list.add(conversation);
1058 }
1059 }
1060 }
1061 Collections.sort(list, new Comparator<Conversation>() {
1062 @Override
1063 public int compare(Conversation lhs, Conversation rhs) {
1064 Message left = lhs.getLatestMessage();
1065 Message right = rhs.getLatestMessage();
1066 if (left.getTimeSent() > right.getTimeSent()) {
1067 return -1;
1068 } else if (left.getTimeSent() < right.getTimeSent()) {
1069 return 1;
1070 } else {
1071 return 0;
1072 }
1073 }
1074 });
1075 }
1076
1077 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1078 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1079 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1080 return;
1081 }
1082 Runnable runnable = new Runnable() {
1083 @Override
1084 public void run() {
1085 final Account account = conversation.getAccount();
1086 List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1087 if (messages.size() > 0) {
1088 conversation.addAll(0, messages);
1089 checkDeletedFiles(conversation);
1090 callback.onMoreMessagesLoaded(messages.size(), conversation);
1091 } else if (conversation.hasMessagesLeftOnServer()
1092 && account.isOnlineAndConnected()
1093 && account.getXmppConnection().getFeatures().mam()) {
1094 MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1095 if (query != null) {
1096 query.setCallback(callback);
1097 }
1098 callback.informUser(R.string.fetching_history_from_server);
1099 }
1100 }
1101 };
1102 mDatabaseExecutor.execute(runnable);
1103 }
1104
1105 public List<Account> getAccounts() {
1106 return this.accounts;
1107 }
1108
1109 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1110 for (final Conversation conversation : haystack) {
1111 if (conversation.getContact() == contact) {
1112 return conversation;
1113 }
1114 }
1115 return null;
1116 }
1117
1118 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1119 if (jid == null) {
1120 return null;
1121 }
1122 for (final Conversation conversation : haystack) {
1123 if ((account == null || conversation.getAccount() == account)
1124 && (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1125 return conversation;
1126 }
1127 }
1128 return null;
1129 }
1130
1131 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1132 return this.findOrCreateConversation(account, jid, muc, null);
1133 }
1134
1135 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1136 synchronized (this.conversations) {
1137 Conversation conversation = find(account, jid);
1138 if (conversation != null) {
1139 return conversation;
1140 }
1141 conversation = databaseBackend.findConversation(account, jid);
1142 if (conversation != null) {
1143 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1144 conversation.setAccount(account);
1145 if (muc) {
1146 conversation.setMode(Conversation.MODE_MULTI);
1147 conversation.setContactJid(jid);
1148 } else {
1149 conversation.setMode(Conversation.MODE_SINGLE);
1150 conversation.setContactJid(jid.toBareJid());
1151 }
1152 conversation.setNextEncryption(-1);
1153 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1154 this.databaseBackend.updateConversation(conversation);
1155 } else {
1156 String conversationName;
1157 Contact contact = account.getRoster().getContact(jid);
1158 if (contact != null) {
1159 conversationName = contact.getDisplayName();
1160 } else {
1161 conversationName = jid.getLocalpart();
1162 }
1163 if (muc) {
1164 conversation = new Conversation(conversationName, account, jid,
1165 Conversation.MODE_MULTI);
1166 } else {
1167 conversation = new Conversation(conversationName, account, jid.toBareJid(),
1168 Conversation.MODE_SINGLE);
1169 }
1170 this.databaseBackend.createConversation(conversation);
1171 }
1172 if (account.getXmppConnection() != null
1173 && account.getXmppConnection().getFeatures().mam()
1174 && !muc) {
1175 if (query == null) {
1176 this.mMessageArchiveService.query(conversation);
1177 } else {
1178 if (query.getConversation() == null) {
1179 this.mMessageArchiveService.query(conversation, query.getStart());
1180 }
1181 }
1182 }
1183 checkDeletedFiles(conversation);
1184 this.conversations.add(conversation);
1185 updateConversationUi();
1186 return conversation;
1187 }
1188 }
1189
1190 public void archiveConversation(Conversation conversation) {
1191 getNotificationService().clear(conversation);
1192 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1193 conversation.setNextEncryption(-1);
1194 synchronized (this.conversations) {
1195 if (conversation.getMode() == Conversation.MODE_MULTI) {
1196 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1197 Bookmark bookmark = conversation.getBookmark();
1198 if (bookmark != null && bookmark.autojoin()) {
1199 bookmark.setAutojoin(false);
1200 pushBookmarks(bookmark.getAccount());
1201 }
1202 }
1203 leaveMuc(conversation);
1204 } else {
1205 conversation.endOtrIfNeeded();
1206 }
1207 this.databaseBackend.updateConversation(conversation);
1208 this.conversations.remove(conversation);
1209 updateConversationUi();
1210 }
1211 }
1212
1213 public void createAccount(final Account account) {
1214 account.initAccountServices(this);
1215 databaseBackend.createAccount(account);
1216 this.accounts.add(account);
1217 this.reconnectAccountInBackground(account);
1218 updateAccountUi();
1219 }
1220
1221 public void updateAccount(final Account account) {
1222 this.statusListener.onStatusChanged(account);
1223 databaseBackend.updateAccount(account);
1224 reconnectAccount(account, false);
1225 updateAccountUi();
1226 getNotificationService().updateErrorNotification();
1227 }
1228
1229 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1230 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1231 sendIqPacket(account, iq, new OnIqPacketReceived() {
1232 @Override
1233 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1234 if (packet.getType() == IqPacket.TYPE.RESULT) {
1235 account.setPassword(newPassword);
1236 databaseBackend.updateAccount(account);
1237 callback.onPasswordChangeSucceeded();
1238 } else {
1239 callback.onPasswordChangeFailed();
1240 }
1241 }
1242 });
1243 }
1244
1245 public void deleteAccount(final Account account) {
1246 synchronized (this.conversations) {
1247 for (final Conversation conversation : conversations) {
1248 if (conversation.getAccount() == account) {
1249 if (conversation.getMode() == Conversation.MODE_MULTI) {
1250 leaveMuc(conversation);
1251 } else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1252 conversation.endOtrIfNeeded();
1253 }
1254 conversations.remove(conversation);
1255 }
1256 }
1257 if (account.getXmppConnection() != null) {
1258 this.disconnect(account, true);
1259 }
1260 databaseBackend.deleteAccount(account);
1261 this.accounts.remove(account);
1262 updateAccountUi();
1263 getNotificationService().updateErrorNotification();
1264 }
1265 }
1266
1267 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1268 synchronized (this) {
1269 if (checkListeners()) {
1270 switchToForeground();
1271 }
1272 this.mOnConversationUpdate = listener;
1273 this.mNotificationService.setIsInForeground(true);
1274 if (this.convChangedListenerCount < 2) {
1275 this.convChangedListenerCount++;
1276 }
1277 }
1278 }
1279
1280 public void removeOnConversationListChangedListener() {
1281 synchronized (this) {
1282 this.convChangedListenerCount--;
1283 if (this.convChangedListenerCount <= 0) {
1284 this.convChangedListenerCount = 0;
1285 this.mOnConversationUpdate = null;
1286 this.mNotificationService.setIsInForeground(false);
1287 if (checkListeners()) {
1288 switchToBackground();
1289 }
1290 }
1291 }
1292 }
1293
1294 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1295 synchronized (this) {
1296 if (checkListeners()) {
1297 switchToForeground();
1298 }
1299 this.mOnAccountUpdate = listener;
1300 if (this.accountChangedListenerCount < 2) {
1301 this.accountChangedListenerCount++;
1302 }
1303 }
1304 }
1305
1306 public void removeOnAccountListChangedListener() {
1307 synchronized (this) {
1308 this.accountChangedListenerCount--;
1309 if (this.accountChangedListenerCount <= 0) {
1310 this.mOnAccountUpdate = null;
1311 this.accountChangedListenerCount = 0;
1312 if (checkListeners()) {
1313 switchToBackground();
1314 }
1315 }
1316 }
1317 }
1318
1319 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1320 synchronized (this) {
1321 if (checkListeners()) {
1322 switchToForeground();
1323 }
1324 this.mOnRosterUpdate = listener;
1325 if (this.rosterChangedListenerCount < 2) {
1326 this.rosterChangedListenerCount++;
1327 }
1328 }
1329 }
1330
1331 public void removeOnRosterUpdateListener() {
1332 synchronized (this) {
1333 this.rosterChangedListenerCount--;
1334 if (this.rosterChangedListenerCount <= 0) {
1335 this.rosterChangedListenerCount = 0;
1336 this.mOnRosterUpdate = null;
1337 if (checkListeners()) {
1338 switchToBackground();
1339 }
1340 }
1341 }
1342 }
1343
1344 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1345 synchronized (this) {
1346 if (checkListeners()) {
1347 switchToForeground();
1348 }
1349 this.mOnUpdateBlocklist = listener;
1350 if (this.updateBlocklistListenerCount < 2) {
1351 this.updateBlocklistListenerCount++;
1352 }
1353 }
1354 }
1355
1356 public void removeOnUpdateBlocklistListener() {
1357 synchronized (this) {
1358 this.updateBlocklistListenerCount--;
1359 if (this.updateBlocklistListenerCount <= 0) {
1360 this.updateBlocklistListenerCount = 0;
1361 this.mOnUpdateBlocklist = null;
1362 if (checkListeners()) {
1363 switchToBackground();
1364 }
1365 }
1366 }
1367 }
1368
1369 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1370 synchronized (this) {
1371 if (checkListeners()) {
1372 switchToForeground();
1373 }
1374 this.mOnMucRosterUpdate = listener;
1375 if (this.mucRosterChangedListenerCount < 2) {
1376 this.mucRosterChangedListenerCount++;
1377 }
1378 }
1379 }
1380
1381 public void removeOnMucRosterUpdateListener() {
1382 synchronized (this) {
1383 this.mucRosterChangedListenerCount--;
1384 if (this.mucRosterChangedListenerCount <= 0) {
1385 this.mucRosterChangedListenerCount = 0;
1386 this.mOnMucRosterUpdate = null;
1387 if (checkListeners()) {
1388 switchToBackground();
1389 }
1390 }
1391 }
1392 }
1393
1394 private boolean checkListeners() {
1395 return (this.mOnAccountUpdate == null
1396 && this.mOnConversationUpdate == null
1397 && this.mOnRosterUpdate == null
1398 && this.mOnUpdateBlocklist == null);
1399 }
1400
1401 private void switchToForeground() {
1402 for (Account account : getAccounts()) {
1403 if (account.getStatus() == Account.State.ONLINE) {
1404 XmppConnection connection = account.getXmppConnection();
1405 if (connection != null && connection.getFeatures().csi()) {
1406 connection.sendActive();
1407 }
1408 }
1409 }
1410 Log.d(Config.LOGTAG, "app switched into foreground");
1411 }
1412
1413 private void switchToBackground() {
1414 for (Account account : getAccounts()) {
1415 if (account.getStatus() == Account.State.ONLINE) {
1416 XmppConnection connection = account.getXmppConnection();
1417 if (connection != null && connection.getFeatures().csi()) {
1418 connection.sendInactive();
1419 }
1420 }
1421 }
1422 for(Conversation conversation : getConversations()) {
1423 conversation.setIncomingChatState(ChatState.ACTIVE);
1424 }
1425 this.mNotificationService.setIsInForeground(false);
1426 Log.d(Config.LOGTAG, "app switched into background");
1427 }
1428
1429 private void connectMultiModeConversations(Account account) {
1430 List<Conversation> conversations = getConversations();
1431 for (Conversation conversation : conversations) {
1432 if ((conversation.getMode() == Conversation.MODE_MULTI)
1433 && (conversation.getAccount() == account)) {
1434 conversation.resetMucOptions();
1435 joinMuc(conversation);
1436 }
1437 }
1438 }
1439
1440 public void joinMuc(Conversation conversation) {
1441 Account account = conversation.getAccount();
1442 account.pendingConferenceJoins.remove(conversation);
1443 account.pendingConferenceLeaves.remove(conversation);
1444 if (account.getStatus() == Account.State.ONLINE) {
1445 final String nick = conversation.getMucOptions().getProposedNick();
1446 final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1447 if (joinJid == null) {
1448 return; //safety net
1449 }
1450 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1451 PresencePacket packet = new PresencePacket();
1452 packet.setFrom(conversation.getAccount().getJid());
1453 packet.setTo(joinJid);
1454 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1455 if (conversation.getMucOptions().getPassword() != null) {
1456 x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1457 }
1458 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1459 String sig = account.getPgpSignature();
1460 if (sig != null) {
1461 packet.addChild("status").setContent("online");
1462 packet.addChild("x", "jabber:x:signed").setContent(sig);
1463 }
1464 sendPresencePacket(account, packet);
1465 fetchConferenceConfiguration(conversation);
1466 if (!joinJid.equals(conversation.getJid())) {
1467 conversation.setContactJid(joinJid);
1468 databaseBackend.updateConversation(conversation);
1469 }
1470 conversation.setHasMessagesLeftOnServer(false);
1471 } else {
1472 account.pendingConferenceJoins.add(conversation);
1473 }
1474 }
1475
1476 public void providePasswordForMuc(Conversation conversation, String password) {
1477 if (conversation.getMode() == Conversation.MODE_MULTI) {
1478 conversation.getMucOptions().setPassword(password);
1479 if (conversation.getBookmark() != null) {
1480 conversation.getBookmark().setAutojoin(true);
1481 pushBookmarks(conversation.getAccount());
1482 }
1483 databaseBackend.updateConversation(conversation);
1484 joinMuc(conversation);
1485 }
1486 }
1487
1488 public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1489 final MucOptions options = conversation.getMucOptions();
1490 final Jid joinJid = options.createJoinJid(nick);
1491 if (options.online()) {
1492 Account account = conversation.getAccount();
1493 options.setOnRenameListener(new OnRenameListener() {
1494
1495 @Override
1496 public void onSuccess() {
1497 conversation.setContactJid(joinJid);
1498 databaseBackend.updateConversation(conversation);
1499 Bookmark bookmark = conversation.getBookmark();
1500 if (bookmark != null) {
1501 bookmark.setNick(nick);
1502 pushBookmarks(bookmark.getAccount());
1503 }
1504 callback.success(conversation);
1505 }
1506
1507 @Override
1508 public void onFailure() {
1509 callback.error(R.string.nick_in_use, conversation);
1510 }
1511 });
1512
1513 PresencePacket packet = new PresencePacket();
1514 packet.setTo(joinJid);
1515 packet.setFrom(conversation.getAccount().getJid());
1516
1517 String sig = account.getPgpSignature();
1518 if (sig != null) {
1519 packet.addChild("status").setContent("online");
1520 packet.addChild("x", "jabber:x:signed").setContent(sig);
1521 }
1522 sendPresencePacket(account, packet);
1523 } else {
1524 conversation.setContactJid(joinJid);
1525 databaseBackend.updateConversation(conversation);
1526 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1527 Bookmark bookmark = conversation.getBookmark();
1528 if (bookmark != null) {
1529 bookmark.setNick(nick);
1530 pushBookmarks(bookmark.getAccount());
1531 }
1532 joinMuc(conversation);
1533 }
1534 }
1535 }
1536
1537 public void leaveMuc(Conversation conversation) {
1538 Account account = conversation.getAccount();
1539 account.pendingConferenceJoins.remove(conversation);
1540 account.pendingConferenceLeaves.remove(conversation);
1541 if (account.getStatus() == Account.State.ONLINE) {
1542 PresencePacket packet = new PresencePacket();
1543 packet.setTo(conversation.getJid());
1544 packet.setFrom(conversation.getAccount().getJid());
1545 packet.setAttribute("type", "unavailable");
1546 sendPresencePacket(conversation.getAccount(), packet);
1547 conversation.getMucOptions().setOffline();
1548 conversation.deregisterWithBookmark();
1549 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1550 + ": leaving muc " + conversation.getJid());
1551 } else {
1552 account.pendingConferenceLeaves.add(conversation);
1553 }
1554 }
1555
1556 private String findConferenceServer(final Account account) {
1557 String server;
1558 if (account.getXmppConnection() != null) {
1559 server = account.getXmppConnection().getMucServer();
1560 if (server != null) {
1561 return server;
1562 }
1563 }
1564 for (Account other : getAccounts()) {
1565 if (other != account && other.getXmppConnection() != null) {
1566 server = other.getXmppConnection().getMucServer();
1567 if (server != null) {
1568 return server;
1569 }
1570 }
1571 }
1572 return null;
1573 }
1574
1575 public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1576 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1577 if (account.getStatus() == Account.State.ONLINE) {
1578 try {
1579 String server = findConferenceServer(account);
1580 if (server == null) {
1581 if (callback != null) {
1582 callback.error(R.string.no_conference_server_found, null);
1583 }
1584 return;
1585 }
1586 String name = new BigInteger(75, getRNG()).toString(32);
1587 Jid jid = Jid.fromParts(name, server, null);
1588 final Conversation conversation = findOrCreateConversation(account, jid, true);
1589 joinMuc(conversation);
1590 Bundle options = new Bundle();
1591 options.putString("muc#roomconfig_persistentroom", "1");
1592 options.putString("muc#roomconfig_membersonly", "1");
1593 options.putString("muc#roomconfig_publicroom", "0");
1594 options.putString("muc#roomconfig_whois", "anyone");
1595 pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1596 @Override
1597 public void onPushSucceeded() {
1598 for (Jid invite : jids) {
1599 invite(conversation, invite);
1600 }
1601 if (account.countPresences() > 1) {
1602 directInvite(conversation, account.getJid().toBareJid());
1603 }
1604 if (callback != null) {
1605 callback.success(conversation);
1606 }
1607 }
1608
1609 @Override
1610 public void onPushFailed() {
1611 if (callback != null) {
1612 callback.error(R.string.conference_creation_failed, conversation);
1613 }
1614 }
1615 });
1616
1617 } catch (InvalidJidException e) {
1618 if (callback != null) {
1619 callback.error(R.string.conference_creation_failed, null);
1620 }
1621 }
1622 } else {
1623 if (callback != null) {
1624 callback.error(R.string.not_connected_try_again, null);
1625 }
1626 }
1627 }
1628
1629 public void fetchConferenceConfiguration(final Conversation conversation) {
1630 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1631 request.setTo(conversation.getJid().toBareJid());
1632 request.query("http://jabber.org/protocol/disco#info");
1633 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1634 @Override
1635 public void onIqPacketReceived(Account account, IqPacket packet) {
1636 if (packet.getType() != IqPacket.TYPE.ERROR) {
1637 ArrayList<String> features = new ArrayList<>();
1638 for (Element child : packet.query().getChildren()) {
1639 if (child != null && child.getName().equals("feature")) {
1640 String var = child.getAttribute("var");
1641 if (var != null) {
1642 features.add(var);
1643 }
1644 }
1645 }
1646 conversation.getMucOptions().updateFeatures(features);
1647 updateConversationUi();
1648 }
1649 }
1650 });
1651 }
1652
1653 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1654 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1655 request.setTo(conversation.getJid().toBareJid());
1656 request.query("http://jabber.org/protocol/muc#owner");
1657 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1658 @Override
1659 public void onIqPacketReceived(Account account, IqPacket packet) {
1660 if (packet.getType() != IqPacket.TYPE.ERROR) {
1661 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1662 for (Field field : data.getFields()) {
1663 if (options.containsKey(field.getName())) {
1664 field.setValue(options.getString(field.getName()));
1665 }
1666 }
1667 data.submit();
1668 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1669 set.setTo(conversation.getJid().toBareJid());
1670 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1671 sendIqPacket(account, set, new OnIqPacketReceived() {
1672 @Override
1673 public void onIqPacketReceived(Account account, IqPacket packet) {
1674 if (packet.getType() == IqPacket.TYPE.RESULT) {
1675 if (callback != null) {
1676 callback.onPushSucceeded();
1677 }
1678 } else {
1679 if (callback != null) {
1680 callback.onPushFailed();
1681 }
1682 }
1683 }
1684 });
1685 } else {
1686 if (callback != null) {
1687 callback.onPushFailed();
1688 }
1689 }
1690 }
1691 });
1692 }
1693
1694 public void pushSubjectToConference(final Conversation conference, final String subject) {
1695 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1696 this.sendMessagePacket(conference.getAccount(), packet);
1697 final MucOptions mucOptions = conference.getMucOptions();
1698 final MucOptions.User self = mucOptions.getSelf();
1699 if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1700 Bundle options = new Bundle();
1701 options.putString("muc#roomconfig_persistentroom", "1");
1702 this.pushConferenceConfiguration(conference, options, null);
1703 }
1704 }
1705
1706 public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1707 final Jid jid = user.toBareJid();
1708 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1709 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1710 @Override
1711 public void onIqPacketReceived(Account account, IqPacket packet) {
1712 if (packet.getType() == IqPacket.TYPE.RESULT) {
1713 callback.onAffiliationChangedSuccessful(jid);
1714 } else {
1715 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1716 }
1717 }
1718 });
1719 }
1720
1721 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1722 List<Jid> jids = new ArrayList<>();
1723 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1724 if (user.getAffiliation() == before) {
1725 jids.add(user.getJid());
1726 }
1727 }
1728 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1729 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1730 }
1731
1732 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1733 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1734 Log.d(Config.LOGTAG, request.toString());
1735 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1736 @Override
1737 public void onIqPacketReceived(Account account, IqPacket packet) {
1738 Log.d(Config.LOGTAG, packet.toString());
1739 if (packet.getType() == IqPacket.TYPE.RESULT) {
1740 callback.onRoleChangedSuccessful(nick);
1741 } else {
1742 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1743 }
1744 }
1745 });
1746 }
1747
1748 public void disconnect(Account account, boolean force) {
1749 if ((account.getStatus() == Account.State.ONLINE)
1750 || (account.getStatus() == Account.State.DISABLED)) {
1751 if (!force) {
1752 List<Conversation> conversations = getConversations();
1753 for (Conversation conversation : conversations) {
1754 if (conversation.getAccount() == account) {
1755 if (conversation.getMode() == Conversation.MODE_MULTI) {
1756 leaveMuc(conversation);
1757 } else {
1758 if (conversation.endOtrIfNeeded()) {
1759 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1760 + ": ended otr session with "
1761 + conversation.getJid());
1762 }
1763 }
1764 }
1765 }
1766 sendOfflinePresence(account);
1767 }
1768 account.getXmppConnection().disconnect(force);
1769 }
1770 }
1771
1772 @Override
1773 public IBinder onBind(Intent intent) {
1774 return mBinder;
1775 }
1776
1777 public void updateMessage(Message message) {
1778 databaseBackend.updateMessage(message);
1779 updateConversationUi();
1780 }
1781
1782 protected void syncDirtyContacts(Account account) {
1783 for (Contact contact : account.getRoster().getContacts()) {
1784 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1785 pushContactToServer(contact);
1786 }
1787 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1788 deleteContactOnServer(contact);
1789 }
1790 }
1791 }
1792
1793 public void createContact(Contact contact) {
1794 SharedPreferences sharedPref = getPreferences();
1795 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1796 if (autoGrant) {
1797 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1798 contact.setOption(Contact.Options.ASKING);
1799 }
1800 pushContactToServer(contact);
1801 }
1802
1803 public void onOtrSessionEstablished(Conversation conversation) {
1804 final Account account = conversation.getAccount();
1805 final Session otrSession = conversation.getOtrSession();
1806 Log.d(Config.LOGTAG,
1807 account.getJid().toBareJid() + " otr session established with "
1808 + conversation.getJid() + "/"
1809 + otrSession.getSessionID().getUserID());
1810 conversation.findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
1811
1812 @Override
1813 public void onMessageFound(Message message) {
1814 SessionID id = otrSession.getSessionID();
1815 try {
1816 message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1817 } catch (InvalidJidException e) {
1818 return;
1819 }
1820 if (message.needsUploading()) {
1821 mJingleConnectionManager.createNewConnection(message);
1822 } else {
1823 MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1824 if (outPacket != null) {
1825 message.setStatus(Message.STATUS_SEND);
1826 databaseBackend.updateMessage(message);
1827 sendMessagePacket(account, outPacket);
1828 }
1829 }
1830 updateConversationUi();
1831 }
1832 });
1833 }
1834
1835 public boolean renewSymmetricKey(Conversation conversation) {
1836 Account account = conversation.getAccount();
1837 byte[] symmetricKey = new byte[32];
1838 this.mRandom.nextBytes(symmetricKey);
1839 Session otrSession = conversation.getOtrSession();
1840 if (otrSession != null) {
1841 MessagePacket packet = new MessagePacket();
1842 packet.setType(MessagePacket.TYPE_CHAT);
1843 packet.setFrom(account.getJid());
1844 packet.addChild("private", "urn:xmpp:carbons:2");
1845 packet.addChild("no-copy", "urn:xmpp:hints");
1846 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1847 + otrSession.getSessionID().getUserID());
1848 try {
1849 packet.setBody(otrSession
1850 .transformSending(CryptoHelper.FILETRANSFER
1851 + CryptoHelper.bytesToHex(symmetricKey))[0]);
1852 sendMessagePacket(account, packet);
1853 conversation.setSymmetricKey(symmetricKey);
1854 return true;
1855 } catch (OtrException e) {
1856 return false;
1857 }
1858 }
1859 return false;
1860 }
1861
1862 public void pushContactToServer(final Contact contact) {
1863 contact.resetOption(Contact.Options.DIRTY_DELETE);
1864 contact.setOption(Contact.Options.DIRTY_PUSH);
1865 final Account account = contact.getAccount();
1866 if (account.getStatus() == Account.State.ONLINE) {
1867 final boolean ask = contact.getOption(Contact.Options.ASKING);
1868 final boolean sendUpdates = contact
1869 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1870 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1871 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1872 iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1873 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
1874 if (sendUpdates) {
1875 sendPresencePacket(account,
1876 mPresenceGenerator.sendPresenceUpdatesTo(contact));
1877 }
1878 if (ask) {
1879 sendPresencePacket(account,
1880 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1881 }
1882 }
1883 }
1884
1885 public void publishAvatar(final Account account,
1886 final Uri image,
1887 final UiCallback<Avatar> callback) {
1888 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1889 final int size = Config.AVATAR_SIZE;
1890 final Avatar avatar = getFileBackend()
1891 .getPepAvatar(image, size, format);
1892 if (avatar != null) {
1893 avatar.height = size;
1894 avatar.width = size;
1895 if (format.equals(Bitmap.CompressFormat.WEBP)) {
1896 avatar.type = "image/webp";
1897 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1898 avatar.type = "image/jpeg";
1899 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1900 avatar.type = "image/png";
1901 }
1902 if (!getFileBackend().save(avatar)) {
1903 callback.error(R.string.error_saving_avatar, avatar);
1904 return;
1905 }
1906 final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1907 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1908
1909 @Override
1910 public void onIqPacketReceived(Account account, IqPacket result) {
1911 if (result.getType() == IqPacket.TYPE.RESULT) {
1912 final IqPacket packet = XmppConnectionService.this.mIqGenerator
1913 .publishAvatarMetadata(avatar);
1914 sendIqPacket(account, packet, new OnIqPacketReceived() {
1915
1916 @Override
1917 public void onIqPacketReceived(Account account,
1918 IqPacket result) {
1919 if (result.getType() == IqPacket.TYPE.RESULT) {
1920 if (account.setAvatar(avatar.getFilename())) {
1921 getAvatarService().clear(account);
1922 databaseBackend.updateAccount(account);
1923 }
1924 callback.success(avatar);
1925 } else {
1926 callback.error(
1927 R.string.error_publish_avatar_server_reject,
1928 avatar);
1929 }
1930 }
1931 });
1932 } else {
1933 callback.error(
1934 R.string.error_publish_avatar_server_reject,
1935 avatar);
1936 }
1937 }
1938 });
1939 } else {
1940 callback.error(R.string.error_publish_avatar_converting, null);
1941 }
1942 }
1943
1944 public void fetchAvatar(Account account, Avatar avatar) {
1945 fetchAvatar(account, avatar, null);
1946 }
1947
1948 private static String generateFetchKey(Account account, final Avatar avatar) {
1949 return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
1950 }
1951
1952 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1953 final String KEY = generateFetchKey(account, avatar);
1954 synchronized(this.mInProgressAvatarFetches) {
1955 if (this.mInProgressAvatarFetches.contains(KEY)) {
1956 return;
1957 } else {
1958 switch (avatar.origin) {
1959 case PEP:
1960 this.mInProgressAvatarFetches.add(KEY);
1961 fetchAvatarPep(account, avatar, callback);
1962 break;
1963 case VCARD:
1964 this.mInProgressAvatarFetches.add(KEY);
1965 fetchAvatarVcard(account, avatar, callback);
1966 break;
1967 }
1968 }
1969 }
1970 }
1971
1972 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1973 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
1974 sendIqPacket(account, packet, new OnIqPacketReceived() {
1975
1976 @Override
1977 public void onIqPacketReceived(Account account, IqPacket result) {
1978 synchronized (mInProgressAvatarFetches) {
1979 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
1980 }
1981 final String ERROR = account.getJid().toBareJid()
1982 + ": fetching avatar for " + avatar.owner + " failed ";
1983 if (result.getType() == IqPacket.TYPE.RESULT) {
1984 avatar.image = mIqParser.avatarData(result);
1985 if (avatar.image != null) {
1986 if (getFileBackend().save(avatar)) {
1987 if (account.getJid().toBareJid().equals(avatar.owner)) {
1988 if (account.setAvatar(avatar.getFilename())) {
1989 databaseBackend.updateAccount(account);
1990 }
1991 getAvatarService().clear(account);
1992 updateConversationUi();
1993 updateAccountUi();
1994 } else {
1995 Contact contact = account.getRoster()
1996 .getContact(avatar.owner);
1997 contact.setAvatar(avatar);
1998 getAvatarService().clear(contact);
1999 updateConversationUi();
2000 updateRosterUi();
2001 }
2002 if (callback != null) {
2003 callback.success(avatar);
2004 }
2005 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2006 + ": succesfuly fetched pep avatar for " + avatar.owner);
2007 return;
2008 }
2009 } else {
2010
2011 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2012 }
2013 } else {
2014 Element error = result.findChild("error");
2015 if (error == null) {
2016 Log.d(Config.LOGTAG, ERROR + "(server error)");
2017 } else {
2018 Log.d(Config.LOGTAG, ERROR + error.toString());
2019 }
2020 }
2021 if (callback != null) {
2022 callback.error(0, null);
2023 }
2024
2025 }
2026 });
2027 }
2028
2029 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2030 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2031 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2032 @Override
2033 public void onIqPacketReceived(Account account, IqPacket packet) {
2034 synchronized (mInProgressAvatarFetches) {
2035 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2036 }
2037 if (packet.getType() == IqPacket.TYPE.RESULT) {
2038 Element vCard = packet.findChild("vCard", "vcard-temp");
2039 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2040 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2041 if (image != null) {
2042 avatar.image = image;
2043 if (getFileBackend().save(avatar)) {
2044 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2045 + ": successfully fetched vCard avatar for " + avatar.owner);
2046 Contact contact = account.getRoster()
2047 .getContact(avatar.owner);
2048 contact.setAvatar(avatar);
2049 getAvatarService().clear(contact);
2050 updateConversationUi();
2051 updateRosterUi();
2052 }
2053 }
2054 }
2055 }
2056 });
2057 }
2058
2059 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2060 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2061 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2062
2063 @Override
2064 public void onIqPacketReceived(Account account, IqPacket packet) {
2065 if (packet.getType() == IqPacket.TYPE.RESULT) {
2066 Element pubsub = packet.findChild("pubsub",
2067 "http://jabber.org/protocol/pubsub");
2068 if (pubsub != null) {
2069 Element items = pubsub.findChild("items");
2070 if (items != null) {
2071 Avatar avatar = Avatar.parseMetadata(items);
2072 if (avatar != null) {
2073 avatar.owner = account.getJid().toBareJid();
2074 if (fileBackend.isAvatarCached(avatar)) {
2075 if (account.setAvatar(avatar.getFilename())) {
2076 databaseBackend.updateAccount(account);
2077 }
2078 getAvatarService().clear(account);
2079 callback.success(avatar);
2080 } else {
2081 fetchAvatarPep(account, avatar, callback);
2082 }
2083 return;
2084 }
2085 }
2086 }
2087 }
2088 callback.error(0, null);
2089 }
2090 });
2091 }
2092
2093 public void deleteContactOnServer(Contact contact) {
2094 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2095 contact.resetOption(Contact.Options.DIRTY_PUSH);
2096 contact.setOption(Contact.Options.DIRTY_DELETE);
2097 Account account = contact.getAccount();
2098 if (account.getStatus() == Account.State.ONLINE) {
2099 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2100 Element item = iq.query(Xmlns.ROSTER).addChild("item");
2101 item.setAttribute("jid", contact.getJid().toString());
2102 item.setAttribute("subscription", "remove");
2103 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2104 }
2105 }
2106
2107 public void updateConversation(Conversation conversation) {
2108 this.databaseBackend.updateConversation(conversation);
2109 }
2110
2111 public void reconnectAccount(final Account account, final boolean force) {
2112 synchronized (account) {
2113 if (account.getXmppConnection() != null) {
2114 disconnect(account, force);
2115 }
2116 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2117
2118 synchronized (this.mInProgressAvatarFetches) {
2119 for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2120 final String KEY = iterator.next();
2121 if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2122 iterator.remove();
2123 }
2124 }
2125 }
2126
2127 if (account.getXmppConnection() == null) {
2128 account.setXmppConnection(createConnection(account));
2129 }
2130 Thread thread = new Thread(account.getXmppConnection());
2131 thread.start();
2132 scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2133 } else {
2134 account.getRoster().clearPresences();
2135 account.setXmppConnection(null);
2136 }
2137 }
2138 }
2139
2140 public void reconnectAccountInBackground(final Account account) {
2141 new Thread(new Runnable() {
2142 @Override
2143 public void run() {
2144 reconnectAccount(account,false);
2145 }
2146 }).start();
2147 }
2148
2149 public void invite(Conversation conversation, Jid contact) {
2150 Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2151 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2152 sendMessagePacket(conversation.getAccount(), packet);
2153 }
2154
2155 public void directInvite(Conversation conversation, Jid jid) {
2156 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2157 sendMessagePacket(conversation.getAccount(),packet);
2158 }
2159
2160 public void resetSendingToWaiting(Account account) {
2161 for (Conversation conversation : getConversations()) {
2162 if (conversation.getAccount() == account) {
2163 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2164
2165 @Override
2166 public void onMessageFound(Message message) {
2167 markMessage(message, Message.STATUS_WAITING);
2168 }
2169 });
2170 }
2171 }
2172 }
2173
2174 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2175 if (uuid == null) {
2176 return null;
2177 }
2178 for (Conversation conversation : getConversations()) {
2179 if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2180 final Message message = conversation.findSentMessageWithUuid(uuid);
2181 if (message != null) {
2182 markMessage(message, status);
2183 }
2184 return message;
2185 }
2186 }
2187 return null;
2188 }
2189
2190 public boolean markMessage(Conversation conversation, String uuid,
2191 int status) {
2192 if (uuid == null) {
2193 return false;
2194 } else {
2195 Message message = conversation.findSentMessageWithUuid(uuid);
2196 if (message != null) {
2197 markMessage(message, status);
2198 return true;
2199 } else {
2200 return false;
2201 }
2202 }
2203 }
2204
2205 public void markMessage(Message message, int status) {
2206 if (status == Message.STATUS_SEND_FAILED
2207 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2208 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2209 return;
2210 }
2211 message.setStatus(status);
2212 databaseBackend.updateMessage(message);
2213 updateConversationUi();
2214 }
2215
2216 public SharedPreferences getPreferences() {
2217 return PreferenceManager
2218 .getDefaultSharedPreferences(getApplicationContext());
2219 }
2220
2221 public boolean forceEncryption() {
2222 return getPreferences().getBoolean("force_encryption", false);
2223 }
2224
2225 public boolean confirmMessages() {
2226 return getPreferences().getBoolean("confirm_messages", true);
2227 }
2228
2229 public boolean sendChatStates() {
2230 return getPreferences().getBoolean("chat_states", false);
2231 }
2232
2233 public boolean saveEncryptedMessages() {
2234 return !getPreferences().getBoolean("dont_save_encrypted", false);
2235 }
2236
2237 public boolean indicateReceived() {
2238 return getPreferences().getBoolean("indicate_received", false);
2239 }
2240
2241 public int unreadCount() {
2242 int count = 0;
2243 for(Conversation conversation : getConversations()) {
2244 count += conversation.unreadCount();
2245 }
2246 return count;
2247 }
2248
2249 public void updateConversationUi() {
2250 if (mOnConversationUpdate != null) {
2251 mOnConversationUpdate.onConversationUpdate();
2252 }
2253 }
2254
2255 public void updateAccountUi() {
2256 if (mOnAccountUpdate != null) {
2257 mOnAccountUpdate.onAccountUpdate();
2258 }
2259 }
2260
2261 public void updateRosterUi() {
2262 if (mOnRosterUpdate != null) {
2263 mOnRosterUpdate.onRosterUpdate();
2264 }
2265 }
2266
2267 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2268 if (mOnUpdateBlocklist != null) {
2269 mOnUpdateBlocklist.OnUpdateBlocklist(status);
2270 }
2271 }
2272
2273 public void updateMucRosterUi() {
2274 if (mOnMucRosterUpdate != null) {
2275 mOnMucRosterUpdate.onMucRosterUpdate();
2276 }
2277 }
2278
2279 public Account findAccountByJid(final Jid accountJid) {
2280 for (Account account : this.accounts) {
2281 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2282 return account;
2283 }
2284 }
2285 return null;
2286 }
2287
2288 public Conversation findConversationByUuid(String uuid) {
2289 for (Conversation conversation : getConversations()) {
2290 if (conversation.getUuid().equals(uuid)) {
2291 return conversation;
2292 }
2293 }
2294 return null;
2295 }
2296
2297 public void markRead(final Conversation conversation) {
2298 mNotificationService.clear(conversation);
2299 conversation.markRead();
2300 updateUnreadCountBadge();
2301 }
2302
2303 public synchronized void updateUnreadCountBadge() {
2304 int count = unreadCount();
2305 if (unreadCount != count) {
2306 Log.d(Config.LOGTAG, "update unread count to " + count);
2307 if (count > 0) {
2308 ShortcutBadger.with(getApplicationContext()).count(count);
2309 } else {
2310 ShortcutBadger.with(getApplicationContext()).remove();
2311 }
2312 unreadCount = count;
2313 }
2314 }
2315
2316 public void sendReadMarker(final Conversation conversation) {
2317 final Message markable = conversation.getLatestMarkableMessage();
2318 this.markRead(conversation);
2319 if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2320 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2321 Account account = conversation.getAccount();
2322 final Jid to = markable.getCounterpart();
2323 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2324 this.sendMessagePacket(conversation.getAccount(), packet);
2325 }
2326 updateConversationUi();
2327 }
2328
2329 public SecureRandom getRNG() {
2330 return this.mRandom;
2331 }
2332
2333 public MemorizingTrustManager getMemorizingTrustManager() {
2334 return this.mMemorizingTrustManager;
2335 }
2336
2337 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2338 this.mMemorizingTrustManager = trustManager;
2339 }
2340
2341 public void updateMemorizingTrustmanager() {
2342 final MemorizingTrustManager tm;
2343 final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2344 if (dontTrustSystemCAs) {
2345 tm = new MemorizingTrustManager(getApplicationContext(), null);
2346 } else {
2347 tm = new MemorizingTrustManager(getApplicationContext());
2348 }
2349 setMemorizingTrustManager(tm);
2350 }
2351
2352 public PowerManager getPowerManager() {
2353 return this.pm;
2354 }
2355
2356 public LruCache<String, Bitmap> getBitmapCache() {
2357 return this.mBitmapCache;
2358 }
2359
2360 public void syncRosterToDisk(final Account account) {
2361 Runnable runnable = new Runnable() {
2362
2363 @Override
2364 public void run() {
2365 databaseBackend.writeRoster(account.getRoster());
2366 }
2367 };
2368 mDatabaseExecutor.execute(runnable);
2369
2370 }
2371
2372 public List<String> getKnownHosts() {
2373 final List<String> hosts = new ArrayList<>();
2374 for (final Account account : getAccounts()) {
2375 if (!hosts.contains(account.getServer().toString())) {
2376 hosts.add(account.getServer().toString());
2377 }
2378 for (final Contact contact : account.getRoster().getContacts()) {
2379 if (contact.showInRoster()) {
2380 final String server = contact.getServer().toString();
2381 if (server != null && !hosts.contains(server)) {
2382 hosts.add(server);
2383 }
2384 }
2385 }
2386 }
2387 return hosts;
2388 }
2389
2390 public List<String> getKnownConferenceHosts() {
2391 final ArrayList<String> mucServers = new ArrayList<>();
2392 for (final Account account : accounts) {
2393 if (account.getXmppConnection() != null) {
2394 final String server = account.getXmppConnection().getMucServer();
2395 if (server != null && !mucServers.contains(server)) {
2396 mucServers.add(server);
2397 }
2398 }
2399 }
2400 return mucServers;
2401 }
2402
2403 public void sendMessagePacket(Account account, MessagePacket packet) {
2404 XmppConnection connection = account.getXmppConnection();
2405 if (connection != null) {
2406 connection.sendMessagePacket(packet);
2407 }
2408 }
2409
2410 public void sendPresencePacket(Account account, PresencePacket packet) {
2411 XmppConnection connection = account.getXmppConnection();
2412 if (connection != null) {
2413 connection.sendPresencePacket(packet);
2414 }
2415 }
2416
2417 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2418 final XmppConnection connection = account.getXmppConnection();
2419 if (connection != null) {
2420 connection.sendIqPacket(packet, callback);
2421 }
2422 }
2423
2424 public void sendPresence(final Account account) {
2425 sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2426 }
2427
2428 public void sendOfflinePresence(final Account account) {
2429 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2430 }
2431
2432 public MessageGenerator getMessageGenerator() {
2433 return this.mMessageGenerator;
2434 }
2435
2436 public PresenceGenerator getPresenceGenerator() {
2437 return this.mPresenceGenerator;
2438 }
2439
2440 public IqGenerator getIqGenerator() {
2441 return this.mIqGenerator;
2442 }
2443
2444 public IqParser getIqParser() {
2445 return this.mIqParser;
2446 }
2447
2448 public JingleConnectionManager getJingleConnectionManager() {
2449 return this.mJingleConnectionManager;
2450 }
2451
2452 public MessageArchiveService getMessageArchiveService() {
2453 return this.mMessageArchiveService;
2454 }
2455
2456 public List<Contact> findContacts(Jid jid) {
2457 ArrayList<Contact> contacts = new ArrayList<>();
2458 for (Account account : getAccounts()) {
2459 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2460 Contact contact = account.getRoster().getContactFromRoster(jid);
2461 if (contact != null) {
2462 contacts.add(contact);
2463 }
2464 }
2465 }
2466 return contacts;
2467 }
2468
2469 public NotificationService getNotificationService() {
2470 return this.mNotificationService;
2471 }
2472
2473 public HttpConnectionManager getHttpConnectionManager() {
2474 return this.mHttpConnectionManager;
2475 }
2476
2477 public void resendFailedMessages(final Message message) {
2478 final Collection<Message> messages = new ArrayList<>();
2479 Message current = message;
2480 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2481 messages.add(current);
2482 if (current.mergeable(current.next())) {
2483 current = current.next();
2484 } else {
2485 break;
2486 }
2487 }
2488 for (final Message msg : messages) {
2489 markMessage(msg, Message.STATUS_WAITING);
2490 this.resendMessage(msg);
2491 }
2492 }
2493
2494 public void clearConversationHistory(final Conversation conversation) {
2495 conversation.clearMessages();
2496 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2497 new Thread(new Runnable() {
2498 @Override
2499 public void run() {
2500 databaseBackend.deleteMessagesInConversation(conversation);
2501 }
2502 }).start();
2503 }
2504
2505 public void sendBlockRequest(final Blockable blockable) {
2506 if (blockable != null && blockable.getBlockedJid() != null) {
2507 final Jid jid = blockable.getBlockedJid();
2508 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2509
2510 @Override
2511 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2512 if (packet.getType() == IqPacket.TYPE.RESULT) {
2513 account.getBlocklist().add(jid);
2514 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2515 }
2516 }
2517 });
2518 }
2519 }
2520
2521 public void sendUnblockRequest(final Blockable blockable) {
2522 if (blockable != null && blockable.getJid() != null) {
2523 final Jid jid = blockable.getBlockedJid();
2524 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2525 @Override
2526 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2527 if (packet.getType() == IqPacket.TYPE.RESULT) {
2528 account.getBlocklist().remove(jid);
2529 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2530 }
2531 }
2532 });
2533 }
2534 }
2535
2536 public interface OnMoreMessagesLoaded {
2537 public void onMoreMessagesLoaded(int count, Conversation conversation);
2538
2539 public void informUser(int r);
2540 }
2541
2542 public interface OnAccountPasswordChanged {
2543 public void onPasswordChangeSucceeded();
2544
2545 public void onPasswordChangeFailed();
2546 }
2547
2548 public interface OnAffiliationChanged {
2549 public void onAffiliationChangedSuccessful(Jid jid);
2550
2551 public void onAffiliationChangeFailed(Jid jid, int resId);
2552 }
2553
2554 public interface OnRoleChanged {
2555 public void onRoleChangedSuccessful(String nick);
2556
2557 public void onRoleChangeFailed(String nick, int resid);
2558 }
2559
2560 public interface OnConversationUpdate {
2561 public void onConversationUpdate();
2562 }
2563
2564 public interface OnAccountUpdate {
2565 public void onAccountUpdate();
2566 }
2567
2568 public interface OnRosterUpdate {
2569 public void onRosterUpdate();
2570 }
2571
2572 public interface OnMucRosterUpdate {
2573 public void onMucRosterUpdate();
2574 }
2575
2576 public interface OnConferenceOptionsPushed {
2577 public void onPushSucceeded();
2578
2579 public void onPushFailed();
2580 }
2581
2582 public class XmppConnectionBinder extends Binder {
2583 public XmppConnectionService getService() {
2584 return XmppConnectionService.this;
2585 }
2586 }
2587}