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