XmppConnectionService.java

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