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