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