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