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 super.onBackPressed();
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 case Surface.ROTATION_0:
998 default:
999 upKey = KeyEvent.KEYCODE_DPAD_UP;
1000 downKey = KeyEvent.KEYCODE_DPAD_DOWN;
1001 }
1002 final boolean modifier = event.isCtrlPressed() || (event.getMetaState() & KeyEvent.META_ALT_LEFT_ON) != 0;
1003 if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
1004 toggleConversationsOverview();
1005 return true;
1006 } else if (modifier && key == KeyEvent.KEYCODE_SPACE) {
1007 startActivity(new Intent(this, StartConversationActivity.class));
1008 return true;
1009 } else if (modifier && key == downKey) {
1010 if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1011 showConversationsOverview();
1012 ;
1013 }
1014 return selectDownConversation();
1015 } else if (modifier && key == upKey) {
1016 if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1017 showConversationsOverview();
1018 }
1019 return selectUpConversation();
1020 } else if (modifier && key == KeyEvent.KEYCODE_1) {
1021 return openConversationByIndex(0);
1022 } else if (modifier && key == KeyEvent.KEYCODE_2) {
1023 return openConversationByIndex(1);
1024 } else if (modifier && key == KeyEvent.KEYCODE_3) {
1025 return openConversationByIndex(2);
1026 } else if (modifier && key == KeyEvent.KEYCODE_4) {
1027 return openConversationByIndex(3);
1028 } else if (modifier && key == KeyEvent.KEYCODE_5) {
1029 return openConversationByIndex(4);
1030 } else if (modifier && key == KeyEvent.KEYCODE_6) {
1031 return openConversationByIndex(5);
1032 } else if (modifier && key == KeyEvent.KEYCODE_7) {
1033 return openConversationByIndex(6);
1034 } else if (modifier && key == KeyEvent.KEYCODE_8) {
1035 return openConversationByIndex(7);
1036 } else if (modifier && key == KeyEvent.KEYCODE_9) {
1037 return openConversationByIndex(8);
1038 } else if (modifier && key == KeyEvent.KEYCODE_0) {
1039 return openConversationByIndex(9);
1040 } else {
1041 return super.onKeyUp(key, event);
1042 }
1043 }
1044
1045 private void toggleConversationsOverview() {
1046 if (isConversationsOverviewVisable()) {
1047 hideConversationsOverview();
1048 if (mConversationFragment != null) {
1049 mConversationFragment.setFocusOnInputField();
1050 }
1051 } else {
1052 showConversationsOverview();
1053 }
1054 }
1055
1056 private boolean selectUpConversation() {
1057 if (this.mSelectedConversation != null) {
1058 int index = this.conversationList.indexOf(this.mSelectedConversation);
1059 if (index > 0) {
1060 return openConversationByIndex(index - 1);
1061 }
1062 }
1063 return false;
1064 }
1065
1066 private boolean selectDownConversation() {
1067 if (this.mSelectedConversation != null) {
1068 int index = this.conversationList.indexOf(this.mSelectedConversation);
1069 if (index != -1 && index < this.conversationList.size() - 1) {
1070 return openConversationByIndex(index + 1);
1071 }
1072 }
1073 return false;
1074 }
1075
1076 private boolean openConversationByIndex(int index) {
1077 try {
1078 this.conversationWasSelectedByKeyboard = true;
1079 setSelectedConversation(this.conversationList.get(index));
1080 this.mConversationFragment.reInit(getSelectedConversation());
1081 if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
1082 this.listView.setSelection(index);
1083 }
1084 openConversation();
1085 return true;
1086 } catch (IndexOutOfBoundsException e) {
1087 return false;
1088 }
1089 }
1090
1091 @Override
1092 protected void onNewIntent(final Intent intent) {
1093 if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1094 mOpenConversation = null;
1095 mUnprocessedNewIntent = true;
1096 if (xmppConnectionServiceBound) {
1097 handleViewConversationIntent(intent);
1098 intent.setAction(Intent.ACTION_MAIN);
1099 } else {
1100 setIntent(intent);
1101 }
1102 }
1103 }
1104
1105 @Override
1106 public void onStart() {
1107 super.onStart();
1108 this.mRedirected.set(false);
1109 if (this.xmppConnectionServiceBound) {
1110 this.onBackendConnected();
1111 }
1112 if (conversationList.size() >= 1) {
1113 this.onConversationUpdate();
1114 }
1115 }
1116
1117 @Override
1118 public void onPause() {
1119 listView.discardUndo();
1120 super.onPause();
1121 this.mActivityPaused = true;
1122 }
1123
1124 @Override
1125 public void onResume() {
1126 super.onResume();
1127 final int theme = findTheme();
1128 final boolean usingEnterKey = usingEnterKey();
1129 if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1130 recreate();
1131 }
1132 this.mActivityPaused = false;
1133
1134
1135 if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1136 sendReadMarkerIfNecessary(getSelectedConversation());
1137 }
1138
1139 }
1140
1141 @Override
1142 public void onSaveInstanceState(final Bundle savedInstanceState) {
1143 Conversation conversation = getSelectedConversation();
1144 if (conversation != null) {
1145 savedInstanceState.putString(STATE_OPEN_CONVERSATION, conversation.getUuid());
1146 Pair<Integer,Integer> scrollPosition = mConversationFragment.getScrollPosition();
1147 if (scrollPosition != null) {
1148 savedInstanceState.putInt(STATE_FIRST_VISIBLE, scrollPosition.first);
1149 savedInstanceState.putInt(STATE_OFFSET_FROM_TOP, scrollPosition.second);
1150 }
1151 } else {
1152 savedInstanceState.remove(STATE_OPEN_CONVERSATION);
1153 }
1154 savedInstanceState.putBoolean(STATE_PANEL_OPEN, isConversationsOverviewVisable());
1155 if (this.mPendingImageUris.size() >= 1) {
1156 Log.d(Config.LOGTAG,"ConversationsActivity.onSaveInstanceState() - saving pending image uri");
1157 savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1158 } else {
1159 savedInstanceState.remove(STATE_PENDING_URI);
1160 }
1161 super.onSaveInstanceState(savedInstanceState);
1162 }
1163
1164 private void clearPending() {
1165 mPendingImageUris.clear();
1166 mPendingFileUris.clear();
1167 mPendingGeoUri = null;
1168 mPostponedActivityResult = null;
1169 }
1170
1171 @Override
1172 void onBackendConnected() {
1173 this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1174 updateConversationList();
1175
1176 if (mPendingConferenceInvite != null) {
1177 if (mPendingConferenceInvite.execute(this)) {
1178 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1179 mToast.show();
1180 }
1181 mPendingConferenceInvite = null;
1182 }
1183
1184 final Intent intent = getIntent();
1185
1186 if (xmppConnectionService.getAccounts().size() == 0) {
1187 if (mRedirected.compareAndSet(false, true)) {
1188 if (Config.X509_VERIFICATION) {
1189 startActivity(new Intent(this, ManageAccountActivity.class));
1190 } else if (Config.MAGIC_CREATE_DOMAIN != null) {
1191 startActivity(new Intent(this, WelcomeActivity.class));
1192 } else {
1193 Intent editAccount = new Intent(this, EditAccountActivity.class);
1194 editAccount.putExtra("init",true);
1195 startActivity(editAccount);
1196 }
1197 finish();
1198 }
1199 } else if (conversationList.size() <= 0) {
1200 if (mRedirected.compareAndSet(false, true)) {
1201 Account pendingAccount = xmppConnectionService.getPendingAccount();
1202 if (pendingAccount == null) {
1203 Intent startConversationActivity = new Intent(this, StartConversationActivity.class);
1204 intent.putExtra("init", true);
1205 startActivity(startConversationActivity);
1206 } else {
1207 switchToAccount(pendingAccount, true);
1208 }
1209 finish();
1210 }
1211 } else if (selectConversationByUuid(mOpenConversation)) {
1212 if (mPanelOpen) {
1213 showConversationsOverview();
1214 } else {
1215 if (isConversationsOverviewHideable()) {
1216 openConversation();
1217 updateActionBarTitle(true);
1218 }
1219 }
1220 if (this.mConversationFragment.reInit(getSelectedConversation())) {
1221 Log.d(Config.LOGTAG,"setting scroll position on fragment");
1222 this.mConversationFragment.setScrollPosition(mScrollPosition);
1223 }
1224 mOpenConversation = null;
1225 } else if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1226 clearPending();
1227 handleViewConversationIntent(intent);
1228 intent.setAction(Intent.ACTION_MAIN);
1229 } else if (getSelectedConversation() == null) {
1230 showConversationsOverview();
1231 clearPending();
1232 setSelectedConversation(conversationList.get(0));
1233 this.mConversationFragment.reInit(getSelectedConversation());
1234 } else {
1235 this.mConversationFragment.messageListAdapter.updatePreferences();
1236 this.mConversationFragment.messagesView.invalidateViews();
1237 this.mConversationFragment.setupIme();
1238 }
1239
1240 if (this.mPostponedActivityResult != null) {
1241 this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1242 }
1243
1244 final boolean stopping;
1245 if (Build.VERSION.SDK_INT >= 17) {
1246 stopping = isFinishing() || isDestroyed();
1247 } else {
1248 stopping = isFinishing();
1249 }
1250
1251 if (!forbidProcessingPendings) {
1252 for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1253 Uri foo = i.next();
1254 Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching image to conversations. stopping="+Boolean.toString(stopping));
1255 attachImageToConversation(getSelectedConversation(), foo);
1256 }
1257
1258 for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1259 Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching file to conversations. stopping="+Boolean.toString(stopping));
1260 attachFileToConversation(getSelectedConversation(), i.next());
1261 }
1262
1263 if (mPendingGeoUri != null) {
1264 attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1265 mPendingGeoUri = null;
1266 }
1267 }
1268 forbidProcessingPendings = false;
1269
1270 if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService)) {
1271 openBatteryOptimizationDialogIfNeeded();
1272 }
1273 if (isConversationsOverviewVisable() && isConversationsOverviewHideable()) {
1274 xmppConnectionService.getNotificationService().setOpenConversation(null);
1275 } else {
1276 xmppConnectionService.getNotificationService().setOpenConversation(getSelectedConversation());
1277 }
1278 }
1279
1280 private void handleViewConversationIntent(final Intent intent) {
1281 final String uuid = intent.getStringExtra(CONVERSATION);
1282 final String downloadUuid = intent.getStringExtra(EXTRA_DOWNLOAD_UUID);
1283 final String text = intent.getStringExtra(TEXT);
1284 final String nick = intent.getStringExtra(NICK);
1285 final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1286 if (selectConversationByUuid(uuid)) {
1287 this.mConversationFragment.reInit(getSelectedConversation());
1288 if (nick != null) {
1289 if (pm) {
1290 Jid jid = getSelectedConversation().getJid();
1291 try {
1292 Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1293 this.mConversationFragment.privateMessageWith(next);
1294 } catch (final InvalidJidException ignored) {
1295 //do nothing
1296 }
1297 } else {
1298 this.mConversationFragment.highlightInConference(nick);
1299 }
1300 } else {
1301 this.mConversationFragment.appendText(text);
1302 }
1303 hideConversationsOverview();
1304 mUnprocessedNewIntent = false;
1305 openConversation();
1306 if (mContentView instanceof SlidingPaneLayout) {
1307 updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1308 }
1309 if (downloadUuid != null) {
1310 final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1311 if (message != null) {
1312 startDownloadable(message);
1313 }
1314 }
1315 } else {
1316 mUnprocessedNewIntent = false;
1317 }
1318 }
1319
1320 private boolean selectConversationByUuid(String uuid) {
1321 if (uuid == null) {
1322 return false;
1323 }
1324 for (Conversation aConversationList : conversationList) {
1325 if (aConversationList.getUuid().equals(uuid)) {
1326 setSelectedConversation(aConversationList);
1327 return true;
1328 }
1329 }
1330 return false;
1331 }
1332
1333 @Override
1334 protected void unregisterListeners() {
1335 super.unregisterListeners();
1336 xmppConnectionService.getNotificationService().setOpenConversation(null);
1337 }
1338
1339 @SuppressLint("NewApi")
1340 private static List<Uri> extractUriFromIntent(final Intent intent) {
1341 List<Uri> uris = new ArrayList<>();
1342 if (intent == null) {
1343 return uris;
1344 }
1345 Uri uri = intent.getData();
1346 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1347 final ClipData clipData = intent.getClipData();
1348 if (clipData != null) {
1349 for (int i = 0; i < clipData.getItemCount(); ++i) {
1350 uris.add(clipData.getItemAt(i).getUri());
1351 }
1352 }
1353 } else {
1354 uris.add(uri);
1355 }
1356 return uris;
1357 }
1358
1359 @Override
1360 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1361 super.onActivityResult(requestCode, resultCode, data);
1362 if (resultCode == RESULT_OK) {
1363 if (requestCode == REQUEST_DECRYPT_PGP) {
1364 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1365 } else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1366 // the user chose OpenPGP for encryption and selected his key in the PGP provider
1367 if (xmppConnectionServiceBound) {
1368 if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1369 // associate selected PGP keyId with the account
1370 mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1371 // we need to announce the key as described in XEP-027
1372 announcePgp(mSelectedConversation.getAccount(), null, onOpenPGPKeyPublished);
1373 } else {
1374 choosePgpSignId(mSelectedConversation.getAccount());
1375 }
1376 this.mPostponedActivityResult = null;
1377 } else {
1378 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1379 }
1380 } else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1381 if (xmppConnectionServiceBound) {
1382 announcePgp(mSelectedConversation.getAccount(), mSelectedConversation, onOpenPGPKeyPublished);
1383 this.mPostponedActivityResult = null;
1384 } else {
1385 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1386 }
1387 } else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1388 mPendingImageUris.clear();
1389 mPendingImageUris.addAll(extractUriFromIntent(data));
1390 if (xmppConnectionServiceBound) {
1391 for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1392 Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. CHOOSE_IMAGE");
1393 attachImageToConversation(getSelectedConversation(), i.next());
1394 }
1395 }
1396 } else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1397 final List<Uri> uris = extractUriFromIntent(data);
1398 final Conversation c = getSelectedConversation();
1399 final OnPresenceSelected callback = new OnPresenceSelected() {
1400 @Override
1401 public void onPresenceSelected() {
1402 mPendingFileUris.clear();
1403 mPendingFileUris.addAll(uris);
1404 if (xmppConnectionServiceBound) {
1405 for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1406 Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE");
1407 attachFileToConversation(c, i.next());
1408 }
1409 }
1410 }
1411 };
1412 if (c == null || c.getMode() == Conversation.MODE_MULTI
1413 || FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1414 || c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1415 callback.onPresenceSelected();
1416 } else {
1417 selectPresence(c, callback);
1418 }
1419 } else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1420 if (mPendingImageUris.size() == 1) {
1421 Uri uri = FileBackend.getIndexableTakePhotoUri(mPendingImageUris.get(0));
1422 mPendingImageUris.set(0, uri);
1423 if (xmppConnectionServiceBound) {
1424 Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. TAKE_PHOTO");
1425 attachImageToConversation(getSelectedConversation(), uri);
1426 mPendingImageUris.clear();
1427 }
1428 if (!Config.ONLY_INTERNAL_STORAGE) {
1429 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1430 intent.setData(uri);
1431 sendBroadcast(intent);
1432 }
1433 } else {
1434 mPendingImageUris.clear();
1435 }
1436 } else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1437 double latitude = data.getDoubleExtra("latitude", 0);
1438 double longitude = data.getDoubleExtra("longitude", 0);
1439 this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1440 if (xmppConnectionServiceBound) {
1441 attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1442 this.mPendingGeoUri = null;
1443 }
1444 } else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1445 this.forbidProcessingPendings = !xmppConnectionServiceBound;
1446 if (xmppConnectionServiceBound) {
1447 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1448 this.mPostponedActivityResult = null;
1449 } else {
1450 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1451 }
1452
1453 }
1454 } else {
1455 mPendingImageUris.clear();
1456 mPendingFileUris.clear();
1457 if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1458 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1459 }
1460 if (requestCode == REQUEST_BATTERY_OP) {
1461 setNeverAskForBatteryOptimizationsAgain();
1462 }
1463 }
1464 }
1465
1466 private long getMaxHttpUploadSize(Conversation conversation) {
1467 final XmppConnection connection = conversation.getAccount().getXmppConnection();
1468 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
1469 }
1470
1471 private void setNeverAskForBatteryOptimizationsAgain() {
1472 getPreferences().edit().putBoolean("show_battery_optimization", false).commit();
1473 }
1474
1475 private void openBatteryOptimizationDialogIfNeeded() {
1476 if (hasAccountWithoutPush()
1477 && isOptimizingBattery()
1478 && getPreferences().getBoolean("show_battery_optimization", true)) {
1479 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1480 builder.setTitle(R.string.battery_optimizations_enabled);
1481 builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1482 builder.setPositiveButton(R.string.next, new OnClickListener() {
1483 @Override
1484 public void onClick(DialogInterface dialog, int which) {
1485 Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1486 Uri uri = Uri.parse("package:" + getPackageName());
1487 intent.setData(uri);
1488 try {
1489 startActivityForResult(intent, REQUEST_BATTERY_OP);
1490 } catch (ActivityNotFoundException e) {
1491 Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1492 }
1493 }
1494 });
1495 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1496 builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1497 @Override
1498 public void onDismiss(DialogInterface dialog) {
1499 setNeverAskForBatteryOptimizationsAgain();
1500 }
1501 });
1502 }
1503 builder.create().show();
1504 }
1505 }
1506
1507 private boolean hasAccountWithoutPush() {
1508 for(Account account : xmppConnectionService.getAccounts()) {
1509 if (account.getStatus() != Account.State.DISABLED
1510 && !xmppConnectionService.getPushManagementService().availableAndUseful(account)) {
1511 return true;
1512 }
1513 }
1514 return false;
1515 }
1516
1517 private void attachLocationToConversation(Conversation conversation, Uri uri) {
1518 if (conversation == null) {
1519 return;
1520 }
1521 xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1522
1523 @Override
1524 public void success(Message message) {
1525 xmppConnectionService.sendMessage(message);
1526 }
1527
1528 @Override
1529 public void error(int errorCode, Message object) {
1530
1531 }
1532
1533 @Override
1534 public void userInputRequried(PendingIntent pi, Message object) {
1535
1536 }
1537 });
1538 }
1539
1540 private void attachFileToConversation(Conversation conversation, Uri uri) {
1541 if (conversation == null) {
1542 return;
1543 }
1544 final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1545 prepareFileToast.show();
1546 xmppConnectionService.attachFileToConversation(conversation, uri, new UiInformableCallback<Message>() {
1547 @Override
1548 public void inform(final String text) {
1549 hidePrepareFileToast(prepareFileToast);
1550 runOnUiThread(new Runnable() {
1551 @Override
1552 public void run() {
1553 replaceToast(text);
1554 }
1555 });
1556 }
1557
1558 @Override
1559 public void success(Message message) {
1560 runOnUiThread(new Runnable() {
1561 @Override
1562 public void run() {
1563 hideToast();
1564 }
1565 });
1566 hidePrepareFileToast(prepareFileToast);
1567 xmppConnectionService.sendMessage(message);
1568 }
1569
1570 @Override
1571 public void error(final int errorCode, Message message) {
1572 hidePrepareFileToast(prepareFileToast);
1573 runOnUiThread(new Runnable() {
1574 @Override
1575 public void run() {
1576 replaceToast(getString(errorCode));
1577 }
1578 });
1579
1580 }
1581
1582 @Override
1583 public void userInputRequried(PendingIntent pi, Message message) {
1584 hidePrepareFileToast(prepareFileToast);
1585 }
1586 });
1587 }
1588
1589 public void attachImageToConversation(Uri uri) {
1590 this.attachImageToConversation(getSelectedConversation(), uri);
1591 }
1592
1593 private void attachImageToConversation(Conversation conversation, Uri uri) {
1594 if (conversation == null) {
1595 return;
1596 }
1597 final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1598 prepareFileToast.show();
1599 xmppConnectionService.attachImageToConversation(conversation, uri,
1600 new UiCallback<Message>() {
1601
1602 @Override
1603 public void userInputRequried(PendingIntent pi, Message object) {
1604 hidePrepareFileToast(prepareFileToast);
1605 }
1606
1607 @Override
1608 public void success(Message message) {
1609 hidePrepareFileToast(prepareFileToast);
1610 xmppConnectionService.sendMessage(message);
1611 }
1612
1613 @Override
1614 public void error(final int error, Message message) {
1615 hidePrepareFileToast(prepareFileToast);
1616 runOnUiThread(new Runnable() {
1617 @Override
1618 public void run() {
1619 replaceToast(getString(error));
1620 }
1621 });
1622 }
1623 });
1624 }
1625
1626 private void hidePrepareFileToast(final Toast prepareFileToast) {
1627 if (prepareFileToast != null) {
1628 runOnUiThread(new Runnable() {
1629
1630 @Override
1631 public void run() {
1632 prepareFileToast.cancel();
1633 }
1634 });
1635 }
1636 }
1637
1638 public void updateConversationList() {
1639 xmppConnectionService
1640 .populateWithOrderedConversations(conversationList);
1641 if (swipedConversation != null) {
1642 if (swipedConversation.isRead()) {
1643 conversationList.remove(swipedConversation);
1644 } else {
1645 listView.discardUndo();
1646 }
1647 }
1648 listAdapter.notifyDataSetChanged();
1649 }
1650
1651 public void runIntent(PendingIntent pi, int requestCode) {
1652 try {
1653 this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1654 null, 0, 0, 0);
1655 } catch (final SendIntentException ignored) {
1656 }
1657 }
1658
1659 public void encryptTextMessage(Message message) {
1660 xmppConnectionService.getPgpEngine().encrypt(message,
1661 new UiCallback<Message>() {
1662
1663 @Override
1664 public void userInputRequried(PendingIntent pi,Message message) {
1665 ConversationActivity.this.runIntent(pi,ConversationActivity.REQUEST_SEND_MESSAGE);
1666 }
1667
1668 @Override
1669 public void success(Message message) {
1670 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1671 xmppConnectionService.sendMessage(message);
1672 if (mConversationFragment != null) {
1673 mConversationFragment.messageSent();
1674 }
1675 }
1676
1677 @Override
1678 public void error(final int error, Message message) {
1679 runOnUiThread(new Runnable() {
1680 @Override
1681 public void run() {
1682 Toast.makeText(ConversationActivity.this,
1683 R.string.unable_to_connect_to_keychain,
1684 Toast.LENGTH_SHORT
1685 ).show();
1686 }
1687 });
1688 }
1689 });
1690 }
1691
1692 public boolean useSendButtonToIndicateStatus() {
1693 return getPreferences().getBoolean("send_button_status", false);
1694 }
1695
1696 public boolean indicateReceived() {
1697 return getPreferences().getBoolean("indicate_received", false);
1698 }
1699
1700 public boolean useGreenBackground() {
1701 return getPreferences().getBoolean("use_green_background",true);
1702 }
1703
1704 protected boolean trustKeysIfNeeded(int requestCode) {
1705 return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1706 }
1707
1708 protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1709 AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1710 final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1711 boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1712 boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty();
1713 boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty();
1714 boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1715 boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1716 if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1717 axolotlService.createSessionsIfNeeded(mSelectedConversation);
1718 Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1719 String[] contacts = new String[targets.size()];
1720 for(int i = 0; i < contacts.length; ++i) {
1721 contacts[i] = targets.get(i).toString();
1722 }
1723 intent.putExtra("contacts", contacts);
1724 intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1725 intent.putExtra("choice", attachmentChoice);
1726 intent.putExtra("conversation",mSelectedConversation.getUuid());
1727 startActivityForResult(intent, requestCode);
1728 return true;
1729 } else {
1730 return false;
1731 }
1732 }
1733
1734 @Override
1735 protected void refreshUiReal() {
1736 updateConversationList();
1737 if (conversationList.size() > 0) {
1738 if (!this.mConversationFragment.isAdded()) {
1739 Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1740 }
1741 ConversationActivity.this.mConversationFragment.updateMessages();
1742 updateActionBarTitle();
1743 invalidateOptionsMenu();
1744 } else {
1745 Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1746 }
1747 }
1748
1749 @Override
1750 public void onAccountUpdate() {
1751 this.refreshUi();
1752 }
1753
1754 @Override
1755 public void onConversationUpdate() {
1756 this.refreshUi();
1757 }
1758
1759 @Override
1760 public void onRosterUpdate() {
1761 this.refreshUi();
1762 }
1763
1764 @Override
1765 public void OnUpdateBlocklist(Status status) {
1766 this.refreshUi();
1767 }
1768
1769 public void unblockConversation(final Blockable conversation) {
1770 xmppConnectionService.sendUnblockRequest(conversation);
1771 }
1772
1773 public boolean enterIsSend() {
1774 return getPreferences().getBoolean("enter_is_send",false);
1775 }
1776
1777 @Override
1778 public void onShowErrorToast(final int resId) {
1779 runOnUiThread(new Runnable() {
1780 @Override
1781 public void run() {
1782 Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1783 }
1784 });
1785 }
1786
1787 public boolean highlightSelectedConversations() {
1788 return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1789 }
1790}