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