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