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 public void sendMessage(final Message message) {
675 final Account account = message.getConversation().getAccount();
676 account.deactivateGracePeriod();
677 final Conversation conv = message.getConversation();
678 MessagePacket packet = null;
679 boolean saveInDb = true;
680 boolean send = false;
681 if (account.getStatus() == Account.State.ONLINE
682 && account.getXmppConnection() != null) {
683 if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
684 if (message.getCounterpart() != null) {
685 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
686 if (!conv.hasValidOtrSession()) {
687 conv.startOtrSession(message.getCounterpart().getResourcepart(),true);
688 message.setStatus(Message.STATUS_WAITING);
689 } else if (conv.hasValidOtrSession()
690 && conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
691 mJingleConnectionManager
692 .createNewConnection(message);
693 }
694 } else {
695 mJingleConnectionManager.createNewConnection(message);
696 }
697 } else {
698 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
699 conv.startOtrIfNeeded();
700 }
701 message.setStatus(Message.STATUS_WAITING);
702 }
703 } else {
704 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
705 if (!conv.hasValidOtrSession() && (message.getCounterpart() != null)) {
706 conv.startOtrSession(message.getCounterpart().getResourcepart(), true);
707 message.setStatus(Message.STATUS_WAITING);
708 } else if (conv.hasValidOtrSession()) {
709 if (conv.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED) {
710 packet = mMessageGenerator.generateOtrChat(message);
711 send = true;
712 } else {
713 message.setStatus(Message.STATUS_WAITING);
714 conv.startOtrIfNeeded();
715 }
716 } else {
717 message.setStatus(Message.STATUS_WAITING);
718 }
719 } else if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
720 message.getConversation().endOtrIfNeeded();
721 message.getConversation().findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
722 @Override
723 public void onMessageFound(Message message) {
724 markMessage(message,Message.STATUS_SEND_FAILED);
725 }
726 });
727 packet = mMessageGenerator.generatePgpChat(message);
728 send = true;
729 } else {
730 message.getConversation().endOtrIfNeeded();
731 message.getConversation().findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
732 @Override
733 public void onMessageFound(Message message) {
734 markMessage(message,Message.STATUS_SEND_FAILED);
735 }
736 });
737 packet = mMessageGenerator.generateChat(message);
738 send = true;
739 }
740 }
741 if (!account.getXmppConnection().getFeatures().sm()
742 && conv.getMode() != Conversation.MODE_MULTI) {
743 message.setStatus(Message.STATUS_SEND);
744 }
745 } else {
746 message.setStatus(Message.STATUS_WAITING);
747 if (message.getType() == Message.TYPE_TEXT) {
748 if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
749 String pgpBody = message.getEncryptedBody();
750 String decryptedBody = message.getBody();
751 message.setBody(pgpBody);
752 message.setEncryption(Message.ENCRYPTION_PGP);
753 databaseBackend.createMessage(message);
754 saveInDb = false;
755 message.setBody(decryptedBody);
756 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
757 } else if (message.getEncryption() == Message.ENCRYPTION_OTR) {
758 if (!conv.hasValidOtrSession()
759 && message.getCounterpart() != null) {
760 conv.startOtrSession(message.getCounterpart().getResourcepart(), false);
761 }
762 }
763 }
764
765 }
766 conv.add(message);
767 if (saveInDb) {
768 if (message.getEncryption() == Message.ENCRYPTION_NONE
769 || saveEncryptedMessages()) {
770 databaseBackend.createMessage(message);
771 }
772 }
773 if ((send) && (packet != null)) {
774 if (conv.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
775 if (this.sendChatStates()) {
776 packet.addChild(ChatState.toElement(conv.getOutgoingChatState()));
777 }
778 }
779 sendMessagePacket(account, packet);
780 }
781 updateConversationUi();
782 }
783
784 private void sendUnsentMessages(final Conversation conversation) {
785 conversation.findWaitingMessages(new Conversation.OnMessageFound() {
786
787 @Override
788 public void onMessageFound(Message message) {
789 resendMessage(message);
790 }
791 });
792 }
793
794 private void resendMessage(final Message message) {
795 Account account = message.getConversation().getAccount();
796 MessagePacket packet = null;
797 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
798 Presences presences = message.getConversation().getContact()
799 .getPresences();
800 if (!message.getConversation().hasValidOtrSession()) {
801 if ((message.getCounterpart() != null)
802 && (presences.has(message.getCounterpart().getResourcepart()))) {
803 message.getConversation().startOtrSession(message.getCounterpart().getResourcepart(), true);
804 } else {
805 if (presences.size() == 1) {
806 String presence = presences.asStringArray()[0];
807 message.getConversation().startOtrSession(presence, true);
808 }
809 }
810 } else {
811 if (message.getConversation().getOtrSession()
812 .getSessionStatus() == SessionStatus.ENCRYPTED) {
813 try {
814 message.setCounterpart(Jid.fromSessionID(message.getConversation().getOtrSession().getSessionID()));
815 if (message.getType() == Message.TYPE_TEXT) {
816 packet = mMessageGenerator.generateOtrChat(message,
817 true);
818 } else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
819 mJingleConnectionManager.createNewConnection(message);
820 }
821 } catch (final InvalidJidException ignored) {
822
823 }
824 }
825 }
826 } else if (message.getType() == Message.TYPE_TEXT) {
827 if (message.getEncryption() == Message.ENCRYPTION_NONE) {
828 packet = mMessageGenerator.generateChat(message, true);
829 } else if ((message.getEncryption() == Message.ENCRYPTION_DECRYPTED)
830 || (message.getEncryption() == Message.ENCRYPTION_PGP)) {
831 packet = mMessageGenerator.generatePgpChat(message, true);
832 }
833 } else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
834 Contact contact = message.getConversation().getContact();
835 Presences presences = contact.getPresences();
836 if ((message.getCounterpart() != null)
837 && (presences.has(message.getCounterpart().getResourcepart()))) {
838 mJingleConnectionManager.createNewConnection(message);
839 } else {
840 if (presences.size() == 1) {
841 String presence = presences.asStringArray()[0];
842 try {
843 message.setCounterpart(Jid.fromParts(contact.getJid().getLocalpart(), contact.getJid().getDomainpart(), presence));
844 } catch (InvalidJidException e) {
845 return;
846 }
847 mJingleConnectionManager.createNewConnection(message);
848 }
849 }
850 }
851 if (packet != null) {
852 if (!account.getXmppConnection().getFeatures().sm()
853 && message.getConversation().getMode() != Conversation.MODE_MULTI) {
854 markMessage(message, Message.STATUS_SEND);
855 } else {
856 markMessage(message, Message.STATUS_UNSEND);
857 }
858 if (message.getConversation().setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
859 if (this.sendChatStates()) {
860 packet.addChild(ChatState.toElement(message.getConversation().getOutgoingChatState()));
861 }
862 }
863 sendMessagePacket(account, packet);
864 }
865 }
866
867 public void fetchRosterFromServer(final Account account) {
868 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
869 if (!"".equals(account.getRosterVersion())) {
870 Log.d(Config.LOGTAG, account.getJid().toBareJid()
871 + ": fetching roster version " + account.getRosterVersion());
872 } else {
873 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": fetching roster");
874 }
875 iqPacket.query(Xmlns.ROSTER).setAttribute("ver",
876 account.getRosterVersion());
877 account.getXmppConnection().sendIqPacket(iqPacket, mIqParser);
878 }
879
880 public void fetchBookmarks(final Account account) {
881 final IqPacket iqPacket = new IqPacket(IqPacket.TYPE.GET);
882 final Element query = iqPacket.query("jabber:iq:private");
883 query.addChild("storage", "storage:bookmarks");
884 final OnIqPacketReceived callback = new OnIqPacketReceived() {
885
886 @Override
887 public void onIqPacketReceived(final Account account, final IqPacket packet) {
888 final Element query = packet.query();
889 final List<Bookmark> bookmarks = new CopyOnWriteArrayList<>();
890 final Element storage = query.findChild("storage",
891 "storage:bookmarks");
892 if (storage != null) {
893 for (final Element item : storage.getChildren()) {
894 if (item.getName().equals("conference")) {
895 final Bookmark bookmark = Bookmark.parse(item, account);
896 bookmarks.add(bookmark);
897 Conversation conversation = find(bookmark);
898 if (conversation != null) {
899 conversation.setBookmark(bookmark);
900 } else if (bookmark.autojoin() && bookmark.getJid() != null) {
901 conversation = findOrCreateConversation(
902 account, bookmark.getJid(), true);
903 conversation.setBookmark(bookmark);
904 joinMuc(conversation);
905 }
906 }
907 }
908 }
909 account.setBookmarks(bookmarks);
910 }
911 };
912 sendIqPacket(account, iqPacket, callback);
913 }
914
915 public void pushBookmarks(Account account) {
916 IqPacket iqPacket = new IqPacket(IqPacket.TYPE.SET);
917 Element query = iqPacket.query("jabber:iq:private");
918 Element storage = query.addChild("storage", "storage:bookmarks");
919 for (Bookmark bookmark : account.getBookmarks()) {
920 storage.addChild(bookmark);
921 }
922 sendIqPacket(account, iqPacket, mDefaultIqHandler);
923 }
924
925 public void onPhoneContactsLoaded(final List<Bundle> phoneContacts) {
926 if (mPhoneContactMergerThread != null) {
927 mPhoneContactMergerThread.interrupt();
928 }
929 mPhoneContactMergerThread = new Thread(new Runnable() {
930 @Override
931 public void run() {
932 Log.d(Config.LOGTAG,"start merging phone contacts with roster");
933 for (Account account : accounts) {
934 List<Contact> withSystemAccounts = account.getRoster().getWithSystemAccounts();
935 for (Bundle phoneContact : phoneContacts) {
936 if (Thread.interrupted()) {
937 Log.d(Config.LOGTAG,"interrupted merging phone contacts");
938 return;
939 }
940 Jid jid;
941 try {
942 jid = Jid.fromString(phoneContact.getString("jid"));
943 } catch (final InvalidJidException e) {
944 continue;
945 }
946 final Contact contact = account.getRoster().getContact(jid);
947 String systemAccount = phoneContact.getInt("phoneid")
948 + "#"
949 + phoneContact.getString("lookup");
950 contact.setSystemAccount(systemAccount);
951 if (contact.setPhotoUri(phoneContact.getString("photouri"))) {
952 getAvatarService().clear(contact);
953 }
954 contact.setSystemName(phoneContact.getString("displayname"));
955 withSystemAccounts.remove(contact);
956 }
957 for(Contact contact : withSystemAccounts) {
958 contact.setSystemAccount(null);
959 contact.setSystemName(null);
960 if (contact.setPhotoUri(null)) {
961 getAvatarService().clear(contact);
962 }
963 }
964 }
965 Log.d(Config.LOGTAG,"finished merging phone contacts");
966 updateAccountUi();
967 }
968 });
969 mPhoneContactMergerThread.start();
970 }
971
972 private void restoreFromDatabase() {
973 synchronized (this.conversations) {
974 final Map<String, Account> accountLookupTable = new Hashtable<>();
975 for (Account account : this.accounts) {
976 accountLookupTable.put(account.getUuid(), account);
977 }
978 this.conversations.addAll(databaseBackend.getConversations(Conversation.STATUS_AVAILABLE));
979 for (Conversation conversation : this.conversations) {
980 Account account = accountLookupTable.get(conversation.getAccountUuid());
981 conversation.setAccount(account);
982 }
983 Runnable runnable =new Runnable() {
984 @Override
985 public void run() {
986 Log.d(Config.LOGTAG,"restoring roster");
987 for(Account account : accounts) {
988 databaseBackend.readRoster(account.getRoster());
989 }
990 getBitmapCache().evictAll();
991 Looper.prepare();
992 PhoneHelper.loadPhoneContacts(getApplicationContext(),
993 new CopyOnWriteArrayList<Bundle>(),
994 XmppConnectionService.this);
995 Log.d(Config.LOGTAG,"restoring messages");
996 for (Conversation conversation : conversations) {
997 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
998 checkDeletedFiles(conversation);
999 }
1000 mRestoredFromDatabase = true;
1001 Log.d(Config.LOGTAG,"restored all messages");
1002 updateConversationUi();
1003 }
1004 };
1005 mDatabaseExecutor.execute(runnable);
1006 }
1007 }
1008
1009 public List<Conversation> getConversations() {
1010 return this.conversations;
1011 }
1012
1013 private void checkDeletedFiles(Conversation conversation) {
1014 conversation.findMessagesWithFiles(new Conversation.OnMessageFound() {
1015
1016 @Override
1017 public void onMessageFound(Message message) {
1018 if (!getFileBackend().isFileAvailable(message)) {
1019 message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
1020 }
1021 }
1022 });
1023 }
1024
1025 private void markFileDeleted(String uuid) {
1026 for (Conversation conversation : getConversations()) {
1027 Message message = conversation.findMessageWithFileAndUuid(uuid);
1028 if (message != null) {
1029 if (!getFileBackend().isFileAvailable(message)) {
1030 message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
1031 updateConversationUi();
1032 }
1033 return;
1034 }
1035 }
1036 }
1037
1038 public void populateWithOrderedConversations(final List<Conversation> list) {
1039 populateWithOrderedConversations(list, true);
1040 }
1041
1042 public void populateWithOrderedConversations(final List<Conversation> list, boolean includeConferences) {
1043 list.clear();
1044 if (includeConferences) {
1045 list.addAll(getConversations());
1046 } else {
1047 for (Conversation conversation : getConversations()) {
1048 if (conversation.getMode() == Conversation.MODE_SINGLE) {
1049 list.add(conversation);
1050 }
1051 }
1052 }
1053 Collections.sort(list, new Comparator<Conversation>() {
1054 @Override
1055 public int compare(Conversation lhs, Conversation rhs) {
1056 Message left = lhs.getLatestMessage();
1057 Message right = rhs.getLatestMessage();
1058 if (left.getTimeSent() > right.getTimeSent()) {
1059 return -1;
1060 } else if (left.getTimeSent() < right.getTimeSent()) {
1061 return 1;
1062 } else {
1063 return 0;
1064 }
1065 }
1066 });
1067 }
1068
1069 public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) {
1070 Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp));
1071 if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) {
1072 return;
1073 }
1074 Runnable runnable = new Runnable() {
1075 @Override
1076 public void run() {
1077 final Account account = conversation.getAccount();
1078 List<Message> messages = databaseBackend.getMessages(conversation, 50,timestamp);
1079 if (messages.size() > 0) {
1080 conversation.addAll(0, messages);
1081 checkDeletedFiles(conversation);
1082 callback.onMoreMessagesLoaded(messages.size(), conversation);
1083 } else if (conversation.hasMessagesLeftOnServer()
1084 && account.isOnlineAndConnected()
1085 && account.getXmppConnection().getFeatures().mam()) {
1086 MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1);
1087 if (query != null) {
1088 query.setCallback(callback);
1089 }
1090 callback.informUser(R.string.fetching_history_from_server);
1091 }
1092 }
1093 };
1094 mDatabaseExecutor.execute(runnable);
1095 }
1096
1097 public List<Account> getAccounts() {
1098 return this.accounts;
1099 }
1100
1101 public Conversation find(final Iterable<Conversation> haystack, final Contact contact) {
1102 for (final Conversation conversation : haystack) {
1103 if (conversation.getContact() == contact) {
1104 return conversation;
1105 }
1106 }
1107 return null;
1108 }
1109
1110 public Conversation find(final Iterable<Conversation> haystack, final Account account, final Jid jid) {
1111 if (jid == null) {
1112 return null;
1113 }
1114 for (final Conversation conversation : haystack) {
1115 if ((account == null || conversation.getAccount() == account)
1116 && (conversation.getJid().toBareJid().equals(jid.toBareJid()))) {
1117 return conversation;
1118 }
1119 }
1120 return null;
1121 }
1122
1123 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc) {
1124 return this.findOrCreateConversation(account, jid, muc, null);
1125 }
1126
1127 public Conversation findOrCreateConversation(final Account account, final Jid jid, final boolean muc, final MessageArchiveService.Query query) {
1128 synchronized (this.conversations) {
1129 Conversation conversation = find(account, jid);
1130 if (conversation != null) {
1131 return conversation;
1132 }
1133 conversation = databaseBackend.findConversation(account, jid);
1134 if (conversation != null) {
1135 conversation.setStatus(Conversation.STATUS_AVAILABLE);
1136 conversation.setAccount(account);
1137 if (muc) {
1138 conversation.setMode(Conversation.MODE_MULTI);
1139 conversation.setContactJid(jid);
1140 } else {
1141 conversation.setMode(Conversation.MODE_SINGLE);
1142 conversation.setContactJid(jid.toBareJid());
1143 }
1144 conversation.setNextEncryption(-1);
1145 conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE));
1146 this.databaseBackend.updateConversation(conversation);
1147 } else {
1148 String conversationName;
1149 Contact contact = account.getRoster().getContact(jid);
1150 if (contact != null) {
1151 conversationName = contact.getDisplayName();
1152 } else {
1153 conversationName = jid.getLocalpart();
1154 }
1155 if (muc) {
1156 conversation = new Conversation(conversationName, account, jid,
1157 Conversation.MODE_MULTI);
1158 } else {
1159 conversation = new Conversation(conversationName, account, jid.toBareJid(),
1160 Conversation.MODE_SINGLE);
1161 }
1162 this.databaseBackend.createConversation(conversation);
1163 }
1164 if (account.getXmppConnection() != null
1165 && account.getXmppConnection().getFeatures().mam()
1166 && !muc) {
1167 if (query == null) {
1168 this.mMessageArchiveService.query(conversation);
1169 } else {
1170 if (query.getConversation() == null) {
1171 this.mMessageArchiveService.query(conversation, query.getStart());
1172 }
1173 }
1174 }
1175 checkDeletedFiles(conversation);
1176 this.conversations.add(conversation);
1177 updateConversationUi();
1178 return conversation;
1179 }
1180 }
1181
1182 public void archiveConversation(Conversation conversation) {
1183 getNotificationService().clear(conversation);
1184 conversation.setStatus(Conversation.STATUS_ARCHIVED);
1185 conversation.setNextEncryption(-1);
1186 synchronized (this.conversations) {
1187 if (conversation.getMode() == Conversation.MODE_MULTI) {
1188 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1189 Bookmark bookmark = conversation.getBookmark();
1190 if (bookmark != null && bookmark.autojoin()) {
1191 bookmark.setAutojoin(false);
1192 pushBookmarks(bookmark.getAccount());
1193 }
1194 }
1195 leaveMuc(conversation);
1196 } else {
1197 conversation.endOtrIfNeeded();
1198 }
1199 this.databaseBackend.updateConversation(conversation);
1200 this.conversations.remove(conversation);
1201 updateConversationUi();
1202 }
1203 }
1204
1205 public void createAccount(final Account account) {
1206 account.initAccountServices(this);
1207 databaseBackend.createAccount(account);
1208 this.accounts.add(account);
1209 this.reconnectAccountInBackground(account);
1210 updateAccountUi();
1211 }
1212
1213 public void updateAccount(final Account account) {
1214 this.statusListener.onStatusChanged(account);
1215 databaseBackend.updateAccount(account);
1216 reconnectAccount(account, false);
1217 updateAccountUi();
1218 getNotificationService().updateErrorNotification();
1219 }
1220
1221 public void updateAccountPasswordOnServer(final Account account, final String newPassword, final OnAccountPasswordChanged callback) {
1222 final IqPacket iq = getIqGenerator().generateSetPassword(account, newPassword);
1223 sendIqPacket(account, iq, new OnIqPacketReceived() {
1224 @Override
1225 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1226 if (packet.getType() == IqPacket.TYPE.RESULT) {
1227 account.setPassword(newPassword);
1228 databaseBackend.updateAccount(account);
1229 callback.onPasswordChangeSucceeded();
1230 } else {
1231 callback.onPasswordChangeFailed();
1232 }
1233 }
1234 });
1235 }
1236
1237 public void deleteAccount(final Account account) {
1238 synchronized (this.conversations) {
1239 for (final Conversation conversation : conversations) {
1240 if (conversation.getAccount() == account) {
1241 if (conversation.getMode() == Conversation.MODE_MULTI) {
1242 leaveMuc(conversation);
1243 } else if (conversation.getMode() == Conversation.MODE_SINGLE) {
1244 conversation.endOtrIfNeeded();
1245 }
1246 conversations.remove(conversation);
1247 }
1248 }
1249 if (account.getXmppConnection() != null) {
1250 this.disconnect(account, true);
1251 }
1252 databaseBackend.deleteAccount(account);
1253 this.accounts.remove(account);
1254 updateAccountUi();
1255 getNotificationService().updateErrorNotification();
1256 }
1257 }
1258
1259 public void setOnConversationListChangedListener(OnConversationUpdate listener) {
1260 synchronized (this) {
1261 if (checkListeners()) {
1262 switchToForeground();
1263 }
1264 this.mOnConversationUpdate = listener;
1265 this.mNotificationService.setIsInForeground(true);
1266 if (this.convChangedListenerCount < 2) {
1267 this.convChangedListenerCount++;
1268 }
1269 }
1270 }
1271
1272 public void removeOnConversationListChangedListener() {
1273 synchronized (this) {
1274 this.convChangedListenerCount--;
1275 if (this.convChangedListenerCount <= 0) {
1276 this.convChangedListenerCount = 0;
1277 this.mOnConversationUpdate = null;
1278 this.mNotificationService.setIsInForeground(false);
1279 if (checkListeners()) {
1280 switchToBackground();
1281 }
1282 }
1283 }
1284 }
1285
1286 public void setOnAccountListChangedListener(OnAccountUpdate listener) {
1287 synchronized (this) {
1288 if (checkListeners()) {
1289 switchToForeground();
1290 }
1291 this.mOnAccountUpdate = listener;
1292 if (this.accountChangedListenerCount < 2) {
1293 this.accountChangedListenerCount++;
1294 }
1295 }
1296 }
1297
1298 public void removeOnAccountListChangedListener() {
1299 synchronized (this) {
1300 this.accountChangedListenerCount--;
1301 if (this.accountChangedListenerCount <= 0) {
1302 this.mOnAccountUpdate = null;
1303 this.accountChangedListenerCount = 0;
1304 if (checkListeners()) {
1305 switchToBackground();
1306 }
1307 }
1308 }
1309 }
1310
1311 public void setOnRosterUpdateListener(final OnRosterUpdate listener) {
1312 synchronized (this) {
1313 if (checkListeners()) {
1314 switchToForeground();
1315 }
1316 this.mOnRosterUpdate = listener;
1317 if (this.rosterChangedListenerCount < 2) {
1318 this.rosterChangedListenerCount++;
1319 }
1320 }
1321 }
1322
1323 public void removeOnRosterUpdateListener() {
1324 synchronized (this) {
1325 this.rosterChangedListenerCount--;
1326 if (this.rosterChangedListenerCount <= 0) {
1327 this.rosterChangedListenerCount = 0;
1328 this.mOnRosterUpdate = null;
1329 if (checkListeners()) {
1330 switchToBackground();
1331 }
1332 }
1333 }
1334 }
1335
1336 public void setOnUpdateBlocklistListener(final OnUpdateBlocklist listener) {
1337 synchronized (this) {
1338 if (checkListeners()) {
1339 switchToForeground();
1340 }
1341 this.mOnUpdateBlocklist = listener;
1342 if (this.updateBlocklistListenerCount < 2) {
1343 this.updateBlocklistListenerCount++;
1344 }
1345 }
1346 }
1347
1348 public void removeOnUpdateBlocklistListener() {
1349 synchronized (this) {
1350 this.updateBlocklistListenerCount--;
1351 if (this.updateBlocklistListenerCount <= 0) {
1352 this.updateBlocklistListenerCount = 0;
1353 this.mOnUpdateBlocklist = null;
1354 if (checkListeners()) {
1355 switchToBackground();
1356 }
1357 }
1358 }
1359 }
1360
1361 public void setOnMucRosterUpdateListener(OnMucRosterUpdate listener) {
1362 synchronized (this) {
1363 if (checkListeners()) {
1364 switchToForeground();
1365 }
1366 this.mOnMucRosterUpdate = listener;
1367 if (this.mucRosterChangedListenerCount < 2) {
1368 this.mucRosterChangedListenerCount++;
1369 }
1370 }
1371 }
1372
1373 public void removeOnMucRosterUpdateListener() {
1374 synchronized (this) {
1375 this.mucRosterChangedListenerCount--;
1376 if (this.mucRosterChangedListenerCount <= 0) {
1377 this.mucRosterChangedListenerCount = 0;
1378 this.mOnMucRosterUpdate = null;
1379 if (checkListeners()) {
1380 switchToBackground();
1381 }
1382 }
1383 }
1384 }
1385
1386 private boolean checkListeners() {
1387 return (this.mOnAccountUpdate == null
1388 && this.mOnConversationUpdate == null
1389 && this.mOnRosterUpdate == null
1390 && this.mOnUpdateBlocklist == null);
1391 }
1392
1393 private void switchToForeground() {
1394 for (Account account : getAccounts()) {
1395 if (account.getStatus() == Account.State.ONLINE) {
1396 XmppConnection connection = account.getXmppConnection();
1397 if (connection != null && connection.getFeatures().csi()) {
1398 connection.sendActive();
1399 }
1400 }
1401 }
1402 Log.d(Config.LOGTAG, "app switched into foreground");
1403 }
1404
1405 private void switchToBackground() {
1406 for (Account account : getAccounts()) {
1407 if (account.getStatus() == Account.State.ONLINE) {
1408 XmppConnection connection = account.getXmppConnection();
1409 if (connection != null && connection.getFeatures().csi()) {
1410 connection.sendInactive();
1411 }
1412 }
1413 }
1414 for(Conversation conversation : getConversations()) {
1415 conversation.setIncomingChatState(ChatState.ACTIVE);
1416 }
1417 this.mNotificationService.setIsInForeground(false);
1418 Log.d(Config.LOGTAG, "app switched into background");
1419 }
1420
1421 private void connectMultiModeConversations(Account account) {
1422 List<Conversation> conversations = getConversations();
1423 for (Conversation conversation : conversations) {
1424 if ((conversation.getMode() == Conversation.MODE_MULTI)
1425 && (conversation.getAccount() == account)) {
1426 conversation.resetMucOptions();
1427 joinMuc(conversation);
1428 }
1429 }
1430 }
1431
1432 public void joinMuc(Conversation conversation) {
1433 Account account = conversation.getAccount();
1434 account.pendingConferenceJoins.remove(conversation);
1435 account.pendingConferenceLeaves.remove(conversation);
1436 if (account.getStatus() == Account.State.ONLINE) {
1437 final String nick = conversation.getMucOptions().getProposedNick();
1438 final Jid joinJid = conversation.getMucOptions().createJoinJid(nick);
1439 if (joinJid == null) {
1440 return; //safety net
1441 }
1442 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": joining conversation " + joinJid.toString());
1443 PresencePacket packet = new PresencePacket();
1444 packet.setFrom(conversation.getAccount().getJid());
1445 packet.setTo(joinJid);
1446 Element x = packet.addChild("x", "http://jabber.org/protocol/muc");
1447 if (conversation.getMucOptions().getPassword() != null) {
1448 x.addChild("password").setContent(conversation.getMucOptions().getPassword());
1449 }
1450 x.addChild("history").setAttribute("since", PresenceGenerator.getTimestamp(conversation.getLastMessageTransmitted()));
1451 String sig = account.getPgpSignature();
1452 if (sig != null) {
1453 packet.addChild("status").setContent("online");
1454 packet.addChild("x", "jabber:x:signed").setContent(sig);
1455 }
1456 sendPresencePacket(account, packet);
1457 fetchConferenceConfiguration(conversation);
1458 if (!joinJid.equals(conversation.getJid())) {
1459 conversation.setContactJid(joinJid);
1460 databaseBackend.updateConversation(conversation);
1461 }
1462 conversation.setHasMessagesLeftOnServer(false);
1463 } else {
1464 account.pendingConferenceJoins.add(conversation);
1465 }
1466 }
1467
1468 public void providePasswordForMuc(Conversation conversation, String password) {
1469 if (conversation.getMode() == Conversation.MODE_MULTI) {
1470 conversation.getMucOptions().setPassword(password);
1471 if (conversation.getBookmark() != null) {
1472 conversation.getBookmark().setAutojoin(true);
1473 pushBookmarks(conversation.getAccount());
1474 }
1475 databaseBackend.updateConversation(conversation);
1476 joinMuc(conversation);
1477 }
1478 }
1479
1480 public void renameInMuc(final Conversation conversation, final String nick, final UiCallback<Conversation> callback) {
1481 final MucOptions options = conversation.getMucOptions();
1482 final Jid joinJid = options.createJoinJid(nick);
1483 if (options.online()) {
1484 Account account = conversation.getAccount();
1485 options.setOnRenameListener(new OnRenameListener() {
1486
1487 @Override
1488 public void onSuccess() {
1489 conversation.setContactJid(joinJid);
1490 databaseBackend.updateConversation(conversation);
1491 Bookmark bookmark = conversation.getBookmark();
1492 if (bookmark != null) {
1493 bookmark.setNick(nick);
1494 pushBookmarks(bookmark.getAccount());
1495 }
1496 callback.success(conversation);
1497 }
1498
1499 @Override
1500 public void onFailure() {
1501 callback.error(R.string.nick_in_use, conversation);
1502 }
1503 });
1504
1505 PresencePacket packet = new PresencePacket();
1506 packet.setTo(joinJid);
1507 packet.setFrom(conversation.getAccount().getJid());
1508
1509 String sig = account.getPgpSignature();
1510 if (sig != null) {
1511 packet.addChild("status").setContent("online");
1512 packet.addChild("x", "jabber:x:signed").setContent(sig);
1513 }
1514 sendPresencePacket(account, packet);
1515 } else {
1516 conversation.setContactJid(joinJid);
1517 databaseBackend.updateConversation(conversation);
1518 if (conversation.getAccount().getStatus() == Account.State.ONLINE) {
1519 Bookmark bookmark = conversation.getBookmark();
1520 if (bookmark != null) {
1521 bookmark.setNick(nick);
1522 pushBookmarks(bookmark.getAccount());
1523 }
1524 joinMuc(conversation);
1525 }
1526 }
1527 }
1528
1529 public void leaveMuc(Conversation conversation) {
1530 Account account = conversation.getAccount();
1531 account.pendingConferenceJoins.remove(conversation);
1532 account.pendingConferenceLeaves.remove(conversation);
1533 if (account.getStatus() == Account.State.ONLINE) {
1534 PresencePacket packet = new PresencePacket();
1535 packet.setTo(conversation.getJid());
1536 packet.setFrom(conversation.getAccount().getJid());
1537 packet.setAttribute("type", "unavailable");
1538 sendPresencePacket(conversation.getAccount(), packet);
1539 conversation.getMucOptions().setOffline();
1540 conversation.deregisterWithBookmark();
1541 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid()
1542 + ": leaving muc " + conversation.getJid());
1543 } else {
1544 account.pendingConferenceLeaves.add(conversation);
1545 }
1546 }
1547
1548 private String findConferenceServer(final Account account) {
1549 String server;
1550 if (account.getXmppConnection() != null) {
1551 server = account.getXmppConnection().getMucServer();
1552 if (server != null) {
1553 return server;
1554 }
1555 }
1556 for (Account other : getAccounts()) {
1557 if (other != account && other.getXmppConnection() != null) {
1558 server = other.getXmppConnection().getMucServer();
1559 if (server != null) {
1560 return server;
1561 }
1562 }
1563 }
1564 return null;
1565 }
1566
1567 public void createAdhocConference(final Account account, final Iterable<Jid> jids, final UiCallback<Conversation> callback) {
1568 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": creating adhoc conference with " + jids.toString());
1569 if (account.getStatus() == Account.State.ONLINE) {
1570 try {
1571 String server = findConferenceServer(account);
1572 if (server == null) {
1573 if (callback != null) {
1574 callback.error(R.string.no_conference_server_found, null);
1575 }
1576 return;
1577 }
1578 String name = new BigInteger(75, getRNG()).toString(32);
1579 Jid jid = Jid.fromParts(name, server, null);
1580 final Conversation conversation = findOrCreateConversation(account, jid, true);
1581 joinMuc(conversation);
1582 Bundle options = new Bundle();
1583 options.putString("muc#roomconfig_persistentroom", "1");
1584 options.putString("muc#roomconfig_membersonly", "1");
1585 options.putString("muc#roomconfig_publicroom", "0");
1586 options.putString("muc#roomconfig_whois", "anyone");
1587 pushConferenceConfiguration(conversation, options, new OnConferenceOptionsPushed() {
1588 @Override
1589 public void onPushSucceeded() {
1590 for (Jid invite : jids) {
1591 invite(conversation, invite);
1592 }
1593 if (account.countPresences() > 1) {
1594 directInvite(conversation, account.getJid().toBareJid());
1595 }
1596 if (callback != null) {
1597 callback.success(conversation);
1598 }
1599 }
1600
1601 @Override
1602 public void onPushFailed() {
1603 if (callback != null) {
1604 callback.error(R.string.conference_creation_failed, conversation);
1605 }
1606 }
1607 });
1608
1609 } catch (InvalidJidException e) {
1610 if (callback != null) {
1611 callback.error(R.string.conference_creation_failed, null);
1612 }
1613 }
1614 } else {
1615 if (callback != null) {
1616 callback.error(R.string.not_connected_try_again, null);
1617 }
1618 }
1619 }
1620
1621 public void fetchConferenceConfiguration(final Conversation conversation) {
1622 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1623 request.setTo(conversation.getJid().toBareJid());
1624 request.query("http://jabber.org/protocol/disco#info");
1625 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1626 @Override
1627 public void onIqPacketReceived(Account account, IqPacket packet) {
1628 if (packet.getType() != IqPacket.TYPE.ERROR) {
1629 ArrayList<String> features = new ArrayList<>();
1630 for (Element child : packet.query().getChildren()) {
1631 if (child != null && child.getName().equals("feature")) {
1632 String var = child.getAttribute("var");
1633 if (var != null) {
1634 features.add(var);
1635 }
1636 }
1637 }
1638 conversation.getMucOptions().updateFeatures(features);
1639 updateConversationUi();
1640 }
1641 }
1642 });
1643 }
1644
1645 public void pushConferenceConfiguration(final Conversation conversation, final Bundle options, final OnConferenceOptionsPushed callback) {
1646 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1647 request.setTo(conversation.getJid().toBareJid());
1648 request.query("http://jabber.org/protocol/muc#owner");
1649 sendIqPacket(conversation.getAccount(), request, new OnIqPacketReceived() {
1650 @Override
1651 public void onIqPacketReceived(Account account, IqPacket packet) {
1652 if (packet.getType() != IqPacket.TYPE.ERROR) {
1653 Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
1654 for (Field field : data.getFields()) {
1655 if (options.containsKey(field.getName())) {
1656 field.setValue(options.getString(field.getName()));
1657 }
1658 }
1659 data.submit();
1660 IqPacket set = new IqPacket(IqPacket.TYPE.SET);
1661 set.setTo(conversation.getJid().toBareJid());
1662 set.query("http://jabber.org/protocol/muc#owner").addChild(data);
1663 sendIqPacket(account, set, new OnIqPacketReceived() {
1664 @Override
1665 public void onIqPacketReceived(Account account, IqPacket packet) {
1666 if (packet.getType() == IqPacket.TYPE.RESULT) {
1667 if (callback != null) {
1668 callback.onPushSucceeded();
1669 }
1670 } else {
1671 if (callback != null) {
1672 callback.onPushFailed();
1673 }
1674 }
1675 }
1676 });
1677 } else {
1678 if (callback != null) {
1679 callback.onPushFailed();
1680 }
1681 }
1682 }
1683 });
1684 }
1685
1686 public void pushSubjectToConference(final Conversation conference, final String subject) {
1687 MessagePacket packet = this.getMessageGenerator().conferenceSubject(conference, subject);
1688 this.sendMessagePacket(conference.getAccount(), packet);
1689 final MucOptions mucOptions = conference.getMucOptions();
1690 final MucOptions.User self = mucOptions.getSelf();
1691 if (!mucOptions.persistent() && self.getAffiliation().ranks(MucOptions.Affiliation.OWNER)) {
1692 Bundle options = new Bundle();
1693 options.putString("muc#roomconfig_persistentroom", "1");
1694 this.pushConferenceConfiguration(conference, options, null);
1695 }
1696 }
1697
1698 public void changeAffiliationInConference(final Conversation conference, Jid user, MucOptions.Affiliation affiliation, final OnAffiliationChanged callback) {
1699 final Jid jid = user.toBareJid();
1700 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jid, affiliation.toString());
1701 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1702 @Override
1703 public void onIqPacketReceived(Account account, IqPacket packet) {
1704 if (packet.getType() == IqPacket.TYPE.RESULT) {
1705 callback.onAffiliationChangedSuccessful(jid);
1706 } else {
1707 callback.onAffiliationChangeFailed(jid, R.string.could_not_change_affiliation);
1708 }
1709 }
1710 });
1711 }
1712
1713 public void changeAffiliationsInConference(final Conversation conference, MucOptions.Affiliation before, MucOptions.Affiliation after) {
1714 List<Jid> jids = new ArrayList<>();
1715 for (MucOptions.User user : conference.getMucOptions().getUsers()) {
1716 if (user.getAffiliation() == before) {
1717 jids.add(user.getJid());
1718 }
1719 }
1720 IqPacket request = this.mIqGenerator.changeAffiliation(conference, jids, after.toString());
1721 sendIqPacket(conference.getAccount(), request, mDefaultIqHandler);
1722 }
1723
1724 public void changeRoleInConference(final Conversation conference, final String nick, MucOptions.Role role, final OnRoleChanged callback) {
1725 IqPacket request = this.mIqGenerator.changeRole(conference, nick, role.toString());
1726 Log.d(Config.LOGTAG, request.toString());
1727 sendIqPacket(conference.getAccount(), request, new OnIqPacketReceived() {
1728 @Override
1729 public void onIqPacketReceived(Account account, IqPacket packet) {
1730 Log.d(Config.LOGTAG, packet.toString());
1731 if (packet.getType() == IqPacket.TYPE.RESULT) {
1732 callback.onRoleChangedSuccessful(nick);
1733 } else {
1734 callback.onRoleChangeFailed(nick, R.string.could_not_change_role);
1735 }
1736 }
1737 });
1738 }
1739
1740 public void disconnect(Account account, boolean force) {
1741 if ((account.getStatus() == Account.State.ONLINE)
1742 || (account.getStatus() == Account.State.DISABLED)) {
1743 if (!force) {
1744 List<Conversation> conversations = getConversations();
1745 for (Conversation conversation : conversations) {
1746 if (conversation.getAccount() == account) {
1747 if (conversation.getMode() == Conversation.MODE_MULTI) {
1748 leaveMuc(conversation);
1749 } else {
1750 if (conversation.endOtrIfNeeded()) {
1751 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1752 + ": ended otr session with "
1753 + conversation.getJid());
1754 }
1755 }
1756 }
1757 }
1758 sendOfflinePresence(account);
1759 }
1760 account.getXmppConnection().disconnect(force);
1761 }
1762 }
1763
1764 @Override
1765 public IBinder onBind(Intent intent) {
1766 return mBinder;
1767 }
1768
1769 public void updateMessage(Message message) {
1770 databaseBackend.updateMessage(message);
1771 updateConversationUi();
1772 }
1773
1774 protected void syncDirtyContacts(Account account) {
1775 for (Contact contact : account.getRoster().getContacts()) {
1776 if (contact.getOption(Contact.Options.DIRTY_PUSH)) {
1777 pushContactToServer(contact);
1778 }
1779 if (contact.getOption(Contact.Options.DIRTY_DELETE)) {
1780 deleteContactOnServer(contact);
1781 }
1782 }
1783 }
1784
1785 public void createContact(Contact contact) {
1786 SharedPreferences sharedPref = getPreferences();
1787 boolean autoGrant = sharedPref.getBoolean("grant_new_contacts", true);
1788 if (autoGrant) {
1789 contact.setOption(Contact.Options.PREEMPTIVE_GRANT);
1790 contact.setOption(Contact.Options.ASKING);
1791 }
1792 pushContactToServer(contact);
1793 }
1794
1795 public void onOtrSessionEstablished(Conversation conversation) {
1796 final Account account = conversation.getAccount();
1797 final Session otrSession = conversation.getOtrSession();
1798 Log.d(Config.LOGTAG,
1799 account.getJid().toBareJid() + " otr session established with "
1800 + conversation.getJid() + "/"
1801 + otrSession.getSessionID().getUserID());
1802 conversation.findUnsentMessagesWithOtrEncryption(new Conversation.OnMessageFound() {
1803
1804 @Override
1805 public void onMessageFound(Message message) {
1806 SessionID id = otrSession.getSessionID();
1807 try {
1808 message.setCounterpart(Jid.fromString(id.getAccountID() + "/" + id.getUserID()));
1809 } catch (InvalidJidException e) {
1810 return;
1811 }
1812 if (message.getType() == Message.TYPE_TEXT) {
1813 MessagePacket outPacket = mMessageGenerator.generateOtrChat(message, true);
1814 if (outPacket != null) {
1815 message.setStatus(Message.STATUS_SEND);
1816 databaseBackend.updateMessage(message);
1817 sendMessagePacket(account, outPacket);
1818 }
1819 } else if (message.getType() == Message.TYPE_IMAGE || message.getType() == Message.TYPE_FILE) {
1820 mJingleConnectionManager.createNewConnection(message);
1821 }
1822 updateConversationUi();
1823 }
1824 });
1825 }
1826
1827 public boolean renewSymmetricKey(Conversation conversation) {
1828 Account account = conversation.getAccount();
1829 byte[] symmetricKey = new byte[32];
1830 this.mRandom.nextBytes(symmetricKey);
1831 Session otrSession = conversation.getOtrSession();
1832 if (otrSession != null) {
1833 MessagePacket packet = new MessagePacket();
1834 packet.setType(MessagePacket.TYPE_CHAT);
1835 packet.setFrom(account.getJid());
1836 packet.addChild("private", "urn:xmpp:carbons:2");
1837 packet.addChild("no-copy", "urn:xmpp:hints");
1838 packet.setAttribute("to", otrSession.getSessionID().getAccountID() + "/"
1839 + otrSession.getSessionID().getUserID());
1840 try {
1841 packet.setBody(otrSession
1842 .transformSending(CryptoHelper.FILETRANSFER
1843 + CryptoHelper.bytesToHex(symmetricKey))[0]);
1844 sendMessagePacket(account, packet);
1845 conversation.setSymmetricKey(symmetricKey);
1846 return true;
1847 } catch (OtrException e) {
1848 return false;
1849 }
1850 }
1851 return false;
1852 }
1853
1854 public void pushContactToServer(final Contact contact) {
1855 contact.resetOption(Contact.Options.DIRTY_DELETE);
1856 contact.setOption(Contact.Options.DIRTY_PUSH);
1857 final Account account = contact.getAccount();
1858 if (account.getStatus() == Account.State.ONLINE) {
1859 final boolean ask = contact.getOption(Contact.Options.ASKING);
1860 final boolean sendUpdates = contact
1861 .getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)
1862 && contact.getOption(Contact.Options.PREEMPTIVE_GRANT);
1863 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1864 iq.query(Xmlns.ROSTER).addChild(contact.asElement());
1865 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
1866 if (sendUpdates) {
1867 sendPresencePacket(account,
1868 mPresenceGenerator.sendPresenceUpdatesTo(contact));
1869 }
1870 if (ask) {
1871 sendPresencePacket(account,
1872 mPresenceGenerator.requestPresenceUpdatesFrom(contact));
1873 }
1874 }
1875 }
1876
1877 public void publishAvatar(final Account account,
1878 final Uri image,
1879 final UiCallback<Avatar> callback) {
1880 final Bitmap.CompressFormat format = Config.AVATAR_FORMAT;
1881 final int size = Config.AVATAR_SIZE;
1882 final Avatar avatar = getFileBackend()
1883 .getPepAvatar(image, size, format);
1884 if (avatar != null) {
1885 avatar.height = size;
1886 avatar.width = size;
1887 if (format.equals(Bitmap.CompressFormat.WEBP)) {
1888 avatar.type = "image/webp";
1889 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1890 avatar.type = "image/jpeg";
1891 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1892 avatar.type = "image/png";
1893 }
1894 if (!getFileBackend().save(avatar)) {
1895 callback.error(R.string.error_saving_avatar, avatar);
1896 return;
1897 }
1898 final IqPacket packet = this.mIqGenerator.publishAvatar(avatar);
1899 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
1900
1901 @Override
1902 public void onIqPacketReceived(Account account, IqPacket result) {
1903 if (result.getType() == IqPacket.TYPE.RESULT) {
1904 final IqPacket packet = XmppConnectionService.this.mIqGenerator
1905 .publishAvatarMetadata(avatar);
1906 sendIqPacket(account, packet, new OnIqPacketReceived() {
1907
1908 @Override
1909 public void onIqPacketReceived(Account account,
1910 IqPacket result) {
1911 if (result.getType() == IqPacket.TYPE.RESULT) {
1912 if (account.setAvatar(avatar.getFilename())) {
1913 getAvatarService().clear(account);
1914 databaseBackend.updateAccount(account);
1915 }
1916 callback.success(avatar);
1917 } else {
1918 callback.error(
1919 R.string.error_publish_avatar_server_reject,
1920 avatar);
1921 }
1922 }
1923 });
1924 } else {
1925 callback.error(
1926 R.string.error_publish_avatar_server_reject,
1927 avatar);
1928 }
1929 }
1930 });
1931 } else {
1932 callback.error(R.string.error_publish_avatar_converting, null);
1933 }
1934 }
1935
1936 public void fetchAvatar(Account account, Avatar avatar) {
1937 fetchAvatar(account, avatar, null);
1938 }
1939
1940 private static String generateFetchKey(Account account, final Avatar avatar) {
1941 return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum;
1942 }
1943
1944 public void fetchAvatar(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1945 final String KEY = generateFetchKey(account, avatar);
1946 synchronized(this.mInProgressAvatarFetches) {
1947 if (this.mInProgressAvatarFetches.contains(KEY)) {
1948 return;
1949 } else {
1950 switch (avatar.origin) {
1951 case PEP:
1952 this.mInProgressAvatarFetches.add(KEY);
1953 fetchAvatarPep(account, avatar, callback);
1954 break;
1955 case VCARD:
1956 this.mInProgressAvatarFetches.add(KEY);
1957 fetchAvatarVcard(account, avatar, callback);
1958 break;
1959 }
1960 }
1961 }
1962 }
1963
1964 private void fetchAvatarPep(Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
1965 IqPacket packet = this.mIqGenerator.retrievePepAvatar(avatar);
1966 sendIqPacket(account, packet, new OnIqPacketReceived() {
1967
1968 @Override
1969 public void onIqPacketReceived(Account account, IqPacket result) {
1970 synchronized (mInProgressAvatarFetches) {
1971 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
1972 }
1973 final String ERROR = account.getJid().toBareJid()
1974 + ": fetching avatar for " + avatar.owner + " failed ";
1975 if (result.getType() == IqPacket.TYPE.RESULT) {
1976 avatar.image = mIqParser.avatarData(result);
1977 if (avatar.image != null) {
1978 if (getFileBackend().save(avatar)) {
1979 if (account.getJid().toBareJid().equals(avatar.owner)) {
1980 if (account.setAvatar(avatar.getFilename())) {
1981 databaseBackend.updateAccount(account);
1982 }
1983 getAvatarService().clear(account);
1984 updateConversationUi();
1985 updateAccountUi();
1986 } else {
1987 Contact contact = account.getRoster()
1988 .getContact(avatar.owner);
1989 contact.setAvatar(avatar);
1990 getAvatarService().clear(contact);
1991 updateConversationUi();
1992 updateRosterUi();
1993 }
1994 if (callback != null) {
1995 callback.success(avatar);
1996 }
1997 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1998 + ": succesfuly fetched pep avatar for " + avatar.owner);
1999 return;
2000 }
2001 } else {
2002
2003 Log.d(Config.LOGTAG, ERROR + "(parsing error)");
2004 }
2005 } else {
2006 Element error = result.findChild("error");
2007 if (error == null) {
2008 Log.d(Config.LOGTAG, ERROR + "(server error)");
2009 } else {
2010 Log.d(Config.LOGTAG, ERROR + error.toString());
2011 }
2012 }
2013 if (callback != null) {
2014 callback.error(0, null);
2015 }
2016
2017 }
2018 });
2019 }
2020
2021 private void fetchAvatarVcard(final Account account, final Avatar avatar, final UiCallback<Avatar> callback) {
2022 IqPacket packet = this.mIqGenerator.retrieveVcardAvatar(avatar);
2023 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2024 @Override
2025 public void onIqPacketReceived(Account account, IqPacket packet) {
2026 synchronized (mInProgressAvatarFetches) {
2027 mInProgressAvatarFetches.remove(generateFetchKey(account, avatar));
2028 }
2029 if (packet.getType() == IqPacket.TYPE.RESULT) {
2030 Element vCard = packet.findChild("vCard", "vcard-temp");
2031 Element photo = vCard != null ? vCard.findChild("PHOTO") : null;
2032 String image = photo != null ? photo.findChildContent("BINVAL") : null;
2033 if (image != null) {
2034 avatar.image = image;
2035 if (getFileBackend().save(avatar)) {
2036 Log.d(Config.LOGTAG, account.getJid().toBareJid()
2037 + ": successfully fetched vCard avatar for " + avatar.owner);
2038 Contact contact = account.getRoster()
2039 .getContact(avatar.owner);
2040 contact.setAvatar(avatar);
2041 getAvatarService().clear(contact);
2042 updateConversationUi();
2043 updateRosterUi();
2044 }
2045 }
2046 }
2047 }
2048 });
2049 }
2050
2051 public void checkForAvatar(Account account, final UiCallback<Avatar> callback) {
2052 IqPacket packet = this.mIqGenerator.retrieveAvatarMetaData(null);
2053 this.sendIqPacket(account, packet, new OnIqPacketReceived() {
2054
2055 @Override
2056 public void onIqPacketReceived(Account account, IqPacket packet) {
2057 if (packet.getType() == IqPacket.TYPE.RESULT) {
2058 Element pubsub = packet.findChild("pubsub",
2059 "http://jabber.org/protocol/pubsub");
2060 if (pubsub != null) {
2061 Element items = pubsub.findChild("items");
2062 if (items != null) {
2063 Avatar avatar = Avatar.parseMetadata(items);
2064 if (avatar != null) {
2065 avatar.owner = account.getJid().toBareJid();
2066 if (fileBackend.isAvatarCached(avatar)) {
2067 if (account.setAvatar(avatar.getFilename())) {
2068 databaseBackend.updateAccount(account);
2069 }
2070 getAvatarService().clear(account);
2071 callback.success(avatar);
2072 } else {
2073 fetchAvatarPep(account, avatar, callback);
2074 }
2075 return;
2076 }
2077 }
2078 }
2079 }
2080 callback.error(0, null);
2081 }
2082 });
2083 }
2084
2085 public void deleteContactOnServer(Contact contact) {
2086 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
2087 contact.resetOption(Contact.Options.DIRTY_PUSH);
2088 contact.setOption(Contact.Options.DIRTY_DELETE);
2089 Account account = contact.getAccount();
2090 if (account.getStatus() == Account.State.ONLINE) {
2091 IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2092 Element item = iq.query(Xmlns.ROSTER).addChild("item");
2093 item.setAttribute("jid", contact.getJid().toString());
2094 item.setAttribute("subscription", "remove");
2095 account.getXmppConnection().sendIqPacket(iq, mDefaultIqHandler);
2096 }
2097 }
2098
2099 public void updateConversation(Conversation conversation) {
2100 this.databaseBackend.updateConversation(conversation);
2101 }
2102
2103 public void reconnectAccount(final Account account, final boolean force) {
2104 synchronized (account) {
2105 if (account.getXmppConnection() != null) {
2106 disconnect(account, force);
2107 }
2108 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2109
2110 synchronized (this.mInProgressAvatarFetches) {
2111 for(Iterator<String> iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) {
2112 final String KEY = iterator.next();
2113 if (KEY.startsWith(account.getJid().toBareJid()+"_")) {
2114 iterator.remove();
2115 }
2116 }
2117 }
2118
2119 if (account.getXmppConnection() == null) {
2120 account.setXmppConnection(createConnection(account));
2121 }
2122 Thread thread = new Thread(account.getXmppConnection());
2123 thread.start();
2124 scheduleWakeUpCall(Config.CONNECT_TIMEOUT, account.getUuid().hashCode());
2125 } else {
2126 account.getRoster().clearPresences();
2127 account.setXmppConnection(null);
2128 }
2129 }
2130 }
2131
2132 public void reconnectAccountInBackground(final Account account) {
2133 new Thread(new Runnable() {
2134 @Override
2135 public void run() {
2136 reconnectAccount(account,false);
2137 }
2138 }).start();
2139 }
2140
2141 public void invite(Conversation conversation, Jid contact) {
2142 Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid());
2143 MessagePacket packet = mMessageGenerator.invite(conversation, contact);
2144 sendMessagePacket(conversation.getAccount(), packet);
2145 }
2146
2147 public void directInvite(Conversation conversation, Jid jid) {
2148 MessagePacket packet = mMessageGenerator.directInvite(conversation, jid);
2149 sendMessagePacket(conversation.getAccount(),packet);
2150 }
2151
2152 public void resetSendingToWaiting(Account account) {
2153 for (Conversation conversation : getConversations()) {
2154 if (conversation.getAccount() == account) {
2155 conversation.findUnsentTextMessages(new Conversation.OnMessageFound() {
2156
2157 @Override
2158 public void onMessageFound(Message message) {
2159 markMessage(message, Message.STATUS_WAITING);
2160 }
2161 });
2162 }
2163 }
2164 }
2165
2166 public Message markMessage(final Account account, final Jid recipient, final String uuid, final int status) {
2167 if (uuid == null) {
2168 return null;
2169 }
2170 for (Conversation conversation : getConversations()) {
2171 if (conversation.getJid().toBareJid().equals(recipient) && conversation.getAccount() == account) {
2172 final Message message = conversation.findSentMessageWithUuid(uuid);
2173 if (message != null) {
2174 markMessage(message, status);
2175 }
2176 return message;
2177 }
2178 }
2179 return null;
2180 }
2181
2182 public boolean markMessage(Conversation conversation, String uuid,
2183 int status) {
2184 if (uuid == null) {
2185 return false;
2186 } else {
2187 Message message = conversation.findSentMessageWithUuid(uuid);
2188 if (message != null) {
2189 markMessage(message, status);
2190 return true;
2191 } else {
2192 return false;
2193 }
2194 }
2195 }
2196
2197 public void markMessage(Message message, int status) {
2198 if (status == Message.STATUS_SEND_FAILED
2199 && (message.getStatus() == Message.STATUS_SEND_RECEIVED || message
2200 .getStatus() == Message.STATUS_SEND_DISPLAYED)) {
2201 return;
2202 }
2203 message.setStatus(status);
2204 databaseBackend.updateMessage(message);
2205 updateConversationUi();
2206 }
2207
2208 public SharedPreferences getPreferences() {
2209 return PreferenceManager
2210 .getDefaultSharedPreferences(getApplicationContext());
2211 }
2212
2213 public boolean forceEncryption() {
2214 return getPreferences().getBoolean("force_encryption", false);
2215 }
2216
2217 public boolean confirmMessages() {
2218 return getPreferences().getBoolean("confirm_messages", true);
2219 }
2220
2221 public boolean sendChatStates() {
2222 return getPreferences().getBoolean("chat_states", false);
2223 }
2224
2225 public boolean saveEncryptedMessages() {
2226 return !getPreferences().getBoolean("dont_save_encrypted", false);
2227 }
2228
2229 public boolean indicateReceived() {
2230 return getPreferences().getBoolean("indicate_received", false);
2231 }
2232
2233 public int unreadCount() {
2234 int count = 0;
2235 for(Conversation conversation : getConversations()) {
2236 count += conversation.unreadCount();
2237 }
2238 return count;
2239 }
2240
2241 public void updateConversationUi() {
2242 if (mOnConversationUpdate != null) {
2243 mOnConversationUpdate.onConversationUpdate();
2244 }
2245 }
2246
2247 public void updateAccountUi() {
2248 if (mOnAccountUpdate != null) {
2249 mOnAccountUpdate.onAccountUpdate();
2250 }
2251 }
2252
2253 public void updateRosterUi() {
2254 if (mOnRosterUpdate != null) {
2255 mOnRosterUpdate.onRosterUpdate();
2256 }
2257 }
2258
2259 public void updateBlocklistUi(final OnUpdateBlocklist.Status status) {
2260 if (mOnUpdateBlocklist != null) {
2261 mOnUpdateBlocklist.OnUpdateBlocklist(status);
2262 }
2263 }
2264
2265 public void updateMucRosterUi() {
2266 if (mOnMucRosterUpdate != null) {
2267 mOnMucRosterUpdate.onMucRosterUpdate();
2268 }
2269 }
2270
2271 public Account findAccountByJid(final Jid accountJid) {
2272 for (Account account : this.accounts) {
2273 if (account.getJid().toBareJid().equals(accountJid.toBareJid())) {
2274 return account;
2275 }
2276 }
2277 return null;
2278 }
2279
2280 public Conversation findConversationByUuid(String uuid) {
2281 for (Conversation conversation : getConversations()) {
2282 if (conversation.getUuid().equals(uuid)) {
2283 return conversation;
2284 }
2285 }
2286 return null;
2287 }
2288
2289 public void markRead(final Conversation conversation) {
2290 mNotificationService.clear(conversation);
2291 conversation.markRead();
2292 updateUnreadCountBadge();
2293 }
2294
2295 public synchronized void updateUnreadCountBadge() {
2296 int count = unreadCount();
2297 if (unreadCount != count) {
2298 Log.d(Config.LOGTAG, "update unread count to " + count);
2299 if (count > 0) {
2300 ShortcutBadger.with(getApplicationContext()).count(count);
2301 } else {
2302 ShortcutBadger.with(getApplicationContext()).remove();
2303 }
2304 unreadCount = count;
2305 }
2306 }
2307
2308 public void sendReadMarker(final Conversation conversation) {
2309 final Message markable = conversation.getLatestMarkableMessage();
2310 this.markRead(conversation);
2311 if (confirmMessages() && markable != null && markable.getRemoteMsgId() != null) {
2312 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": sending read marker to " + markable.getCounterpart().toString());
2313 Account account = conversation.getAccount();
2314 final Jid to = markable.getCounterpart();
2315 MessagePacket packet = mMessageGenerator.confirm(account, to, markable.getRemoteMsgId());
2316 this.sendMessagePacket(conversation.getAccount(), packet);
2317 }
2318 updateConversationUi();
2319 }
2320
2321 public SecureRandom getRNG() {
2322 return this.mRandom;
2323 }
2324
2325 public MemorizingTrustManager getMemorizingTrustManager() {
2326 return this.mMemorizingTrustManager;
2327 }
2328
2329 public void setMemorizingTrustManager(MemorizingTrustManager trustManager) {
2330 this.mMemorizingTrustManager = trustManager;
2331 }
2332
2333 public void updateMemorizingTrustmanager() {
2334 final MemorizingTrustManager tm;
2335 final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false);
2336 if (dontTrustSystemCAs) {
2337 tm = new MemorizingTrustManager(getApplicationContext(), null);
2338 } else {
2339 tm = new MemorizingTrustManager(getApplicationContext());
2340 }
2341 setMemorizingTrustManager(tm);
2342 }
2343
2344 public PowerManager getPowerManager() {
2345 return this.pm;
2346 }
2347
2348 public LruCache<String, Bitmap> getBitmapCache() {
2349 return this.mBitmapCache;
2350 }
2351
2352 public void syncRosterToDisk(final Account account) {
2353 Runnable runnable = new Runnable() {
2354
2355 @Override
2356 public void run() {
2357 databaseBackend.writeRoster(account.getRoster());
2358 }
2359 };
2360 mDatabaseExecutor.execute(runnable);
2361
2362 }
2363
2364 public List<String> getKnownHosts() {
2365 final List<String> hosts = new ArrayList<>();
2366 for (final Account account : getAccounts()) {
2367 if (!hosts.contains(account.getServer().toString())) {
2368 hosts.add(account.getServer().toString());
2369 }
2370 for (final Contact contact : account.getRoster().getContacts()) {
2371 if (contact.showInRoster()) {
2372 final String server = contact.getServer().toString();
2373 if (server != null && !hosts.contains(server)) {
2374 hosts.add(server);
2375 }
2376 }
2377 }
2378 }
2379 return hosts;
2380 }
2381
2382 public List<String> getKnownConferenceHosts() {
2383 final ArrayList<String> mucServers = new ArrayList<>();
2384 for (final Account account : accounts) {
2385 if (account.getXmppConnection() != null) {
2386 final String server = account.getXmppConnection().getMucServer();
2387 if (server != null && !mucServers.contains(server)) {
2388 mucServers.add(server);
2389 }
2390 }
2391 }
2392 return mucServers;
2393 }
2394
2395 public void sendMessagePacket(Account account, MessagePacket packet) {
2396 XmppConnection connection = account.getXmppConnection();
2397 if (connection != null) {
2398 connection.sendMessagePacket(packet);
2399 }
2400 }
2401
2402 public void sendPresencePacket(Account account, PresencePacket packet) {
2403 XmppConnection connection = account.getXmppConnection();
2404 if (connection != null) {
2405 connection.sendPresencePacket(packet);
2406 }
2407 }
2408
2409 public void sendIqPacket(final Account account, final IqPacket packet, final OnIqPacketReceived callback) {
2410 final XmppConnection connection = account.getXmppConnection();
2411 if (connection != null) {
2412 connection.sendIqPacket(packet, callback);
2413 }
2414 }
2415
2416 public void sendPresence(final Account account) {
2417 sendPresencePacket(account, mPresenceGenerator.sendPresence(account));
2418 }
2419
2420 public void sendOfflinePresence(final Account account) {
2421 sendPresencePacket(account, mPresenceGenerator.sendOfflinePresence(account));
2422 }
2423
2424 public MessageGenerator getMessageGenerator() {
2425 return this.mMessageGenerator;
2426 }
2427
2428 public PresenceGenerator getPresenceGenerator() {
2429 return this.mPresenceGenerator;
2430 }
2431
2432 public IqGenerator getIqGenerator() {
2433 return this.mIqGenerator;
2434 }
2435
2436 public IqParser getIqParser() {
2437 return this.mIqParser;
2438 }
2439
2440 public JingleConnectionManager getJingleConnectionManager() {
2441 return this.mJingleConnectionManager;
2442 }
2443
2444 public MessageArchiveService getMessageArchiveService() {
2445 return this.mMessageArchiveService;
2446 }
2447
2448 public List<Contact> findContacts(Jid jid) {
2449 ArrayList<Contact> contacts = new ArrayList<>();
2450 for (Account account : getAccounts()) {
2451 if (!account.isOptionSet(Account.OPTION_DISABLED)) {
2452 Contact contact = account.getRoster().getContactFromRoster(jid);
2453 if (contact != null) {
2454 contacts.add(contact);
2455 }
2456 }
2457 }
2458 return contacts;
2459 }
2460
2461 public NotificationService getNotificationService() {
2462 return this.mNotificationService;
2463 }
2464
2465 public HttpConnectionManager getHttpConnectionManager() {
2466 return this.mHttpConnectionManager;
2467 }
2468
2469 public void resendFailedMessages(final Message message) {
2470 final Collection<Message> messages = new ArrayList<>();
2471 Message current = message;
2472 while (current.getStatus() == Message.STATUS_SEND_FAILED) {
2473 messages.add(current);
2474 if (current.mergeable(current.next())) {
2475 current = current.next();
2476 } else {
2477 break;
2478 }
2479 }
2480 for (final Message msg : messages) {
2481 markMessage(msg, Message.STATUS_WAITING);
2482 this.resendMessage(msg);
2483 }
2484 }
2485
2486 public void clearConversationHistory(final Conversation conversation) {
2487 conversation.clearMessages();
2488 conversation.setHasMessagesLeftOnServer(false); //avoid messages getting loaded through mam
2489 new Thread(new Runnable() {
2490 @Override
2491 public void run() {
2492 databaseBackend.deleteMessagesInConversation(conversation);
2493 }
2494 }).start();
2495 }
2496
2497 public void sendBlockRequest(final Blockable blockable) {
2498 if (blockable != null && blockable.getBlockedJid() != null) {
2499 final Jid jid = blockable.getBlockedJid();
2500 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetBlockRequest(jid), new OnIqPacketReceived() {
2501
2502 @Override
2503 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2504 if (packet.getType() == IqPacket.TYPE.RESULT) {
2505 account.getBlocklist().add(jid);
2506 updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
2507 }
2508 }
2509 });
2510 }
2511 }
2512
2513 public void sendUnblockRequest(final Blockable blockable) {
2514 if (blockable != null && blockable.getJid() != null) {
2515 final Jid jid = blockable.getBlockedJid();
2516 this.sendIqPacket(blockable.getAccount(), getIqGenerator().generateSetUnblockRequest(jid), new OnIqPacketReceived() {
2517 @Override
2518 public void onIqPacketReceived(final Account account, final IqPacket packet) {
2519 if (packet.getType() == IqPacket.TYPE.RESULT) {
2520 account.getBlocklist().remove(jid);
2521 updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
2522 }
2523 }
2524 });
2525 }
2526 }
2527
2528 public interface OnMoreMessagesLoaded {
2529 public void onMoreMessagesLoaded(int count, Conversation conversation);
2530
2531 public void informUser(int r);
2532 }
2533
2534 public interface OnAccountPasswordChanged {
2535 public void onPasswordChangeSucceeded();
2536
2537 public void onPasswordChangeFailed();
2538 }
2539
2540 public interface OnAffiliationChanged {
2541 public void onAffiliationChangedSuccessful(Jid jid);
2542
2543 public void onAffiliationChangeFailed(Jid jid, int resId);
2544 }
2545
2546 public interface OnRoleChanged {
2547 public void onRoleChangedSuccessful(String nick);
2548
2549 public void onRoleChangeFailed(String nick, int resid);
2550 }
2551
2552 public interface OnConversationUpdate {
2553 public void onConversationUpdate();
2554 }
2555
2556 public interface OnAccountUpdate {
2557 public void onAccountUpdate();
2558 }
2559
2560 public interface OnRosterUpdate {
2561 public void onRosterUpdate();
2562 }
2563
2564 public interface OnMucRosterUpdate {
2565 public void onMucRosterUpdate();
2566 }
2567
2568 public interface OnConferenceOptionsPushed {
2569 public void onPushSucceeded();
2570
2571 public void onPushFailed();
2572 }
2573
2574 public class XmppConnectionBinder extends Binder {
2575 public XmppConnectionService getService() {
2576 return XmppConnectionService.this;
2577 }
2578 }
2579}