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