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