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