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