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