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.net.Uri;
  14import android.os.Build;
  15import android.os.Bundle;
  16import android.provider.MediaStore;
  17import android.support.v4.widget.SlidingPaneLayout;
  18import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
  19import android.view.Menu;
  20import android.view.MenuItem;
  21import android.view.View;
  22import android.widget.AdapterView;
  23import android.widget.AdapterView.OnItemClickListener;
  24import android.widget.ArrayAdapter;
  25import android.widget.CheckBox;
  26import android.widget.PopupMenu;
  27import android.widget.PopupMenu.OnMenuItemClickListener;
  28import android.widget.Toast;
  29
  30import net.java.otr4j.session.SessionStatus;
  31import de.timroes.android.listview.EnhancedListView;
  32
  33import java.util.ArrayList;
  34import java.util.Iterator;
  35import java.util.List;
  36
  37import eu.siacs.conversations.R;
  38import eu.siacs.conversations.entities.Blockable;
  39import eu.siacs.conversations.entities.Contact;
  40import eu.siacs.conversations.entities.Conversation;
  41import eu.siacs.conversations.entities.Message;
  42import eu.siacs.conversations.services.XmppConnectionService.OnAccountUpdate;
  43import eu.siacs.conversations.services.XmppConnectionService.OnConversationUpdate;
  44import eu.siacs.conversations.services.XmppConnectionService.OnRosterUpdate;
  45import eu.siacs.conversations.ui.adapter.ConversationAdapter;
  46import eu.siacs.conversations.utils.ExceptionHelper;
  47import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
  48
  49public class ConversationActivity extends XmppActivity
  50	implements OnAccountUpdate, OnConversationUpdate, OnRosterUpdate, OnUpdateBlocklist {
  51
  52	public static final String ACTION_DOWNLOAD = "eu.siacs.conversations.action.DOWNLOAD";
  53
  54	public static final String VIEW_CONVERSATION = "viewConversation";
  55	public static final String CONVERSATION = "conversationUuid";
  56	public static final String MESSAGE = "messageUuid";
  57	public static final String TEXT = "text";
  58	public static final String NICK = "nick";
  59
  60	public static final int REQUEST_SEND_MESSAGE = 0x0201;
  61	public static final int REQUEST_DECRYPT_PGP = 0x0202;
  62	public static final int REQUEST_ENCRYPT_MESSAGE = 0x0207;
  63	public static final int ATTACHMENT_CHOICE_CHOOSE_IMAGE = 0x0301;
  64	public static final int ATTACHMENT_CHOICE_TAKE_PHOTO = 0x0302;
  65	public static final int ATTACHMENT_CHOICE_CHOOSE_FILE = 0x0303;
  66	public static final int ATTACHMENT_CHOICE_RECORD_VOICE = 0x0304;
  67	public static final int ATTACHMENT_CHOICE_LOCATION = 0x0305;
  68	private static final String STATE_OPEN_CONVERSATION = "state_open_conversation";
  69	private static final String STATE_PANEL_OPEN = "state_panel_open";
  70	private static final String STATE_PENDING_URI = "state_pending_uri";
  71
  72	private String mOpenConverstaion = null;
  73	private boolean mPanelOpen = true;
  74	final private List<Uri> mPendingImageUris = new ArrayList<>();
  75	final private List<Uri> mPendingFileUris = new ArrayList<>();
  76	private Uri mPendingGeoUri = null;
  77
  78	private View mContentView;
  79
  80	private List<Conversation> conversationList = new ArrayList<>();
  81	private Conversation swipedConversation = null;
  82	private Conversation mSelectedConversation = null;
  83	private EnhancedListView listView;
  84	private ConversationFragment mConversationFragment;
  85
  86	private ArrayAdapter<Conversation> listAdapter;
  87
  88	private Toast prepareFileToast;
  89
  90	private boolean mActivityPaused = false;
  91	private boolean mRedirected = true;
  92
  93	public Conversation getSelectedConversation() {
  94		return this.mSelectedConversation;
  95	}
  96
  97	public void setSelectedConversation(Conversation conversation) {
  98		this.mSelectedConversation = conversation;
  99	}
 100
 101	public void showConversationsOverview() {
 102		if (mContentView instanceof SlidingPaneLayout) {
 103			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 104			mSlidingPaneLayout.openPane();
 105		}
 106	}
 107
 108	@Override
 109	protected String getShareableUri() {
 110		Conversation conversation = getSelectedConversation();
 111		if (conversation != null) {
 112			return conversation.getAccount().getShareableUri();
 113		} else {
 114			return "";
 115		}
 116	}
 117
 118	public void hideConversationsOverview() {
 119		if (mContentView instanceof SlidingPaneLayout) {
 120			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 121			mSlidingPaneLayout.closePane();
 122		}
 123	}
 124
 125	public boolean isConversationsOverviewHideable() {
 126		if (mContentView instanceof SlidingPaneLayout) {
 127			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 128			return mSlidingPaneLayout.isSlideable();
 129		} else {
 130			return false;
 131		}
 132	}
 133
 134	public boolean isConversationsOverviewVisable() {
 135		if (mContentView instanceof SlidingPaneLayout) {
 136			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 137			return mSlidingPaneLayout.isOpen();
 138		} else {
 139			return true;
 140		}
 141	}
 142
 143	@Override
 144	protected void onCreate(final Bundle savedInstanceState) {
 145		super.onCreate(savedInstanceState);
 146		if (savedInstanceState != null) {
 147			mOpenConverstaion = savedInstanceState.getString(STATE_OPEN_CONVERSATION, null);
 148			mPanelOpen = savedInstanceState.getBoolean(STATE_PANEL_OPEN, true);
 149			String pending = savedInstanceState.getString(STATE_PENDING_URI, null);
 150			if (pending != null) {
 151				mPendingImageUris.clear();
 152				mPendingImageUris.add(Uri.parse(pending));
 153			}
 154		}
 155
 156		setContentView(R.layout.fragment_conversations_overview);
 157
 158		this.mConversationFragment = new ConversationFragment();
 159		FragmentTransaction transaction = getFragmentManager().beginTransaction();
 160		transaction.replace(R.id.selected_conversation, this.mConversationFragment, "conversation");
 161		transaction.commit();
 162
 163		listView = (EnhancedListView) findViewById(R.id.list);
 164		this.listAdapter = new ConversationAdapter(this, conversationList);
 165		listView.setAdapter(this.listAdapter);
 166
 167		if (getActionBar() != null) {
 168			getActionBar().setDisplayHomeAsUpEnabled(false);
 169			getActionBar().setHomeButtonEnabled(false);
 170		}
 171
 172		listView.setOnItemClickListener(new OnItemClickListener() {
 173
 174			@Override
 175			public void onItemClick(AdapterView<?> arg0, View clickedView,
 176					int position, long arg3) {
 177				if (getSelectedConversation() != conversationList.get(position)) {
 178					setSelectedConversation(conversationList.get(position));
 179					ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 180				}
 181				hideConversationsOverview();
 182				openConversation();
 183			}
 184		});
 185
 186		listView.setDismissCallback(new EnhancedListView.OnDismissCallback() {
 187
 188			@Override
 189			public EnhancedListView.Undoable onDismiss(final EnhancedListView enhancedListView, final int position) {
 190
 191				final int index = listView.getFirstVisiblePosition();
 192				View v = listView.getChildAt(0);
 193				final int top = (v == null) ? 0 : (v.getTop() - listView.getPaddingTop());
 194
 195				swipedConversation = listAdapter.getItem(position);
 196				listAdapter.remove(swipedConversation);
 197				swipedConversation.markRead();
 198				xmppConnectionService.getNotificationService().clear(swipedConversation);
 199
 200				final boolean formerlySelected = (getSelectedConversation() == swipedConversation);
 201				if (position == 0 && listAdapter.getCount() == 0) {
 202					endConversation(swipedConversation, false, true);
 203					return null;
 204				} else if (formerlySelected) {
 205					setSelectedConversation(listAdapter.getItem(0));
 206					ConversationActivity.this.mConversationFragment
 207							.reInit(getSelectedConversation());
 208				}
 209
 210				return new EnhancedListView.Undoable() {
 211
 212					@Override
 213					public void undo() {
 214						listAdapter.insert(swipedConversation, position);
 215						if (formerlySelected) {
 216							setSelectedConversation(swipedConversation);
 217							ConversationActivity.this.mConversationFragment
 218									.reInit(getSelectedConversation());
 219						}
 220						swipedConversation = null;
 221						listView.setSelectionFromTop(index + (listView.getChildCount() < position ? 1 : 0), top);
 222					}
 223
 224					@Override
 225					public void discard() {
 226						if (!swipedConversation.isRead()
 227								&& swipedConversation.getMode() == Conversation.MODE_SINGLE) {
 228							swipedConversation = null;
 229							return;
 230						}
 231						endConversation(swipedConversation, false, false);
 232						swipedConversation = null;
 233					}
 234
 235					@Override
 236					public String getTitle() {
 237						if (swipedConversation.getMode() == Conversation.MODE_MULTI) {
 238							return getResources().getString(R.string.title_undo_swipe_out_muc);
 239						} else {
 240							return getResources().getString(R.string.title_undo_swipe_out_conversation);
 241						}
 242					}
 243				};
 244			}
 245		});
 246		listView.enableSwipeToDismiss();
 247		listView.setSwipingLayout(R.id.swipeable_item);
 248		listView.setUndoStyle(EnhancedListView.UndoStyle.SINGLE_POPUP);
 249		listView.setUndoHideDelay(5000);
 250		listView.setRequireTouchBeforeDismiss(false);
 251
 252		mContentView = findViewById(R.id.content_view_spl);
 253		if (mContentView == null) {
 254			mContentView = findViewById(R.id.content_view_ll);
 255		}
 256		if (mContentView instanceof SlidingPaneLayout) {
 257			SlidingPaneLayout mSlidingPaneLayout = (SlidingPaneLayout) mContentView;
 258			mSlidingPaneLayout.setParallaxDistance(150);
 259			mSlidingPaneLayout
 260				.setShadowResource(R.drawable.es_slidingpane_shadow);
 261			mSlidingPaneLayout.setSliderFadeColor(0);
 262			mSlidingPaneLayout.setPanelSlideListener(new PanelSlideListener() {
 263
 264				@Override
 265				public void onPanelOpened(View arg0) {
 266					updateActionBarTitle();
 267					invalidateOptionsMenu();
 268					hideKeyboard();
 269					if (xmppConnectionServiceBound) {
 270						xmppConnectionService.getNotificationService()
 271							.setOpenConversation(null);
 272					}
 273					closeContextMenu();
 274				}
 275
 276				@Override
 277				public void onPanelClosed(View arg0) {
 278					listView.discardUndo();
 279					openConversation();
 280				}
 281
 282				@Override
 283				public void onPanelSlide(View arg0, float arg1) {
 284					// TODO Auto-generated method stub
 285
 286				}
 287			});
 288		}
 289	}
 290
 291	@Override
 292	public void switchToConversation(Conversation conversation) {
 293		setSelectedConversation(conversation);
 294		runOnUiThread(new Runnable() {
 295			@Override
 296			public void run() {
 297				ConversationActivity.this.mConversationFragment.reInit(getSelectedConversation());
 298				openConversation();
 299			}
 300		});
 301	}
 302
 303	private void updateActionBarTitle() {
 304		updateActionBarTitle(isConversationsOverviewHideable() && !isConversationsOverviewVisable());
 305	}
 306
 307	private void updateActionBarTitle(boolean titleShouldBeName) {
 308		final ActionBar ab = getActionBar();
 309		final Conversation conversation = getSelectedConversation();
 310		if (ab != null) {
 311			if (titleShouldBeName && conversation != null) {
 312				ab.setDisplayHomeAsUpEnabled(true);
 313				ab.setHomeButtonEnabled(true);
 314				if (conversation.getMode() == Conversation.MODE_SINGLE || useSubjectToIdentifyConference()) {
 315					ab.setTitle(conversation.getName());
 316				} else {
 317					ab.setTitle(conversation.getJid().toBareJid().toString());
 318				}
 319			} else {
 320				ab.setDisplayHomeAsUpEnabled(false);
 321				ab.setHomeButtonEnabled(false);
 322				ab.setTitle(R.string.app_name);
 323			}
 324		}
 325	}
 326
 327	private void openConversation() {
 328		this.updateActionBarTitle();
 329		this.invalidateOptionsMenu();
 330		if (xmppConnectionServiceBound) {
 331			final Conversation conversation = getSelectedConversation();
 332			xmppConnectionService.getNotificationService().setOpenConversation(conversation);
 333			sendReadMarkerIfNecessary(conversation);
 334		}
 335		listAdapter.notifyDataSetChanged();
 336	}
 337
 338	public void sendReadMarkerIfNecessary(final Conversation conversation) {
 339		if (!mActivityPaused && conversation != null) {
 340			if (!conversation.isRead()) {
 341				xmppConnectionService.sendReadMarker(conversation);
 342			} else {
 343				xmppConnectionService.markRead(conversation);
 344			}
 345		}
 346	}
 347
 348	@Override
 349	public boolean onCreateOptionsMenu(Menu menu) {
 350		getMenuInflater().inflate(R.menu.conversations, menu);
 351		final MenuItem menuSecure = menu.findItem(R.id.action_security);
 352		final MenuItem menuArchive = menu.findItem(R.id.action_archive);
 353		final MenuItem menuMucDetails = menu.findItem(R.id.action_muc_details);
 354		final MenuItem menuContactDetails = menu.findItem(R.id.action_contact_details);
 355		final MenuItem menuAttach = menu.findItem(R.id.action_attach_file);
 356		final MenuItem menuClearHistory = menu.findItem(R.id.action_clear_history);
 357		final MenuItem menuAdd = menu.findItem(R.id.action_add);
 358		final MenuItem menuInviteContact = menu.findItem(R.id.action_invite);
 359		final MenuItem menuMute = menu.findItem(R.id.action_mute);
 360		final MenuItem menuUnmute = menu.findItem(R.id.action_unmute);
 361
 362		if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
 363			menuArchive.setVisible(false);
 364			menuMucDetails.setVisible(false);
 365			menuContactDetails.setVisible(false);
 366			menuSecure.setVisible(false);
 367			menuInviteContact.setVisible(false);
 368			menuAttach.setVisible(false);
 369			menuClearHistory.setVisible(false);
 370			menuMute.setVisible(false);
 371			menuUnmute.setVisible(false);
 372		} else {
 373			menuAdd.setVisible(!isConversationsOverviewHideable());
 374			if (this.getSelectedConversation() != null) {
 375				if (this.getSelectedConversation().getLatestMessage()
 376						.getEncryption() != Message.ENCRYPTION_NONE) {
 377					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 378						menuSecure.setIcon(R.drawable.ic_lock_white_24dp);
 379					} else {
 380						menuSecure.setIcon(R.drawable.ic_action_secure);
 381					}
 382				}
 383				if (this.getSelectedConversation().getMode() == Conversation.MODE_MULTI) {
 384					menuContactDetails.setVisible(false);
 385					menuAttach.setVisible(false);
 386					menuInviteContact.setVisible(getSelectedConversation().getMucOptions().canInvite());
 387				} else {
 388					menuMucDetails.setVisible(false);
 389				}
 390				if (this.getSelectedConversation().isMuted()) {
 391					menuMute.setVisible(false);
 392				} else {
 393					menuUnmute.setVisible(false);
 394				}
 395			}
 396		}
 397		return true;
 398	}
 399
 400	private void selectPresenceToAttachFile(final int attachmentChoice, final int encryption) {
 401		final OnPresenceSelected callback = new OnPresenceSelected() {
 402
 403			@Override
 404			public void onPresenceSelected() {
 405				Intent intent = new Intent();
 406				boolean chooser = false;
 407				String fallbackPackageId = null;
 408				switch (attachmentChoice) {
 409					case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 410						intent.setAction(Intent.ACTION_GET_CONTENT);
 411						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
 412							intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true);
 413						}
 414						intent.setType("image/*");
 415						chooser = true;
 416						break;
 417					case ATTACHMENT_CHOICE_TAKE_PHOTO:
 418						Uri uri = xmppConnectionService.getFileBackend().getTakePhotoUri();
 419						intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 420						intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
 421						mPendingImageUris.clear();
 422						mPendingImageUris.add(uri);
 423						break;
 424					case ATTACHMENT_CHOICE_CHOOSE_FILE:
 425						chooser = true;
 426						intent.setType("*/*");
 427						intent.addCategory(Intent.CATEGORY_OPENABLE);
 428						intent.setAction(Intent.ACTION_GET_CONTENT);
 429						break;
 430					case ATTACHMENT_CHOICE_RECORD_VOICE:
 431						intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
 432						fallbackPackageId = "eu.siacs.conversations.voicerecorder";
 433						break;
 434					case ATTACHMENT_CHOICE_LOCATION:
 435						intent.setAction("eu.siacs.conversations.location.request");
 436						fallbackPackageId = "eu.siacs.conversations.sharelocation";
 437						break;
 438				}
 439				if (intent.resolveActivity(getPackageManager()) != null) {
 440					if (chooser) {
 441						startActivityForResult(
 442								Intent.createChooser(intent, getString(R.string.perform_action_with)),
 443								attachmentChoice);
 444					} else {
 445						startActivityForResult(intent, attachmentChoice);
 446					}
 447				} else if (fallbackPackageId != null) {
 448					startActivity(getInstallApkIntent(fallbackPackageId));
 449				}
 450			}
 451		};
 452		if (attachmentChoice == ATTACHMENT_CHOICE_LOCATION && encryption != Message.ENCRYPTION_OTR) {
 453			getSelectedConversation().setNextCounterpart(null);
 454			callback.onPresenceSelected();
 455		} else {
 456			selectPresence(getSelectedConversation(),callback);
 457		}
 458	}
 459
 460	private Intent getInstallApkIntent(final String packageId) {
 461		Intent intent = new Intent(Intent.ACTION_VIEW);
 462		intent.setData(Uri.parse("market://details?id="+packageId));
 463		if (intent.resolveActivity(getPackageManager()) != null) {
 464			return intent;
 465		} else {
 466			intent.setData(Uri.parse("http://play.google.com/store/apps/details?id="+packageId));
 467			return intent;
 468		}
 469	}
 470
 471	public void attachFile(final int attachmentChoice) {
 472		switch (attachmentChoice) {
 473			case ATTACHMENT_CHOICE_LOCATION:
 474				getPreferences().edit().putString("recently_used_quick_action","location").apply();
 475				break;
 476			case ATTACHMENT_CHOICE_RECORD_VOICE:
 477				getPreferences().edit().putString("recently_used_quick_action","voice").apply();
 478				break;
 479			case ATTACHMENT_CHOICE_TAKE_PHOTO:
 480				getPreferences().edit().putString("recently_used_quick_action","photo").apply();
 481				break;
 482			case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
 483				getPreferences().edit().putString("recently_used_quick_action","picture").apply();
 484				break;
 485		}
 486		final Conversation conversation = getSelectedConversation();
 487		final int encryption = conversation.getNextEncryption(forceEncryption());
 488		if (encryption == Message.ENCRYPTION_PGP) {
 489			if (hasPgp()) {
 490				if (conversation.getContact().getPgpKeyId() != 0) {
 491					xmppConnectionService.getPgpEngine().hasKey(
 492							conversation.getContact(),
 493							new UiCallback<Contact>() {
 494
 495								@Override
 496								public void userInputRequried(PendingIntent pi,
 497										Contact contact) {
 498									ConversationActivity.this.runIntent(pi,attachmentChoice);
 499								}
 500
 501								@Override
 502								public void success(Contact contact) {
 503									selectPresenceToAttachFile(attachmentChoice,encryption);
 504								}
 505
 506								@Override
 507								public void error(int error, Contact contact) {
 508									displayErrorDialog(error);
 509								}
 510							});
 511				} else {
 512					final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 513						.findFragmentByTag("conversation");
 514					if (fragment != null) {
 515						fragment.showNoPGPKeyDialog(false,
 516								new OnClickListener() {
 517
 518									@Override
 519									public void onClick(DialogInterface dialog,
 520											int which) {
 521										conversation
 522											.setNextEncryption(Message.ENCRYPTION_NONE);
 523										xmppConnectionService.databaseBackend
 524											.updateConversation(conversation);
 525										selectPresenceToAttachFile(attachmentChoice,Message.ENCRYPTION_NONE);
 526									}
 527								});
 528					}
 529				}
 530			} else {
 531				showInstallPgpDialog();
 532			}
 533		} else {
 534			selectPresenceToAttachFile(attachmentChoice,encryption);
 535		}
 536	}
 537
 538	@Override
 539	public boolean onOptionsItemSelected(final MenuItem item) {
 540		if (item.getItemId() == android.R.id.home) {
 541			showConversationsOverview();
 542			return true;
 543		} else if (item.getItemId() == R.id.action_add) {
 544			startActivity(new Intent(this, StartConversationActivity.class));
 545			return true;
 546		} else if (getSelectedConversation() != null) {
 547			switch (item.getItemId()) {
 548				case R.id.action_attach_file:
 549					attachFileDialog();
 550					break;
 551				case R.id.action_archive:
 552					this.endConversation(getSelectedConversation());
 553					break;
 554				case R.id.action_contact_details:
 555					switchToContactDetails(getSelectedConversation().getContact());
 556					break;
 557				case R.id.action_muc_details:
 558					Intent intent = new Intent(this,
 559							ConferenceDetailsActivity.class);
 560					intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 561					intent.putExtra("uuid", getSelectedConversation().getUuid());
 562					startActivity(intent);
 563					break;
 564				case R.id.action_invite:
 565					inviteToConversation(getSelectedConversation());
 566					break;
 567				case R.id.action_security:
 568					selectEncryptionDialog(getSelectedConversation());
 569					break;
 570				case R.id.action_clear_history:
 571					clearHistoryDialog(getSelectedConversation());
 572					break;
 573				case R.id.action_mute:
 574					muteConversationDialog(getSelectedConversation());
 575					break;
 576				case R.id.action_unmute:
 577					unmuteConversation(getSelectedConversation());
 578					break;
 579				case R.id.action_block:
 580					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 581					break;
 582				case R.id.action_unblock:
 583					BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
 584					break;
 585				default:
 586					break;
 587			}
 588			return super.onOptionsItemSelected(item);
 589		} else {
 590			return super.onOptionsItemSelected(item);
 591		}
 592	}
 593
 594	public void endConversation(Conversation conversation) {
 595		endConversation(conversation, true, true);
 596	}
 597
 598	public void endConversation(Conversation conversation, boolean showOverview, boolean reinit) {
 599		if (showOverview) {
 600			showConversationsOverview();
 601		}
 602		xmppConnectionService.archiveConversation(conversation);
 603		if (reinit) {
 604			if (conversationList.size() > 0) {
 605				setSelectedConversation(conversationList.get(0));
 606				this.mConversationFragment.reInit(getSelectedConversation());
 607			} else {
 608				setSelectedConversation(null);
 609			}
 610		}
 611	}
 612
 613	@SuppressLint("InflateParams")
 614	protected void clearHistoryDialog(final Conversation conversation) {
 615		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 616		builder.setTitle(getString(R.string.clear_conversation_history));
 617		View dialogView = getLayoutInflater().inflate(
 618				R.layout.dialog_clear_history, null);
 619		final CheckBox endConversationCheckBox = (CheckBox) dialogView
 620			.findViewById(R.id.end_conversation_checkbox);
 621		builder.setView(dialogView);
 622		builder.setNegativeButton(getString(R.string.cancel), null);
 623		builder.setPositiveButton(getString(R.string.delete_messages),
 624				new OnClickListener() {
 625
 626					@Override
 627					public void onClick(DialogInterface dialog, int which) {
 628						ConversationActivity.this.xmppConnectionService.clearConversationHistory(conversation);
 629						if (endConversationCheckBox.isChecked()) {
 630							endConversation(conversation);
 631						} else {
 632							updateConversationList();
 633							ConversationActivity.this.mConversationFragment.updateMessages();
 634						}
 635					}
 636				});
 637		builder.create().show();
 638	}
 639
 640	protected void attachFileDialog() {
 641		View menuAttachFile = findViewById(R.id.action_attach_file);
 642		if (menuAttachFile == null) {
 643			return;
 644		}
 645		PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
 646		attachFilePopup.inflate(R.menu.attachment_choices);
 647		if (new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) == null) {
 648			attachFilePopup.getMenu().findItem(R.id.attach_record_voice).setVisible(false);
 649		}
 650		if (new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) == null) {
 651			attachFilePopup.getMenu().findItem(R.id.attach_location).setVisible(false);
 652		}
 653		attachFilePopup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 654
 655			@Override
 656			public boolean onMenuItemClick(MenuItem item) {
 657				switch (item.getItemId()) {
 658					case R.id.attach_choose_picture:
 659						attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
 660						break;
 661					case R.id.attach_take_picture:
 662						attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
 663						break;
 664					case R.id.attach_choose_file:
 665						attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
 666						break;
 667					case R.id.attach_record_voice:
 668						attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
 669						break;
 670					case R.id.attach_location:
 671						attachFile(ATTACHMENT_CHOICE_LOCATION);
 672						break;
 673				}
 674				return false;
 675			}
 676		});
 677		attachFilePopup.show();
 678	}
 679
 680	public void verifyOtrSessionDialog(final Conversation conversation, View view) {
 681		if (!conversation.hasValidOtrSession() || conversation.getOtrSession().getSessionStatus() != SessionStatus.ENCRYPTED) {
 682			Toast.makeText(this, R.string.otr_session_not_started, Toast.LENGTH_LONG).show();
 683			return;
 684		}
 685		if (view == null) {
 686			return;
 687		}
 688		PopupMenu popup = new PopupMenu(this, view);
 689		popup.inflate(R.menu.verification_choices);
 690		popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 691			@Override
 692			public boolean onMenuItemClick(MenuItem menuItem) {
 693				Intent intent = new Intent(ConversationActivity.this, VerifyOTRActivity.class);
 694				intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 695				intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 696				intent.putExtra("account", conversation.getAccount().getJid().toBareJid().toString());
 697				switch (menuItem.getItemId()) {
 698					case R.id.scan_fingerprint:
 699						intent.putExtra("mode",VerifyOTRActivity.MODE_SCAN_FINGERPRINT);
 700						break;
 701					case R.id.ask_question:
 702						intent.putExtra("mode",VerifyOTRActivity.MODE_ASK_QUESTION);
 703						break;
 704					case R.id.manual_verification:
 705						intent.putExtra("mode",VerifyOTRActivity.MODE_MANUAL_VERIFICATION);
 706						break;
 707				}
 708				startActivity(intent);
 709				return true;
 710			}
 711		});
 712		popup.show();
 713	}
 714
 715	protected void selectEncryptionDialog(final Conversation conversation) {
 716		View menuItemView = findViewById(R.id.action_security);
 717		if (menuItemView == null) {
 718			return;
 719		}
 720		PopupMenu popup = new PopupMenu(this, menuItemView);
 721		final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
 722			.findFragmentByTag("conversation");
 723		if (fragment != null) {
 724			popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
 725
 726				@Override
 727				public boolean onMenuItemClick(MenuItem item) {
 728					switch (item.getItemId()) {
 729						case R.id.encryption_choice_none:
 730							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 731							item.setChecked(true);
 732							break;
 733						case R.id.encryption_choice_otr:
 734							conversation.setNextEncryption(Message.ENCRYPTION_OTR);
 735							item.setChecked(true);
 736							break;
 737						case R.id.encryption_choice_pgp:
 738							if (hasPgp()) {
 739								if (conversation.getAccount().getKeys()
 740										.has("pgp_signature")) {
 741									conversation
 742										.setNextEncryption(Message.ENCRYPTION_PGP);
 743									item.setChecked(true);
 744								} else {
 745									announcePgp(conversation.getAccount(),
 746											conversation);
 747								}
 748							} else {
 749								showInstallPgpDialog();
 750							}
 751							break;
 752						default:
 753							conversation.setNextEncryption(Message.ENCRYPTION_NONE);
 754							break;
 755					}
 756					xmppConnectionService.databaseBackend
 757						.updateConversation(conversation);
 758					fragment.updateChatMsgHint();
 759					return true;
 760				}
 761			});
 762			popup.inflate(R.menu.encryption_choices);
 763			MenuItem otr = popup.getMenu().findItem(R.id.encryption_choice_otr);
 764			MenuItem none = popup.getMenu().findItem(
 765					R.id.encryption_choice_none);
 766			if (conversation.getMode() == Conversation.MODE_MULTI) {
 767				otr.setEnabled(false);
 768			} else {
 769				if (forceEncryption()) {
 770					none.setVisible(false);
 771				}
 772			}
 773			switch (conversation.getNextEncryption(forceEncryption())) {
 774				case Message.ENCRYPTION_NONE:
 775					none.setChecked(true);
 776					break;
 777				case Message.ENCRYPTION_OTR:
 778					otr.setChecked(true);
 779					break;
 780				case Message.ENCRYPTION_PGP:
 781					popup.getMenu().findItem(R.id.encryption_choice_pgp)
 782						.setChecked(true);
 783					break;
 784				default:
 785					popup.getMenu().findItem(R.id.encryption_choice_none)
 786						.setChecked(true);
 787					break;
 788			}
 789			popup.show();
 790		}
 791	}
 792
 793	protected void muteConversationDialog(final Conversation conversation) {
 794		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 795		builder.setTitle(R.string.disable_notifications);
 796		final int[] durations = getResources().getIntArray(
 797				R.array.mute_options_durations);
 798		builder.setItems(R.array.mute_options_descriptions,
 799				new OnClickListener() {
 800
 801					@Override
 802					public void onClick(final DialogInterface dialog, final int which) {
 803						final long till;
 804						if (durations[which] == -1) {
 805							till = Long.MAX_VALUE;
 806						} else {
 807							till = System.currentTimeMillis() + (durations[which] * 1000);
 808						}
 809						conversation.setMutedTill(till);
 810						ConversationActivity.this.xmppConnectionService.databaseBackend
 811							.updateConversation(conversation);
 812						updateConversationList();
 813						ConversationActivity.this.mConversationFragment.updateMessages();
 814						invalidateOptionsMenu();
 815					}
 816				});
 817		builder.create().show();
 818	}
 819
 820	public void unmuteConversation(final Conversation conversation) {
 821		conversation.setMutedTill(0);
 822		this.xmppConnectionService.databaseBackend.updateConversation(conversation);
 823		updateConversationList();
 824		ConversationActivity.this.mConversationFragment.updateMessages();
 825		invalidateOptionsMenu();
 826	}
 827
 828	@Override
 829	public void onBackPressed() {
 830		if (!isConversationsOverviewVisable()) {
 831			showConversationsOverview();
 832		} else {
 833			moveTaskToBack(true);
 834		}
 835	}
 836
 837	@Override
 838	protected void onNewIntent(final Intent intent) {
 839		if (xmppConnectionServiceBound) {
 840			if (intent != null && VIEW_CONVERSATION.equals(intent.getType())) {
 841				handleViewConversationIntent(intent);
 842			}
 843		} else {
 844			setIntent(intent);
 845		}
 846	}
 847
 848	@Override
 849	public void onStart() {
 850		super.onStart();
 851		this.mRedirected = false;
 852		if (this.xmppConnectionServiceBound) {
 853			this.onBackendConnected();
 854		}
 855		if (conversationList.size() >= 1) {
 856			this.onConversationUpdate();
 857		}
 858	}
 859
 860	@Override
 861	public void onPause() {
 862		listView.discardUndo();
 863		super.onPause();
 864		this.mActivityPaused = true;
 865		if (this.xmppConnectionServiceBound) {
 866			this.xmppConnectionService.getNotificationService().setIsInForeground(false);
 867		}
 868	}
 869
 870	@Override
 871	public void onResume() {
 872		super.onResume();
 873		final int theme = findTheme();
 874		final boolean usingEnterKey = usingEnterKey();
 875		if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
 876			recreate();
 877		}
 878		this.mActivityPaused = false;
 879		if (this.xmppConnectionServiceBound) {
 880			this.xmppConnectionService.getNotificationService().setIsInForeground(true);
 881		}
 882
 883		if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
 884			sendReadMarkerIfNecessary(getSelectedConversation());
 885		}
 886
 887	}
 888
 889	@Override
 890	public void onSaveInstanceState(final Bundle savedInstanceState) {
 891		Conversation conversation = getSelectedConversation();
 892		if (conversation != null) {
 893			savedInstanceState.putString(STATE_OPEN_CONVERSATION,
 894					conversation.getUuid());
 895		}
 896		savedInstanceState.putBoolean(STATE_PANEL_OPEN,
 897				isConversationsOverviewVisable());
 898		if (this.mPendingImageUris.size() >= 1) {
 899			savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
 900		}
 901		super.onSaveInstanceState(savedInstanceState);
 902	}
 903
 904	@Override
 905	void onBackendConnected() {
 906		this.xmppConnectionService.getNotificationService().setIsInForeground(true);
 907		updateConversationList();
 908
 909		if (mPendingConferenceInvite != null) {
 910			mPendingConferenceInvite.execute(this);
 911			mPendingConferenceInvite = null;
 912		}
 913
 914		if (xmppConnectionService.getAccounts().size() == 0) {
 915			if (!mRedirected) {
 916				this.mRedirected = true;
 917				startActivity(new Intent(this, EditAccountActivity.class));
 918				finish();
 919			}
 920		} else if (conversationList.size() <= 0) {
 921			if (!mRedirected) {
 922				this.mRedirected = true;
 923				Intent intent = new Intent(this, StartConversationActivity.class);
 924				intent.putExtra("init",true);
 925				startActivity(intent);
 926				finish();
 927			}
 928		} else if (getIntent() != null && VIEW_CONVERSATION.equals(getIntent().getType())) {
 929			handleViewConversationIntent(getIntent());
 930		} else if (selectConversationByUuid(mOpenConverstaion)) {
 931			if (mPanelOpen) {
 932				showConversationsOverview();
 933			} else {
 934				if (isConversationsOverviewHideable()) {
 935					openConversation();
 936				}
 937			}
 938			this.mConversationFragment.reInit(getSelectedConversation());
 939			mOpenConverstaion = null;
 940		} else if (getSelectedConversation() == null) {
 941			showConversationsOverview();
 942			mPendingImageUris.clear();
 943			mPendingFileUris.clear();
 944			mPendingGeoUri = null;
 945			setSelectedConversation(conversationList.get(0));
 946			this.mConversationFragment.reInit(getSelectedConversation());
 947		}
 948
 949		for(Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
 950			attachImageToConversation(getSelectedConversation(),i.next());
 951		}
 952
 953		for(Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
 954			attachFileToConversation(getSelectedConversation(),i.next());
 955		}
 956
 957		if (mPendingGeoUri != null) {
 958			attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
 959			mPendingGeoUri = null;
 960		}
 961		ExceptionHelper.checkForCrash(this, this.xmppConnectionService);
 962		setIntent(new Intent());
 963	}
 964
 965	private void handleViewConversationIntent(final Intent intent) {
 966		final String uuid = intent.getStringExtra(CONVERSATION);
 967		final String downloadUuid = intent.getStringExtra(MESSAGE);
 968		final String text = intent.getStringExtra(TEXT);
 969		final String nick = intent.getStringExtra(NICK);
 970		if (selectConversationByUuid(uuid)) {
 971			this.mConversationFragment.reInit(getSelectedConversation());
 972			if (nick != null) {
 973				this.mConversationFragment.highlightInConference(nick);
 974			} else {
 975				this.mConversationFragment.appendText(text);
 976			}
 977			hideConversationsOverview();
 978			openConversation();
 979			if (mContentView instanceof SlidingPaneLayout) {
 980				updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
 981			}
 982			if (downloadUuid != null) {
 983				final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
 984				if (message != null) {
 985					mConversationFragment.messageListAdapter.startDownloadable(message);
 986				}
 987			}
 988		}
 989	}
 990
 991	private boolean selectConversationByUuid(String uuid) {
 992		if (uuid == null) {
 993			return false;
 994		}
 995		for (Conversation aConversationList : conversationList) {
 996			if (aConversationList.getUuid().equals(uuid)) {
 997				setSelectedConversation(aConversationList);
 998				return true;
 999			}
1000		}
1001		return false;
1002	}
1003
1004	@Override
1005	protected void unregisterListeners() {
1006		super.unregisterListeners();
1007		xmppConnectionService.getNotificationService().setOpenConversation(null);
1008	}
1009
1010	@SuppressLint("NewApi")
1011	private static List<Uri> extractUriFromIntent(final Intent intent) {
1012		List<Uri> uris = new ArrayList<>();
1013		Uri uri = intent.getData();
1014		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1015			ClipData clipData = intent.getClipData();
1016			for(int i = 0; i < clipData.getItemCount(); ++i) {
1017				uris.add(clipData.getItemAt(i).getUri());
1018			}
1019		} else {
1020			uris.add(uri);
1021		}
1022		return uris;
1023	}
1024
1025	@Override
1026	protected void onActivityResult(int requestCode, int resultCode,
1027			final Intent data) {
1028		super.onActivityResult(requestCode, resultCode, data);
1029		if (resultCode == RESULT_OK) {
1030			if (requestCode == REQUEST_DECRYPT_PGP) {
1031				mConversationFragment.hideSnackbar();
1032				mConversationFragment.updateMessages();
1033			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1034				mPendingImageUris.clear();
1035				mPendingImageUris.addAll(extractUriFromIntent(data));
1036				if (xmppConnectionServiceBound) {
1037					for(Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1038						attachImageToConversation(getSelectedConversation(),i.next());
1039					}
1040				}
1041			} else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1042				mPendingFileUris.clear();
1043				mPendingFileUris.addAll(extractUriFromIntent(data));
1044				if (xmppConnectionServiceBound) {
1045					for(Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1046						attachFileToConversation(getSelectedConversation(), i.next());
1047					}
1048				}
1049			} else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1050				if (mPendingImageUris.size() == 1) {
1051					Uri uri = mPendingImageUris.get(0);
1052					if (xmppConnectionServiceBound) {
1053						attachImageToConversation(getSelectedConversation(), uri);
1054						mPendingImageUris.clear();
1055					}
1056					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1057					intent.setData(uri);
1058					sendBroadcast(intent);
1059				} else {
1060					mPendingImageUris.clear();
1061				}
1062			} else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1063				double latitude = data.getDoubleExtra("latitude",0);
1064				double longitude = data.getDoubleExtra("longitude",0);
1065				this.mPendingGeoUri = Uri.parse("geo:"+String.valueOf(latitude)+","+String.valueOf(longitude));
1066				if (xmppConnectionServiceBound) {
1067					attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1068					this.mPendingGeoUri = null;
1069				}
1070			}
1071		} else {
1072			mPendingImageUris.clear();
1073			mPendingFileUris.clear();
1074		}
1075	}
1076
1077	private void attachLocationToConversation(Conversation conversation, Uri uri) {
1078		xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1079
1080			@Override
1081			public void success(Message message) {
1082				xmppConnectionService.sendMessage(message);
1083			}
1084
1085			@Override
1086			public void error(int errorCode, Message object) {
1087
1088			}
1089
1090			@Override
1091			public void userInputRequried(PendingIntent pi, Message object) {
1092
1093			}
1094		});
1095	}
1096
1097	private void attachFileToConversation(Conversation conversation, Uri uri) {
1098		prepareFileToast = Toast.makeText(getApplicationContext(),
1099				getText(R.string.preparing_file), Toast.LENGTH_LONG);
1100		prepareFileToast.show();
1101		xmppConnectionService.attachFileToConversation(conversation,uri, new UiCallback<Message>() {
1102			@Override
1103			public void success(Message message) {
1104				hidePrepareFileToast();
1105				xmppConnectionService.sendMessage(message);
1106			}
1107
1108			@Override
1109			public void error(int errorCode, Message message) {
1110				displayErrorDialog(errorCode);
1111			}
1112
1113			@Override
1114			public void userInputRequried(PendingIntent pi, Message message) {
1115
1116			}
1117		});
1118	}
1119
1120	private void attachImageToConversation(Conversation conversation, Uri uri) {
1121		prepareFileToast = Toast.makeText(getApplicationContext(),
1122				getText(R.string.preparing_image), Toast.LENGTH_LONG);
1123		prepareFileToast.show();
1124		xmppConnectionService.attachImageToConversation(conversation, uri,
1125				new UiCallback<Message>() {
1126
1127					@Override
1128					public void userInputRequried(PendingIntent pi,
1129							Message object) {
1130						hidePrepareFileToast();
1131					}
1132
1133					@Override
1134					public void success(Message message) {
1135						xmppConnectionService.sendMessage(message);
1136					}
1137
1138					@Override
1139					public void error(int error, Message message) {
1140						hidePrepareFileToast();
1141						displayErrorDialog(error);
1142					}
1143				});
1144	}
1145
1146	private void hidePrepareFileToast() {
1147		if (prepareFileToast != null) {
1148			runOnUiThread(new Runnable() {
1149
1150				@Override
1151				public void run() {
1152					prepareFileToast.cancel();
1153				}
1154			});
1155		}
1156	}
1157
1158	public void updateConversationList() {
1159		xmppConnectionService
1160			.populateWithOrderedConversations(conversationList);
1161		if (swipedConversation != null) {
1162			if (swipedConversation.isRead()) {
1163				conversationList.remove(swipedConversation);
1164			} else {
1165				listView.discardUndo();
1166			}
1167		}
1168		listAdapter.notifyDataSetChanged();
1169	}
1170
1171	public void runIntent(PendingIntent pi, int requestCode) {
1172		try {
1173			this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1174					null, 0, 0, 0);
1175		} catch (final SendIntentException ignored) {
1176		}
1177	}
1178
1179	public void encryptTextMessage(Message message) {
1180		xmppConnectionService.getPgpEngine().encrypt(message,
1181				new UiCallback<Message>() {
1182
1183					@Override
1184					public void userInputRequried(PendingIntent pi,
1185							Message message) {
1186						ConversationActivity.this.runIntent(pi,
1187								ConversationActivity.REQUEST_SEND_MESSAGE);
1188					}
1189
1190					@Override
1191					public void success(Message message) {
1192						message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1193						xmppConnectionService.sendMessage(message);
1194					}
1195
1196					@Override
1197					public void error(int error, Message message) {
1198
1199					}
1200				});
1201	}
1202
1203	public boolean forceEncryption() {
1204		return getPreferences().getBoolean("force_encryption", false);
1205	}
1206
1207	public boolean useSendButtonToIndicateStatus() {
1208		return getPreferences().getBoolean("send_button_status", false);
1209	}
1210
1211	public boolean indicateReceived() {
1212		return getPreferences().getBoolean("indicate_received", false);
1213	}
1214
1215	@Override
1216	protected void refreshUiReal() {
1217		updateConversationList();
1218		if (xmppConnectionService != null && xmppConnectionService.getAccounts().size() == 0) {
1219			if (!mRedirected) {
1220				this.mRedirected = true;
1221				startActivity(new Intent(this, EditAccountActivity.class));
1222				finish();
1223			}
1224		} else if (conversationList.size() == 0) {
1225			if (!mRedirected) {
1226				this.mRedirected = true;
1227				Intent intent = new Intent(this, StartConversationActivity.class);
1228				intent.putExtra("init",true);
1229				startActivity(intent);
1230				finish();
1231			}
1232		} else {
1233			ConversationActivity.this.mConversationFragment.updateMessages();
1234			updateActionBarTitle();
1235		}
1236	}
1237
1238	@Override
1239	public void onAccountUpdate() {
1240		this.refreshUi();
1241	}
1242
1243	@Override
1244	public void onConversationUpdate() {
1245		this.refreshUi();
1246	}
1247
1248	@Override
1249	public void onRosterUpdate() {
1250		this.refreshUi();
1251	}
1252
1253	@Override
1254	public void OnUpdateBlocklist(Status status) {
1255		this.refreshUi();
1256		runOnUiThread(new Runnable() {
1257			@Override
1258			public void run() {
1259				invalidateOptionsMenu();
1260			}
1261		});
1262	}
1263
1264	public void unblockConversation(final Blockable conversation) {
1265		xmppConnectionService.sendUnblockRequest(conversation);
1266	}
1267
1268	public boolean enterIsSend() {
1269		return getPreferences().getBoolean("enter_is_send",false);
1270	}
1271}