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