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