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			boolean single = c.getMode() == Conversation.MODE_SINGLE;
 455			AxolotlService axolotlService = c.getAccount().getAxolotlService();
 456			Pair<AxolotlService.AxolotlCapability,Jid> capabilityJidPair = axolotlService.isConversationAxolotlCapableDetailed(c);
 457			switch (capabilityJidPair.first) {
 458				case MISSING_PRESENCE:
 459					Toast.makeText(ConversationActivity.this,single ? getString(R.string.missing_presence_subscription) : getString(R.string.missing_presence_subscription_with_x,capabilityJidPair.second.toBareJid().toString()),Toast.LENGTH_SHORT).show();
 460					return true;
 461				case MISSING_KEYS:
 462					Toast.makeText(ConversationActivity.this,single ? getString(R.string.missing_omemo_keys) : getString(R.string.missing_keys_from_x,capabilityJidPair.second.toBareJid().toString()),Toast.LENGTH_SHORT).show();
 463					return true;
 464				case WRONG_CONFIGURATION:
 465					Toast.makeText(ConversationActivity.this,R.string.wrong_conference_configuration, Toast.LENGTH_SHORT).show();
 466					return true;
 467				case NO_MEMBERS:
 468					Toast.makeText(ConversationActivity.this,R.string.this_conference_has_no_members, Toast.LENGTH_SHORT).show();
 469					return true;
 470			}
 471		}
 472		return false;
 473	}
 474
 475	protected void selectPresenceToAttachFile(final int attachmentChoice, final int encryption) {
 476		final Conversation conversation = getSelectedConversation();
 477		final Account account = conversation.getAccount();
 478		final OnPresenceSelected callback = new OnPresenceSelected() {
 479
 480			@Override
 481			public void onPresenceSelected() {
 482				Intent intent = new Intent();
 483				boolean chooser = false;
 484				String fallbackPackageId = null;
 485				switch (attachmentChoice) {
 486					case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 487						intent.setAction(Intent.ACTION_GET_CONTENT);
 488						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
 489							intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
 490						}
 491						intent.setType("image/*");
 492						chooser = true;
 493						break;
 494					case ATTACHMENT_CHOICE_TAKE_PHOTO:
 495						Uri uri = xmppConnectionService.getFileBackend().getTakePhotoUri();
 496						intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
 497						intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 498						intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
 499						mPendingImageUris.clear();
 500						mPendingImageUris.add(uri);
 501						break;
 502					case ATTACHMENT_CHOICE_CHOOSE_FILE:
 503						chooser = true;
 504						intent.setType("*/*");
 505						intent.addCategory(Intent.CATEGORY_OPENABLE);
 506						intent.setAction(Intent.ACTION_GET_CONTENT);
 507						break;
 508					case ATTACHMENT_CHOICE_RECORD_VOICE:
 509						intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
 510						fallbackPackageId = "eu.siacs.conversations.voicerecorder";
 511						break;
 512					case ATTACHMENT_CHOICE_LOCATION:
 513						intent.setAction("eu.siacs.conversations.location.request");
 514						fallbackPackageId = "eu.siacs.conversations.sharelocation";
 515						break;
 516				}
 517				if (intent.resolveActivity(getPackageManager()) != null) {
 518					if (chooser) {
 519						startActivityForResult(
 520								Intent.createChooser(intent, getString(R.string.perform_action_with)),
 521								attachmentChoice);
 522					} else {
 523						startActivityForResult(intent, attachmentChoice);
 524					}
 525				} else if (fallbackPackageId != null) {
 526					startActivity(getInstallApkIntent(fallbackPackageId));
 527				}
 528			}
 529		};
 530		if ((account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) && encryption != Message.ENCRYPTION_OTR) {
 531			conversation.setNextCounterpart(null);
 532			callback.onPresenceSelected();
 533		} else {
 534			selectPresence(conversation, callback);
 535		}
 536	}
 537
 538	private Intent getInstallApkIntent(final String packageId) {
 539		Intent intent = new Intent(Intent.ACTION_VIEW);
 540		intent.setData(Uri.parse("market://details?id=" + packageId));
 541		if (intent.resolveActivity(getPackageManager()) != null) {
 542			return intent;
 543		} else {
 544			intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
 545			return intent;
 546		}
 547	}
 548
 549	public void attachFile(final int attachmentChoice) {
 550		if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
 551			if (!hasStoragePermission(attachmentChoice)) {
 552				return;
 553			}
 554		}
 555		switch (attachmentChoice) {
 556			case ATTACHMENT_CHOICE_LOCATION:
 557				getPreferences().edit().putString("recently_used_quick_action", "location").apply();
 558				break;
 559			case ATTACHMENT_CHOICE_RECORD_VOICE:
 560				getPreferences().edit().putString("recently_used_quick_action", "voice").apply();
 561				break;
 562			case ATTACHMENT_CHOICE_TAKE_PHOTO:
 563				getPreferences().edit().putString("recently_used_quick_action", "photo").apply();
 564				break;
 565			case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 566				getPreferences().edit().putString("recently_used_quick_action", "picture").apply();
 567				break;
 568		}
 569		final Conversation conversation = getSelectedConversation();
 570		final int encryption = conversation.getNextEncryption();
 571		final int mode = conversation.getMode();
 572		if (encryption == Message.ENCRYPTION_PGP) {
 573			if (hasPgp()) {
 574				if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
 575					xmppConnectionService.getPgpEngine().hasKey(
 576							conversation.getContact(),
 577							new UiCallback<Contact>() {
 578
 579								@Override
 580								public void userInputRequried(PendingIntent pi, Contact contact) {
 581									ConversationActivity.this.runIntent(pi, attachmentChoice);
 582								}
 583
 584								@Override
 585								public void success(Contact contact) {
 586									selectPresenceToAttachFile(attachmentChoice, encryption);
 587								}
 588
 589								@Override
 590								public void error(int error, Contact contact) {
 591									replaceToast(getString(error));
 592								}
 593							});
 594				} else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
 595					if (!conversation.getMucOptions().everybodyHasKeys()) {
 596						Toast warning = Toast
 597								.makeText(this,
 598										R.string.missing_public_keys,
 599										Toast.LENGTH_LONG);
 600						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
 601						warning.show();
 602					}
 603					selectPresenceToAttachFile(attachmentChoice, encryption);
 604				} else {
 605					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 606							.findFragmentByTag("conversation");
 607					if (fragment != null) {
 608						fragment.showNoPGPKeyDialog(false,
 609								new OnClickListener() {
 610
 611									@Override
 612									public void onClick(DialogInterface dialog,
 613														int which) {
 614										conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 615										xmppConnectionService.updateConversation(conversation);
 616										selectPresenceToAttachFile(attachmentChoice, Message.ENCRYPTION_NONE);
 617									}
 618								});
 619					}
 620				}
 621			} else {
 622				showInstallPgpDialog();
 623			}
 624		} else {
 625			if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
 626				selectPresenceToAttachFile(attachmentChoice, encryption);
 627			}
 628		}
 629	}
 630
 631	@Override
 632	public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
 633		if (grantResults.length > 0)
 634			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 635				if (requestCode == REQUEST_START_DOWNLOAD) {
 636					if (this.mPendingDownloadableMessage != null) {
 637						startDownloadable(this.mPendingDownloadableMessage);
 638					}
 639				} else {
 640					attachFile(requestCode);
 641				}
 642			} else {
 643				Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
 644			}
 645	}
 646
 647	public void startDownloadable(Message message) {
 648		if (!hasStoragePermission(ConversationActivity.REQUEST_START_DOWNLOAD)) {
 649			this.mPendingDownloadableMessage = message;
 650			return;
 651		}
 652		Transferable transferable = message.getTransferable();
 653		if (transferable != null) {
 654			if (!transferable.start()) {
 655				Toast.makeText(this, R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
 656			}
 657		} else if (message.treatAsDownloadable() != Message.Decision.NEVER) {
 658			xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
 659		}
 660	}
 661
 662	@Override
 663	public boolean onOptionsItemSelected(final MenuItem item) {
 664		if (item.getItemId() == android.R.id.home) {
 665			showConversationsOverview();
 666			return true;
 667		} else if (item.getItemId() == R.id.action_add) {
 668			startActivity(new Intent(this, StartConversationActivity.class));
 669			return true;
 670		} else if (getSelectedConversation() != null) {
 671			switch (item.getItemId()) {
 672				case R.id.action_attach_file:
 673					attachFileDialog();
 674					break;
 675				case R.id.action_archive:
 676					this.endConversation(getSelectedConversation());
 677					break;
 678				case R.id.action_contact_details:
 679					switchToContactDetails(getSelectedConversation().getContact());
 680					break;
 681				case R.id.action_muc_details:
 682					Intent intent = new Intent(this,
 683							ConferenceDetailsActivity.class);
 684					intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 685					intent.putExtra("uuid", getSelectedConversation().getUuid());
 686					startActivity(intent);
 687					break;
 688				case R.id.action_invite:
 689					inviteToConversation(getSelectedConversation());
 690					break;
 691				case R.id.action_security:
 692					selectEncryptionDialog(getSelectedConversation());
 693					break;
 694				case R.id.action_clear_history:
 695					clearHistoryDialog(getSelectedConversation());
 696					break;
 697				case R.id.action_mute:
 698					muteConversationDialog(getSelectedConversation());
 699					break;
 700				case R.id.action_unmute:
 701					unmuteConversation(getSelectedConversation());
 702					break;
 703				case R.id.action_block:
 704					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 705					break;
 706				case R.id.action_unblock:
 707					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 708					break;
 709				default:
 710					break;
 711			}
 712			return super.onOptionsItemSelected(item);
 713		} else {
 714			return super.onOptionsItemSelected(item);
 715		}
 716	}
 717
 718	public void endConversation(Conversation conversation) {
 719		endConversation(conversation, true, true);
 720	}
 721
 722	public void endConversation(Conversation conversation, boolean showOverview, boolean reinit) {
 723		if (showOverview) {
 724			showConversationsOverview();
 725		}
 726		xmppConnectionService.archiveConversation(conversation);
 727		if (reinit) {
 728			if (conversationList.size() > 0) {
 729				setSelectedConversation(conversationList.get(0));
 730				this.mConversationFragment.reInit(getSelectedConversation());
 731			} else {
 732				setSelectedConversation(null);
 733				if (mRedirected.compareAndSet(false, true)) {
 734					Intent intent = new Intent(this, StartConversationActivity.class);
 735					intent.putExtra("init", true);
 736					startActivity(intent);
 737					finish();
 738				}
 739			}
 740		}
 741	}
 742
 743	@SuppressLint("InflateParams")
 744	protected void clearHistoryDialog(final Conversation conversation) {
 745		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 746		builder.setTitle(getString(R.string.clear_conversation_history));
 747		View dialogView = getLayoutInflater().inflate(
 748				R.layout.dialog_clear_history, null);
 749		final CheckBox endConversationCheckBox = (CheckBox) dialogView
 750				.findViewById(R.id.end_conversation_checkbox);
 751		builder.setView(dialogView);
 752		builder.setNegativeButton(getString(R.string.cancel), null);
 753		builder.setPositiveButton(getString(R.string.delete_messages),
 754				new OnClickListener() {
 755
 756					@Override
 757					public void onClick(DialogInterface dialog, int which) {
 758						ConversationActivity.this.xmppConnectionService.clearConversationHistory(conversation);
 759						if (endConversationCheckBox.isChecked()) {
 760							endConversation(conversation);
 761						} else {
 762							updateConversationList();
 763							ConversationActivity.this.mConversationFragment.updateMessages();
 764						}
 765					}
 766				});
 767		builder.create().show();
 768	}
 769
 770	protected void attachFileDialog() {
 771		View menuAttachFile = findViewById(R.id.action_attach_file);
 772		if (menuAttachFile == null) {
 773			return;
 774		}
 775		PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
 776		attachFilePopup.inflate(R.menu.attachment_choices);
 777		if (new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) == null) {
 778			attachFilePopup.getMenu().findItem(R.id.attach_record_voice).setVisible(false);
 779		}
 780		if (new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) == null) {
 781			attachFilePopup.getMenu().findItem(R.id.attach_location).setVisible(false);
 782		}
 783		attachFilePopup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 784
 785			@Override
 786			public boolean onMenuItemClick(MenuItem item) {
 787				switch (item.getItemId()) {
 788					case R.id.attach_choose_picture:
 789						attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 790						break;
 791					case R.id.attach_take_picture:
 792						attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
 793						break;
 794					case R.id.attach_choose_file:
 795						attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
 796						break;
 797					case R.id.attach_record_voice:
 798						attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
 799						break;
 800					case R.id.attach_location:
 801						attachFile(ATTACHMENT_CHOICE_LOCATION);
 802						break;
 803				}
 804				return false;
 805			}
 806		});
 807		attachFilePopup.show();
 808	}
 809
 810	public void verifyOtrSessionDialog(final Conversation conversation, View view) {
 811		if (!conversation.hasValidOtrSession() || conversation.getOtrSession().getSessionStatus() != SessionStatus.ENCRYPTED) {
 812			Toast.makeText(this, R.string.otr_session_not_started, Toast.LENGTH_LONG).show();
 813			return;
 814		}
 815		if (view == null) {
 816			return;
 817		}
 818		PopupMenu popup = new PopupMenu(this, view);
 819		popup.inflate(R.menu.verification_choices);
 820		popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 821			@Override
 822			public boolean onMenuItemClick(MenuItem menuItem) {
 823				Intent intent = new Intent(ConversationActivity.this, VerifyOTRActivity.class);
 824				intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 825				intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 826				intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
 827				switch (menuItem.getItemId()) {
 828					case R.id.scan_fingerprint:
 829						intent.putExtra("mode", VerifyOTRActivity.MODE_SCAN_FINGERPRINT);
 830						break;
 831					case R.id.ask_question:
 832						intent.putExtra("mode", VerifyOTRActivity.MODE_ASK_QUESTION);
 833						break;
 834					case R.id.manual_verification:
 835						intent.putExtra("mode", VerifyOTRActivity.MODE_MANUAL_VERIFICATION);
 836						break;
 837				}
 838				startActivity(intent);
 839				return true;
 840			}
 841		});
 842		popup.show();
 843	}
 844
 845	protected void selectEncryptionDialog(final Conversation conversation) {
 846		View menuItemView = findViewById(R.id.action_security);
 847		if (menuItemView == null) {
 848			return;
 849		}
 850		PopupMenu popup = new PopupMenu(this, menuItemView);
 851		final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 852				.findFragmentByTag("conversation");
 853		if (fragment != null) {
 854			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 855
 856				@Override
 857				public boolean onMenuItemClick(MenuItem item) {
 858					switch (item.getItemId()) {
 859						case R.id.encryption_choice_none:
 860							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 861							item.setChecked(true);
 862							break;
 863						case R.id.encryption_choice_otr:
 864							conversation.setNextEncryption(Message.ENCRYPTION_OTR);
 865							item.setChecked(true);
 866							break;
 867						case R.id.encryption_choice_pgp:
 868							if (hasPgp()) {
 869								if (conversation.getAccount().getPgpSignature() != null) {
 870									conversation.setNextEncryption(Message.ENCRYPTION_PGP);
 871									item.setChecked(true);
 872								} else {
 873									announcePgp(conversation.getAccount(), conversation, onOpenPGPKeyPublished);
 874								}
 875							} else {
 876								showInstallPgpDialog();
 877							}
 878							break;
 879						case R.id.encryption_choice_axolotl:
 880							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
 881									+ "Enabled axolotl for Contact " + conversation.getContact().getJid());
 882							conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
 883							item.setChecked(true);
 884							break;
 885						default:
 886							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 887							break;
 888					}
 889					xmppConnectionService.updateConversation(conversation);
 890					fragment.updateChatMsgHint();
 891					invalidateOptionsMenu();
 892					refreshUi();
 893					return true;
 894				}
 895			});
 896			popup.inflate(R.menu.encryption_choices);
 897			MenuItem otr = popup.getMenu().findItem(R.id.encryption_choice_otr);
 898			MenuItem none = popup.getMenu().findItem(R.id.encryption_choice_none);
 899			MenuItem pgp = popup.getMenu().findItem(R.id.encryption_choice_pgp);
 900			MenuItem axolotl = popup.getMenu().findItem(R.id.encryption_choice_axolotl);
 901			pgp.setVisible(Config.supportOpenPgp());
 902			none.setVisible(Config.supportUnencrypted() || conversation.getMode() == Conversation.MODE_MULTI);
 903			otr.setVisible(Config.supportOtr());
 904			axolotl.setVisible(Config.supportOmemo());
 905			if (conversation.getMode() == Conversation.MODE_MULTI) {
 906				otr.setVisible(false);
 907			}
 908			if (!conversation.getAccount().getAxolotlService().isConversationAxolotlCapable(conversation)) {
 909				axolotl.setEnabled(false);
 910			}
 911			switch (conversation.getNextEncryption()) {
 912				case Message.ENCRYPTION_NONE:
 913					none.setChecked(true);
 914					break;
 915				case Message.ENCRYPTION_OTR:
 916					otr.setChecked(true);
 917					break;
 918				case Message.ENCRYPTION_PGP:
 919					pgp.setChecked(true);
 920					break;
 921				case Message.ENCRYPTION_AXOLOTL:
 922					axolotl.setChecked(true);
 923					break;
 924				default:
 925					none.setChecked(true);
 926					break;
 927			}
 928			popup.show();
 929		}
 930	}
 931
 932	protected void muteConversationDialog(final Conversation conversation) {
 933		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 934		builder.setTitle(R.string.disable_notifications);
 935		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
 936		builder.setItems(R.array.mute_options_descriptions,
 937				new OnClickListener() {
 938
 939					@Override
 940					public void onClick(final DialogInterface dialog, final int which) {
 941						final long till;
 942						if (durations[which] == -1) {
 943							till = Long.MAX_VALUE;
 944						} else {
 945							till = System.currentTimeMillis() + (durations[which] * 1000);
 946						}
 947						conversation.setMutedTill(till);
 948						ConversationActivity.this.xmppConnectionService.updateConversation(conversation);
 949						updateConversationList();
 950						ConversationActivity.this.mConversationFragment.updateMessages();
 951						invalidateOptionsMenu();
 952					}
 953				});
 954		builder.create().show();
 955	}
 956
 957	public void unmuteConversation(final Conversation conversation) {
 958		conversation.setMutedTill(0);
 959		this.xmppConnectionService.updateConversation(conversation);
 960		updateConversationList();
 961		ConversationActivity.this.mConversationFragment.updateMessages();
 962		invalidateOptionsMenu();
 963	}
 964
 965	@Override
 966	public void onBackPressed() {
 967		if (!isConversationsOverviewVisable()) {
 968			showConversationsOverview();
 969		} else {
 970			moveTaskToBack(true);
 971		}
 972	}
 973
 974	@Override
 975	public boolean onKeyUp(int key, KeyEvent event) {
 976		int rotation = getWindowManager().getDefaultDisplay().getRotation();
 977		final int upKey;
 978		final int downKey;
 979		switch (rotation) {
 980			case Surface.ROTATION_90:
 981				upKey = KeyEvent.KEYCODE_DPAD_LEFT;
 982				downKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 983				break;
 984			case Surface.ROTATION_180:
 985				upKey = KeyEvent.KEYCODE_DPAD_DOWN;
 986				downKey = KeyEvent.KEYCODE_DPAD_UP;
 987				break;
 988			case Surface.ROTATION_270:
 989				upKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 990				downKey = KeyEvent.KEYCODE_DPAD_LEFT;
 991				break;
 992			default:
 993				upKey = KeyEvent.KEYCODE_DPAD_UP;
 994				downKey = KeyEvent.KEYCODE_DPAD_DOWN;
 995		}
 996		final boolean modifier = event.isCtrlPressed() || (event.getMetaState() & KeyEvent.META_ALT_LEFT_ON) != 0;
 997		if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
 998			toggleConversationsOverview();
 999			return true;
1000		} else if (modifier && key == KeyEvent.KEYCODE_SPACE) {
1001			startActivity(new Intent(this, StartConversationActivity.class));
1002			return true;
1003		} else if (modifier && key == downKey) {
1004			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1005				showConversationsOverview();
1006				;
1007			}
1008			return selectDownConversation();
1009		} else if (modifier && key == upKey) {
1010			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1011				showConversationsOverview();
1012			}
1013			return selectUpConversation();
1014		} else if (modifier && key == KeyEvent.KEYCODE_1) {
1015			return openConversationByIndex(0);
1016		} else if (modifier && key == KeyEvent.KEYCODE_2) {
1017			return openConversationByIndex(1);
1018		} else if (modifier && key == KeyEvent.KEYCODE_3) {
1019			return openConversationByIndex(2);
1020		} else if (modifier && key == KeyEvent.KEYCODE_4) {
1021			return openConversationByIndex(3);
1022		} else if (modifier && key == KeyEvent.KEYCODE_5) {
1023			return openConversationByIndex(4);
1024		} else if (modifier && key == KeyEvent.KEYCODE_6) {
1025			return openConversationByIndex(5);
1026		} else if (modifier && key == KeyEvent.KEYCODE_7) {
1027			return openConversationByIndex(6);
1028		} else if (modifier && key == KeyEvent.KEYCODE_8) {
1029			return openConversationByIndex(7);
1030		} else if (modifier && key == KeyEvent.KEYCODE_9) {
1031			return openConversationByIndex(8);
1032		} else if (modifier && key == KeyEvent.KEYCODE_0) {
1033			return openConversationByIndex(9);
1034		} else {
1035			return super.onKeyUp(key, event);
1036		}
1037	}
1038
1039	private void toggleConversationsOverview() {
1040		if (isConversationsOverviewVisable()) {
1041			hideConversationsOverview();
1042			if (mConversationFragment != null) {
1043				mConversationFragment.setFocusOnInputField();
1044			}
1045		} else {
1046			showConversationsOverview();
1047		}
1048	}
1049
1050	private boolean selectUpConversation() {
1051		if (this.mSelectedConversation != null) {
1052			int index = this.conversationList.indexOf(this.mSelectedConversation);
1053			if (index > 0) {
1054				return openConversationByIndex(index - 1);
1055			}
1056		}
1057		return false;
1058	}
1059
1060	private boolean selectDownConversation() {
1061		if (this.mSelectedConversation != null) {
1062			int index = this.conversationList.indexOf(this.mSelectedConversation);
1063			if (index != -1 && index < this.conversationList.size() - 1) {
1064				return openConversationByIndex(index + 1);
1065			}
1066		}
1067		return false;
1068	}
1069
1070	private boolean openConversationByIndex(int index) {
1071		try {
1072			this.conversationWasSelectedByKeyboard = true;
1073			setSelectedConversation(this.conversationList.get(index));
1074			this.mConversationFragment.reInit(getSelectedConversation());
1075			if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
1076				this.listView.setSelection(index);
1077			}
1078			openConversation();
1079			return true;
1080		} catch (IndexOutOfBoundsException e) {
1081			return false;
1082		}
1083	}
1084
1085	@Override
1086	protected void onNewIntent(final Intent intent) {
1087		if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1088			mOpenConversation = null;
1089			if (xmppConnectionServiceBound) {
1090				handleViewConversationIntent(intent);
1091				intent.setAction(Intent.ACTION_MAIN);
1092			} else {
1093				setIntent(intent);
1094			}
1095		}
1096	}
1097
1098	@Override
1099	public void onStart() {
1100		super.onStart();
1101		this.mRedirected.set(false);
1102		if (this.xmppConnectionServiceBound) {
1103			this.onBackendConnected();
1104		}
1105		if (conversationList.size() >= 1) {
1106			this.onConversationUpdate();
1107		}
1108	}
1109
1110	@Override
1111	public void onPause() {
1112		listView.discardUndo();
1113		super.onPause();
1114		this.mActivityPaused = true;
1115	}
1116
1117	@Override
1118	public void onResume() {
1119		super.onResume();
1120		final int theme = findTheme();
1121		final boolean usingEnterKey = usingEnterKey();
1122		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1123			recreate();
1124		}
1125		this.mActivityPaused = false;
1126
1127		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1128			sendReadMarkerIfNecessary(getSelectedConversation());
1129		}
1130
1131	}
1132
1133	@Override
1134	public void onSaveInstanceState(final Bundle savedInstanceState) {
1135		Conversation conversation = getSelectedConversation();
1136		if (conversation != null) {
1137			savedInstanceState.putString(STATE_OPEN_CONVERSATION, conversation.getUuid());
1138			Pair<Integer,Integer> scrollPosition = mConversationFragment.getScrollPosition();
1139			if (scrollPosition != null) {
1140				savedInstanceState.putInt(STATE_FIRST_VISIBLE, scrollPosition.first);
1141				savedInstanceState.putInt(STATE_OFFSET_FROM_TOP, scrollPosition.second);
1142			}
1143		} else {
1144			savedInstanceState.remove(STATE_OPEN_CONVERSATION);
1145		}
1146		savedInstanceState.putBoolean(STATE_PANEL_OPEN, isConversationsOverviewVisable());
1147		if (this.mPendingImageUris.size() >= 1) {
1148			Log.d(Config.LOGTAG,"ConversationsActivity.onSaveInstanceState() - saving pending image uri");
1149			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1150		} else {
1151			savedInstanceState.remove(STATE_PENDING_URI);
1152		}
1153		super.onSaveInstanceState(savedInstanceState);
1154	}
1155
1156	private void clearPending() {
1157		mPendingImageUris.clear();
1158		mPendingFileUris.clear();
1159		mPendingGeoUri = null;
1160		mPostponedActivityResult = null;
1161	}
1162
1163	@Override
1164	void onBackendConnected() {
1165		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1166		updateConversationList();
1167
1168		if (mPendingConferenceInvite != null) {
1169			if (mPendingConferenceInvite.execute(this)) {
1170				mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1171				mToast.show();
1172			}
1173			mPendingConferenceInvite = null;
1174		}
1175
1176		final Intent intent = getIntent();
1177
1178		if (xmppConnectionService.getAccounts().size() == 0) {
1179			if (mRedirected.compareAndSet(false, true)) {
1180				if (Config.X509_VERIFICATION) {
1181					startActivity(new Intent(this, ManageAccountActivity.class));
1182				} else if (Config.MAGIC_CREATE_DOMAIN != null) {
1183					startActivity(new Intent(this, WelcomeActivity.class));
1184				} else {
1185					Intent editAccount = new Intent(this, EditAccountActivity.class);
1186					editAccount.putExtra("init",true);
1187					startActivity(editAccount);
1188				}
1189				finish();
1190			}
1191		} else if (conversationList.size() <= 0) {
1192			if (mRedirected.compareAndSet(false, true)) {
1193				Account pendingAccount = xmppConnectionService.getPendingAccount();
1194				if (pendingAccount == null) {
1195					Intent startConversationActivity = new Intent(this, StartConversationActivity.class);
1196					intent.putExtra("init", true);
1197					startActivity(startConversationActivity);
1198				} else {
1199					switchToAccount(pendingAccount, true);
1200				}
1201				finish();
1202			}
1203		} else if (selectConversationByUuid(mOpenConversation)) {
1204			if (mPanelOpen) {
1205				showConversationsOverview();
1206			} else {
1207				if (isConversationsOverviewHideable()) {
1208					openConversation();
1209					updateActionBarTitle(true);
1210				}
1211			}
1212			if (this.mConversationFragment.reInit(getSelectedConversation())) {
1213				Log.d(Config.LOGTAG,"setting scroll position on fragment");
1214				this.mConversationFragment.setScrollPosition(mScrollPosition);
1215			}
1216			mOpenConversation = null;
1217		} else if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1218			clearPending();
1219			handleViewConversationIntent(intent);
1220			intent.setAction(Intent.ACTION_MAIN);
1221		} else if (getSelectedConversation() == null) {
1222			showConversationsOverview();
1223			clearPending();
1224			setSelectedConversation(conversationList.get(0));
1225			this.mConversationFragment.reInit(getSelectedConversation());
1226		} else {
1227			this.mConversationFragment.messageListAdapter.updatePreferences();
1228			this.mConversationFragment.messagesView.invalidateViews();
1229			this.mConversationFragment.setupIme();
1230		}
1231
1232		if (this.mPostponedActivityResult != null) {
1233			this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1234		}
1235
1236		final boolean stopping;
1237		if (Build.VERSION.SDK_INT >= 17) {
1238			stopping = isFinishing() || isDestroyed();
1239		} else {
1240			stopping = isFinishing();
1241		}
1242
1243		if (!forbidProcessingPendings) {
1244			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1245				Uri foo = i.next();
1246				Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching image to conversations. stopping="+Boolean.toString(stopping));
1247				attachImageToConversation(getSelectedConversation(), foo);
1248			}
1249
1250			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1251				Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching file to conversations. stopping="+Boolean.toString(stopping));
1252				attachFileToConversation(getSelectedConversation(), i.next());
1253			}
1254
1255			if (mPendingGeoUri != null) {
1256				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1257				mPendingGeoUri = null;
1258			}
1259		}
1260		forbidProcessingPendings = false;
1261
1262		if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService)) {
1263			openBatteryOptimizationDialogIfNeeded();
1264		}
1265	}
1266
1267	private void handleViewConversationIntent(final Intent intent) {
1268		final String uuid = intent.getStringExtra(CONVERSATION);
1269		final String downloadUuid = intent.getStringExtra(EXTRA_DOWNLOAD_UUID);
1270		final String text = intent.getStringExtra(TEXT);
1271		final String nick = intent.getStringExtra(NICK);
1272		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1273		if (selectConversationByUuid(uuid)) {
1274			this.mConversationFragment.reInit(getSelectedConversation());
1275			if (nick != null) {
1276				if (pm) {
1277					Jid jid = getSelectedConversation().getJid();
1278					try {
1279						Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1280						this.mConversationFragment.privateMessageWith(next);
1281					} catch (final InvalidJidException ignored) {
1282						//do nothing
1283					}
1284				} else {
1285					this.mConversationFragment.highlightInConference(nick);
1286				}
1287			} else {
1288				this.mConversationFragment.appendText(text);
1289			}
1290			hideConversationsOverview();
1291			openConversation();
1292			if (mContentView instanceof SlidingPaneLayout) {
1293				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1294			}
1295			if (downloadUuid != null) {
1296				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1297				if (message != null) {
1298					startDownloadable(message);
1299				}
1300			}
1301		}
1302	}
1303
1304	private boolean selectConversationByUuid(String uuid) {
1305		if (uuid == null) {
1306			return false;
1307		}
1308		for (Conversation aConversationList : conversationList) {
1309			if (aConversationList.getUuid().equals(uuid)) {
1310				setSelectedConversation(aConversationList);
1311				return true;
1312			}
1313		}
1314		return false;
1315	}
1316
1317	@Override
1318	protected void unregisterListeners() {
1319		super.unregisterListeners();
1320		xmppConnectionService.getNotificationService().setOpenConversation(null);
1321	}
1322
1323	@SuppressLint("NewApi")
1324	private static List<Uri> extractUriFromIntent(final Intent intent) {
1325		List<Uri> uris = new ArrayList<>();
1326		if (intent == null) {
1327			return uris;
1328		}
1329		Uri uri = intent.getData();
1330		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1331			final ClipData clipData = intent.getClipData();
1332			if (clipData != null) {
1333				for (int i = 0; i < clipData.getItemCount(); ++i) {
1334					uris.add(clipData.getItemAt(i).getUri());
1335				}
1336			}
1337		} else {
1338			uris.add(uri);
1339		}
1340		return uris;
1341	}
1342
1343	@Override
1344	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1345		super.onActivityResult(requestCode, resultCode, data);
1346		if (resultCode == RESULT_OK) {
1347			if (requestCode == REQUEST_DECRYPT_PGP) {
1348				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1349			} else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1350				// the user chose OpenPGP for encryption and selected his key in the PGP provider
1351				if (xmppConnectionServiceBound) {
1352					if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1353						// associate selected PGP keyId with the account
1354						mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1355						// we need to announce the key as described in XEP-027
1356						announcePgp(mSelectedConversation.getAccount(), null, onOpenPGPKeyPublished);
1357					} else {
1358						choosePgpSignId(mSelectedConversation.getAccount());
1359					}
1360					this.mPostponedActivityResult = null;
1361				} else {
1362					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1363				}
1364			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1365				if (xmppConnectionServiceBound) {
1366					announcePgp(mSelectedConversation.getAccount(), mSelectedConversation, onOpenPGPKeyPublished);
1367					this.mPostponedActivityResult = null;
1368				} else {
1369					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1370				}
1371			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1372				mPendingImageUris.clear();
1373				mPendingImageUris.addAll(extractUriFromIntent(data));
1374				if (xmppConnectionServiceBound) {
1375					for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1376						Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. CHOOSE_IMAGE");
1377						attachImageToConversation(getSelectedConversation(), i.next());
1378					}
1379				}
1380			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1381				final List<Uri> uris = extractUriFromIntent(data);
1382				final Conversation c = getSelectedConversation();
1383				final OnPresenceSelected callback = new OnPresenceSelected() {
1384					@Override
1385					public void onPresenceSelected() {
1386						mPendingFileUris.clear();
1387						mPendingFileUris.addAll(uris);
1388						if (xmppConnectionServiceBound) {
1389							for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1390								Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE");
1391								attachFileToConversation(c, i.next());
1392							}
1393						}
1394					}
1395				};
1396				if (c == null || c.getMode() == Conversation.MODE_MULTI
1397						|| FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1398						|| c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1399					callback.onPresenceSelected();
1400				} else {
1401					selectPresence(c, callback);
1402				}
1403			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1404				if (mPendingImageUris.size() == 1) {
1405					Uri uri = FileBackend.getIndexableTakePhotoUri(mPendingImageUris.get(0));
1406					mPendingImageUris.set(0, uri);
1407					if (xmppConnectionServiceBound) {
1408						Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. TAKE_PHOTO");
1409						attachImageToConversation(getSelectedConversation(), uri);
1410						mPendingImageUris.clear();
1411					}
1412					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1413					intent.setData(uri);
1414					sendBroadcast(intent);
1415				} else {
1416					mPendingImageUris.clear();
1417				}
1418			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1419				double latitude = data.getDoubleExtra("latitude", 0);
1420				double longitude = data.getDoubleExtra("longitude", 0);
1421				this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1422				if (xmppConnectionServiceBound) {
1423					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1424					this.mPendingGeoUri = null;
1425				}
1426			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1427				this.forbidProcessingPendings = !xmppConnectionServiceBound;
1428				if (xmppConnectionServiceBound) {
1429					mConversationFragment.onActivityResult(requestCode, resultCode, data);
1430					this.mPostponedActivityResult = null;
1431				} else {
1432					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1433				}
1434
1435			}
1436		} else {
1437			mPendingImageUris.clear();
1438			mPendingFileUris.clear();
1439			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1440				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1441			}
1442			if (requestCode == REQUEST_BATTERY_OP) {
1443				setNeverAskForBatteryOptimizationsAgain();
1444			}
1445		}
1446	}
1447
1448	private long getMaxHttpUploadSize(Conversation conversation) {
1449		return conversation.getAccount().getXmppConnection().getFeatures().getMaxHttpUploadSize();
1450	}
1451
1452	private void setNeverAskForBatteryOptimizationsAgain() {
1453		getPreferences().edit().putBoolean("show_battery_optimization", false).commit();
1454	}
1455
1456	private void openBatteryOptimizationDialogIfNeeded() {
1457		if (hasAccountWithoutPush()
1458				&& isOptimizingBattery()
1459				&& getPreferences().getBoolean("show_battery_optimization", true)) {
1460			AlertDialog.Builder builder = new AlertDialog.Builder(this);
1461			builder.setTitle(R.string.battery_optimizations_enabled);
1462			builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1463			builder.setPositiveButton(R.string.next, new OnClickListener() {
1464				@Override
1465				public void onClick(DialogInterface dialog, int which) {
1466					Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1467					Uri uri = Uri.parse("package:" + getPackageName());
1468					intent.setData(uri);
1469					try {
1470						startActivityForResult(intent, REQUEST_BATTERY_OP);
1471					} catch (ActivityNotFoundException e) {
1472						Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1473					}
1474				}
1475			});
1476			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1477				builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1478					@Override
1479					public void onDismiss(DialogInterface dialog) {
1480						setNeverAskForBatteryOptimizationsAgain();
1481					}
1482				});
1483			}
1484			builder.create().show();
1485		}
1486	}
1487
1488	private boolean hasAccountWithoutPush() {
1489		for(Account account : xmppConnectionService.getAccounts()) {
1490			if (account.getStatus() != Account.State.DISABLED
1491					&& !xmppConnectionService.getPushManagementService().available(account)) {
1492				return true;
1493			}
1494		}
1495		return false;
1496	}
1497
1498	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1499		if (conversation == null) {
1500			return;
1501		}
1502		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1503
1504			@Override
1505			public void success(Message message) {
1506				xmppConnectionService.sendMessage(message);
1507			}
1508
1509			@Override
1510			public void error(int errorCode, Message object) {
1511
1512			}
1513
1514			@Override
1515			public void userInputRequried(PendingIntent pi, Message object) {
1516
1517			}
1518		});
1519	}
1520
1521	private void attachFileToConversation(Conversation conversation, Uri uri) {
1522		if (conversation == null) {
1523			return;
1524		}
1525		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1526		prepareFileToast.show();
1527		xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1528			@Override
1529			public void success(Message message) {
1530				hidePrepareFileToast(prepareFileToast);
1531				xmppConnectionService.sendMessage(message);
1532			}
1533
1534			@Override
1535			public void error(final int errorCode, Message message) {
1536				hidePrepareFileToast(prepareFileToast);
1537				runOnUiThread(new Runnable() {
1538					@Override
1539					public void run() {
1540						replaceToast(getString(errorCode));
1541					}
1542				});
1543
1544			}
1545
1546			@Override
1547			public void userInputRequried(PendingIntent pi, Message message) {
1548				hidePrepareFileToast(prepareFileToast);
1549			}
1550		});
1551	}
1552
1553	private void attachImageToConversation(Conversation conversation, Uri uri) {
1554		if (conversation == null) {
1555			return;
1556		}
1557		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1558		prepareFileToast.show();
1559		xmppConnectionService.attachImageToConversation(conversation, uri,
1560				new UiCallback<Message>() {
1561
1562					@Override
1563					public void userInputRequried(PendingIntent pi, Message object) {
1564						hidePrepareFileToast(prepareFileToast);
1565					}
1566
1567					@Override
1568					public void success(Message message) {
1569						hidePrepareFileToast(prepareFileToast);
1570						xmppConnectionService.sendMessage(message);
1571					}
1572
1573					@Override
1574					public void error(final int error, Message message) {
1575						hidePrepareFileToast(prepareFileToast);
1576						runOnUiThread(new Runnable() {
1577							@Override
1578							public void run() {
1579								replaceToast(getString(error));
1580							}
1581						});
1582					}
1583				});
1584	}
1585
1586	private void hidePrepareFileToast(final Toast prepareFileToast) {
1587		if (prepareFileToast != null) {
1588			runOnUiThread(new Runnable() {
1589
1590				@Override
1591				public void run() {
1592					prepareFileToast.cancel();
1593				}
1594			});
1595		}
1596	}
1597
1598	public void updateConversationList() {
1599		xmppConnectionService
1600			.populateWithOrderedConversations(conversationList);
1601		if (swipedConversation != null) {
1602			if (swipedConversation.isRead()) {
1603				conversationList.remove(swipedConversation);
1604			} else {
1605				listView.discardUndo();
1606			}
1607		}
1608		listAdapter.notifyDataSetChanged();
1609	}
1610
1611	public void runIntent(PendingIntent pi, int requestCode) {
1612		try {
1613			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1614					null, 0, 0, 0);
1615		} catch (final SendIntentException ignored) {
1616		}
1617	}
1618
1619	public void encryptTextMessage(Message message) {
1620		xmppConnectionService.getPgpEngine().encrypt(message,
1621				new UiCallback<Message>() {
1622
1623					@Override
1624					public void userInputRequried(PendingIntent pi,Message message) {
1625						ConversationActivity.this.runIntent(pi,ConversationActivity.REQUEST_SEND_MESSAGE);
1626					}
1627
1628					@Override
1629					public void success(Message message) {
1630						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1631						xmppConnectionService.sendMessage(message);
1632						if (mConversationFragment != null) {
1633							mConversationFragment.messageSent();
1634						}
1635					}
1636
1637					@Override
1638					public void error(final int error, Message message) {
1639						runOnUiThread(new Runnable() {
1640							@Override
1641							public void run() {
1642								Toast.makeText(ConversationActivity.this,
1643										R.string.unable_to_connect_to_keychain,
1644										Toast.LENGTH_SHORT
1645								).show();
1646							}
1647						});
1648					}
1649				});
1650	}
1651
1652	public boolean useSendButtonToIndicateStatus() {
1653		return getPreferences().getBoolean("send_button_status", false);
1654	}
1655
1656	public boolean indicateReceived() {
1657		return getPreferences().getBoolean("indicate_received", false);
1658	}
1659
1660	public boolean useGreenBackground() {
1661		return getPreferences().getBoolean("use_green_background",true);
1662	}
1663
1664	protected boolean trustKeysIfNeeded(int requestCode) {
1665		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1666	}
1667
1668	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1669		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1670		final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1671		boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1672		boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED).isEmpty();
1673		boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED, targets).isEmpty();
1674		boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1675		boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1676		if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1677			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1678			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1679			String[] contacts = new String[targets.size()];
1680			for(int i = 0; i < contacts.length; ++i) {
1681				contacts[i] = targets.get(i).toString();
1682			}
1683			intent.putExtra("contacts", contacts);
1684			intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1685			intent.putExtra("choice", attachmentChoice);
1686			intent.putExtra("conversation",mSelectedConversation.getUuid());
1687			startActivityForResult(intent, requestCode);
1688			return true;
1689		} else {
1690			return false;
1691		}
1692	}
1693
1694	@Override
1695	protected void refreshUiReal() {
1696		updateConversationList();
1697		if (conversationList.size() > 0) {
1698			if (!this.mConversationFragment.isAdded()) {
1699				Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1700			}
1701			ConversationActivity.this.mConversationFragment.updateMessages();
1702			updateActionBarTitle();
1703			invalidateOptionsMenu();
1704		} else {
1705			Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1706		}
1707	}
1708
1709	@Override
1710	public void onAccountUpdate() {
1711		this.refreshUi();
1712	}
1713
1714	@Override
1715	public void onConversationUpdate() {
1716		this.refreshUi();
1717	}
1718
1719	@Override
1720	public void onRosterUpdate() {
1721		this.refreshUi();
1722	}
1723
1724	@Override
1725	public void OnUpdateBlocklist(Status status) {
1726		this.refreshUi();
1727	}
1728
1729	public void unblockConversation(final Blockable conversation) {
1730		xmppConnectionService.sendUnblockRequest(conversation);
1731	}
1732
1733	public boolean enterIsSend() {
1734		return getPreferences().getBoolean("enter_is_send",false);
1735	}
1736
1737	@Override
1738	public void onShowErrorToast(final int resId) {
1739		runOnUiThread(new Runnable() {
1740			@Override
1741			public void run() {
1742				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1743			}
1744		});
1745	}
1746
1747	public boolean highlightSelectedConversations() {
1748		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1749	}
1750
1751	public void setMessagesLoaded() {
1752		if (mConversationFragment != null) {
1753			mConversationFragment.setMessagesLoaded();
1754			mConversationFragment.updateMessages();
1755		}
1756	}
1757}