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