XmppConnectionService.java

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