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