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