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