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