ConversationActivity.java

   1package eu.siacs.conversations.ui;
   2
   3import android.annotation.SuppressLint;
   4import android.app.ActionBar;
   5import android.app.AlertDialog;
   6import android.app.FragmentTransaction;
   7import android.app.PendingIntent;
   8import android.content.ClipData;
   9import android.content.DialogInterface;
  10import android.content.DialogInterface.OnClickListener;
  11import android.content.Intent;
  12import android.content.IntentSender.SendIntentException;
  13import android.content.pm.PackageManager;
  14import android.net.Uri;
  15import android.os.Build;
  16import android.os.Bundle;
  17import android.provider.MediaStore;
  18import android.provider.Settings;
  19import android.support.v4.widget.SlidingPaneLayout;
  20import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
  21import android.util.Log;
  22import android.util.Pair;
  23import android.view.Gravity;
  24import android.view.KeyEvent;
  25import android.view.Menu;
  26import android.view.MenuItem;
  27import android.view.Surface;
  28import android.view.View;
  29import android.widget.AdapterView;
  30import android.widget.AdapterView.OnItemClickListener;
  31import android.widget.ArrayAdapter;
  32import android.widget.CheckBox;
  33import android.widget.PopupMenu;
  34import android.widget.PopupMenu.OnMenuItemClickListener;
  35import android.widget.Toast;
  36
  37import net.java.otr4j.session.SessionStatus;
  38
  39import org.openintents.openpgp.util.OpenPgpApi;
  40
  41import java.util.ArrayList;
  42import java.util.Iterator;
  43import java.util.List;
  44import java.util.concurrent.atomic.AtomicBoolean;
  45
  46import de.timroes.android.listview.EnhancedListView;
  47import eu.siacs.conversations.Config;
  48import eu.siacs.conversations.R;
  49import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  50import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession;
  51import eu.siacs.conversations.entities.Account;
  52import eu.siacs.conversations.entities.Blockable;
  53import eu.siacs.conversations.entities.Contact;
  54import eu.siacs.conversations.entities.Conversation;
  55import eu.siacs.conversations.entities.Message;
  56import eu.siacs.conversations.entities.Transferable;
  57import eu.siacs.conversations.services.XmppConnectionService;
  58import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
  59import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate;
  60import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
  61import eu.siacs.conversations.ui.adapter.ConversationAdapter;
  62import eu.siacs.conversations.utils.ExceptionHelper;
  63import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  64import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  65import eu.siacs.conversations.xmpp.jid.Jid;
  66
  67public class ConversationActivity extends XmppActivity
  68	implements OnAccountUpdate, OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast {
  69
  70	public static final String ACTION_DOWNLOAD = "eu.siacs.conversations.action.DOWNLOAD";
  71
  72	public static final String VIEW_CONVERSATION = "viewConversation";
  73	public static final String CONVERSATION = "conversationUuid";
  74	public static final String MESSAGE = "messageUuid";
  75	public static final String TEXT = "text";
  76	public static final String NICK = "nick";
  77	public static final String PRIVATE_MESSAGE = "pm";
  78
  79	public static final int REQUEST_SEND_MESSAGE = 0x0201;
  80	public static final int REQUEST_DECRYPT_PGP = 0x0202;
  81	public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
  82	public static final int REQUEST_TRUST_KEYS_TEXT = 0x0208;
  83	public static final int REQUEST_TRUST_KEYS_MENU = 0x0209;
  84	public static final int REQUEST_START_DOWNLOAD = 0x0210;
  85	public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
  86	public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
  87	public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
  88	public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
  89	public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
  90	public static final int ATTACHMENT_CHOICE_INVALID = 0x0306;
  91	private static final String STATE_OPEN_CONVERSATION = "state_open_conversation";
  92	private static final String STATE_PANEL_OPEN = "state_panel_open";
  93	private static final String STATE_PENDING_URI = "state_pending_uri";
  94
  95	private String mOpenConverstaion = null;
  96	private boolean mPanelOpen = true;
  97	final private List<Uri> mPendingImageUris = new ArrayList<>();
  98	final private List<Uri> mPendingFileUris = new ArrayList<>();
  99	private Uri mPendingGeoUri = null;
 100	private boolean forbidProcessingPendings = false;
 101	private Message mPendingDownloadableMessage = null;
 102
 103	private boolean conversationWasSelectedByKeyboard = false;
 104
 105	private View mContentView;
 106
 107	private List<Conversation> conversationList = new ArrayList<>();
 108	private Conversation swipedConversation = null;
 109	private Conversation mSelectedConversation = null;
 110	private EnhancedListView listView;
 111	private ConversationFragment mConversationFragment;
 112
 113	private ArrayAdapter<Conversation> listAdapter;
 114
 115	private boolean mActivityPaused = false;
 116	private AtomicBoolean mRedirected = new AtomicBoolean(false);
 117	private Pair<Integer, Intent> mPostponedActivityResult;
 118
 119	public Conversation getSelectedConversation() {
 120		return this.mSelectedConversation;
 121	}
 122
 123	public void setSelectedConversation(Conversation conversation) {
 124		this.mSelectedConversation = conversation;
 125	}
 126
 127	public void showConversationsOverview() {
 128		if (mContentView instanceof SlidingPaneLayout) {
 129			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 130			mSlidingPaneLayout.openPane();
 131		}
 132	}
 133
 134	@Override
 135	protected String getShareableUri() {
 136		Conversation conversation = getSelectedConversation();
 137		if (conversation != null) {
 138			return conversation.getAccount().getShareableUri();
 139		} else {
 140			return "";
 141		}
 142	}
 143
 144	public void hideConversationsOverview() {
 145		if (mContentView instanceof SlidingPaneLayout) {
 146			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 147			mSlidingPaneLayout.closePane();
 148		}
 149	}
 150
 151	public boolean isConversationsOverviewHideable() {
 152		if (mContentView instanceof SlidingPaneLayout) {
 153			return true;
 154		} else {
 155			return false;
 156		}
 157	}
 158
 159	public boolean isConversationsOverviewVisable() {
 160		if (mContentView instanceof SlidingPaneLayout) {
 161			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 162			return mSlidingPaneLayout.isOpen();
 163		} else {
 164			return true;
 165		}
 166	}
 167
 168	@Override
 169	protected void onCreate(final Bundle savedInstanceState) {
 170		super.onCreate(savedInstanceState);
 171		if (savedInstanceState != null) {
 172			mOpenConverstaion = savedInstanceState.getString(STATE_OPEN_CONVERSATION, null);
 173			mPanelOpen = savedInstanceState.getBoolean(STATE_PANEL_OPEN, true);
 174			String pending = savedInstanceState.getString(STATE_PENDING_URI, null);
 175			if (pending != null) {
 176				mPendingImageUris.clear();
 177				mPendingImageUris.add(Uri.parse(pending));
 178			}
 179		}
 180
 181		setContentView(R.layout.fragment_conversations_overview);
 182
 183		this.mConversationFragment = new ConversationFragment();
 184		FragmentTransaction transaction = getFragmentManager().beginTransaction();
 185		transaction.replace(R.id.selected_conversation, this.mConversationFragment, "conversation");
 186		transaction.commit();
 187
 188		listView = (EnhancedListView) findViewById(R.id.list);
 189		this.listAdapter = new ConversationAdapter(this, conversationList);
 190		listView.setAdapter(this.listAdapter);
 191
 192		if (getActionBar() != null) {
 193			getActionBar().setDisplayHomeAsUpEnabled(false);
 194			getActionBar().setHomeButtonEnabled(false);
 195		}
 196
 197		listView.setOnItemClickListener(new OnItemClickListener() {
 198
 199			@Override
 200			public void onItemClick(AdapterView<?> arg0, View clickedView,
 201									int position, long arg3) {
 202				if (getSelectedConversation() != conversationList.get(position)) {
 203					setSelectedConversation(conversationList.get(position));
 204					ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 205					conversationWasSelectedByKeyboard = false;
 206				}
 207				hideConversationsOverview();
 208				openConversation();
 209			}
 210		});
 211
 212		listView.setDismissCallback(new EnhancedListView.OnDismissCallback() {
 213
 214			@Override
 215			public EnhancedListView.Undoable onDismiss(final EnhancedListView enhancedListView, final int position) {
 216
 217				final int index = listView.getFirstVisiblePosition();
 218				View v = listView.getChildAt(0);
 219				final int top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());
 220
 221				try {
 222					swipedConversation = listAdapter.getItem(position);
 223				} catch (IndexOutOfBoundsException e) {
 224					return null;
 225				}
 226				listAdapter.remove(swipedConversation);
 227				xmppConnectionService.markRead(swipedConversation);
 228
 229				final boolean formerlySelected = (getSelectedConversation() == swipedConversation);
 230				if (position == 0 && listAdapter.getCount() == 0) {
 231					endConversation(swipedConversation, false, true);
 232					return null;
 233				} else if (formerlySelected) {
 234					setSelectedConversation(listAdapter.getItem(0));
 235					ConversationActivity.this.mConversationFragment
 236							.reInit(getSelectedConversation());
 237				}
 238
 239				return new EnhancedListView.Undoable() {
 240
 241					@Override
 242					public void undo() {
 243						listAdapter.insert(swipedConversation, position);
 244						if (formerlySelected) {
 245							setSelectedConversation(swipedConversation);
 246							ConversationActivity.this.mConversationFragment
 247									.reInit(getSelectedConversation());
 248						}
 249						swipedConversation = null;
 250						listView.setSelectionFromTop(index + (listView.getChildCount() < position ? 1 : 0), top);
 251					}
 252
 253					@Override
 254					public void discard() {
 255						if (!swipedConversation.isRead()
 256								&& swipedConversation.getMode() == Conversation.MODE_SINGLE) {
 257							swipedConversation = null;
 258							return;
 259						}
 260						endConversation(swipedConversation, false, false);
 261						swipedConversation = null;
 262					}
 263
 264					@Override
 265					public String getTitle() {
 266						if (swipedConversation.getMode() == Conversation.MODE_MULTI) {
 267							return getResources().getString(R.string.title_undo_swipe_out_muc);
 268						} else {
 269							return getResources().getString(R.string.title_undo_swipe_out_conversation);
 270						}
 271					}
 272				};
 273			}
 274		});
 275		listView.enableSwipeToDismiss();
 276		listView.setSwipingLayout(R.id.swipeable_item);
 277		listView.setUndoStyle(EnhancedListView.UndoStyle.SINGLE_POPUP);
 278		listView.setUndoHideDelay(5000);
 279		listView.setRequireTouchBeforeDismiss(false);
 280
 281		mContentView = findViewById(R.id.content_view_spl);
 282		if (mContentView == null) {
 283			mContentView = findViewById(R.id.content_view_ll);
 284		}
 285		if (mContentView instanceof SlidingPaneLayout) {
 286			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 287			mSlidingPaneLayout.setParallaxDistance(150);
 288			mSlidingPaneLayout
 289					.setShadowResource(R.drawable.es_slidingpane_shadow);
 290			mSlidingPaneLayout.setSliderFadeColor(0);
 291			mSlidingPaneLayout.setPanelSlideListener(new PanelSlideListener() {
 292
 293				@Override
 294				public void onPanelOpened(View arg0) {
 295					updateActionBarTitle();
 296					invalidateOptionsMenu();
 297					hideKeyboard();
 298					if (xmppConnectionServiceBound) {
 299						xmppConnectionService.getNotificationService()
 300								.setOpenConversation(null);
 301					}
 302					closeContextMenu();
 303				}
 304
 305				@Override
 306				public void onPanelClosed(View arg0) {
 307					listView.discardUndo();
 308					openConversation();
 309				}
 310
 311				@Override
 312				public void onPanelSlide(View arg0, float arg1) {
 313					// TODO Auto-generated method stub
 314
 315				}
 316			});
 317		}
 318	}
 319
 320	@Override
 321	public void switchToConversation(Conversation conversation) {
 322		setSelectedConversation(conversation);
 323		runOnUiThread(new Runnable() {
 324			@Override
 325			public void run() {
 326				ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 327				openConversation();
 328			}
 329		});
 330	}
 331
 332	private void updateActionBarTitle() {
 333		updateActionBarTitle(isConversationsOverviewHideable() && !isConversationsOverviewVisable());
 334	}
 335
 336	private void updateActionBarTitle(boolean titleShouldBeName) {
 337		final ActionBar ab = getActionBar();
 338		final Conversation conversation = getSelectedConversation();
 339		if (ab != null) {
 340			if (titleShouldBeName && conversation != null) {
 341				ab.setDisplayHomeAsUpEnabled(true);
 342				ab.setHomeButtonEnabled(true);
 343				if (conversation.getMode() == Conversation.MODE_SINGLE || useSubjectToIdentifyConference()) {
 344					ab.setTitle(conversation.getName());
 345				} else {
 346					ab.setTitle(conversation.getJid().toBareJid().toString());
 347				}
 348			} else {
 349				ab.setDisplayHomeAsUpEnabled(false);
 350				ab.setHomeButtonEnabled(false);
 351				ab.setTitle(R.string.app_name);
 352			}
 353		}
 354	}
 355
 356	private void openConversation() {
 357		this.updateActionBarTitle();
 358		this.invalidateOptionsMenu();
 359		if (xmppConnectionServiceBound) {
 360			final Conversation conversation = getSelectedConversation();
 361			xmppConnectionService.getNotificationService().setOpenConversation(conversation);
 362			sendReadMarkerIfNecessary(conversation);
 363		}
 364		listAdapter.notifyDataSetChanged();
 365	}
 366
 367	public void sendReadMarkerIfNecessary(final Conversation conversation) {
 368		if (!mActivityPaused && conversation != null) {
 369			if (!conversation.isRead()) {
 370				xmppConnectionService.sendReadMarker(conversation);
 371			} else {
 372				xmppConnectionService.markRead(conversation);
 373			}
 374		}
 375	}
 376
 377	@Override
 378	public boolean onCreateOptionsMenu(Menu menu) {
 379		getMenuInflater().inflate(R.menu.conversations, menu);
 380		final MenuItem menuSecure = menu.findItem(R.id.action_security);
 381		final MenuItem menuArchive = menu.findItem(R.id.action_archive);
 382		final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 383		final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 384		final MenuItem menuAttach = menu.findItem(R.id.action_attach_file);
 385		final MenuItem menuClearHistory = menu.findItem(R.id.action_clear_history);
 386		final MenuItem menuAdd = menu.findItem(R.id.action_add);
 387		final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 388		final MenuItem menuMute = menu.findItem(R.id.action_mute);
 389		final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 390
 391		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
 392			menuArchive.setVisible(false);
 393			menuMucDetails.setVisible(false);
 394			menuContactDetails.setVisible(false);
 395			menuSecure.setVisible(false);
 396			menuInviteContact.setVisible(false);
 397			menuAttach.setVisible(false);
 398			menuClearHistory.setVisible(false);
 399			menuMute.setVisible(false);
 400			menuUnmute.setVisible(false);
 401		} else {
 402			menuAdd.setVisible(!isConversationsOverviewHideable());
 403			if (this.getSelectedConversation() != null) {
 404				if (this.getSelectedConversation().getNextEncryption() != Message.ENCRYPTION_NONE) {
 405					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 406						menuSecure.setIcon(R.drawable.ic_lock_white_24dp);
 407					} else {
 408						menuSecure.setIcon(R.drawable.ic_action_secure);
 409					}
 410				}
 411				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
 412					menuContactDetails.setVisible(false);
 413					menuAttach.setVisible(getSelectedConversation().getAccount().httpUploadAvailable() && getSelectedConversation().getMucOptions().participating());
 414					menuInviteContact.setVisible(getSelectedConversation().getMucOptions().canInvite());
 415					menuSecure.setVisible(!Config.HIDE_PGP_IN_UI && !Config.X509_VERIFICATION); //if pgp is hidden conferences have no choice of encryption
 416				} else {
 417					menuMucDetails.setVisible(false);
 418				}
 419				if (this.getSelectedConversation().isMuted()) {
 420					menuMute.setVisible(false);
 421				} else {
 422					menuUnmute.setVisible(false);
 423				}
 424			}
 425		}
 426		return true;
 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									displayErrorDialog(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);
 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.HIDE_PGP_IN_UI && !Config.X509_VERIFICATION);
 857			none.setVisible(!Config.FORCE_E2E_ENCRYPTION);
 858			otr.setVisible(!Config.X509_VERIFICATION);
 859			if (conversation.getMode() == Conversation.MODE_MULTI) {
 860				otr.setVisible(false);
 861				axolotl.setVisible(false);
 862			} else if (!conversation.getAccount().getAxolotlService().isContactAxolotlCapable(conversation.getContact())) {
 863				axolotl.setEnabled(false);
 864			}
 865			switch (conversation.getNextEncryption()) {
 866				case Message.ENCRYPTION_NONE:
 867					none.setChecked(true);
 868					break;
 869				case Message.ENCRYPTION_OTR:
 870					otr.setChecked(true);
 871					break;
 872				case Message.ENCRYPTION_PGP:
 873					pgp.setChecked(true);
 874					break;
 875				case Message.ENCRYPTION_AXOLOTL:
 876					axolotl.setChecked(true);
 877					break;
 878				default:
 879					none.setChecked(true);
 880					break;
 881			}
 882			popup.show();
 883		}
 884	}
 885
 886	protected void muteConversationDialog(final Conversation conversation) {
 887		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 888		builder.setTitle(R.string.disable_notifications);
 889		final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
 890		builder.setItems(R.array.mute_options_descriptions,
 891				new OnClickListener() {
 892
 893					@Override
 894					public void onClick(final DialogInterface dialog, final int which) {
 895						final long till;
 896						if (durations[which] == -1) {
 897							till = Long.MAX_VALUE;
 898						} else {
 899							till = System.currentTimeMillis() + (durations[which] * 1000);
 900						}
 901						conversation.setMutedTill(till);
 902						ConversationActivity.this.xmppConnectionService.databaseBackend
 903								.updateConversation(conversation);
 904						updateConversationList();
 905						ConversationActivity.this.mConversationFragment.updateMessages();
 906						invalidateOptionsMenu();
 907					}
 908				});
 909		builder.create().show();
 910	}
 911
 912	public void unmuteConversation(final Conversation conversation) {
 913		conversation.setMutedTill(0);
 914		this.xmppConnectionService.databaseBackend.updateConversation(conversation);
 915		updateConversationList();
 916		ConversationActivity.this.mConversationFragment.updateMessages();
 917		invalidateOptionsMenu();
 918	}
 919
 920	@Override
 921	public void onBackPressed() {
 922		if (!isConversationsOverviewVisable()) {
 923			showConversationsOverview();
 924		} else {
 925			moveTaskToBack(true);
 926		}
 927	}
 928
 929	@Override
 930	public boolean onKeyUp(int key, KeyEvent event) {
 931		int rotation = getWindowManager().getDefaultDisplay().getRotation();
 932		final int upKey;
 933		final int downKey;
 934		switch (rotation) {
 935			case Surface.ROTATION_90:
 936				upKey = KeyEvent.KEYCODE_DPAD_LEFT;
 937				downKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 938				break;
 939			case Surface.ROTATION_180:
 940				upKey = KeyEvent.KEYCODE_DPAD_DOWN;
 941				downKey = KeyEvent.KEYCODE_DPAD_UP;
 942				break;
 943			case Surface.ROTATION_270:
 944				upKey = KeyEvent.KEYCODE_DPAD_RIGHT;
 945				downKey = KeyEvent.KEYCODE_DPAD_LEFT;
 946				break;
 947			default:
 948				upKey = KeyEvent.KEYCODE_DPAD_UP;
 949				downKey = KeyEvent.KEYCODE_DPAD_DOWN;
 950		}
 951		final boolean modifier = event.isCtrlPressed() || event.isAltPressed();
 952		if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
 953			toggleConversationsOverview();
 954			return true;
 955		} else if (modifier && key == downKey) {
 956			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 957				showConversationsOverview();
 958				;
 959			}
 960			return selectDownConversation();
 961		} else if (modifier && key == upKey) {
 962			if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
 963				showConversationsOverview();
 964			}
 965			return selectUpConversation();
 966		} else if (modifier && key == KeyEvent.KEYCODE_1) {
 967			return openConversationByIndex(0);
 968		} else if (modifier && key == KeyEvent.KEYCODE_2) {
 969			return openConversationByIndex(1);
 970		} else if (modifier && key == KeyEvent.KEYCODE_3) {
 971			return openConversationByIndex(2);
 972		} else if (modifier && key == KeyEvent.KEYCODE_4) {
 973			return openConversationByIndex(3);
 974		} else if (modifier && key == KeyEvent.KEYCODE_5) {
 975			return openConversationByIndex(4);
 976		} else if (modifier && key == KeyEvent.KEYCODE_6) {
 977			return openConversationByIndex(5);
 978		} else if (modifier && key == KeyEvent.KEYCODE_7) {
 979			return openConversationByIndex(6);
 980		} else if (modifier && key == KeyEvent.KEYCODE_8) {
 981			return openConversationByIndex(7);
 982		} else if (modifier && key == KeyEvent.KEYCODE_9) {
 983			return openConversationByIndex(8);
 984		} else if (modifier && key == KeyEvent.KEYCODE_0) {
 985			return openConversationByIndex(9);
 986		} else {
 987			return super.onKeyUp(key, event);
 988		}
 989	}
 990
 991	private void toggleConversationsOverview() {
 992		if (isConversationsOverviewVisable()) {
 993			hideConversationsOverview();
 994			if (mConversationFragment != null) {
 995				mConversationFragment.setFocusOnInputField();
 996			}
 997		} else {
 998			showConversationsOverview();
 999		}
1000	}
1001
1002	private boolean selectUpConversation() {
1003		if (this.mSelectedConversation != null) {
1004			int index = this.conversationList.indexOf(this.mSelectedConversation);
1005			if (index > 0) {
1006				return openConversationByIndex(index - 1);
1007			}
1008		}
1009		return false;
1010	}
1011
1012	private boolean selectDownConversation() {
1013		if (this.mSelectedConversation != null) {
1014			int index = this.conversationList.indexOf(this.mSelectedConversation);
1015			if (index != -1 && index < this.conversationList.size() - 1) {
1016				return openConversationByIndex(index + 1);
1017			}
1018		}
1019		return false;
1020	}
1021
1022	private boolean openConversationByIndex(int index) {
1023		try {
1024			this.conversationWasSelectedByKeyboard = true;
1025			setSelectedConversation(this.conversationList.get(index));
1026			this.mConversationFragment.reInit(getSelectedConversation());
1027			if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
1028				this.listView.setSelection(index);
1029			}
1030			openConversation();
1031			return true;
1032		} catch (IndexOutOfBoundsException e) {
1033			return false;
1034		}
1035	}
1036
1037	@Override
1038	protected void onNewIntent(final Intent intent) {
1039		if (xmppConnectionServiceBound) {
1040			if (intent != null && VIEW_CONVERSATION.equals(intent.getType())) {
1041				handleViewConversationIntent(intent);
1042				setIntent(new Intent());
1043			}
1044		} else {
1045			setIntent(intent);
1046		}
1047	}
1048
1049	@Override
1050	public void onStart() {
1051		super.onStart();
1052		this.mRedirected.set(false);
1053		if (this.xmppConnectionServiceBound) {
1054			this.onBackendConnected();
1055		}
1056		if (conversationList.size() >= 1) {
1057			this.onConversationUpdate();
1058		}
1059	}
1060
1061	@Override
1062	public void onPause() {
1063		listView.discardUndo();
1064		super.onPause();
1065		this.mActivityPaused = true;
1066		if (this.xmppConnectionServiceBound) {
1067			this.xmppConnectionService.getNotificationService().setIsInForeground(false);
1068		}
1069	}
1070
1071	@Override
1072	public void onResume() {
1073		super.onResume();
1074		final int theme = findTheme();
1075		final boolean usingEnterKey = usingEnterKey();
1076		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1077			recreate();
1078		}
1079		this.mActivityPaused = false;
1080		if (this.xmppConnectionServiceBound) {
1081			this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1082		}
1083
1084		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1085			sendReadMarkerIfNecessary(getSelectedConversation());
1086		}
1087
1088	}
1089
1090	@Override
1091	public void onSaveInstanceState(final Bundle savedInstanceState) {
1092		Conversation conversation = getSelectedConversation();
1093		if (conversation != null) {
1094			savedInstanceState.putString(STATE_OPEN_CONVERSATION, conversation.getUuid());
1095		} else {
1096			savedInstanceState.remove(STATE_OPEN_CONVERSATION);
1097		}
1098		savedInstanceState.putBoolean(STATE_PANEL_OPEN, isConversationsOverviewVisable());
1099		if (this.mPendingImageUris.size() >= 1) {
1100			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1101		} else {
1102			savedInstanceState.remove(STATE_PENDING_URI);
1103		}
1104		super.onSaveInstanceState(savedInstanceState);
1105	}
1106
1107	private void clearPending() {
1108		mPendingImageUris.clear();
1109		mPendingFileUris.clear();
1110		mPendingGeoUri = null;
1111		mPostponedActivityResult = null;
1112	}
1113
1114	@Override
1115	void onBackendConnected() {
1116		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1117		updateConversationList();
1118
1119		if (mPendingConferenceInvite != null) {
1120			mPendingConferenceInvite.execute(this);
1121			mPendingConferenceInvite = null;
1122		}
1123
1124		if (xmppConnectionService.getAccounts().size() == 0) {
1125			if (mRedirected.compareAndSet(false, true)) {
1126				if (Config.X509_VERIFICATION) {
1127					startActivity(new Intent(this, ManageAccountActivity.class));
1128				} else {
1129					startActivity(new Intent(this, EditAccountActivity.class));
1130				}
1131				finish();
1132			}
1133		} else if (conversationList.size() <= 0) {
1134			if (mRedirected.compareAndSet(false, true)) {
1135				Intent intent = new Intent(this, StartConversationActivity.class);
1136				intent.putExtra("init", true);
1137				startActivity(intent);
1138				finish();
1139			}
1140		} else if (getIntent() != null && VIEW_CONVERSATION.equals(getIntent().getType())) {
1141			clearPending();
1142			handleViewConversationIntent(getIntent());
1143		} else if (selectConversationByUuid(mOpenConverstaion)) {
1144			if (mPanelOpen) {
1145				showConversationsOverview();
1146			} else {
1147				if (isConversationsOverviewHideable()) {
1148					openConversation();
1149					updateActionBarTitle(true);
1150				}
1151			}
1152			this.mConversationFragment.reInit(getSelectedConversation());
1153			mOpenConverstaion = null;
1154		} else if (getSelectedConversation() == null) {
1155			showConversationsOverview();
1156			clearPending();
1157			setSelectedConversation(conversationList.get(0));
1158			this.mConversationFragment.reInit(getSelectedConversation());
1159		} else {
1160			this.mConversationFragment.messageListAdapter.updatePreferences();
1161			this.mConversationFragment.messagesView.invalidateViews();
1162			this.mConversationFragment.setupIme();
1163		}
1164
1165		if (this.mPostponedActivityResult != null) {
1166			this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1167		}
1168
1169		if (!forbidProcessingPendings) {
1170			for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1171				Uri foo = i.next();
1172				attachImageToConversation(getSelectedConversation(), foo);
1173			}
1174
1175			for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1176				attachFileToConversation(getSelectedConversation(), i.next());
1177			}
1178
1179			if (mPendingGeoUri != null) {
1180				attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1181				mPendingGeoUri = null;
1182			}
1183		}
1184		forbidProcessingPendings = false;
1185
1186		if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService)) {
1187			openBatteryOptimizationDialogIfNeeded();
1188		}
1189		setIntent(new Intent());
1190	}
1191
1192	private void handleViewConversationIntent(final Intent intent) {
1193		final String uuid = intent.getStringExtra(CONVERSATION);
1194		final String downloadUuid = intent.getStringExtra(MESSAGE);
1195		final String text = intent.getStringExtra(TEXT);
1196		final String nick = intent.getStringExtra(NICK);
1197		final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1198		if (selectConversationByUuid(uuid)) {
1199			this.mConversationFragment.reInit(getSelectedConversation());
1200			if (nick != null) {
1201				if (pm) {
1202					Jid jid = getSelectedConversation().getJid();
1203					try {
1204						Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1205						this.mConversationFragment.privateMessageWith(next);
1206					} catch (final InvalidJidException ignored) {
1207						//do nothing
1208					}
1209				} else {
1210					this.mConversationFragment.highlightInConference(nick);
1211				}
1212			} else {
1213				this.mConversationFragment.appendText(text);
1214			}
1215			hideConversationsOverview();
1216			openConversation();
1217			if (mContentView instanceof SlidingPaneLayout) {
1218				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1219			}
1220			if (downloadUuid != null) {
1221				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1222				if (message != null) {
1223					startDownloadable(message);
1224				}
1225			}
1226		}
1227	}
1228
1229	private boolean selectConversationByUuid(String uuid) {
1230		if (uuid == null) {
1231			return false;
1232		}
1233		for (Conversation aConversationList : conversationList) {
1234			if (aConversationList.getUuid().equals(uuid)) {
1235				setSelectedConversation(aConversationList);
1236				return true;
1237			}
1238		}
1239		return false;
1240	}
1241
1242	@Override
1243	protected void unregisterListeners() {
1244		super.unregisterListeners();
1245		xmppConnectionService.getNotificationService().setOpenConversation(null);
1246	}
1247
1248	@SuppressLint("NewApi")
1249	private static List<Uri> extractUriFromIntent(final Intent intent) {
1250		List<Uri> uris = new ArrayList<>();
1251		if (intent == null) {
1252			return uris;
1253		}
1254		Uri uri = intent.getData();
1255		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1256			ClipData clipData = intent.getClipData();
1257			for (int i = 0; i < clipData.getItemCount(); ++i) {
1258				uris.add(clipData.getItemAt(i).getUri());
1259			}
1260		} else {
1261			uris.add(uri);
1262		}
1263		return uris;
1264	}
1265
1266	@Override
1267	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1268		super.onActivityResult(requestCode, resultCode, data);
1269		if (resultCode == RESULT_OK) {
1270			if (requestCode == REQUEST_DECRYPT_PGP) {
1271				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1272			} else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1273				// the user chose OpenPGP for encryption and selected his key in the PGP provider
1274				if (xmppConnectionServiceBound) {
1275					if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1276						// associate selected PGP keyId with the account
1277						mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1278						// we need to announce the key as described in XEP-027
1279						announcePgp(mSelectedConversation.getAccount(), null);
1280					} else {
1281						choosePgpSignId(mSelectedConversation.getAccount());
1282					}
1283					this.mPostponedActivityResult = null;
1284				} else {
1285					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1286				}
1287			} else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1288				if (xmppConnectionServiceBound) {
1289					announcePgp(mSelectedConversation.getAccount(), mSelectedConversation);
1290					this.mPostponedActivityResult = null;
1291				} else {
1292					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1293				}
1294			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1295				mPendingImageUris.clear();
1296				mPendingImageUris.addAll(extractUriFromIntent(data));
1297				if (xmppConnectionServiceBound) {
1298					for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1299						attachImageToConversation(getSelectedConversation(), i.next());
1300					}
1301				}
1302			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1303				mPendingFileUris.clear();
1304				mPendingFileUris.addAll(extractUriFromIntent(data));
1305				if (xmppConnectionServiceBound) {
1306					for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1307						attachFileToConversation(getSelectedConversation(), i.next());
1308					}
1309				}
1310			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1311				if (mPendingImageUris.size() == 1) {
1312					Uri uri = mPendingImageUris.get(0);
1313					if (xmppConnectionServiceBound) {
1314						attachImageToConversation(getSelectedConversation(), uri);
1315						mPendingImageUris.clear();
1316					}
1317					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1318					intent.setData(uri);
1319					sendBroadcast(intent);
1320				} else {
1321					mPendingImageUris.clear();
1322				}
1323			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1324				double latitude = data.getDoubleExtra("latitude", 0);
1325				double longitude = data.getDoubleExtra("longitude", 0);
1326				this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1327				if (xmppConnectionServiceBound) {
1328					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1329					this.mPendingGeoUri = null;
1330				}
1331			} else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1332				this.forbidProcessingPendings = !xmppConnectionServiceBound;
1333				if (xmppConnectionServiceBound) {
1334					mConversationFragment.onActivityResult(requestCode, resultCode, data);
1335					this.mPostponedActivityResult = null;
1336				} else {
1337					this.mPostponedActivityResult = new Pair<>(requestCode, data);
1338				}
1339
1340			}
1341		} else {
1342			mPendingImageUris.clear();
1343			mPendingFileUris.clear();
1344			if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1345				mConversationFragment.onActivityResult(requestCode, resultCode, data);
1346			}
1347			if (requestCode == REQUEST_BATTERY_OP) {
1348				setNeverAskForBatteryOptimizationsAgain();
1349			}
1350		}
1351	}
1352
1353	private void setNeverAskForBatteryOptimizationsAgain() {
1354		getPreferences().edit().putBoolean("show_battery_optimization", false).commit();
1355	}
1356
1357	private void openBatteryOptimizationDialogIfNeeded() {
1358		if (showBatteryOptimizationWarning() && getPreferences().getBoolean("show_battery_optimization", true)) {
1359			AlertDialog.Builder builder = new AlertDialog.Builder(this);
1360			builder.setTitle(R.string.battery_optimizations_enabled);
1361			builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1362			builder.setPositiveButton(R.string.next, new OnClickListener() {
1363				@Override
1364				public void onClick(DialogInterface dialog, int which) {
1365					Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1366					Uri uri = Uri.parse("package:" + getPackageName());
1367					intent.setData(uri);
1368					startActivityForResult(intent, REQUEST_BATTERY_OP);
1369				}
1370			});
1371			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1372				builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1373					@Override
1374					public void onDismiss(DialogInterface dialog) {
1375						setNeverAskForBatteryOptimizationsAgain();
1376					}
1377				});
1378			}
1379			builder.create().show();
1380		}
1381	}
1382
1383	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1384		if (conversation == null) {
1385			return;
1386		}
1387		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1388
1389			@Override
1390			public void success(Message message) {
1391				xmppConnectionService.sendMessage(message);
1392			}
1393
1394			@Override
1395			public void error(int errorCode, Message object) {
1396
1397			}
1398
1399			@Override
1400			public void userInputRequried(PendingIntent pi, Message object) {
1401
1402			}
1403		});
1404	}
1405
1406	private void attachFileToConversation(Conversation conversation, Uri uri) {
1407		if (conversation == null) {
1408			return;
1409		}
1410		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1411		prepareFileToast.show();
1412		xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1413			@Override
1414			public void success(Message message) {
1415				hidePrepareFileToast(prepareFileToast);
1416				xmppConnectionService.sendMessage(message);
1417			}
1418
1419			@Override
1420			public void error(int errorCode, Message message) {
1421				hidePrepareFileToast(prepareFileToast);
1422				displayErrorDialog(errorCode);
1423			}
1424
1425			@Override
1426			public void userInputRequried(PendingIntent pi, Message message) {
1427
1428			}
1429		});
1430	}
1431
1432	private void attachImageToConversation(Conversation conversation, Uri uri) {
1433		if (conversation == null) {
1434			return;
1435		}
1436		final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1437		prepareFileToast.show();
1438		xmppConnectionService.attachImageToConversation(conversation, uri,
1439				new UiCallback<Message>() {
1440
1441					@Override
1442					public void userInputRequried(PendingIntent pi, Message object) {
1443						hidePrepareFileToast(prepareFileToast);
1444					}
1445
1446					@Override
1447					public void success(Message message) {
1448						hidePrepareFileToast(prepareFileToast);
1449						xmppConnectionService.sendMessage(message);
1450					}
1451
1452					@Override
1453					public void error(int error, Message message) {
1454						hidePrepareFileToast(prepareFileToast);
1455						displayErrorDialog(error);
1456					}
1457				});
1458	}
1459
1460	private void hidePrepareFileToast(final Toast prepareFileToast) {
1461		if (prepareFileToast != null) {
1462			runOnUiThread(new Runnable() {
1463
1464				@Override
1465				public void run() {
1466					prepareFileToast.cancel();
1467				}
1468			});
1469		}
1470	}
1471
1472	public void updateConversationList() {
1473		xmppConnectionService
1474			.populateWithOrderedConversations(conversationList);
1475		if (swipedConversation != null) {
1476			if (swipedConversation.isRead()) {
1477				conversationList.remove(swipedConversation);
1478			} else {
1479				listView.discardUndo();
1480			}
1481		}
1482		listAdapter.notifyDataSetChanged();
1483	}
1484
1485	public void runIntent(PendingIntent pi, int requestCode) {
1486		try {
1487			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1488					null, 0, 0, 0);
1489		} catch (final SendIntentException ignored) {
1490		}
1491	}
1492
1493	public void encryptTextMessage(Message message) {
1494		xmppConnectionService.getPgpEngine().encrypt(message,
1495				new UiCallback<Message>() {
1496
1497					@Override
1498					public void userInputRequried(PendingIntent pi,
1499												  Message message) {
1500						ConversationActivity.this.runIntent(pi,
1501								ConversationActivity.REQUEST_SEND_MESSAGE);
1502					}
1503
1504					@Override
1505					public void success(Message message) {
1506						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1507						xmppConnectionService.sendMessage(message);
1508					}
1509
1510					@Override
1511					public void error(int error, Message message) {
1512
1513					}
1514				});
1515	}
1516
1517	public boolean useSendButtonToIndicateStatus() {
1518		return getPreferences().getBoolean("send_button_status", false);
1519	}
1520
1521	public boolean indicateReceived() {
1522		return getPreferences().getBoolean("indicate_received", false);
1523	}
1524
1525	public boolean useWhiteBackground() {
1526		return getPreferences().getBoolean("use_white_background",false);
1527	}
1528
1529	protected boolean trustKeysIfNeeded(int requestCode) {
1530		return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1531	}
1532
1533	protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1534		AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1535		Contact contact = mSelectedConversation.getContact();
1536		boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED).isEmpty();
1537		boolean hasUndecidedContact = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED,contact).isEmpty();
1538		boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1539		boolean hasNoTrustedKeys = axolotlService.getNumTrustedKeys(mSelectedConversation.getContact()) == 0;
1540		if(hasUndecidedOwn || hasUndecidedContact || hasPendingKeys || hasNoTrustedKeys) {
1541			axolotlService.createSessionsIfNeeded(mSelectedConversation);
1542			Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1543			intent.putExtra("contact", mSelectedConversation.getContact().getJid().toBareJid().toString());
1544			intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1545			intent.putExtra("choice", attachmentChoice);
1546			intent.putExtra("has_no_trusted", hasNoTrustedKeys);
1547			startActivityForResult(intent, requestCode);
1548			return true;
1549		} else {
1550			return false;
1551		}
1552	}
1553
1554	@Override
1555	protected void refreshUiReal() {
1556		updateConversationList();
1557		if (conversationList.size() > 0) {
1558			ConversationActivity.this.mConversationFragment.updateMessages();
1559			updateActionBarTitle();
1560			invalidateOptionsMenu();
1561		}
1562	}
1563
1564	@Override
1565	public void onAccountUpdate() {
1566		this.refreshUi();
1567	}
1568
1569	@Override
1570	public void onConversationUpdate() {
1571		this.refreshUi();
1572	}
1573
1574	@Override
1575	public void onRosterUpdate() {
1576		this.refreshUi();
1577	}
1578
1579	@Override
1580	public void OnUpdateBlocklist(Status status) {
1581		this.refreshUi();
1582	}
1583
1584	public void unblockConversation(final Blockable conversation) {
1585		xmppConnectionService.sendUnblockRequest(conversation);
1586	}
1587
1588	public boolean enterIsSend() {
1589		return getPreferences().getBoolean("enter_is_send",false);
1590	}
1591
1592	@Override
1593	public void onShowErrorToast(final int resId) {
1594		runOnUiThread(new Runnable() {
1595			@Override
1596			public void run() {
1597				Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1598			}
1599		});
1600	}
1601
1602	public boolean highlightSelectedConversations() {
1603		return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1604	}
1605}