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