ConversationActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.annotation.SuppressLint;
   4import android.app.ActionBar;
   5import android.app.AlertDialog;
   6import android.app.FragmentTransaction;
   7import android.app.PendingIntent;
   8import android.content.ActivityNotFoundException;
   9import android.content.ClipData;
  10import android.content.DialogInterface;
  11import android.content.DialogInterface.OnClickListener;
  12import android.content.Intent;
  13import android.content.IntentSender.SendIntentException;
  14import android.content.pm.PackageManager;
  15import android.net.Uri;
  16import android.os.Build;
  17import android.os.Bundle;
  18import android.os.Handler;
  19import android.provider.MediaStore;
  20import android.provider.Settings;
  21import android.support.v4.widget.SlidingPaneLayout;
  22import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
  23import android.util.Log;
  24import android.util.Pair;
  25import android.view.Gravity;
  26import android.view.KeyEvent;
  27import android.view.Menu;
  28import android.view.MenuItem;
  29import android.view.Surface;
  30import android.view.View;
  31import android.widget.AdapterView;
  32import android.widget.AdapterView.OnItemClickListener;
  33import android.widget.ArrayAdapter;
  34import android.widget.CheckBox;
  35import android.widget.PopupMenu;
  36import android.widget.PopupMenu.OnMenuItemClickListener;
  37import android.widget.Toast;
  38
  39import net.java.otr4j.session.SessionStatus;
  40
  41import org.openintents.openpgp.util.OpenPgpApi;
  42
  43import java.util.ArrayList;
  44import java.util.Iterator;
  45import java.util.List;
  46import java.util.concurrent.atomic.AtomicBoolean;
  47
  48import de.timroes.android.listview.EnhancedListView;
  49import eu.siacs.conversations.Config;
  50import eu.siacs.conversations.R;
  51import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  52import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
  53import eu.siacs.conversations.entities.Account;
  54import eu.siacs.conversations.entities.Blockable;
  55import eu.siacs.conversations.entities.Contact;
  56import eu.siacs.conversations.entities.Conversation;
  57import eu.siacs.conversations.entities.Message;
  58import eu.siacs.conversations.entities.Transferable;
  59import eu.siacs.conversations.persistance.FileBackend;
  60import eu.siacs.conversations.services.XmppConnectionService;
  61import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
  62import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate;
  63import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
  64import eu.siacs.conversations.ui.adapter.ConversationAdapter;
  65import eu.siacs.conversations.utils.ExceptionHelper;
  66import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  67import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  68import eu.siacs.conversations.xmpp.jid.Jid;
  69
  70public class ConversationActivity extends XmppActivity
  71	implements OnAccountUpdate, OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast {
  72
  73	public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
  74	public static final String CONVERSATION = "conversationUuid";
  75	public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
  76	public static final String TEXT = "text";
  77	public static final String NICK = "nick";
  78	public static final String PRIVATE_MESSAGE = "pm";
  79
  80	public static final int REQUEST_SEND_MESSAGE = 0x0201;
  81	public static final int REQUEST_DECRYPT_PGP = 0x0202;
  82	public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
  83	public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
  84	public static final int REQUEST_TRUST_KEYS_MENU = 0x0209;
  85	public static final int REQUEST_START_DOWNLOAD = 0x0210;
  86	public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
  87	public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
  88	public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
  89	public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
  90	public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
  91	public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
  92	private static final String STATE_OPEN_CONVERSATION = "state_open_conversation";
  93	private static final String STATE_PANEL_OPEN = "state_panel_open";
  94	private static final String STATE_PENDING_URI = "state_pending_uri";
  95	private static final String STATE_FIRST_VISIBLE = "first_visible";
  96	private static final String STATE_OFFSET_FROM_TOP = "offset_from_top";
  97
  98	private String mOpenConversation = null;
  99	private boolean mPanelOpen = true;
 100	private Pair<Integer,Integer> mScrollPosition = null;
 101	final private List<Uri> mPendingImageUris = new ArrayList<>();
 102	final private List<Uri> mPendingFileUris = new ArrayList<>();
 103	private Uri mPendingGeoUri = null;
 104	private boolean forbidProcessingPendings = false;
 105	private Message mPendingDownloadableMessage = null;
 106
 107	private boolean conversationWasSelectedByKeyboard = false;
 108
 109	private View mContentView;
 110
 111	private List<Conversation> conversationList = new ArrayList<>();
 112	private Conversation swipedConversation = null;
 113	private Conversation mSelectedConversation = null;
 114	private EnhancedListView listView;
 115	private ConversationFragment mConversationFragment;
 116
 117	private ArrayAdapter<Conversation> listAdapter;
 118
 119	private boolean mActivityPaused = false;
 120	private AtomicBoolean mRedirected = new AtomicBoolean(false);
 121	private Pair<Integer, Intent> mPostponedActivityResult;
 122
 123	public Conversation getSelectedConversation() {
 124		return this.mSelectedConversation;
 125	}
 126
 127	public void setSelectedConversation(Conversation conversation) {
 128		this.mSelectedConversation = conversation;
 129	}
 130
 131	public void showConversationsOverview() {
 132		if (mContentView instanceof SlidingPaneLayout) {
 133			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 134			mSlidingPaneLayout.openPane();
 135		}
 136	}
 137
 138	@Override
 139	protected String getShareableUri() {
 140		Conversation conversation = getSelectedConversation();
 141		if (conversation != null) {
 142			return conversation.getAccount().getShareableUri();
 143		} else {
 144			return "";
 145		}
 146	}
 147
 148	public void hideConversationsOverview() {
 149		if (mContentView instanceof SlidingPaneLayout) {
 150			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 151			mSlidingPaneLayout.closePane();
 152		}
 153	}
 154
 155	public boolean isConversationsOverviewHideable() {
 156		return mContentView instanceof SlidingPaneLayout;
 157	}
 158
 159	public boolean isConversationsOverviewVisable() {
 160		if (mContentView instanceof SlidingPaneLayout) {
 161			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 162			return mSlidingPaneLayout.isOpen();
 163		} else {
 164			return true;
 165		}
 166	}
 167
 168	@Override
 169	protected void onCreate(final Bundle savedInstanceState) {
 170		super.onCreate(savedInstanceState);
 171		if (savedInstanceState != null) {
 172			mOpenConversation = savedInstanceState.getString(STATE_OPEN_CONVERSATION, null);
 173			mPanelOpen = savedInstanceState.getBoolean(STATE_PANEL_OPEN, true);
 174			int pos = savedInstanceState.getInt(STATE_FIRST_VISIBLE, -1);
 175			int offset = savedInstanceState.getInt(STATE_OFFSET_FROM_TOP, 1);
 176			if (pos >= 0 && offset <= 0) {
 177				Log.d(Config.LOGTAG,"retrieved scroll position from instanceState "+pos+":"+offset);
 178				mScrollPosition = new Pair<>(pos,offset);
 179			} else {
 180				mScrollPosition = null;
 181			}
 182			String pending = savedInstanceState.getString(STATE_PENDING_URI, null);
 183			if (pending != null) {
 184				Log.d(Config.LOGTAG,"ConversationsActivity.onCreate() - restoring pending image uri");
 185				mPendingImageUris.clear();
 186				mPendingImageUris.add(Uri.parse(pending));
 187			}
 188		}
 189
 190		setContentView(R.layout.fragment_conversations_overview);
 191
 192		this.mConversationFragment = new ConversationFragment();
 193		FragmentTransaction transaction = getFragmentManager().beginTransaction();
 194		transaction.replace(R.id.selected_conversation, this.mConversationFragment, "conversation");
 195		transaction.commit();
 196
 197		listView = (EnhancedListView) findViewById(R.id.list);
 198		this.listAdapter = new ConversationAdapter(this, conversationList);
 199		listView.setAdapter(this.listAdapter);
 200
 201		if (getActionBar() != null) {
 202			getActionBar().setDisplayHomeAsUpEnabled(false);
 203			getActionBar().setHomeButtonEnabled(false);
 204		}
 205
 206		listView.setOnItemClickListener(new OnItemClickListener() {
 207
 208			@Override
 209			public void onItemClick(AdapterView<?> arg0, View clickedView,
 210									int position, long arg3) {
 211				if (getSelectedConversation() != conversationList.get(position)) {
 212					setSelectedConversation(conversationList.get(position));
 213					ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 214					conversationWasSelectedByKeyboard = false;
 215				}
 216				hideConversationsOverview();
 217				openConversation();
 218			}
 219		});
 220
 221		listView.setDismissCallback(new EnhancedListView.OnDismissCallback() {
 222
 223			@Override
 224			public EnhancedListView.Undoable onDismiss(final EnhancedListView enhancedListView, final int position) {
 225
 226				final int index = listView.getFirstVisiblePosition();
 227				View v = listView.getChildAt(0);
 228				final int top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());
 229
 230				try {
 231					swipedConversation = listAdapter.getItem(position);
 232				} catch (IndexOutOfBoundsException e) {
 233					return null;
 234				}
 235				listAdapter.remove(swipedConversation);
 236				xmppConnectionService.markRead(swipedConversation);
 237
 238				final boolean formerlySelected = (getSelectedConversation() == swipedConversation);
 239				if (position == 0 && listAdapter.getCount() == 0) {
 240					endConversation(swipedConversation, false, true);
 241					return null;
 242				} else if (formerlySelected) {
 243					setSelectedConversation(listAdapter.getItem(0));
 244					ConversationActivity.this.mConversationFragment
 245							.reInit(getSelectedConversation());
 246				}
 247
 248				return new EnhancedListView.Undoable() {
 249
 250					@Override
 251					public void undo() {
 252						listAdapter.insert(swipedConversation, position);
 253						if (formerlySelected) {
 254							setSelectedConversation(swipedConversation);
 255							ConversationActivity.this.mConversationFragment
 256									.reInit(getSelectedConversation());
 257						}
 258						swipedConversation = null;
 259						listView.setSelectionFromTop(index + (listView.getChildCount() < position ? 1 : 0), top);
 260					}
 261
 262					@Override
 263					public void discard() {
 264						if (!swipedConversation.isRead()
 265								&& swipedConversation.getMode() == Conversation.MODE_SINGLE) {
 266							swipedConversation = null;
 267							return;
 268						}
 269						endConversation(swipedConversation, false, false);
 270						swipedConversation = null;
 271					}
 272
 273					@Override
 274					public String getTitle() {
 275						if (swipedConversation.getMode() == Conversation.MODE_MULTI) {
 276							return getResources().getString(R.string.title_undo_swipe_out_muc);
 277						} else {
 278							return getResources().getString(R.string.title_undo_swipe_out_conversation);
 279						}
 280					}
 281				};
 282			}
 283		});
 284		listView.enableSwipeToDismiss();
 285		listView.setSwipingLayout(R.id.swipeable_item);
 286		listView.setUndoStyle(EnhancedListView.UndoStyle.SINGLE_POPUP);
 287		listView.setUndoHideDelay(5000);
 288		listView.setRequireTouchBeforeDismiss(false);
 289
 290		mContentView = findViewById(R.id.content_view_spl);
 291		if (mContentView == null) {
 292			mContentView = findViewById(R.id.content_view_ll);
 293		}
 294		if (mContentView instanceof SlidingPaneLayout) {
 295			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 296			mSlidingPaneLayout.setParallaxDistance(150);
 297			mSlidingPaneLayout
 298					.setShadowResource(R.drawable.es_slidingpane_shadow);
 299			mSlidingPaneLayout.setSliderFadeColor(0);
 300			mSlidingPaneLayout.setPanelSlideListener(new PanelSlideListener() {
 301
 302				@Override
 303				public void onPanelOpened(View arg0) {
 304					updateActionBarTitle();
 305					invalidateOptionsMenu();
 306					hideKeyboard();
 307					if (xmppConnectionServiceBound) {
 308						xmppConnectionService.getNotificationService()
 309								.setOpenConversation(null);
 310					}
 311					closeContextMenu();
 312				}
 313
 314				@Override
 315				public void onPanelClosed(View arg0) {
 316					listView.discardUndo();
 317					openConversation();
 318				}
 319
 320				@Override
 321				public void onPanelSlide(View arg0, float arg1) {
 322					// TODO Auto-generated method stub
 323
 324				}
 325			});
 326		}
 327	}
 328
 329	@Override
 330	public void switchToConversation(Conversation conversation) {
 331		setSelectedConversation(conversation);
 332		runOnUiThread(new Runnable() {
 333			@Override
 334			public void run() {
 335				ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 336				openConversation();
 337			}
 338		});
 339	}
 340
 341	private void updateActionBarTitle() {
 342		updateActionBarTitle(isConversationsOverviewHideable() && !isConversationsOverviewVisable());
 343	}
 344
 345	private void updateActionBarTitle(boolean titleShouldBeName) {
 346		final ActionBar ab = getActionBar();
 347		final Conversation conversation = getSelectedConversation();
 348		if (ab != null) {
 349			if (titleShouldBeName && conversation != null) {
 350				ab.setDisplayHomeAsUpEnabled(true);
 351				ab.setHomeButtonEnabled(true);
 352				if (conversation.getMode() == Conversation.MODE_SINGLE || useSubjectToIdentifyConference()) {
 353					ab.setTitle(conversation.getName());
 354				} else {
 355					ab.setTitle(conversation.getJid().toBareJid().toString());
 356				}
 357			} else {
 358				ab.setDisplayHomeAsUpEnabled(false);
 359				ab.setHomeButtonEnabled(false);
 360				ab.setTitle(R.string.app_name);
 361			}
 362		}
 363	}
 364
 365	private void openConversation() {
 366		this.updateActionBarTitle();
 367		this.invalidateOptionsMenu();
 368		if (xmppConnectionServiceBound) {
 369			final Conversation conversation = getSelectedConversation();
 370			xmppConnectionService.getNotificationService().setOpenConversation(conversation);
 371			sendReadMarkerIfNecessary(conversation);
 372		}
 373		listAdapter.notifyDataSetChanged();
 374	}
 375
 376	public void sendReadMarkerIfNecessary(final Conversation conversation) {
 377		if (!mActivityPaused && conversation != null) {
 378			xmppConnectionService.sendReadMarker(conversation);
 379		}
 380	}
 381
 382	@Override
 383	public boolean onCreateOptionsMenu(Menu menu) {
 384		getMenuInflater().inflate(R.menu.conversations, menu);
 385		final MenuItem menuSecure = menu.findItem(R.id.action_security);
 386		final MenuItem menuArchive = menu.findItem(R.id.action_archive);
 387		final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 388		final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 389		final MenuItem menuAttach = menu.findItem(R.id.action_attach_file);
 390		final MenuItem menuClearHistory = menu.findItem(R.id.action_clear_history);
 391		final MenuItem menuAdd = menu.findItem(R.id.action_add);
 392		final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 393		final MenuItem menuMute = menu.findItem(R.id.action_mute);
 394		final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 395
 396		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
 397			menuArchive.setVisible(false);
 398			menuMucDetails.setVisible(false);
 399			menuContactDetails.setVisible(false);
 400			menuSecure.setVisible(false);
 401			menuInviteContact.setVisible(false);
 402			menuAttach.setVisible(false);
 403			menuClearHistory.setVisible(false);
 404			menuMute.setVisible(false);
 405			menuUnmute.setVisible(false);
 406		} else {
 407			menuAdd.setVisible(!isConversationsOverviewHideable());
 408			if (this.getSelectedConversation() != null) {
 409				if (this.getSelectedConversation().getNextEncryption() != Message.ENCRYPTION_NONE) {
 410					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 411						menuSecure.setIcon(R.drawable.ic_lock_white_24dp);
 412					} else {
 413						menuSecure.setIcon(R.drawable.ic_action_secure);
 414					}
 415				}
 416				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
 417					menuContactDetails.setVisible(false);
 418					menuAttach.setVisible(getSelectedConversation().getAccount().httpUploadAvailable() && getSelectedConversation().getMucOptions().participating());
 419					menuInviteContact.setVisible(getSelectedConversation().getMucOptions().canInvite());
 420					menuSecure.setVisible((Config.supportOpenPgp() || Config.supportOmemo()) && Config.multipleEncryptionChoices()); //only if pgp is supported we have a choice
 421				} else {
 422					menuContactDetails.setVisible(!this.getSelectedConversation().withSelf());
 423					menuMucDetails.setVisible(false);
 424					menuSecure.setVisible(Config.multipleEncryptionChoices());
 425				}
 426				if (this.getSelectedConversation().isMuted()) {
 427					menuMute.setVisible(false);
 428				} else {
 429					menuUnmute.setVisible(false);
 430				}
 431			}
 432		}
 433		if (Config.supportOmemo()) {
 434			new Handler().post(new Runnable() {
 435				@Override
 436				public void run() {
 437					View view = findViewById(R.id.action_security);
 438					if (view != null) {
 439						view.setOnLongClickListener(new View.OnLongClickListener() {
 440							@Override
 441							public boolean onLongClick(View v) {
 442								return quickOmemoDebugger(getSelectedConversation());
 443							}
 444						});
 445					}
 446				}
 447			});
 448		}
 449		return super.onCreateOptionsMenu(menu);
 450	}
 451
 452	private boolean quickOmemoDebugger(Conversation c) {
 453		if (c != null) {
 454			AxolotlService axolotlService = c.getAccount().getAxolotlService();
 455			Pair<AxolotlService.AxolotlCapability,Jid> capabilityJidPair = axolotlService.isConversationAxolotlCapableDetailed(c);
 456			switch (capabilityJidPair.first) {
 457				case MISSING_PRESENCE:
 458					Toast.makeText(ConversationActivity.this,getString(R.string.missing_presence_subscription_with_x,capabilityJidPair.second.toBareJid().toString()),Toast.LENGTH_SHORT).show();
 459					return true;
 460				case MISSING_KEYS:
 461					Toast.makeText(ConversationActivity.this,getString(R.string.missing_keys_from_x,capabilityJidPair.second.toBareJid().toString()),Toast.LENGTH_SHORT).show();
 462					return true;
 463				case WRONG_CONFIGURATION:
 464					Toast.makeText(ConversationActivity.this,R.string.wrong_conference_configuration, Toast.LENGTH_SHORT).show();
 465					return true;
 466				case NO_MEMBERS:
 467					Toast.makeText(ConversationActivity.this,R.string.this_conference_has_no_members, Toast.LENGTH_SHORT).show();
 468					return true;
 469			}
 470		}
 471		return false;
 472	}
 473
 474	protected void selectPresenceToAttachFile(final int attachmentChoice, final int encryption) {
 475		final Conversation conversation = getSelectedConversation();
 476		final Account account = conversation.getAccount();
 477		final OnPresenceSelected callback = new OnPresenceSelected() {
 478
 479			@Override
 480			public void onPresenceSelected() {
 481				Intent intent = new Intent();
 482				boolean chooser = false;
 483				String fallbackPackageId = null;
 484				switch (attachmentChoice) {
 485					case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 486						intent.setAction(Intent.ACTION_GET_CONTENT);
 487						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
 488							intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
 489						}
 490						intent.setType("image/*");
 491						chooser = true;
 492						break;
 493					case ATTACHMENT_CHOICE_TAKE_PHOTO:
 494						Uri uri = xmppConnectionService.getFileBackend().getTakePhotoUri();
 495						intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
 496						intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 497						intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
 498						mPendingImageUris.clear();
 499						mPendingImageUris.add(uri);
 500						break;
 501					case ATTACHMENT_CHOICE_CHOOSE_FILE:
 502						chooser = true;
 503						intent.setType("*/*");
 504						intent.addCategory(Intent.CATEGORY_OPENABLE);
 505						intent.setAction(Intent.ACTION_GET_CONTENT);
 506						break;
 507					case ATTACHMENT_CHOICE_RECORD_VOICE:
 508						intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
 509						fallbackPackageId = "eu.siacs.conversations.voicerecorder";
 510						break;
 511					case ATTACHMENT_CHOICE_LOCATION:
 512						intent.setAction("eu.siacs.conversations.location.request");
 513						fallbackPackageId = "eu.siacs.conversations.sharelocation";
 514						break;
 515				}
 516				if (intent.resolveActivity(getPackageManager()) != null) {
 517					if (chooser) {
 518						startActivityForResult(
 519								Intent.createChooser(intent, getString(R.string.perform_action_with)),
 520								attachmentChoice);
 521					} else {
 522						startActivityForResult(intent, attachmentChoice);
 523					}
 524				} else if (fallbackPackageId != null) {
 525					startActivity(getInstallApkIntent(fallbackPackageId));
 526				}
 527			}
 528		};
 529		if ((account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) && encryption != Message.ENCRYPTION_OTR) {
 530			conversation.setNextCounterpart(null);
 531			callback.onPresenceSelected();
 532		} else {
 533			selectPresence(conversation, callback);
 534		}
 535	}
 536
 537	private Intent getInstallApkIntent(final String packageId) {
 538		Intent intent = new Intent(Intent.ACTION_VIEW);
 539		intent.setData(Uri.parse("market://details?id=" + packageId));
 540		if (intent.resolveActivity(getPackageManager()) != null) {
 541			return intent;
 542		} else {
 543			intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
 544			return intent;
 545		}
 546	}
 547
 548	public void attachFile(final int attachmentChoice) {
 549		if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
 550			if (!hasStoragePermission(attachmentChoice)) {
 551				return;
 552			}
 553		}
 554		switch (attachmentChoice) {
 555			case ATTACHMENT_CHOICE_LOCATION:
 556				getPreferences().edit().putString("recently_used_quick_action", "location").apply();
 557				break;
 558			case ATTACHMENT_CHOICE_RECORD_VOICE:
 559				getPreferences().edit().putString("recently_used_quick_action", "voice").apply();
 560				break;
 561			case ATTACHMENT_CHOICE_TAKE_PHOTO:
 562				getPreferences().edit().putString("recently_used_quick_action", "photo").apply();
 563				break;
 564			case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 565				getPreferences().edit().putString("recently_used_quick_action", "picture").apply();
 566				break;
 567		}
 568		final Conversation conversation = getSelectedConversation();
 569		final int encryption = conversation.getNextEncryption();
 570		final int mode = conversation.getMode();
 571		if (encryption == Message.ENCRYPTION_PGP) {
 572			if (hasPgp()) {
 573				if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
 574					xmppConnectionService.getPgpEngine().hasKey(
 575							conversation.getContact(),
 576							new UiCallback<Contact>() {
 577
 578								@Override
 579								public void userInputRequried(PendingIntent pi, Contact contact) {
 580									ConversationActivity.this.runIntent(pi, attachmentChoice);
 581								}
 582
 583								@Override
 584								public void success(Contact contact) {
 585									selectPresenceToAttachFile(attachmentChoice, encryption);
 586								}
 587
 588								@Override
 589								public void error(int error, Contact contact) {
 590									replaceToast(getString(error));
 591								}
 592							});
 593				} else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
 594					if (!conversation.getMucOptions().everybodyHasKeys()) {
 595						Toast warning = Toast
 596								.makeText(this,
 597										R.string.missing_public_keys,
 598										Toast.LENGTH_LONG);
 599						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
 600						warning.show();
 601					}
 602					selectPresenceToAttachFile(attachmentChoice, encryption);
 603				} else {
 604					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 605							.findFragmentByTag("conversation");
 606					if (fragment != null) {
 607						fragment.showNoPGPKeyDialog(false,
 608								new OnClickListener() {
 609
 610									@Override
 611									public void onClick(DialogInterface dialog,
 612														int which) {
 613										conversation
 614												.setNextEncryption(Message.ENCRYPTION_NONE);
 615										xmppConnectionService.databaseBackend
 616												.updateConversation(conversation);
 617										selectPresenceToAttachFile(attachmentChoice, Message.ENCRYPTION_NONE);
 618									}
 619								});
 620					}
 621				}
 622			} else {
 623				showInstallPgpDialog();
 624			}
 625		} else {
 626			if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
 627				selectPresenceToAttachFile(attachmentChoice, encryption);
 628			}
 629		}
 630	}
 631
 632	@Override
 633	public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
 634		if (grantResults.length > 0)
 635			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 636				if (requestCode == REQUEST_START_DOWNLOAD) {
 637					if (this.mPendingDownloadableMessage != null) {
 638						startDownloadable(this.mPendingDownloadableMessage);
 639					}
 640				} else {
 641					attachFile(requestCode);
 642				}
 643			} else {
 644				Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
 645			}
 646	}
 647
 648	public void startDownloadable(Message message) {
 649		if (!hasStoragePermission(ConversationActivity.REQUEST_START_DOWNLOAD)) {
 650			this.mPendingDownloadableMessage = message;
 651			return;
 652		}
 653		Transferable transferable = message.getTransferable();
 654		if (transferable != null) {
 655			if (!transferable.start()) {
 656				Toast.makeText(this, R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
 657			}
 658		} else if (message.treatAsDownloadable() != Message.Decision.NEVER) {
 659			xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
 660		}
 661	}
 662
 663	@Override
 664	public boolean onOptionsItemSelected(final MenuItem item) {
 665		if (item.getItemId() == android.R.id.home) {
 666			showConversationsOverview();
 667			return true;
 668		} else if (item.getItemId() == R.id.action_add) {
 669			startActivity(new Intent(this, StartConversationActivity.class));
 670			return true;
 671		} else if (getSelectedConversation() != null) {
 672			switch (item.getItemId()) {
 673				case R.id.action_attach_file:
 674					attachFileDialog();
 675					break;
 676				case R.id.action_archive:
 677					this.endConversation(getSelectedConversation());
 678					break;
 679				case R.id.action_contact_details:
 680					switchToContactDetails(getSelectedConversation().getContact());
 681					break;
 682				case R.id.action_muc_details:
 683					Intent intent = new Intent(this,
 684							ConferenceDetailsActivity.class);
 685					intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 686					intent.putExtra("uuid", getSelectedConversation().getUuid());
 687					startActivity(intent);
 688					break;
 689				case R.id.action_invite:
 690					inviteToConversation(getSelectedConversation());
 691					break;
 692				case R.id.action_security:
 693					selectEncryptionDialog(getSelectedConversation());
 694					break;
 695				case R.id.action_clear_history:
 696					clearHistoryDialog(getSelectedConversation());
 697					break;
 698				case R.id.action_mute:
 699					muteConversationDialog(getSelectedConversation());
 700					break;
 701				case R.id.action_unmute:
 702					unmuteConversation(getSelectedConversation());
 703					break;
 704				case R.id.action_block:
 705					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 706					break;
 707				case R.id.action_unblock:
 708					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 709					break;
 710				default:
 711					break;
 712			}
 713			return super.onOptionsItemSelected(item);
 714		} else {
 715			return super.onOptionsItemSelected(item);
 716		}
 717	}
 718
 719	public void endConversation(Conversation conversation) {
 720		endConversation(conversation, true, true);
 721	}
 722
 723	public void endConversation(Conversation conversation, boolean showOverview, boolean reinit) {
 724		if (showOverview) {
 725			showConversationsOverview();
 726		}
 727		xmppConnectionService.archiveConversation(conversation);
 728		if (reinit) {
 729			if (conversationList.size() > 0) {
 730				setSelectedConversation(conversationList.get(0));
 731				this.mConversationFragment.reInit(getSelectedConversation());
 732			} else {
 733				setSelectedConversation(null);
 734				if (mRedirected.compareAndSet(false, true)) {
 735					Intent intent = new Intent(this, StartConversationActivity.class);
 736					intent.putExtra("init", true);
 737					startActivity(intent);
 738					finish();
 739				}
 740			}
 741		}
 742	}
 743
 744	@SuppressLint("InflateParams")
 745	protected void clearHistoryDialog(final Conversation conversation) {
 746		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 747		builder.setTitle(getString(R.string.clear_conversation_history));
 748		View dialogView = getLayoutInflater().inflate(
 749				R.layout.dialog_clear_history, null);
 750		final CheckBox endConversationCheckBox = (CheckBox) dialogView
 751				.findViewById(R.id.end_conversation_checkbox);
 752		builder.setView(dialogView);
 753		builder.setNegativeButton(getString(R.string.cancel), null);
 754		builder.setPositiveButton(getString(R.string.delete_messages),
 755				new OnClickListener() {
 756
 757					@Override
 758					public void onClick(DialogInterface dialog, int which) {
 759						ConversationActivity.this.xmppConnectionService.clearConversationHistory(conversation);
 760						if (endConversationCheckBox.isChecked()) {
 761							endConversation(conversation);
 762						} else {
 763							updateConversationList();
 764							ConversationActivity.this.mConversationFragment.updateMessages();
 765						}
 766					}
 767				});
 768		builder.create().show();
 769	}
 770
 771	protected void attachFileDialog() {
 772		View menuAttachFile = findViewById(R.id.action_attach_file);
 773		if (menuAttachFile == null) {
 774			return;
 775		}
 776		PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
 777		attachFilePopup.inflate(R.menu.attachment_choices);
 778		if (new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) == null) {
 779			attachFilePopup.getMenu().findItem(R.id.attach_record_voice).setVisible(false);
 780		}
 781		if (new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) == null) {
 782			attachFilePopup.getMenu().findItem(R.id.attach_location).setVisible(false);
 783		}
 784		attachFilePopup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 785
 786			@Override
 787			public boolean onMenuItemClick(MenuItem item) {
 788				switch (item.getItemId()) {
 789					case R.id.attach_choose_picture:
 790						attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 791						break;
 792					case R.id.attach_take_picture:
 793						attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
 794						break;
 795					case R.id.attach_choose_file:
 796						attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
 797						break;
 798					case R.id.attach_record_voice:
 799						attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
 800						break;
 801					case R.id.attach_location:
 802						attachFile(ATTACHMENT_CHOICE_LOCATION);
 803						break;
 804				}
 805				return false;
 806			}
 807		});
 808		attachFilePopup.show();
 809	}
 810
 811	public void verifyOtrSessionDialog(final Conversation conversation, View view) {
 812		if (!conversation.hasValidOtrSession() || conversation.getOtrSession().getSessionStatus() != SessionStatus.ENCRYPTED) {
 813			Toast.makeText(this, R.string.otr_session_not_started, Toast.LENGTH_LONG).show();
 814			return;
 815		}
 816		if (view == null) {
 817			return;
 818		}
 819		PopupMenu popup = new PopupMenu(this, view);
 820		popup.inflate(R.menu.verification_choices);
 821		popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 822			@Override
 823			public boolean onMenuItemClick(MenuItem menuItem) {
 824				Intent intent = new Intent(ConversationActivity.this, VerifyOTRActivity.class);
 825				intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 826				intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 827				intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
 828				switch (menuItem.getItemId()) {
 829					case R.id.scan_fingerprint:
 830						intent.putExtra("mode", VerifyOTRActivity.MODE_SCAN_FINGERPRINT);
 831						break;
 832					case R.id.ask_question:
 833						intent.putExtra("mode", VerifyOTRActivity.MODE_ASK_QUESTION);
 834						break;
 835					case R.id.manual_verification:
 836						intent.putExtra("mode", VerifyOTRActivity.MODE_MANUAL_VERIFICATION);
 837						break;
 838				}
 839				startActivity(intent);
 840				return true;
 841			}
 842		});
 843		popup.show();
 844	}
 845
 846	protected void selectEncryptionDialog(final Conversation conversation) {
 847		View menuItemView = findViewById(R.id.action_security);
 848		if (menuItemView == null) {
 849			return;
 850		}
 851		PopupMenu popup = new PopupMenu(this, menuItemView);
 852		final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 853				.findFragmentByTag("conversation");
 854		if (fragment != null) {
 855			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 856
 857				@Override
 858				public boolean onMenuItemClick(MenuItem item) {
 859					switch (item.getItemId()) {
 860						case R.id.encryption_choice_none:
 861							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 862							item.setChecked(true);
 863							break;
 864						case R.id.encryption_choice_otr:
 865							conversation.setNextEncryption(Message.ENCRYPTION_OTR);
 866							item.setChecked(true);
 867							break;
 868						case R.id.encryption_choice_pgp:
 869							if (hasPgp()) {
 870								if (conversation.getAccount().getPgpSignature() != null) {
 871									conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 872									item.setChecked(true);
 873								} else {
 874									announcePgp(conversation.getAccount(), conversation, onOpenPGPKeyPublished);
 875								}
 876							} else {
 877								showInstallPgpDialog();
 878							}
 879							break;
 880						case R.id.encryption_choice_axolotl:
 881							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
 882									+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
 883							conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
 884							item.setChecked(true);
 885							break;
 886						default:
 887							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 888							break;
 889					}
 890					xmppConnectionService.databaseBackend.updateConversation(conversation);
 891					fragment.updateChatMsgHint();
 892					invalidateOptionsMenu();
 893					refreshUi();
 894					return true;
 895				}
 896			});
 897			popup.inflate(R.menu.encryption_choices);
 898			MenuItem otr = popup.getMenu().findItem(R.id.encryption_choice_otr);
 899			MenuItem none = popup.getMenu().findItem(R.id.encryption_choice_none);
 900			MenuItem pgp = popup.getMenu().findItem(R.id.encryption_choice_pgp);
 901			MenuItem axolotl = popup.getMenu().findItem(R.id.encryption_choice_axolotl);
 902			pgp.setVisible(Config.supportOpenPgp());
 903			none.setVisible(Config.supportUnencrypted() || conversation.getMode() == Conversation.MODE_MULTI);
 904			otr.setVisible(Config.supportOtr());
 905			axolotl.setVisible(Config.supportOmemo());
 906			if (conversation.getMode() == Conversation.MODE_MULTI) {
 907				otr.setVisible(false);
 908			}
 909			if (!conversation.getAccount().getAxolotlService().isConversationAxolotlCapable(conversation)) {
 910				axolotl.setEnabled(false);
 911			}
 912			switch (conversation.getNextEncryption()) {
 913				case Message.ENCRYPTION_NONE:
 914					none.setChecked(true);
 915					break;
 916				case Message.ENCRYPTION_OTR:
 917					otr.setChecked(true);
 918					break;
 919				case Message.ENCRYPTION_PGP:
 920					pgp.setChecked(true);
 921					break;
 922				case Message.ENCRYPTION_AXOLOTL:
 923					axolotl.setChecked(true);
 924					break;
 925				default:
 926					none.setChecked(true);
 927					break;
 928			}
 929			popup.show();
 930		}
 931	}
 932
 933	protected void muteConversationDialog(final Conversation conversation) {
 934		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 935		builder.setTitle(R.string.disable_notifications);
 936		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
 937		builder.setItems(R.array.mute_options_descriptions,
 938				new OnClickListener() {
 939
 940					@Override
 941					public void onClick(final DialogInterface dialog, final int which) {
 942						final long till;
 943						if (durations[which] == -1) {
 944							till = Long.MAX_VALUE;
 945						} else {
 946							till = System.currentTimeMillis() + (durations[which] * 1000);
 947						}
 948						conversation.setMutedTill(till);
 949						ConversationActivity.this.xmppConnectionService.databaseBackend
 950								.updateConversation(conversation);
 951						updateConversationList();
 952						ConversationActivity.this.mConversationFragment.updateMessages();
 953						invalidateOptionsMenu();
 954					}
 955				});
 956		builder.create().show();
 957	}
 958
 959	public void unmuteConversation(final Conversation conversation) {
 960		conversation.setMutedTill(0);
 961		this.xmppConnectionService.databaseBackend.updateConversation(conversation);
 962		updateConversationList();
 963		ConversationActivity.this.mConversationFragment.updateMessages();
 964		invalidateOptionsMenu();
 965	}
 966
 967	@Override
 968	public void onBackPressed() {
 969		if (!isConversationsOverviewVisable()) {
 970			showConversationsOverview();
 971		} else {
 972			moveTaskToBack(true);
 973		}
 974	}
 975
 976	@Override
 977	public boolean onKeyUp(int key, KeyEvent event) {
 978		int rotation = getWindowManager().getDefaultDisplay().getRotation();
 979		final int upKey;
 980		final int downKey;
 981		switch (rotation) {
 982			case Surface.ROTATION_90:
 983				upKey = KeyEvent.KEYCODE_DPAD_LEFT;
 984				downKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 985				break;
 986			case Surface.ROTATION_180:
 987				upKey = KeyEvent.KEYCODE_DPAD_DOWN;
 988				downKey = KeyEvent.KEYCODE_DPAD_UP;
 989				break;
 990			case Surface.ROTATION_270:
 991				upKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 992				downKey = KeyEvent.KEYCODE_DPAD_LEFT;
 993				break;
 994			default:
 995				upKey = KeyEvent.KEYCODE_DPAD_UP;
 996				downKey = KeyEvent.KEYCODE_DPAD_DOWN;
 997		}
 998		final boolean modifier = event.isCtrlPressed() || (event.getMetaState() & KeyEvent.META_ALT_LEFT_ON) != 0;
 999		if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
1000			toggleConversationsOverview();
1001			return true;
1002		} else if (modifier && key == KeyEvent.KEYCODE_SPACE) {
1003			startActivity(new Intent(this, StartConversationActivity.class));
1004			return true;
1005		} else if (modifier && key == downKey) {
1006			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1007				showConversationsOverview();
1008				;
1009			}
1010			return selectDownConversation();
1011		} else if (modifier && key == upKey) {
1012			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1013				showConversationsOverview();
1014			}
1015			return selectUpConversation();
1016		} else if (modifier && key == KeyEvent.KEYCODE_1) {
1017			return openConversationByIndex(0);
1018		} else if (modifier && key == KeyEvent.KEYCODE_2) {
1019			return openConversationByIndex(1);
1020		} else if (modifier && key == KeyEvent.KEYCODE_3) {
1021			return openConversationByIndex(2);
1022		} else if (modifier && key == KeyEvent.KEYCODE_4) {
1023			return openConversationByIndex(3);
1024		} else if (modifier && key == KeyEvent.KEYCODE_5) {
1025			return openConversationByIndex(4);
1026		} else if (modifier && key == KeyEvent.KEYCODE_6) {
1027			return openConversationByIndex(5);
1028		} else if (modifier && key == KeyEvent.KEYCODE_7) {
1029			return openConversationByIndex(6);
1030		} else if (modifier && key == KeyEvent.KEYCODE_8) {
1031			return openConversationByIndex(7);
1032		} else if (modifier && key == KeyEvent.KEYCODE_9) {
1033			return openConversationByIndex(8);
1034		} else if (modifier && key == KeyEvent.KEYCODE_0) {
1035			return openConversationByIndex(9);
1036		} else {
1037			return super.onKeyUp(key, event);
1038		}
1039	}
1040
1041	private void toggleConversationsOverview() {
1042		if (isConversationsOverviewVisable()) {
1043			hideConversationsOverview();
1044			if (mConversationFragment != null) {
1045				mConversationFragment.setFocusOnInputField();
1046			}
1047		} else {
1048			showConversationsOverview();
1049		}
1050	}
1051
1052	private boolean selectUpConversation() {
1053		if (this.mSelectedConversation != null) {
1054			int index = this.conversationList.indexOf(this.mSelectedConversation);
1055			if (index > 0) {
1056				return openConversationByIndex(index - 1);
1057			}
1058		}
1059		return false;
1060	}
1061
1062	private boolean selectDownConversation() {
1063		if (this.mSelectedConversation != null) {
1064			int index = this.conversationList.indexOf(this.mSelectedConversation);
1065			if (index != -1 && index < this.conversationList.size() - 1) {
1066				return openConversationByIndex(index + 1);
1067			}
1068		}
1069		return false;
1070	}
1071
1072	private boolean openConversationByIndex(int index) {
1073		try {
1074			this.conversationWasSelectedByKeyboard = true;
1075			setSelectedConversation(this.conversationList.get(index));
1076			this.mConversationFragment.reInit(getSelectedConversation());
1077			if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
1078				this.listView.setSelection(index);
1079			}
1080			openConversation();
1081			return true;
1082		} catch (IndexOutOfBoundsException e) {
1083			return false;
1084		}
1085	}
1086
1087	@Override
1088	protected void onNewIntent(final Intent intent) {
1089		if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1090			mOpenConversation = null;
1091			if (xmppConnectionServiceBound) {
1092				handleViewConversationIntent(intent);
1093				intent.setAction(Intent.ACTION_MAIN);
1094			} else {
1095				setIntent(intent);
1096			}
1097		}
1098	}
1099
1100	@Override
1101	public void onStart() {
1102		super.onStart();
1103		this.mRedirected.set(false);
1104		if (this.xmppConnectionServiceBound) {
1105			this.onBackendConnected();
1106		}
1107		if (conversationList.size() >= 1) {
1108			this.onConversationUpdate();
1109		}
1110	}
1111
1112	@Override
1113	public void onPause() {
1114		listView.discardUndo();
1115		super.onPause();
1116		this.mActivityPaused = true;
1117	}
1118
1119	@Override
1120	public void onResume() {
1121		super.onResume();
1122		final int theme = findTheme();
1123		final boolean usingEnterKey = usingEnterKey();
1124		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1125			recreate();
1126		}
1127		this.mActivityPaused = false;
1128
1129		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1130			sendReadMarkerIfNecessary(getSelectedConversation());
1131		}
1132
1133	}
1134
1135	@Override
1136	public void onSaveInstanceState(final Bundle savedInstanceState) {
1137		Conversation conversation = getSelectedConversation();
1138		if (conversation != null) {
1139			savedInstanceState.putString(STATE_OPEN_CONVERSATION, conversation.getUuid());
1140			Pair<Integer,Integer> scrollPosition = mConversationFragment.getScrollPosition();
1141			if (scrollPosition != null) {
1142				savedInstanceState.putInt(STATE_FIRST_VISIBLE, scrollPosition.first);
1143				savedInstanceState.putInt(STATE_OFFSET_FROM_TOP, scrollPosition.second);
1144			}
1145		} else {
1146			savedInstanceState.remove(STATE_OPEN_CONVERSATION);
1147		}
1148		savedInstanceState.putBoolean(STATE_PANEL_OPEN, isConversationsOverviewVisable());
1149		if (this.mPendingImageUris.size() >= 1) {
1150			Log.d(Config.LOGTAG,"ConversationsActivity.onSaveInstanceState() - saving pending image uri");
1151			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1152		} else {
1153			savedInstanceState.remove(STATE_PENDING_URI);
1154		}
1155		super.onSaveInstanceState(savedInstanceState);
1156	}
1157
1158	private void clearPending() {
1159		mPendingImageUris.clear();
1160		mPendingFileUris.clear();
1161		mPendingGeoUri = null;
1162		mPostponedActivityResult = null;
1163	}
1164
1165	@Override
1166	void onBackendConnected() {
1167		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1168		updateConversationList();
1169
1170		if (mPendingConferenceInvite != null) {
1171			if (mPendingConferenceInvite.execute(this)) {
1172				mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1173				mToast.show();
1174			}
1175			mPendingConferenceInvite = null;
1176		}
1177
1178		final Intent intent = getIntent();
1179
1180		if (xmppConnectionService.getAccounts().size() == 0) {
1181			if (mRedirected.compareAndSet(false, true)) {
1182				if (Config.X509_VERIFICATION) {
1183					startActivity(new Intent(this, ManageAccountActivity.class));
1184				} else if (Config.MAGIC_CREATE_DOMAIN != null) {
1185					startActivity(new Intent(this, WelcomeActivity.class));
1186				} else {
1187					Intent editAccount = new Intent(this, EditAccountActivity.class);
1188					editAccount.putExtra("init",true);
1189					startActivity(editAccount);
1190				}
1191				finish();
1192			}
1193		} else if (conversationList.size() <= 0) {
1194			if (mRedirected.compareAndSet(false, true)) {
1195				Account pendingAccount = xmppConnectionService.getPendingAccount();
1196				if (pendingAccount == null) {
1197					Intent startConversationActivity = new Intent(this, StartConversationActivity.class);
1198					intent.putExtra("init", true);
1199					startActivity(startConversationActivity);
1200				} else {
1201					switchToAccount(pendingAccount, true);
1202				}
1203				finish();
1204			}
1205		} else if (selectConversationByUuid(mOpenConversation)) {
1206			if (mPanelOpen) {
1207				showConversationsOverview();
1208			} else {
1209				if (isConversationsOverviewHideable()) {
1210					openConversation();
1211					updateActionBarTitle(true);
1212				}
1213			}
1214			if (this.mConversationFragment.reInit(getSelectedConversation())) {
1215				Log.d(Config.LOGTAG,"setting scroll position on fragment");
1216				this.mConversationFragment.setScrollPosition(mScrollPosition);
1217			}
1218			mOpenConversation = null;
1219		} else if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1220			clearPending();
1221			handleViewConversationIntent(intent);
1222			intent.setAction(Intent.ACTION_MAIN);
1223		} else if (getSelectedConversation() == null) {
1224			showConversationsOverview();
1225			clearPending();
1226			setSelectedConversation(conversationList.get(0));
1227			this.mConversationFragment.reInit(getSelectedConversation());
1228		} else {
1229			this.mConversationFragment.messageListAdapter.updatePreferences();
1230			this.mConversationFragment.messagesView.invalidateViews();
1231			this.mConversationFragment.setupIme();
1232		}
1233
1234		if (this.mPostponedActivityResult != null) {
1235			this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1236		}
1237
1238		final boolean stopping;
1239		if (Build.VERSION.SDK_INT >= 17) {
1240			stopping = isFinishing() || isDestroyed();
1241		} else {
1242			stopping = isFinishing();
1243		}
1244
1245		if (!forbidProcessingPendings) {
1246			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1247				Uri foo = i.next();
1248				Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching image to conversations. stopping="+Boolean.toString(stopping));
1249				attachImageToConversation(getSelectedConversation(), foo);
1250			}
1251
1252			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1253				Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching file to conversations. stopping="+Boolean.toString(stopping));
1254				attachFileToConversation(getSelectedConversation(), i.next());
1255			}
1256
1257			if (mPendingGeoUri != null) {
1258				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1259				mPendingGeoUri = null;
1260			}
1261		}
1262		forbidProcessingPendings = false;
1263
1264		if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService)) {
1265			openBatteryOptimizationDialogIfNeeded();
1266		}
1267	}
1268
1269	private void handleViewConversationIntent(final Intent intent) {
1270		final String uuid = intent.getStringExtra(CONVERSATION);
1271		final String downloadUuid = intent.getStringExtra(EXTRA_DOWNLOAD_UUID);
1272		final String text = intent.getStringExtra(TEXT);
1273		final String nick = intent.getStringExtra(NICK);
1274		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1275		if (selectConversationByUuid(uuid)) {
1276			this.mConversationFragment.reInit(getSelectedConversation());
1277			if (nick != null) {
1278				if (pm) {
1279					Jid jid = getSelectedConversation().getJid();
1280					try {
1281						Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1282						this.mConversationFragment.privateMessageWith(next);
1283					} catch (final InvalidJidException ignored) {
1284						//do nothing
1285					}
1286				} else {
1287					this.mConversationFragment.highlightInConference(nick);
1288				}
1289			} else {
1290				this.mConversationFragment.appendText(text);
1291			}
1292			hideConversationsOverview();
1293			openConversation();
1294			if (mContentView instanceof SlidingPaneLayout) {
1295				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1296			}
1297			if (downloadUuid != null) {
1298				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1299				if (message != null) {
1300					startDownloadable(message);
1301				}
1302			}
1303		}
1304	}
1305
1306	private boolean selectConversationByUuid(String uuid) {
1307		if (uuid == null) {
1308			return false;
1309		}
1310		for (Conversation aConversationList : conversationList) {
1311			if (aConversationList.getUuid().equals(uuid)) {
1312				setSelectedConversation(aConversationList);
1313				return true;
1314			}
1315		}
1316		return false;
1317	}
1318
1319	@Override
1320	protected void unregisterListeners() {
1321		super.unregisterListeners();
1322		xmppConnectionService.getNotificationService().setOpenConversation(null);
1323	}
1324
1325	@SuppressLint("NewApi")
1326	private static List<Uri> extractUriFromIntent(final Intent intent) {
1327		List<Uri> uris = new ArrayList<>();
1328		if (intent == null) {
1329			return uris;
1330		}
1331		Uri uri = intent.getData();
1332		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1333			final ClipData clipData = intent.getClipData();
1334			if (clipData != null) {
1335				for (int i = 0; i < clipData.getItemCount(); ++i) {
1336					uris.add(clipData.getItemAt(i).getUri());
1337				}
1338			}
1339		} else {
1340			uris.add(uri);
1341		}
1342		return uris;
1343	}
1344
1345	@Override
1346	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1347		super.onActivityResult(requestCode, resultCode, data);
1348		if (resultCode == RESULT_OK) {
1349			if (requestCode == REQUEST_DECRYPT_PGP) {
1350				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1351			} else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1352				// the user chose OpenPGP for encryption and selected his key in the PGP provider
1353				if (xmppConnectionServiceBound) {
1354					if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1355						// associate selected PGP keyId with the account
1356						mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1357						// we need to announce the key as described in XEP-027
1358						announcePgp(mSelectedConversation.getAccount(), null, onOpenPGPKeyPublished);
1359					} else {
1360						choosePgpSignId(mSelectedConversation.getAccount());
1361					}
1362					this.mPostponedActivityResult = null;
1363				} else {
1364					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1365				}
1366			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1367				if (xmppConnectionServiceBound) {
1368					announcePgp(mSelectedConversation.getAccount(), mSelectedConversation, onOpenPGPKeyPublished);
1369					this.mPostponedActivityResult = null;
1370				} else {
1371					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1372				}
1373			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1374				mPendingImageUris.clear();
1375				mPendingImageUris.addAll(extractUriFromIntent(data));
1376				if (xmppConnectionServiceBound) {
1377					for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1378						Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. CHOOSE_IMAGE");
1379						attachImageToConversation(getSelectedConversation(), i.next());
1380					}
1381				}
1382			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1383				final List<Uri> uris = extractUriFromIntent(data);
1384				final Conversation c = getSelectedConversation();
1385				final OnPresenceSelected callback = new OnPresenceSelected() {
1386					@Override
1387					public void onPresenceSelected() {
1388						mPendingFileUris.clear();
1389						mPendingFileUris.addAll(uris);
1390						if (xmppConnectionServiceBound) {
1391							for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1392								Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE");
1393								attachFileToConversation(c, i.next());
1394							}
1395						}
1396					}
1397				};
1398				if (c == null || c.getMode() == Conversation.MODE_MULTI
1399						|| FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1400						|| c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1401					callback.onPresenceSelected();
1402				} else {
1403					selectPresence(c, callback);
1404				}
1405			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1406				if (mPendingImageUris.size() == 1) {
1407					Uri uri = FileBackend.getIndexableTakePhotoUri(mPendingImageUris.get(0));
1408					mPendingImageUris.set(0, uri);
1409					if (xmppConnectionServiceBound) {
1410						Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. TAKE_PHOTO");
1411						attachImageToConversation(getSelectedConversation(), uri);
1412						mPendingImageUris.clear();
1413					}
1414					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1415					intent.setData(uri);
1416					sendBroadcast(intent);
1417				} else {
1418					mPendingImageUris.clear();
1419				}
1420			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1421				double latitude = data.getDoubleExtra("latitude", 0);
1422				double longitude = data.getDoubleExtra("longitude", 0);
1423				this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1424				if (xmppConnectionServiceBound) {
1425					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1426					this.mPendingGeoUri = null;
1427				}
1428			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1429				this.forbidProcessingPendings = !xmppConnectionServiceBound;
1430				if (xmppConnectionServiceBound) {
1431					mConversationFragment.onActivityResult(requestCode, resultCode, data);
1432					this.mPostponedActivityResult = null;
1433				} else {
1434					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1435				}
1436
1437			}
1438		} else {
1439			mPendingImageUris.clear();
1440			mPendingFileUris.clear();
1441			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1442				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1443			}
1444			if (requestCode == REQUEST_BATTERY_OP) {
1445				setNeverAskForBatteryOptimizationsAgain();
1446			}
1447		}
1448	}
1449
1450	private long getMaxHttpUploadSize(Conversation conversation) {
1451		return conversation.getAccount().getXmppConnection().getFeatures().getMaxHttpUploadSize();
1452	}
1453
1454	private void setNeverAskForBatteryOptimizationsAgain() {
1455		getPreferences().edit().putBoolean("show_battery_optimization", false).commit();
1456	}
1457
1458	private void openBatteryOptimizationDialogIfNeeded() {
1459		if (hasAccountWithoutPush()
1460				&& isOptimizingBattery()
1461				&& getPreferences().getBoolean("show_battery_optimization", true)) {
1462			AlertDialog.Builder builder = new AlertDialog.Builder(this);
1463			builder.setTitle(R.string.battery_optimizations_enabled);
1464			builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1465			builder.setPositiveButton(R.string.next, new OnClickListener() {
1466				@Override
1467				public void onClick(DialogInterface dialog, int which) {
1468					Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1469					Uri uri = Uri.parse("package:" + getPackageName());
1470					intent.setData(uri);
1471					try {
1472						startActivityForResult(intent, REQUEST_BATTERY_OP);
1473					} catch (ActivityNotFoundException e) {
1474						Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1475					}
1476				}
1477			});
1478			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1479				builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1480					@Override
1481					public void onDismiss(DialogInterface dialog) {
1482						setNeverAskForBatteryOptimizationsAgain();
1483					}
1484				});
1485			}
1486			builder.create().show();
1487		}
1488	}
1489
1490	private boolean hasAccountWithoutPush() {
1491		for(Account account : xmppConnectionService.getAccounts()) {
1492			if (account.getStatus() != Account.State.DISABLED
1493					&& !xmppConnectionService.getPushManagementService().available(account)) {
1494				return true;
1495			}
1496		}
1497		return false;
1498	}
1499
1500	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1501		if (conversation == null) {
1502			return;
1503		}
1504		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1505
1506			@Override
1507			public void success(Message message) {
1508				xmppConnectionService.sendMessage(message);
1509			}
1510
1511			@Override
1512			public void error(int errorCode, Message object) {
1513
1514			}
1515
1516			@Override
1517			public void userInputRequried(PendingIntent pi, Message object) {
1518
1519			}
1520		});
1521	}
1522
1523	private void attachFileToConversation(Conversation conversation, Uri uri) {
1524		if (conversation == null) {
1525			return;
1526		}
1527		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1528		prepareFileToast.show();
1529		xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1530			@Override
1531			public void success(Message message) {
1532				hidePrepareFileToast(prepareFileToast);
1533				xmppConnectionService.sendMessage(message);
1534			}
1535
1536			@Override
1537			public void error(final int errorCode, Message message) {
1538				hidePrepareFileToast(prepareFileToast);
1539				runOnUiThread(new Runnable() {
1540					@Override
1541					public void run() {
1542						replaceToast(getString(errorCode));
1543					}
1544				});
1545
1546			}
1547
1548			@Override
1549			public void userInputRequried(PendingIntent pi, Message message) {
1550				hidePrepareFileToast(prepareFileToast);
1551			}
1552		});
1553	}
1554
1555	private void attachImageToConversation(Conversation conversation, Uri uri) {
1556		if (conversation == null) {
1557			return;
1558		}
1559		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1560		prepareFileToast.show();
1561		xmppConnectionService.attachImageToConversation(conversation, uri,
1562				new UiCallback<Message>() {
1563
1564					@Override
1565					public void userInputRequried(PendingIntent pi, Message object) {
1566						hidePrepareFileToast(prepareFileToast);
1567					}
1568
1569					@Override
1570					public void success(Message message) {
1571						hidePrepareFileToast(prepareFileToast);
1572						xmppConnectionService.sendMessage(message);
1573					}
1574
1575					@Override
1576					public void error(final int error, Message message) {
1577						hidePrepareFileToast(prepareFileToast);
1578						runOnUiThread(new Runnable() {
1579							@Override
1580							public void run() {
1581								replaceToast(getString(error));
1582							}
1583						});
1584					}
1585				});
1586	}
1587
1588	private void hidePrepareFileToast(final Toast prepareFileToast) {
1589		if (prepareFileToast != null) {
1590			runOnUiThread(new Runnable() {
1591
1592				@Override
1593				public void run() {
1594					prepareFileToast.cancel();
1595				}
1596			});
1597		}
1598	}
1599
1600	public void updateConversationList() {
1601		xmppConnectionService
1602			.populateWithOrderedConversations(conversationList);
1603		if (swipedConversation != null) {
1604			if (swipedConversation.isRead()) {
1605				conversationList.remove(swipedConversation);
1606			} else {
1607				listView.discardUndo();
1608			}
1609		}
1610		listAdapter.notifyDataSetChanged();
1611	}
1612
1613	public void runIntent(PendingIntent pi, int requestCode) {
1614		try {
1615			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1616					null, 0, 0, 0);
1617		} catch (final SendIntentException ignored) {
1618		}
1619	}
1620
1621	public void encryptTextMessage(Message message) {
1622		xmppConnectionService.getPgpEngine().encrypt(message,
1623				new UiCallback<Message>() {
1624
1625					@Override
1626					public void userInputRequried(PendingIntent pi,Message message) {
1627						ConversationActivity.this.runIntent(pi,ConversationActivity.REQUEST_SEND_MESSAGE);
1628					}
1629
1630					@Override
1631					public void success(Message message) {
1632						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1633						xmppConnectionService.sendMessage(message);
1634						if (mConversationFragment != null) {
1635							mConversationFragment.messageSent();
1636						}
1637					}
1638
1639					@Override
1640					public void error(final int error, Message message) {
1641						runOnUiThread(new Runnable() {
1642							@Override
1643							public void run() {
1644								Toast.makeText(ConversationActivity.this,
1645										R.string.unable_to_connect_to_keychain,
1646										Toast.LENGTH_SHORT
1647								).show();
1648							}
1649						});
1650					}
1651				});
1652	}
1653
1654	public boolean useSendButtonToIndicateStatus() {
1655		return getPreferences().getBoolean("send_button_status", false);
1656	}
1657
1658	public boolean indicateReceived() {
1659		return getPreferences().getBoolean("indicate_received", false);
1660	}
1661
1662	public boolean useGreenBackground() {
1663		return getPreferences().getBoolean("use_green_background",true);
1664	}
1665
1666	protected boolean trustKeysIfNeeded(int requestCode) {
1667		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1668	}
1669
1670	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1671		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1672		final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1673		boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1674		boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED).isEmpty();
1675		boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED, targets).isEmpty();
1676		boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1677		boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1678		if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1679			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1680			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1681			String[] contacts = new String[targets.size()];
1682			for(int i = 0; i < contacts.length; ++i) {
1683				contacts[i] = targets.get(i).toString();
1684			}
1685			intent.putExtra("contacts", contacts);
1686			intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1687			intent.putExtra("choice", attachmentChoice);
1688			intent.putExtra("conversation",mSelectedConversation.getUuid());
1689			startActivityForResult(intent, requestCode);
1690			return true;
1691		} else {
1692			return false;
1693		}
1694	}
1695
1696	@Override
1697	protected void refreshUiReal() {
1698		updateConversationList();
1699		if (conversationList.size() > 0) {
1700			if (!this.mConversationFragment.isAdded()) {
1701				Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1702			}
1703			ConversationActivity.this.mConversationFragment.updateMessages();
1704			updateActionBarTitle();
1705			invalidateOptionsMenu();
1706		} else {
1707			Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1708		}
1709	}
1710
1711	@Override
1712	public void onAccountUpdate() {
1713		this.refreshUi();
1714	}
1715
1716	@Override
1717	public void onConversationUpdate() {
1718		this.refreshUi();
1719	}
1720
1721	@Override
1722	public void onRosterUpdate() {
1723		this.refreshUi();
1724	}
1725
1726	@Override
1727	public void OnUpdateBlocklist(Status status) {
1728		this.refreshUi();
1729	}
1730
1731	public void unblockConversation(final Blockable conversation) {
1732		xmppConnectionService.sendUnblockRequest(conversation);
1733	}
1734
1735	public boolean enterIsSend() {
1736		return getPreferences().getBoolean("enter_is_send",false);
1737	}
1738
1739	@Override
1740	public void onShowErrorToast(final int resId) {
1741		runOnUiThread(new Runnable() {
1742			@Override
1743			public void run() {
1744				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1745			}
1746		});
1747	}
1748
1749	public boolean highlightSelectedConversations() {
1750		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1751	}
1752
1753	public void setMessagesLoaded() {
1754		if (mConversationFragment != null) {
1755			mConversationFragment.setMessagesLoaded();
1756			mConversationFragment.updateMessages();
1757		}
1758	}
1759}