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