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