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