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