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 }
1275 }
1276
1277 private void handleViewConversationIntent(final Intent intent) {
1278 final String uuid = intent.getStringExtra(CONVERSATION);
1279 final String downloadUuid = intent.getStringExtra(EXTRA_DOWNLOAD_UUID);
1280 final String text = intent.getStringExtra(TEXT);
1281 final String nick = intent.getStringExtra(NICK);
1282 final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1283 if (selectConversationByUuid(uuid)) {
1284 this.mConversationFragment.reInit(getSelectedConversation());
1285 if (nick != null) {
1286 if (pm) {
1287 Jid jid = getSelectedConversation().getJid();
1288 try {
1289 Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1290 this.mConversationFragment.privateMessageWith(next);
1291 } catch (final InvalidJidException ignored) {
1292 //do nothing
1293 }
1294 } else {
1295 this.mConversationFragment.highlightInConference(nick);
1296 }
1297 } else {
1298 this.mConversationFragment.appendText(text);
1299 }
1300 hideConversationsOverview();
1301 mUnprocessedNewIntent = false;
1302 openConversation();
1303 if (mContentView instanceof SlidingPaneLayout) {
1304 updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1305 }
1306 if (downloadUuid != null) {
1307 final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1308 if (message != null) {
1309 startDownloadable(message);
1310 }
1311 }
1312 } else {
1313 mUnprocessedNewIntent = false;
1314 }
1315 }
1316
1317 private boolean selectConversationByUuid(String uuid) {
1318 if (uuid == null) {
1319 return false;
1320 }
1321 for (Conversation aConversationList : conversationList) {
1322 if (aConversationList.getUuid().equals(uuid)) {
1323 setSelectedConversation(aConversationList);
1324 return true;
1325 }
1326 }
1327 return false;
1328 }
1329
1330 @Override
1331 protected void unregisterListeners() {
1332 super.unregisterListeners();
1333 xmppConnectionService.getNotificationService().setOpenConversation(null);
1334 }
1335
1336 @SuppressLint("NewApi")
1337 private static List<Uri> extractUriFromIntent(final Intent intent) {
1338 List<Uri> uris = new ArrayList<>();
1339 if (intent == null) {
1340 return uris;
1341 }
1342 Uri uri = intent.getData();
1343 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1344 final ClipData clipData = intent.getClipData();
1345 if (clipData != null) {
1346 for (int i = 0; i < clipData.getItemCount(); ++i) {
1347 uris.add(clipData.getItemAt(i).getUri());
1348 }
1349 }
1350 } else {
1351 uris.add(uri);
1352 }
1353 return uris;
1354 }
1355
1356 @Override
1357 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1358 super.onActivityResult(requestCode, resultCode, data);
1359 if (resultCode == RESULT_OK) {
1360 if (requestCode == REQUEST_DECRYPT_PGP) {
1361 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1362 } else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1363 // the user chose OpenPGP for encryption and selected his key in the PGP provider
1364 if (xmppConnectionServiceBound) {
1365 if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1366 // associate selected PGP keyId with the account
1367 mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1368 // we need to announce the key as described in XEP-027
1369 announcePgp(mSelectedConversation.getAccount(), null, onOpenPGPKeyPublished);
1370 } else {
1371 choosePgpSignId(mSelectedConversation.getAccount());
1372 }
1373 this.mPostponedActivityResult = null;
1374 } else {
1375 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1376 }
1377 } else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1378 if (xmppConnectionServiceBound) {
1379 announcePgp(mSelectedConversation.getAccount(), mSelectedConversation, onOpenPGPKeyPublished);
1380 this.mPostponedActivityResult = null;
1381 } else {
1382 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1383 }
1384 } else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1385 mPendingImageUris.clear();
1386 mPendingImageUris.addAll(extractUriFromIntent(data));
1387 if (xmppConnectionServiceBound) {
1388 for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1389 Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. CHOOSE_IMAGE");
1390 attachImageToConversation(getSelectedConversation(), i.next());
1391 }
1392 }
1393 } else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1394 final List<Uri> uris = extractUriFromIntent(data);
1395 final Conversation c = getSelectedConversation();
1396 final OnPresenceSelected callback = new OnPresenceSelected() {
1397 @Override
1398 public void onPresenceSelected() {
1399 mPendingFileUris.clear();
1400 mPendingFileUris.addAll(uris);
1401 if (xmppConnectionServiceBound) {
1402 for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1403 Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE");
1404 attachFileToConversation(c, i.next());
1405 }
1406 }
1407 }
1408 };
1409 if (c == null || c.getMode() == Conversation.MODE_MULTI
1410 || FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1411 || c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1412 callback.onPresenceSelected();
1413 } else {
1414 selectPresence(c, callback);
1415 }
1416 } else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1417 if (mPendingImageUris.size() == 1) {
1418 Uri uri = FileBackend.getIndexableTakePhotoUri(mPendingImageUris.get(0));
1419 mPendingImageUris.set(0, uri);
1420 if (xmppConnectionServiceBound) {
1421 Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. TAKE_PHOTO");
1422 attachImageToConversation(getSelectedConversation(), uri);
1423 mPendingImageUris.clear();
1424 }
1425 if (!Config.ONLY_INTERNAL_STORAGE) {
1426 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1427 intent.setData(uri);
1428 sendBroadcast(intent);
1429 }
1430 } else {
1431 mPendingImageUris.clear();
1432 }
1433 } else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1434 double latitude = data.getDoubleExtra("latitude", 0);
1435 double longitude = data.getDoubleExtra("longitude", 0);
1436 this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1437 if (xmppConnectionServiceBound) {
1438 attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1439 this.mPendingGeoUri = null;
1440 }
1441 } else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1442 this.forbidProcessingPendings = !xmppConnectionServiceBound;
1443 if (xmppConnectionServiceBound) {
1444 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1445 this.mPostponedActivityResult = null;
1446 } else {
1447 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1448 }
1449
1450 }
1451 } else {
1452 mPendingImageUris.clear();
1453 mPendingFileUris.clear();
1454 if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1455 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1456 }
1457 if (requestCode == REQUEST_BATTERY_OP) {
1458 setNeverAskForBatteryOptimizationsAgain();
1459 }
1460 }
1461 }
1462
1463 private long getMaxHttpUploadSize(Conversation conversation) {
1464 final XmppConnection connection = conversation.getAccount().getXmppConnection();
1465 return connection == null ? -1 : connection.getFeatures().getMaxHttpUploadSize();
1466 }
1467
1468 private void setNeverAskForBatteryOptimizationsAgain() {
1469 getPreferences().edit().putBoolean("show_battery_optimization", false).commit();
1470 }
1471
1472 private void openBatteryOptimizationDialogIfNeeded() {
1473 if (hasAccountWithoutPush()
1474 && isOptimizingBattery()
1475 && getPreferences().getBoolean("show_battery_optimization", true)) {
1476 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1477 builder.setTitle(R.string.battery_optimizations_enabled);
1478 builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1479 builder.setPositiveButton(R.string.next, new OnClickListener() {
1480 @Override
1481 public void onClick(DialogInterface dialog, int which) {
1482 Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1483 Uri uri = Uri.parse("package:" + getPackageName());
1484 intent.setData(uri);
1485 try {
1486 startActivityForResult(intent, REQUEST_BATTERY_OP);
1487 } catch (ActivityNotFoundException e) {
1488 Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1489 }
1490 }
1491 });
1492 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1493 builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1494 @Override
1495 public void onDismiss(DialogInterface dialog) {
1496 setNeverAskForBatteryOptimizationsAgain();
1497 }
1498 });
1499 }
1500 builder.create().show();
1501 }
1502 }
1503
1504 private boolean hasAccountWithoutPush() {
1505 for(Account account : xmppConnectionService.getAccounts()) {
1506 if (account.getStatus() != Account.State.DISABLED
1507 && !xmppConnectionService.getPushManagementService().availableAndUseful(account)) {
1508 return true;
1509 }
1510 }
1511 return false;
1512 }
1513
1514 private void attachLocationToConversation(Conversation conversation, Uri uri) {
1515 if (conversation == null) {
1516 return;
1517 }
1518 xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1519
1520 @Override
1521 public void success(Message message) {
1522 xmppConnectionService.sendMessage(message);
1523 }
1524
1525 @Override
1526 public void error(int errorCode, Message object) {
1527
1528 }
1529
1530 @Override
1531 public void userInputRequried(PendingIntent pi, Message object) {
1532
1533 }
1534 });
1535 }
1536
1537 private void attachFileToConversation(Conversation conversation, Uri uri) {
1538 if (conversation == null) {
1539 return;
1540 }
1541 final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1542 prepareFileToast.show();
1543 xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1544 @Override
1545 public void success(Message message) {
1546 hidePrepareFileToast(prepareFileToast);
1547 xmppConnectionService.sendMessage(message);
1548 }
1549
1550 @Override
1551 public void error(final int errorCode, Message message) {
1552 hidePrepareFileToast(prepareFileToast);
1553 runOnUiThread(new Runnable() {
1554 @Override
1555 public void run() {
1556 replaceToast(getString(errorCode));
1557 }
1558 });
1559
1560 }
1561
1562 @Override
1563 public void userInputRequried(PendingIntent pi, Message message) {
1564 hidePrepareFileToast(prepareFileToast);
1565 }
1566 });
1567 }
1568
1569 public void attachImageToConversation(Uri uri) {
1570 this.attachImageToConversation(getSelectedConversation(), uri);
1571 }
1572
1573 private void attachImageToConversation(Conversation conversation, Uri uri) {
1574 if (conversation == null) {
1575 return;
1576 }
1577 final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1578 prepareFileToast.show();
1579 xmppConnectionService.attachImageToConversation(conversation, uri,
1580 new UiCallback<Message>() {
1581
1582 @Override
1583 public void userInputRequried(PendingIntent pi, Message object) {
1584 hidePrepareFileToast(prepareFileToast);
1585 }
1586
1587 @Override
1588 public void success(Message message) {
1589 hidePrepareFileToast(prepareFileToast);
1590 xmppConnectionService.sendMessage(message);
1591 }
1592
1593 @Override
1594 public void error(final int error, Message message) {
1595 hidePrepareFileToast(prepareFileToast);
1596 runOnUiThread(new Runnable() {
1597 @Override
1598 public void run() {
1599 replaceToast(getString(error));
1600 }
1601 });
1602 }
1603 });
1604 }
1605
1606 private void hidePrepareFileToast(final Toast prepareFileToast) {
1607 if (prepareFileToast != null) {
1608 runOnUiThread(new Runnable() {
1609
1610 @Override
1611 public void run() {
1612 prepareFileToast.cancel();
1613 }
1614 });
1615 }
1616 }
1617
1618 public void updateConversationList() {
1619 xmppConnectionService
1620 .populateWithOrderedConversations(conversationList);
1621 if (swipedConversation != null) {
1622 if (swipedConversation.isRead()) {
1623 conversationList.remove(swipedConversation);
1624 } else {
1625 listView.discardUndo();
1626 }
1627 }
1628 listAdapter.notifyDataSetChanged();
1629 }
1630
1631 public void runIntent(PendingIntent pi, int requestCode) {
1632 try {
1633 this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1634 null, 0, 0, 0);
1635 } catch (final SendIntentException ignored) {
1636 }
1637 }
1638
1639 public void encryptTextMessage(Message message) {
1640 xmppConnectionService.getPgpEngine().encrypt(message,
1641 new UiCallback<Message>() {
1642
1643 @Override
1644 public void userInputRequried(PendingIntent pi,Message message) {
1645 ConversationActivity.this.runIntent(pi,ConversationActivity.REQUEST_SEND_MESSAGE);
1646 }
1647
1648 @Override
1649 public void success(Message message) {
1650 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1651 xmppConnectionService.sendMessage(message);
1652 if (mConversationFragment != null) {
1653 mConversationFragment.messageSent();
1654 }
1655 }
1656
1657 @Override
1658 public void error(final int error, Message message) {
1659 runOnUiThread(new Runnable() {
1660 @Override
1661 public void run() {
1662 Toast.makeText(ConversationActivity.this,
1663 R.string.unable_to_connect_to_keychain,
1664 Toast.LENGTH_SHORT
1665 ).show();
1666 }
1667 });
1668 }
1669 });
1670 }
1671
1672 public boolean useSendButtonToIndicateStatus() {
1673 return getPreferences().getBoolean("send_button_status", false);
1674 }
1675
1676 public boolean indicateReceived() {
1677 return getPreferences().getBoolean("indicate_received", false);
1678 }
1679
1680 public boolean useGreenBackground() {
1681 return getPreferences().getBoolean("use_green_background",true);
1682 }
1683
1684 protected boolean trustKeysIfNeeded(int requestCode) {
1685 return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1686 }
1687
1688 protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1689 AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1690 final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1691 boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1692 boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided()).isEmpty();
1693 boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), targets).isEmpty();
1694 boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1695 boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1696 if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1697 axolotlService.createSessionsIfNeeded(mSelectedConversation);
1698 Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1699 String[] contacts = new String[targets.size()];
1700 for(int i = 0; i < contacts.length; ++i) {
1701 contacts[i] = targets.get(i).toString();
1702 }
1703 intent.putExtra("contacts", contacts);
1704 intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1705 intent.putExtra("choice", attachmentChoice);
1706 intent.putExtra("conversation",mSelectedConversation.getUuid());
1707 startActivityForResult(intent, requestCode);
1708 return true;
1709 } else {
1710 return false;
1711 }
1712 }
1713
1714 @Override
1715 protected void refreshUiReal() {
1716 updateConversationList();
1717 if (conversationList.size() > 0) {
1718 if (!this.mConversationFragment.isAdded()) {
1719 Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1720 }
1721 ConversationActivity.this.mConversationFragment.updateMessages();
1722 updateActionBarTitle();
1723 invalidateOptionsMenu();
1724 } else {
1725 Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1726 }
1727 }
1728
1729 @Override
1730 public void onAccountUpdate() {
1731 this.refreshUi();
1732 }
1733
1734 @Override
1735 public void onConversationUpdate() {
1736 this.refreshUi();
1737 }
1738
1739 @Override
1740 public void onRosterUpdate() {
1741 this.refreshUi();
1742 }
1743
1744 @Override
1745 public void OnUpdateBlocklist(Status status) {
1746 this.refreshUi();
1747 }
1748
1749 public void unblockConversation(final Blockable conversation) {
1750 xmppConnectionService.sendUnblockRequest(conversation);
1751 }
1752
1753 public boolean enterIsSend() {
1754 return getPreferences().getBoolean("enter_is_send",false);
1755 }
1756
1757 @Override
1758 public void onShowErrorToast(final int resId) {
1759 runOnUiThread(new Runnable() {
1760 @Override
1761 public void run() {
1762 Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1763 }
1764 });
1765 }
1766
1767 public boolean highlightSelectedConversations() {
1768 return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1769 }
1770
1771 public void setMessagesLoaded() {
1772 if (mConversationFragment != null) {
1773 mConversationFragment.setMessagesLoaded();
1774 mConversationFragment.updateMessages();
1775 }
1776 }
1777}