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