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