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