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			if (mPendingConferenceInvite.execute(this)) {
1125				mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1126				mToast.show();
1127			}
1128			mPendingConferenceInvite = null;
1129		}
1130
1131		if (xmppConnectionService.getAccounts().size() == 0) {
1132			if (mRedirected.compareAndSet(false, true)) {
1133				if (Config.X509_VERIFICATION) {
1134					startActivity(new Intent(this, ManageAccountActivity.class));
1135				} else if (Config.MAGIC_CREATE_DOMAIN != null) {
1136					startActivity(new Intent(this, WelcomeActivity.class));
1137				} else {
1138					startActivity(new Intent(this, EditAccountActivity.class));
1139				}
1140				finish();
1141			}
1142		} else if (conversationList.size() <= 0) {
1143			if (mRedirected.compareAndSet(false, true)) {
1144				Account pendingAccount = xmppConnectionService.getPendingAccount();
1145				if (pendingAccount == null) {
1146					Intent intent = new Intent(this, StartConversationActivity.class);
1147					intent.putExtra("init", true);
1148					startActivity(intent);
1149				} else {
1150					switchToAccount(pendingAccount, true);
1151				}
1152				finish();
1153			}
1154		} else if (getIntent() != null && VIEW_CONVERSATION.equals(getIntent().getType())) {
1155			clearPending();
1156			handleViewConversationIntent(getIntent());
1157		} else if (selectConversationByUuid(mOpenConverstaion)) {
1158			if (mPanelOpen) {
1159				showConversationsOverview();
1160			} else {
1161				if (isConversationsOverviewHideable()) {
1162					openConversation();
1163					updateActionBarTitle(true);
1164				}
1165			}
1166			this.mConversationFragment.reInit(getSelectedConversation());
1167			mOpenConverstaion = null;
1168		} else if (getSelectedConversation() == null) {
1169			showConversationsOverview();
1170			clearPending();
1171			setSelectedConversation(conversationList.get(0));
1172			this.mConversationFragment.reInit(getSelectedConversation());
1173		} else {
1174			this.mConversationFragment.messageListAdapter.updatePreferences();
1175			this.mConversationFragment.messagesView.invalidateViews();
1176			this.mConversationFragment.setupIme();
1177		}
1178
1179		if (this.mPostponedActivityResult != null) {
1180			this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1181		}
1182
1183		if (!forbidProcessingPendings) {
1184			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1185				Uri foo = i.next();
1186				attachImageToConversation(getSelectedConversation(), foo);
1187			}
1188
1189			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1190				attachFileToConversation(getSelectedConversation(), i.next());
1191			}
1192
1193			if (mPendingGeoUri != null) {
1194				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1195				mPendingGeoUri = null;
1196			}
1197		}
1198		forbidProcessingPendings = false;
1199
1200		if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService)) {
1201			openBatteryOptimizationDialogIfNeeded();
1202		}
1203		setIntent(new Intent());
1204	}
1205
1206	private void handleViewConversationIntent(final Intent intent) {
1207		final String uuid = intent.getStringExtra(CONVERSATION);
1208		final String downloadUuid = intent.getStringExtra(MESSAGE);
1209		final String text = intent.getStringExtra(TEXT);
1210		final String nick = intent.getStringExtra(NICK);
1211		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1212		if (selectConversationByUuid(uuid)) {
1213			this.mConversationFragment.reInit(getSelectedConversation());
1214			if (nick != null) {
1215				if (pm) {
1216					Jid jid = getSelectedConversation().getJid();
1217					try {
1218						Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1219						this.mConversationFragment.privateMessageWith(next);
1220					} catch (final InvalidJidException ignored) {
1221						//do nothing
1222					}
1223				} else {
1224					this.mConversationFragment.highlightInConference(nick);
1225				}
1226			} else {
1227				this.mConversationFragment.appendText(text);
1228			}
1229			hideConversationsOverview();
1230			openConversation();
1231			if (mContentView instanceof SlidingPaneLayout) {
1232				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1233			}
1234			if (downloadUuid != null) {
1235				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1236				if (message != null) {
1237					startDownloadable(message);
1238				}
1239			}
1240		}
1241	}
1242
1243	private boolean selectConversationByUuid(String uuid) {
1244		if (uuid == null) {
1245			return false;
1246		}
1247		for (Conversation aConversationList : conversationList) {
1248			if (aConversationList.getUuid().equals(uuid)) {
1249				setSelectedConversation(aConversationList);
1250				return true;
1251			}
1252		}
1253		return false;
1254	}
1255
1256	@Override
1257	protected void unregisterListeners() {
1258		super.unregisterListeners();
1259		xmppConnectionService.getNotificationService().setOpenConversation(null);
1260	}
1261
1262	@SuppressLint("NewApi")
1263	private static List<Uri> extractUriFromIntent(final Intent intent) {
1264		List<Uri> uris = new ArrayList<>();
1265		if (intent == null) {
1266			return uris;
1267		}
1268		Uri uri = intent.getData();
1269		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1270			ClipData clipData = intent.getClipData();
1271			for (int i = 0; i < clipData.getItemCount(); ++i) {
1272				uris.add(clipData.getItemAt(i).getUri());
1273			}
1274		} else {
1275			uris.add(uri);
1276		}
1277		return uris;
1278	}
1279
1280	@Override
1281	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1282		super.onActivityResult(requestCode, resultCode, data);
1283		if (resultCode == RESULT_OK) {
1284			if (requestCode == REQUEST_DECRYPT_PGP) {
1285				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1286			} else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1287				// the user chose OpenPGP for encryption and selected his key in the PGP provider
1288				if (xmppConnectionServiceBound) {
1289					if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1290						// associate selected PGP keyId with the account
1291						mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1292						// we need to announce the key as described in XEP-027
1293						announcePgp(mSelectedConversation.getAccount(), null, onOpenPGPKeyPublished);
1294					} else {
1295						choosePgpSignId(mSelectedConversation.getAccount());
1296					}
1297					this.mPostponedActivityResult = null;
1298				} else {
1299					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1300				}
1301			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1302				if (xmppConnectionServiceBound) {
1303					announcePgp(mSelectedConversation.getAccount(), mSelectedConversation, onOpenPGPKeyPublished);
1304					this.mPostponedActivityResult = null;
1305				} else {
1306					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1307				}
1308			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1309				mPendingImageUris.clear();
1310				mPendingImageUris.addAll(extractUriFromIntent(data));
1311				if (xmppConnectionServiceBound) {
1312					for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1313						attachImageToConversation(getSelectedConversation(), i.next());
1314					}
1315				}
1316			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1317				final List<Uri> uris = extractUriFromIntent(data);
1318				final Conversation c = getSelectedConversation();
1319				final OnPresenceSelected callback = new OnPresenceSelected() {
1320					@Override
1321					public void onPresenceSelected() {
1322						mPendingFileUris.clear();
1323						mPendingFileUris.addAll(uris);
1324						if (xmppConnectionServiceBound) {
1325							for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1326								attachFileToConversation(c, i.next());
1327							}
1328						}
1329					}
1330				};
1331				if (c == null || c.getMode() == Conversation.MODE_MULTI
1332						|| FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1333						|| c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1334					callback.onPresenceSelected();
1335				} else {
1336					selectPresence(c, callback);
1337				}
1338			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1339				if (mPendingImageUris.size() == 1) {
1340					Uri uri = mPendingImageUris.get(0);
1341					if (xmppConnectionServiceBound) {
1342						attachImageToConversation(getSelectedConversation(), uri);
1343						mPendingImageUris.clear();
1344					}
1345					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1346					intent.setData(uri);
1347					sendBroadcast(intent);
1348				} else {
1349					mPendingImageUris.clear();
1350				}
1351			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1352				double latitude = data.getDoubleExtra("latitude", 0);
1353				double longitude = data.getDoubleExtra("longitude", 0);
1354				this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1355				if (xmppConnectionServiceBound) {
1356					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1357					this.mPendingGeoUri = null;
1358				}
1359			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1360				this.forbidProcessingPendings = !xmppConnectionServiceBound;
1361				if (xmppConnectionServiceBound) {
1362					mConversationFragment.onActivityResult(requestCode, resultCode, data);
1363					this.mPostponedActivityResult = null;
1364				} else {
1365					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1366				}
1367
1368			}
1369		} else {
1370			mPendingImageUris.clear();
1371			mPendingFileUris.clear();
1372			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1373				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1374			}
1375			if (requestCode == REQUEST_BATTERY_OP) {
1376				setNeverAskForBatteryOptimizationsAgain();
1377			}
1378		}
1379	}
1380
1381	private long getMaxHttpUploadSize(Conversation conversation) {
1382		return conversation.getAccount().getXmppConnection().getFeatures().getMaxHttpUploadSize();
1383	}
1384
1385	private void setNeverAskForBatteryOptimizationsAgain() {
1386		getPreferences().edit().putBoolean("show_battery_optimization", false).commit();
1387	}
1388
1389	private void openBatteryOptimizationDialogIfNeeded() {
1390		if (hasAccountWithoutPush()
1391				&& isOptimizingBattery()
1392				&& getPreferences().getBoolean("show_battery_optimization", true)) {
1393			AlertDialog.Builder builder = new AlertDialog.Builder(this);
1394			builder.setTitle(R.string.battery_optimizations_enabled);
1395			builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1396			builder.setPositiveButton(R.string.next, new OnClickListener() {
1397				@Override
1398				public void onClick(DialogInterface dialog, int which) {
1399					Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1400					Uri uri = Uri.parse("package:" + getPackageName());
1401					intent.setData(uri);
1402					try {
1403						startActivityForResult(intent, REQUEST_BATTERY_OP);
1404					} catch (ActivityNotFoundException e) {
1405						Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1406					}
1407				}
1408			});
1409			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1410				builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1411					@Override
1412					public void onDismiss(DialogInterface dialog) {
1413						setNeverAskForBatteryOptimizationsAgain();
1414					}
1415				});
1416			}
1417			builder.create().show();
1418		}
1419	}
1420
1421	private boolean hasAccountWithoutPush() {
1422		for(Account account : xmppConnectionService.getAccounts()) {
1423			if (account.getStatus() != Account.State.DISABLED
1424					&& !xmppConnectionService.getPushManagementService().available(account)) {
1425				return true;
1426			}
1427		}
1428		return false;
1429	}
1430
1431	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1432		if (conversation == null) {
1433			return;
1434		}
1435		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1436
1437			@Override
1438			public void success(Message message) {
1439				xmppConnectionService.sendMessage(message);
1440			}
1441
1442			@Override
1443			public void error(int errorCode, Message object) {
1444
1445			}
1446
1447			@Override
1448			public void userInputRequried(PendingIntent pi, Message object) {
1449
1450			}
1451		});
1452	}
1453
1454	private void attachFileToConversation(Conversation conversation, Uri uri) {
1455		if (conversation == null) {
1456			return;
1457		}
1458		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1459		prepareFileToast.show();
1460		xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1461			@Override
1462			public void success(Message message) {
1463				hidePrepareFileToast(prepareFileToast);
1464				xmppConnectionService.sendMessage(message);
1465			}
1466
1467			@Override
1468			public void error(final int errorCode, Message message) {
1469				hidePrepareFileToast(prepareFileToast);
1470				runOnUiThread(new Runnable() {
1471					@Override
1472					public void run() {
1473						replaceToast(getString(errorCode));
1474					}
1475				});
1476
1477			}
1478
1479			@Override
1480			public void userInputRequried(PendingIntent pi, Message message) {
1481				hidePrepareFileToast(prepareFileToast);
1482			}
1483		});
1484	}
1485
1486	private void attachImageToConversation(Conversation conversation, Uri uri) {
1487		if (conversation == null) {
1488			return;
1489		}
1490		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1491		prepareFileToast.show();
1492		xmppConnectionService.attachImageToConversation(conversation, uri,
1493				new UiCallback<Message>() {
1494
1495					@Override
1496					public void userInputRequried(PendingIntent pi, Message object) {
1497						hidePrepareFileToast(prepareFileToast);
1498					}
1499
1500					@Override
1501					public void success(Message message) {
1502						hidePrepareFileToast(prepareFileToast);
1503						xmppConnectionService.sendMessage(message);
1504					}
1505
1506					@Override
1507					public void error(final int error, Message message) {
1508						hidePrepareFileToast(prepareFileToast);
1509						runOnUiThread(new Runnable() {
1510							@Override
1511							public void run() {
1512								replaceToast(getString(error));
1513							}
1514						});
1515					}
1516				});
1517	}
1518
1519	private void hidePrepareFileToast(final Toast prepareFileToast) {
1520		if (prepareFileToast != null) {
1521			runOnUiThread(new Runnable() {
1522
1523				@Override
1524				public void run() {
1525					prepareFileToast.cancel();
1526				}
1527			});
1528		}
1529	}
1530
1531	public void updateConversationList() {
1532		xmppConnectionService
1533			.populateWithOrderedConversations(conversationList);
1534		if (swipedConversation != null) {
1535			if (swipedConversation.isRead()) {
1536				conversationList.remove(swipedConversation);
1537			} else {
1538				listView.discardUndo();
1539			}
1540		}
1541		listAdapter.notifyDataSetChanged();
1542	}
1543
1544	public void runIntent(PendingIntent pi, int requestCode) {
1545		try {
1546			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1547					null, 0, 0, 0);
1548		} catch (final SendIntentException ignored) {
1549		}
1550	}
1551
1552	public void encryptTextMessage(Message message) {
1553		xmppConnectionService.getPgpEngine().encrypt(message,
1554				new UiCallback<Message>() {
1555
1556					@Override
1557					public void userInputRequried(PendingIntent pi,Message message) {
1558						ConversationActivity.this.runIntent(pi,ConversationActivity.REQUEST_SEND_MESSAGE);
1559					}
1560
1561					@Override
1562					public void success(Message message) {
1563						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1564						xmppConnectionService.sendMessage(message);
1565						if (mConversationFragment != null) {
1566							mConversationFragment.messageSent();
1567						}
1568					}
1569
1570					@Override
1571					public void error(final int error, Message message) {
1572						runOnUiThread(new Runnable() {
1573							@Override
1574							public void run() {
1575								Toast.makeText(ConversationActivity.this,
1576										R.string.unable_to_connect_to_keychain,
1577										Toast.LENGTH_SHORT
1578								).show();
1579							}
1580						});
1581					}
1582				});
1583	}
1584
1585	public boolean useSendButtonToIndicateStatus() {
1586		return getPreferences().getBoolean("send_button_status", false);
1587	}
1588
1589	public boolean indicateReceived() {
1590		return getPreferences().getBoolean("indicate_received", false);
1591	}
1592
1593	public boolean useGreenBackground() {
1594		return getPreferences().getBoolean("use_green_background",true);
1595	}
1596
1597	protected boolean trustKeysIfNeeded(int requestCode) {
1598		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1599	}
1600
1601	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1602		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1603		final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1604		boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1605		boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED).isEmpty();
1606		boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED, targets).isEmpty();
1607		boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1608		boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1609		if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1610			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1611			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1612			String[] contacts = new String[targets.size()];
1613			for(int i = 0; i < contacts.length; ++i) {
1614				contacts[i] = targets.get(i).toString();
1615			}
1616			intent.putExtra("contacts", contacts);
1617			intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1618			intent.putExtra("choice", attachmentChoice);
1619			intent.putExtra("conversation",mSelectedConversation.getUuid());
1620			startActivityForResult(intent, requestCode);
1621			return true;
1622		} else {
1623			return false;
1624		}
1625	}
1626
1627	@Override
1628	protected void refreshUiReal() {
1629		updateConversationList();
1630		if (conversationList.size() > 0) {
1631			if (!this.mConversationFragment.isAdded()) {
1632				Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1633			}
1634			ConversationActivity.this.mConversationFragment.updateMessages();
1635			updateActionBarTitle();
1636			invalidateOptionsMenu();
1637		} else {
1638			Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1639		}
1640	}
1641
1642	@Override
1643	public void onAccountUpdate() {
1644		this.refreshUi();
1645	}
1646
1647	@Override
1648	public void onConversationUpdate() {
1649		this.refreshUi();
1650	}
1651
1652	@Override
1653	public void onRosterUpdate() {
1654		this.refreshUi();
1655	}
1656
1657	@Override
1658	public void OnUpdateBlocklist(Status status) {
1659		this.refreshUi();
1660	}
1661
1662	public void unblockConversation(final Blockable conversation) {
1663		xmppConnectionService.sendUnblockRequest(conversation);
1664	}
1665
1666	public boolean enterIsSend() {
1667		return getPreferences().getBoolean("enter_is_send",false);
1668	}
1669
1670	@Override
1671	public void onShowErrorToast(final int resId) {
1672		runOnUiThread(new Runnable() {
1673			@Override
1674			public void run() {
1675				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1676			}
1677		});
1678	}
1679
1680	public boolean highlightSelectedConversations() {
1681		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1682	}
1683
1684	public void setMessagesLoaded() {
1685		if (mConversationFragment != null) {
1686			mConversationFragment.setMessagesLoaded();
1687			mConversationFragment.updateMessages();
1688		}
1689	}
1690}