ConversationFragment.java

   1package eu.siacs.conversations.ui;
   2
   3import android.app.AlertDialog;
   4import android.app.Fragment;
   5import android.app.PendingIntent;
   6import android.content.Context;
   7import android.content.DialogInterface;
   8import android.content.Intent;
   9import android.content.IntentSender;
  10import android.content.IntentSender.SendIntentException;
  11import android.os.Bundle;
  12import android.text.InputType;
  13import android.view.ContextMenu;
  14import android.view.ContextMenu.ContextMenuInfo;
  15import android.view.Gravity;
  16import android.view.KeyEvent;
  17import android.view.LayoutInflater;
  18import android.view.MenuItem;
  19import android.view.View;
  20import android.view.View.OnClickListener;
  21import android.view.ViewGroup;
  22import android.view.inputmethod.EditorInfo;
  23import android.view.inputmethod.InputMethodManager;
  24import android.widget.AbsListView;
  25import android.widget.AbsListView.OnScrollListener;
  26import android.widget.AdapterView;
  27import android.widget.AdapterView.AdapterContextMenuInfo;
  28import android.widget.ImageButton;
  29import android.widget.ListView;
  30import android.widget.RelativeLayout;
  31import android.widget.TextView;
  32import android.widget.TextView.OnEditorActionListener;
  33import android.widget.Toast;
  34
  35import net.java.otr4j.session.SessionStatus;
  36
  37import java.net.URLConnection;
  38import java.util.ArrayList;
  39import java.util.List;
  40import java.util.NoSuchElementException;
  41import java.util.concurrent.ConcurrentLinkedQueue;
  42
  43import eu.siacs.conversations.Config;
  44import eu.siacs.conversations.R;
  45import eu.siacs.conversations.crypto.PgpEngine;
  46import eu.siacs.conversations.entities.Account;
  47import eu.siacs.conversations.entities.Contact;
  48import eu.siacs.conversations.entities.Conversation;
  49import eu.siacs.conversations.entities.Downloadable;
  50import eu.siacs.conversations.entities.DownloadableFile;
  51import eu.siacs.conversations.entities.DownloadablePlaceholder;
  52import eu.siacs.conversations.entities.Message;
  53import eu.siacs.conversations.entities.MucOptions;
  54import eu.siacs.conversations.entities.Presences;
  55import eu.siacs.conversations.services.XmppConnectionService;
  56import eu.siacs.conversations.ui.XmppActivity.OnPresenceSelected;
  57import eu.siacs.conversations.ui.XmppActivity.OnValueEdited;
  58import eu.siacs.conversations.ui.adapter.MessageAdapter;
  59import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureClicked;
  60import eu.siacs.conversations.ui.adapter.MessageAdapter.OnContactPictureLongClicked;
  61import eu.siacs.conversations.utils.GeoHelper;
  62import eu.siacs.conversations.utils.UIHelper;
  63import eu.siacs.conversations.xmpp.chatstate.ChatState;
  64import eu.siacs.conversations.xmpp.jid.Jid;
  65
  66public class ConversationFragment extends Fragment implements EditMessage.KeyboardListener {
  67
  68	protected Conversation conversation;
  69	private OnClickListener leaveMuc = new OnClickListener() {
  70
  71		@Override
  72		public void onClick(View v) {
  73			activity.endConversation(conversation);
  74		}
  75	};
  76	private OnClickListener joinMuc = new OnClickListener() {
  77
  78		@Override
  79		public void onClick(View v) {
  80			activity.xmppConnectionService.joinMuc(conversation);
  81		}
  82	};
  83	private OnClickListener enterPassword = new OnClickListener() {
  84
  85		@Override
  86		public void onClick(View v) {
  87			MucOptions muc = conversation.getMucOptions();
  88			String password = muc.getPassword();
  89			if (password == null) {
  90				password = "";
  91			}
  92			activity.quickPasswordEdit(password, new OnValueEdited() {
  93
  94				@Override
  95				public void onValueEdited(String value) {
  96					activity.xmppConnectionService.providePasswordForMuc(
  97							conversation, value);
  98				}
  99			});
 100		}
 101	};
 102	protected ListView messagesView;
 103	final protected List<Message> messageList = new ArrayList<>();
 104	protected MessageAdapter messageListAdapter;
 105	private EditMessage mEditMessage;
 106	private ImageButton mSendButton;
 107	private RelativeLayout snackbar;
 108	private TextView snackbarMessage;
 109	private TextView snackbarAction;
 110	private boolean messagesLoaded = true;
 111	private Toast messageLoaderToast;
 112
 113	private OnScrollListener mOnScrollListener = new OnScrollListener() {
 114
 115		@Override
 116		public void onScrollStateChanged(AbsListView view, int scrollState) {
 117			// TODO Auto-generated method stub
 118
 119		}
 120
 121		private int getIndexOf(String uuid, List<Message> messages) {
 122			if (uuid == null) {
 123				return 0;
 124			}
 125			for(int i = 0; i < messages.size(); ++i) {
 126				if (uuid.equals(messages.get(i).getUuid())) {
 127					return i;
 128				} else {
 129					Message next = messages.get(i);
 130					while(next != null && next.wasMergedIntoPrevious()) {
 131						if (uuid.equals(next.getUuid())) {
 132							return i;
 133						}
 134						next = next.next();
 135					}
 136
 137				}
 138			}
 139			return 0;
 140		}
 141
 142		@Override
 143		public void onScroll(AbsListView view, int firstVisibleItem,
 144							 int visibleItemCount, int totalItemCount) {
 145			synchronized (ConversationFragment.this.messageList) {
 146				if (firstVisibleItem < 5 && messagesLoaded && messageList.size() > 0) {
 147					long timestamp = ConversationFragment.this.messageList.get(0).getTimeSent();
 148					messagesLoaded = false;
 149					activity.xmppConnectionService.loadMoreMessages(conversation, timestamp, new XmppConnectionService.OnMoreMessagesLoaded() {
 150						@Override
 151						public void onMoreMessagesLoaded(final int c, Conversation conversation) {
 152							if (ConversationFragment.this.conversation != conversation) {
 153								return;
 154							}
 155							activity.runOnUiThread(new Runnable() {
 156								@Override
 157								public void run() {
 158									final int oldPosition = messagesView.getFirstVisiblePosition();
 159									Message message = messageList.get(oldPosition);
 160									String uuid = message != null ? message.getUuid() : null;
 161									View v = messagesView.getChildAt(0);
 162									final int pxOffset = (v == null) ? 0 : v.getTop();
 163									ConversationFragment.this.conversation.populateWithMessages(ConversationFragment.this.messageList);
 164									updateStatusMessages();
 165									messageListAdapter.notifyDataSetChanged();
 166									int pos = getIndexOf(uuid,messageList);
 167									messagesView.setSelectionFromTop(pos, pxOffset);
 168									messagesLoaded = true;
 169									if (messageLoaderToast != null) {
 170										messageLoaderToast.cancel();
 171									}
 172								}
 173							});
 174						}
 175
 176						@Override
 177						public void informUser(final int resId) {
 178
 179							activity.runOnUiThread(new Runnable() {
 180								@Override
 181								public void run() {
 182									if (messageLoaderToast != null) {
 183										messageLoaderToast.cancel();
 184									}
 185									if (ConversationFragment.this.conversation != conversation) {
 186										return;
 187									}
 188									messageLoaderToast = Toast.makeText(activity, resId, Toast.LENGTH_LONG);
 189									messageLoaderToast.show();
 190								}
 191							});
 192
 193						}
 194					});
 195
 196				}
 197			}
 198		}
 199	};
 200	private IntentSender askForPassphraseIntent = null;
 201	protected OnClickListener clickToDecryptListener = new OnClickListener() {
 202
 203		@Override
 204		public void onClick(View v) {
 205			if (activity.hasPgp() && askForPassphraseIntent != null) {
 206				try {
 207					getActivity().startIntentSenderForResult(
 208							askForPassphraseIntent,
 209							ConversationActivity.REQUEST_DECRYPT_PGP, null, 0,
 210							0, 0);
 211					askForPassphraseIntent = null;
 212				} catch (SendIntentException e) {
 213					//
 214				}
 215			}
 216		}
 217	};
 218	protected OnClickListener clickToVerify = new OnClickListener() {
 219
 220		@Override
 221		public void onClick(View v) {
 222			activity.verifyOtrSessionDialog(conversation, v);
 223		}
 224	};
 225	private ConcurrentLinkedQueue<Message> mEncryptedMessages = new ConcurrentLinkedQueue<>();
 226	private boolean mDecryptJobRunning = false;
 227	private OnEditorActionListener mEditorActionListener = new OnEditorActionListener() {
 228
 229		@Override
 230		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
 231			if (actionId == EditorInfo.IME_ACTION_SEND) {
 232				InputMethodManager imm = (InputMethodManager) v.getContext()
 233						.getSystemService(Context.INPUT_METHOD_SERVICE);
 234				imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
 235				sendMessage();
 236				return true;
 237			} else {
 238				return false;
 239			}
 240		}
 241	};
 242	private OnClickListener mSendButtonListener = new OnClickListener() {
 243
 244		@Override
 245		public void onClick(View v) {
 246			Object tag = v.getTag();
 247			if (tag instanceof SendButtonAction) {
 248				SendButtonAction action = (SendButtonAction) tag;
 249				switch (action) {
 250					case TAKE_PHOTO:
 251						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_TAKE_PHOTO);
 252						break;
 253					case SEND_LOCATION:
 254						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_LOCATION);
 255						break;
 256					case RECORD_VOICE:
 257						activity.attachFile(ConversationActivity.ATTACHMENT_CHOICE_RECORD_VOICE);
 258						break;
 259					case CANCEL:
 260						if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
 261							conversation.setNextCounterpart(null);
 262							updateChatMsgHint();
 263							updateSendButton();
 264						}
 265						break;
 266					default:
 267						sendMessage();
 268				}
 269			} else {
 270				sendMessage();
 271			}
 272		}
 273	};
 274	private OnClickListener clickToMuc = new OnClickListener() {
 275
 276		@Override
 277		public void onClick(View v) {
 278			Intent intent = new Intent(getActivity(), ConferenceDetailsActivity.class);
 279			intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
 280			intent.putExtra("uuid", conversation.getUuid());
 281			startActivity(intent);
 282		}
 283	};
 284	private ConversationActivity activity;
 285	private Message selectedMessage;
 286
 287	private void sendMessage() {
 288		if (this.conversation == null) {
 289			return;
 290		}
 291		Message message = new Message(conversation, mEditMessage.getText()
 292				.toString(), conversation.getNextEncryption(activity
 293				.forceEncryption()));
 294		if (conversation.getMode() == Conversation.MODE_MULTI) {
 295			if (conversation.getNextCounterpart() != null) {
 296				message.setCounterpart(conversation.getNextCounterpart());
 297				message.setType(Message.TYPE_PRIVATE);
 298			}
 299		}
 300		if (conversation.getNextEncryption(activity.forceEncryption()) == Message.ENCRYPTION_OTR) {
 301			sendOtrMessage(message);
 302		} else if (conversation.getNextEncryption(activity.forceEncryption()) == Message.ENCRYPTION_PGP) {
 303			sendPgpMessage(message);
 304		} else {
 305			sendPlainTextMessage(message);
 306		}
 307	}
 308
 309	public void updateChatMsgHint() {
 310		if (conversation.getMode() == Conversation.MODE_MULTI
 311				&& conversation.getNextCounterpart() != null) {
 312			this.mEditMessage.setHint(getString(
 313					R.string.send_private_message_to,
 314					conversation.getNextCounterpart().getResourcepart()));
 315		} else {
 316			switch (conversation.getNextEncryption(activity.forceEncryption())) {
 317				case Message.ENCRYPTION_NONE:
 318					mEditMessage
 319							.setHint(getString(R.string.send_plain_text_message));
 320					break;
 321				case Message.ENCRYPTION_OTR:
 322					mEditMessage.setHint(getString(R.string.send_otr_message));
 323					break;
 324				case Message.ENCRYPTION_PGP:
 325					mEditMessage.setHint(getString(R.string.send_pgp_message));
 326					break;
 327				default:
 328					break;
 329			}
 330			getActivity().invalidateOptionsMenu();
 331		}
 332	}
 333
 334	private void setupIme() {
 335		if (((ConversationActivity) getActivity()).usingEnterKey()) {
 336			mEditMessage.setInputType(mEditMessage.getInputType() & (~InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE));
 337		} else {
 338			mEditMessage.setInputType(mEditMessage.getInputType() | InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
 339		}
 340	}
 341
 342	@Override
 343	public View onCreateView(final LayoutInflater inflater,
 344							 ViewGroup container, Bundle savedInstanceState) {
 345		final View view = inflater.inflate(R.layout.fragment_conversation, container, false);
 346		view.setOnClickListener(null);
 347		mEditMessage = (EditMessage) view.findViewById(R.id.textinput);
 348		setupIme();
 349		mEditMessage.setOnClickListener(new OnClickListener() {
 350
 351			@Override
 352			public void onClick(View v) {
 353				if (activity != null) {
 354					activity.hideConversationsOverview();
 355				}
 356			}
 357		});
 358		mEditMessage.setOnEditorActionListener(mEditorActionListener);
 359
 360		mSendButton = (ImageButton) view.findViewById(R.id.textSendButton);
 361		mSendButton.setOnClickListener(this.mSendButtonListener);
 362
 363		snackbar = (RelativeLayout) view.findViewById(R.id.snackbar);
 364		snackbarMessage = (TextView) view.findViewById(R.id.snackbar_message);
 365		snackbarAction = (TextView) view.findViewById(R.id.snackbar_action);
 366
 367		messagesView = (ListView) view.findViewById(R.id.messages_view);
 368		messagesView.setOnScrollListener(mOnScrollListener);
 369		messagesView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
 370		messageListAdapter = new MessageAdapter((ConversationActivity) getActivity(), this.messageList);
 371		messageListAdapter.setOnContactPictureClicked(new OnContactPictureClicked() {
 372
 373			@Override
 374			public void onContactPictureClicked(Message message) {
 375				if (message.getStatus() <= Message.STATUS_RECEIVED) {
 376					if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 377						if (message.getCounterpart() != null) {
 378							if (!message.getCounterpart().isBareJid()) {
 379								highlightInConference(message.getCounterpart().getResourcepart());
 380							} else {
 381								highlightInConference(message.getCounterpart().toString());
 382							}
 383						}
 384					} else {
 385						activity.switchToContactDetails(message.getContact());
 386					}
 387				} else {
 388					Account account = message.getConversation().getAccount();
 389					Intent intent = new Intent(activity, EditAccountActivity.class);
 390					intent.putExtra("jid", account.getJid().toBareJid().toString());
 391					startActivity(intent);
 392				}
 393			}
 394		});
 395		messageListAdapter
 396				.setOnContactPictureLongClicked(new OnContactPictureLongClicked() {
 397
 398					@Override
 399					public void onContactPictureLongClicked(Message message) {
 400						if (message.getStatus() <= Message.STATUS_RECEIVED) {
 401							if (message.getConversation().getMode() == Conversation.MODE_MULTI) {
 402								if (message.getCounterpart() != null) {
 403									privateMessageWith(message.getCounterpart());
 404								}
 405							}
 406						} else {
 407							activity.showQrCode();
 408						}
 409					}
 410				});
 411		messagesView.setAdapter(messageListAdapter);
 412
 413		registerForContextMenu(messagesView);
 414
 415		return view;
 416	}
 417
 418	@Override
 419	public void onCreateContextMenu(ContextMenu menu, View v,
 420									ContextMenuInfo menuInfo) {
 421		synchronized (this.messageList) {
 422			super.onCreateContextMenu(menu, v, menuInfo);
 423			AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;
 424			this.selectedMessage = this.messageList.get(acmi.position);
 425			populateContextMenu(menu);
 426		}
 427	}
 428
 429	private void populateContextMenu(ContextMenu menu) {
 430		final Message m = this.selectedMessage;
 431		if (m.getType() != Message.TYPE_STATUS) {
 432			activity.getMenuInflater().inflate(R.menu.message_context, menu);
 433			menu.setHeaderTitle(R.string.message_options);
 434			MenuItem copyText = menu.findItem(R.id.copy_text);
 435			MenuItem shareWith = menu.findItem(R.id.share_with);
 436			MenuItem sendAgain = menu.findItem(R.id.send_again);
 437			MenuItem copyUrl = menu.findItem(R.id.copy_url);
 438			MenuItem downloadImage = menu.findItem(R.id.download_image);
 439			MenuItem cancelTransmission = menu.findItem(R.id.cancel_transmission);
 440			if ((m.getType() != Message.TYPE_TEXT && m.getType() != Message.TYPE_PRIVATE)
 441					|| m.getDownloadable() != null || GeoHelper.isGeoUri(m.getBody())) {
 442				copyText.setVisible(false);
 443			}
 444			if ((m.getType() == Message.TYPE_TEXT
 445					|| m.getType() == Message.TYPE_PRIVATE
 446					|| m.getDownloadable() != null)
 447					&& (!GeoHelper.isGeoUri(m.getBody()))) {
 448				shareWith.setVisible(false);
 449			}
 450			if (m.getStatus() != Message.STATUS_SEND_FAILED) {
 451				sendAgain.setVisible(false);
 452			}
 453			if (((m.getType() != Message.TYPE_IMAGE && m.getDownloadable() == null)
 454					|| m.getImageParams().url == null) && !GeoHelper.isGeoUri(m.getBody())) {
 455				copyUrl.setVisible(false);
 456			}
 457			if (m.getType() != Message.TYPE_TEXT
 458					|| m.getDownloadable() != null
 459					|| !m.bodyContainsDownloadable()) {
 460				downloadImage.setVisible(false);
 461			}
 462			if (!((m.getDownloadable() != null && !(m.getDownloadable() instanceof DownloadablePlaceholder))
 463					|| (m.isFileOrImage() && (m.getStatus() == Message.STATUS_WAITING
 464					|| m.getStatus() == Message.STATUS_OFFERED)))) {
 465				cancelTransmission.setVisible(false);
 466			}
 467		}
 468	}
 469
 470	@Override
 471	public boolean onContextItemSelected(MenuItem item) {
 472		switch (item.getItemId()) {
 473			case R.id.share_with:
 474				shareWith(selectedMessage);
 475				return true;
 476			case R.id.copy_text:
 477				copyText(selectedMessage);
 478				return true;
 479			case R.id.send_again:
 480				resendMessage(selectedMessage);
 481				return true;
 482			case R.id.copy_url:
 483				copyUrl(selectedMessage);
 484				return true;
 485			case R.id.download_image:
 486				downloadImage(selectedMessage);
 487				return true;
 488			case R.id.cancel_transmission:
 489				cancelTransmission(selectedMessage);
 490				return true;
 491			default:
 492				return super.onContextItemSelected(item);
 493		}
 494	}
 495
 496	private void shareWith(Message message) {
 497		Intent shareIntent = new Intent();
 498		shareIntent.setAction(Intent.ACTION_SEND);
 499		if (GeoHelper.isGeoUri(message.getBody())) {
 500			shareIntent.putExtra(Intent.EXTRA_TEXT, message.getBody());
 501			shareIntent.setType("text/plain");
 502		} else {
 503			shareIntent.putExtra(Intent.EXTRA_STREAM,
 504					activity.xmppConnectionService.getFileBackend()
 505							.getJingleFileUri(message));
 506			shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 507			String path = message.getRelativeFilePath();
 508			String mime = path == null ? null : URLConnection.guessContentTypeFromName(path);
 509			if (mime == null) {
 510				mime = "image/webp";
 511			}
 512			shareIntent.setType(mime);
 513		}
 514		activity.startActivity(Intent.createChooser(shareIntent, getText(R.string.share_with)));
 515	}
 516
 517	private void copyText(Message message) {
 518		if (activity.copyTextToClipboard(message.getMergedBody(),
 519				R.string.message_text)) {
 520			Toast.makeText(activity, R.string.message_copied_to_clipboard,
 521					Toast.LENGTH_SHORT).show();
 522		}
 523	}
 524
 525	private void resendMessage(Message message) {
 526		if (message.getType() == Message.TYPE_FILE || message.getType() == Message.TYPE_IMAGE) {
 527			DownloadableFile file = activity.xmppConnectionService.getFileBackend().getFile(message);
 528			if (!file.exists()) {
 529				Toast.makeText(activity, R.string.file_deleted, Toast.LENGTH_SHORT).show();
 530				message.setDownloadable(new DownloadablePlaceholder(Downloadable.STATUS_DELETED));
 531				return;
 532			}
 533		}
 534		activity.xmppConnectionService.resendFailedMessages(message);
 535	}
 536
 537	private void copyUrl(Message message) {
 538		final String url;
 539		final int resId;
 540		if (GeoHelper.isGeoUri(message.getBody())) {
 541			resId = R.string.location;
 542			url = message.getBody();
 543		} else {
 544			resId = R.string.image_url;
 545			url = message.getImageParams().url.toString();
 546		}
 547		if (activity.copyTextToClipboard(url, resId)) {
 548			Toast.makeText(activity, R.string.url_copied_to_clipboard,
 549					Toast.LENGTH_SHORT).show();
 550		}
 551	}
 552
 553	private void downloadImage(Message message) {
 554		activity.xmppConnectionService.getHttpConnectionManager()
 555				.createNewConnection(message);
 556	}
 557
 558	private void cancelTransmission(Message message) {
 559		Downloadable downloadable = message.getDownloadable();
 560		if (downloadable != null) {
 561			downloadable.cancel();
 562		} else {
 563			activity.xmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
 564		}
 565	}
 566
 567	protected void privateMessageWith(final Jid counterpart) {
 568		this.mEditMessage.setText("");
 569		this.conversation.setNextCounterpart(counterpart);
 570		updateChatMsgHint();
 571		updateSendButton();
 572	}
 573
 574	protected void highlightInConference(String nick) {
 575		String oldString = mEditMessage.getText().toString().trim();
 576		if (oldString.isEmpty() || mEditMessage.getSelectionStart() == 0) {
 577			mEditMessage.getText().insert(0, nick + ": ");
 578		} else {
 579			if (mEditMessage.getText().charAt(
 580					mEditMessage.getSelectionStart() - 1) != ' ') {
 581				nick = " " + nick;
 582			}
 583			mEditMessage.getText().insert(mEditMessage.getSelectionStart(),
 584					nick + " ");
 585		}
 586	}
 587
 588	@Override
 589	public void onStop() {
 590		mDecryptJobRunning = false;
 591		super.onStop();
 592		if (this.conversation != null) {
 593			final String msg = mEditMessage.getText().toString();
 594			this.conversation.setNextMessage(msg);
 595			updateChatState(this.conversation, msg);
 596		}
 597	}
 598
 599	private void updateChatState(final Conversation conversation, final String msg) {
 600		ChatState state = msg.length() == 0 ? Config.DEFAULT_CHATSTATE : ChatState.PAUSED;
 601		Account.State status = conversation.getAccount().getStatus();
 602		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(state)) {
 603			activity.xmppConnectionService.sendChatState(conversation);
 604		}
 605	}
 606
 607	public void reInit(Conversation conversation) {
 608		if (conversation == null) {
 609			return;
 610		}
 611
 612		this.activity = (ConversationActivity) getActivity();
 613
 614		if (this.conversation != null) {
 615			final String msg = mEditMessage.getText().toString();
 616			this.conversation.setNextMessage(msg);
 617			if (this.conversation != conversation) {
 618				updateChatState(this.conversation, msg);
 619			}
 620			this.conversation.trim();
 621		}
 622
 623		this.askForPassphraseIntent = null;
 624		this.conversation = conversation;
 625		this.mDecryptJobRunning = false;
 626		this.mEncryptedMessages.clear();
 627		if (this.conversation.getMode() == Conversation.MODE_MULTI) {
 628			this.conversation.setNextCounterpart(null);
 629		}
 630		this.mEditMessage.setKeyboardListener(null);
 631		this.mEditMessage.setText("");
 632		this.mEditMessage.append(this.conversation.getNextMessage());
 633		this.mEditMessage.setKeyboardListener(this);
 634		this.messagesView.setAdapter(messageListAdapter);
 635		updateMessages();
 636		this.messagesLoaded = true;
 637		int size = this.messageList.size();
 638		if (size > 0) {
 639			messagesView.setSelection(size - 1);
 640		}
 641	}
 642
 643	private OnClickListener mUnblockClickListener = new OnClickListener() {
 644		@Override
 645		public void onClick(final View v) {
 646			v.post(new Runnable() {
 647				@Override
 648				public void run() {
 649					v.setVisibility(View.INVISIBLE);
 650				}
 651			});
 652			if (conversation.isDomainBlocked()) {
 653				BlockContactDialog.show(activity, activity.xmppConnectionService, conversation);
 654			} else {
 655				activity.unblockConversation(conversation);
 656			}
 657		}
 658	};
 659
 660	private OnClickListener mAddBackClickListener = new OnClickListener() {
 661
 662		@Override
 663		public void onClick(View v) {
 664			final Contact contact = conversation == null ? null : conversation.getContact();
 665			if (contact != null) {
 666				activity.xmppConnectionService.createContact(contact);
 667				activity.switchToContactDetails(contact);
 668			}
 669		}
 670	};
 671
 672	private OnClickListener mUnmuteClickListener = new OnClickListener() {
 673
 674		@Override
 675		public void onClick(final View v) {
 676			activity.unmuteConversation(conversation);
 677		}
 678	};
 679
 680	private OnClickListener mAnswerSmpClickListener = new OnClickListener() {
 681		@Override
 682		public void onClick(View view) {
 683			Intent intent = new Intent(activity, VerifyOTRActivity.class);
 684			intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
 685			intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
 686			intent.putExtra("account", conversation.getAccount().getJid().toBareJid().toString());
 687			intent.putExtra("mode", VerifyOTRActivity.MODE_ANSWER_QUESTION);
 688			startActivity(intent);
 689		}
 690	};
 691
 692	private void updateSnackBar(final Conversation conversation) {
 693		final Account account = conversation.getAccount();
 694		final Contact contact = conversation.getContact();
 695		final int mode = conversation.getMode();
 696		if (conversation.isBlocked()) {
 697			showSnackbar(R.string.contact_blocked, R.string.unblock, this.mUnblockClickListener);
 698		} else if (!contact.showInRoster() && contact.getOption(Contact.Options.PENDING_SUBSCRIPTION_REQUEST)) {
 699			showSnackbar(R.string.contact_added_you, R.string.add_back, this.mAddBackClickListener);
 700		} else if (mode == Conversation.MODE_MULTI
 701				&& !conversation.getMucOptions().online()
 702				&& account.getStatus() == Account.State.ONLINE) {
 703			switch (conversation.getMucOptions().getError()) {
 704				case MucOptions.ERROR_NICK_IN_USE:
 705					showSnackbar(R.string.nick_in_use, R.string.edit, clickToMuc);
 706					break;
 707				case MucOptions.ERROR_UNKNOWN:
 708					showSnackbar(R.string.conference_not_found, R.string.leave, leaveMuc);
 709					break;
 710				case MucOptions.ERROR_PASSWORD_REQUIRED:
 711					showSnackbar(R.string.conference_requires_password, R.string.enter_password, enterPassword);
 712					break;
 713				case MucOptions.ERROR_BANNED:
 714					showSnackbar(R.string.conference_banned, R.string.leave, leaveMuc);
 715					break;
 716				case MucOptions.ERROR_MEMBERS_ONLY:
 717					showSnackbar(R.string.conference_members_only, R.string.leave, leaveMuc);
 718					break;
 719				case MucOptions.KICKED_FROM_ROOM:
 720					showSnackbar(R.string.conference_kicked, R.string.join, joinMuc);
 721					break;
 722				default:
 723					break;
 724			}
 725		} else if (askForPassphraseIntent != null) {
 726			showSnackbar(R.string.openpgp_messages_found, R.string.decrypt, clickToDecryptListener);
 727		} else if (mode == Conversation.MODE_SINGLE
 728				&& conversation.smpRequested()) {
 729			showSnackbar(R.string.smp_requested, R.string.verify, this.mAnswerSmpClickListener);
 730		} else if (mode == Conversation.MODE_SINGLE
 731				&& conversation.hasValidOtrSession()
 732				&& (conversation.getOtrSession().getSessionStatus() == SessionStatus.ENCRYPTED)
 733				&& (!conversation.isOtrFingerprintVerified())) {
 734			showSnackbar(R.string.unknown_otr_fingerprint, R.string.verify, clickToVerify);
 735		} else if (conversation.isMuted()) {
 736			showSnackbar(R.string.notifications_disabled, R.string.enable, this.mUnmuteClickListener);
 737		} else {
 738			hideSnackbar();
 739		}
 740	}
 741
 742	public void updateMessages() {
 743		synchronized (this.messageList) {
 744			if (getView() == null) {
 745				return;
 746			}
 747			final ConversationActivity activity = (ConversationActivity) getActivity();
 748			if (this.conversation != null) {
 749				updateSnackBar(this.conversation);
 750				conversation.populateWithMessages(ConversationFragment.this.messageList);
 751				for (final Message message : this.messageList) {
 752					if (message.getEncryption() == Message.ENCRYPTION_PGP
 753							&& (message.getStatus() == Message.STATUS_RECEIVED || message
 754							.getStatus() >= Message.STATUS_SEND)
 755							&& message.getDownloadable() == null) {
 756						if (!mEncryptedMessages.contains(message)) {
 757							mEncryptedMessages.add(message);
 758						}
 759					}
 760				}
 761				decryptNext();
 762				updateStatusMessages();
 763				this.messageListAdapter.notifyDataSetChanged();
 764				updateChatMsgHint();
 765				if (!activity.isConversationsOverviewVisable() || !activity.isConversationsOverviewHideable()) {
 766					activity.sendReadMarkerIfNecessary(conversation);
 767				}
 768				this.updateSendButton();
 769			}
 770		}
 771	}
 772
 773	private void decryptNext() {
 774		Message next = this.mEncryptedMessages.peek();
 775		PgpEngine engine = activity.xmppConnectionService.getPgpEngine();
 776
 777		if (next != null && engine != null && !mDecryptJobRunning) {
 778			mDecryptJobRunning = true;
 779			engine.decrypt(next, new UiCallback<Message>() {
 780
 781				@Override
 782				public void userInputRequried(PendingIntent pi, Message message) {
 783					mDecryptJobRunning = false;
 784					askForPassphraseIntent = pi.getIntentSender();
 785					updateSnackBar(conversation);
 786				}
 787
 788				@Override
 789				public void success(Message message) {
 790					mDecryptJobRunning = false;
 791					try {
 792						mEncryptedMessages.remove();
 793					} catch (final NoSuchElementException ignored) {
 794
 795					}
 796					askForPassphraseIntent = null;
 797					activity.xmppConnectionService.updateMessage(message);
 798				}
 799
 800				@Override
 801				public void error(int error, Message message) {
 802					message.setEncryption(Message.ENCRYPTION_DECRYPTION_FAILED);
 803					mDecryptJobRunning = false;
 804					try {
 805						mEncryptedMessages.remove();
 806					} catch (final NoSuchElementException ignored) {
 807
 808					}
 809					activity.xmppConnectionService.updateConversationUi();
 810				}
 811			});
 812		}
 813	}
 814
 815	private void messageSent() {
 816		int size = this.messageList.size();
 817		messagesView.setSelection(size - 1);
 818		mEditMessage.setText("");
 819		updateChatMsgHint();
 820	}
 821
 822	enum SendButtonAction {TEXT, TAKE_PHOTO, SEND_LOCATION, RECORD_VOICE, CANCEL}
 823
 824	private int getSendButtonImageResource(SendButtonAction action, int status) {
 825		switch (action) {
 826			case TEXT:
 827				switch (status) {
 828					case Presences.CHAT:
 829					case Presences.ONLINE:
 830						return R.drawable.ic_send_text_online;
 831					case Presences.AWAY:
 832						return R.drawable.ic_send_text_away;
 833					case Presences.XA:
 834					case Presences.DND:
 835						return R.drawable.ic_send_text_dnd;
 836					default:
 837						return R.drawable.ic_send_text_offline;
 838				}
 839			case TAKE_PHOTO:
 840				switch (status) {
 841					case Presences.CHAT:
 842					case Presences.ONLINE:
 843						return R.drawable.ic_send_photo_online;
 844					case Presences.AWAY:
 845						return R.drawable.ic_send_photo_away;
 846					case Presences.XA:
 847					case Presences.DND:
 848						return R.drawable.ic_send_photo_dnd;
 849					default:
 850						return R.drawable.ic_send_photo_offline;
 851				}
 852			case RECORD_VOICE:
 853				switch (status) {
 854					case Presences.CHAT:
 855					case Presences.ONLINE:
 856						return R.drawable.ic_send_voice_online;
 857					case Presences.AWAY:
 858						return R.drawable.ic_send_voice_away;
 859					case Presences.XA:
 860					case Presences.DND:
 861						return R.drawable.ic_send_voice_dnd;
 862					default:
 863						return R.drawable.ic_send_voice_offline;
 864				}
 865			case SEND_LOCATION:
 866				switch (status) {
 867					case Presences.CHAT:
 868					case Presences.ONLINE:
 869						return R.drawable.ic_send_location_online;
 870					case Presences.AWAY:
 871						return R.drawable.ic_send_location_away;
 872					case Presences.XA:
 873					case Presences.DND:
 874						return R.drawable.ic_send_location_dnd;
 875					default:
 876						return R.drawable.ic_send_location_offline;
 877				}
 878			case CANCEL:
 879				switch (status) {
 880					case Presences.CHAT:
 881					case Presences.ONLINE:
 882						return R.drawable.ic_send_cancel_online;
 883					case Presences.AWAY:
 884						return R.drawable.ic_send_cancel_away;
 885					case Presences.XA:
 886					case Presences.DND:
 887						return R.drawable.ic_send_cancel_dnd;
 888					default:
 889						return R.drawable.ic_send_cancel_offline;
 890				}
 891		}
 892		return R.drawable.ic_send_text_offline;
 893	}
 894
 895	public void updateSendButton() {
 896		final Conversation c = this.conversation;
 897		final SendButtonAction action;
 898		final int status;
 899		final boolean empty = this.mEditMessage == null || this.mEditMessage.getText().length() == 0;
 900		if (c.getMode() == Conversation.MODE_MULTI) {
 901			if (empty && c.getNextCounterpart() != null) {
 902				action = SendButtonAction.CANCEL;
 903			} else {
 904				action = SendButtonAction.TEXT;
 905			}
 906		} else {
 907			if (empty) {
 908				String setting = activity.getPreferences().getString("quick_action","recent");
 909				if (!setting.equals("none") && UIHelper.receivedLocationQuestion(conversation.getLatestMessage())) {
 910					setting = "location";
 911				} else if (setting.equals("recent")) {
 912					setting = activity.getPreferences().getString("recently_used_quick_action","text");
 913				}
 914				switch (setting) {
 915					case "photo":
 916						action = SendButtonAction.TAKE_PHOTO;
 917						break;
 918					case "location":
 919						action = SendButtonAction.SEND_LOCATION;
 920						break;
 921					case "voice":
 922						action = SendButtonAction.RECORD_VOICE;
 923						break;
 924					default:
 925						action = SendButtonAction.TEXT;
 926						break;
 927				}
 928			} else {
 929				action = SendButtonAction.TEXT;
 930			}
 931		}
 932		if (activity.useSendButtonToIndicateStatus() && c != null
 933				&& c.getAccount().getStatus() == Account.State.ONLINE) {
 934			if (c.getMode() == Conversation.MODE_SINGLE) {
 935				status = c.getContact().getMostAvailableStatus();
 936			} else {
 937				status = c.getMucOptions().online() ? Presences.ONLINE : Presences.OFFLINE;
 938			}
 939		} else {
 940			status = Presences.OFFLINE;
 941		}
 942		this.mSendButton.setTag(action);
 943		this.mSendButton.setImageResource(getSendButtonImageResource(action, status));
 944	}
 945
 946	protected void updateStatusMessages() {
 947		synchronized (this.messageList) {
 948			if (conversation.getMode() == Conversation.MODE_SINGLE) {
 949				ChatState state = conversation.getIncomingChatState();
 950				if (state == ChatState.COMPOSING) {
 951					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_is_typing, conversation.getName())));
 952				} else if (state == ChatState.PAUSED) {
 953					this.messageList.add(Message.createStatusMessage(conversation, getString(R.string.contact_has_stopped_typing, conversation.getName())));
 954				} else {
 955					for (int i = this.messageList.size() - 1; i >= 0; --i) {
 956						if (this.messageList.get(i).getStatus() == Message.STATUS_RECEIVED) {
 957							return;
 958						} else {
 959							if (this.messageList.get(i).getStatus() == Message.STATUS_SEND_DISPLAYED) {
 960								this.messageList.add(i + 1,
 961										Message.createStatusMessage(conversation, getString(R.string.contact_has_read_up_to_this_point, conversation.getName())));
 962								return;
 963							}
 964						}
 965					}
 966				}
 967			}
 968		}
 969	}
 970
 971	protected void showSnackbar(final int message, final int action,
 972								final OnClickListener clickListener) {
 973		snackbar.setVisibility(View.VISIBLE);
 974		snackbar.setOnClickListener(null);
 975		snackbarMessage.setText(message);
 976		snackbarMessage.setOnClickListener(null);
 977		snackbarAction.setVisibility(View.VISIBLE);
 978		snackbarAction.setText(action);
 979		snackbarAction.setOnClickListener(clickListener);
 980	}
 981
 982	protected void hideSnackbar() {
 983		snackbar.setVisibility(View.GONE);
 984	}
 985
 986	protected void sendPlainTextMessage(Message message) {
 987		ConversationActivity activity = (ConversationActivity) getActivity();
 988		activity.xmppConnectionService.sendMessage(message);
 989		messageSent();
 990	}
 991
 992	protected void sendPgpMessage(final Message message) {
 993		final ConversationActivity activity = (ConversationActivity) getActivity();
 994		final XmppConnectionService xmppService = activity.xmppConnectionService;
 995		final Contact contact = message.getConversation().getContact();
 996		if (activity.hasPgp()) {
 997			if (conversation.getMode() == Conversation.MODE_SINGLE) {
 998				if (contact.getPgpKeyId() != 0) {
 999					xmppService.getPgpEngine().hasKey(contact,
1000							new UiCallback<Contact>() {
1001
1002								@Override
1003								public void userInputRequried(PendingIntent pi,
1004															  Contact contact) {
1005									activity.runIntent(
1006											pi,
1007											ConversationActivity.REQUEST_ENCRYPT_MESSAGE);
1008								}
1009
1010								@Override
1011								public void success(Contact contact) {
1012									messageSent();
1013									activity.encryptTextMessage(message);
1014								}
1015
1016								@Override
1017								public void error(int error, Contact contact) {
1018
1019								}
1020							});
1021
1022				} else {
1023					showNoPGPKeyDialog(false,
1024							new DialogInterface.OnClickListener() {
1025
1026								@Override
1027								public void onClick(DialogInterface dialog,
1028													int which) {
1029									conversation
1030											.setNextEncryption(Message.ENCRYPTION_NONE);
1031									xmppService.databaseBackend
1032											.updateConversation(conversation);
1033									message.setEncryption(Message.ENCRYPTION_NONE);
1034									xmppService.sendMessage(message);
1035									messageSent();
1036								}
1037							});
1038				}
1039			} else {
1040				if (conversation.getMucOptions().pgpKeysInUse()) {
1041					if (!conversation.getMucOptions().everybodyHasKeys()) {
1042						Toast warning = Toast
1043								.makeText(getActivity(),
1044										R.string.missing_public_keys,
1045										Toast.LENGTH_LONG);
1046						warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
1047						warning.show();
1048					}
1049					activity.encryptTextMessage(message);
1050					messageSent();
1051				} else {
1052					showNoPGPKeyDialog(true,
1053							new DialogInterface.OnClickListener() {
1054
1055								@Override
1056								public void onClick(DialogInterface dialog,
1057													int which) {
1058									conversation
1059											.setNextEncryption(Message.ENCRYPTION_NONE);
1060									message.setEncryption(Message.ENCRYPTION_NONE);
1061									xmppService.databaseBackend
1062											.updateConversation(conversation);
1063									xmppService.sendMessage(message);
1064									messageSent();
1065								}
1066							});
1067				}
1068			}
1069		} else {
1070			activity.showInstallPgpDialog();
1071		}
1072	}
1073
1074	public void showNoPGPKeyDialog(boolean plural,
1075								   DialogInterface.OnClickListener listener) {
1076		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
1077		builder.setIconAttribute(android.R.attr.alertDialogIcon);
1078		if (plural) {
1079			builder.setTitle(getString(R.string.no_pgp_keys));
1080			builder.setMessage(getText(R.string.contacts_have_no_pgp_keys));
1081		} else {
1082			builder.setTitle(getString(R.string.no_pgp_key));
1083			builder.setMessage(getText(R.string.contact_has_no_pgp_key));
1084		}
1085		builder.setNegativeButton(getString(R.string.cancel), null);
1086		builder.setPositiveButton(getString(R.string.send_unencrypted),
1087				listener);
1088		builder.create().show();
1089	}
1090
1091	protected void sendOtrMessage(final Message message) {
1092		final ConversationActivity activity = (ConversationActivity) getActivity();
1093		final XmppConnectionService xmppService = activity.xmppConnectionService;
1094		activity.selectPresence(message.getConversation(),
1095				new OnPresenceSelected() {
1096
1097					@Override
1098					public void onPresenceSelected() {
1099						message.setCounterpart(conversation.getNextCounterpart());
1100						xmppService.sendMessage(message);
1101						messageSent();
1102					}
1103				});
1104	}
1105
1106	public void appendText(String text) {
1107		if (text == null) {
1108			return;
1109		}
1110		String previous = this.mEditMessage.getText().toString();
1111		if (previous.length() != 0 && !previous.endsWith(" ")) {
1112			text = " " + text;
1113		}
1114		this.mEditMessage.append(text);
1115	}
1116
1117	@Override
1118	public boolean onEnterPressed() {
1119		if (activity.enterIsSend()) {
1120			sendMessage();
1121			return true;
1122		} else {
1123			return false;
1124		}
1125	}
1126
1127	@Override
1128	public void onTypingStarted() {
1129		Account.State status = conversation.getAccount().getStatus();
1130		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.COMPOSING)) {
1131			activity.xmppConnectionService.sendChatState(conversation);
1132		}
1133		updateSendButton();
1134	}
1135
1136	@Override
1137	public void onTypingStopped() {
1138		Account.State status = conversation.getAccount().getStatus();
1139		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(ChatState.PAUSED)) {
1140			activity.xmppConnectionService.sendChatState(conversation);
1141		}
1142	}
1143
1144	@Override
1145	public void onTextDeleted() {
1146		Account.State status = conversation.getAccount().getStatus();
1147		if (status == Account.State.ONLINE && conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) {
1148			activity.xmppConnectionService.sendChatState(conversation);
1149		}
1150		updateSendButton();
1151	}
1152
1153}