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.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
498 intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
499 mPendingImageUris.clear();
500 mPendingImageUris.add(uri);
501 break;
502 case ATTACHMENT_CHOICE_CHOOSE_FILE:
503 chooser = true;
504 intent.setType("*/*");
505 intent.addCategory(Intent.CATEGORY_OPENABLE);
506 intent.setAction(Intent.ACTION_GET_CONTENT);
507 break;
508 case ATTACHMENT_CHOICE_RECORD_VOICE:
509 intent.setAction(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
510 fallbackPackageId = "eu.siacs.conversations.voicerecorder";
511 break;
512 case ATTACHMENT_CHOICE_LOCATION:
513 intent.setAction("eu.siacs.conversations.location.request");
514 fallbackPackageId = "eu.siacs.conversations.sharelocation";
515 break;
516 }
517 if (intent.resolveActivity(getPackageManager()) != null) {
518 if (chooser) {
519 startActivityForResult(
520 Intent.createChooser(intent, getString(R.string.perform_action_with)),
521 attachmentChoice);
522 } else {
523 startActivityForResult(intent, attachmentChoice);
524 }
525 } else if (fallbackPackageId != null) {
526 startActivity(getInstallApkIntent(fallbackPackageId));
527 }
528 }
529 };
530 if ((account.httpUploadAvailable() || attachmentChoice == ATTACHMENT_CHOICE_LOCATION) && encryption != Message.ENCRYPTION_OTR) {
531 conversation.setNextCounterpart(null);
532 callback.onPresenceSelected();
533 } else {
534 selectPresence(conversation, callback);
535 }
536 }
537
538 private Intent getInstallApkIntent(final String packageId) {
539 Intent intent = new Intent(Intent.ACTION_VIEW);
540 intent.setData(Uri.parse("market://details?id=" + packageId));
541 if (intent.resolveActivity(getPackageManager()) != null) {
542 return intent;
543 } else {
544 intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + packageId));
545 return intent;
546 }
547 }
548
549 public void attachFile(final int attachmentChoice) {
550 if (attachmentChoice != ATTACHMENT_CHOICE_LOCATION) {
551 if (!hasStoragePermission(attachmentChoice)) {
552 return;
553 }
554 }
555 switch (attachmentChoice) {
556 case ATTACHMENT_CHOICE_LOCATION:
557 getPreferences().edit().putString("recently_used_quick_action", "location").apply();
558 break;
559 case ATTACHMENT_CHOICE_RECORD_VOICE:
560 getPreferences().edit().putString("recently_used_quick_action", "voice").apply();
561 break;
562 case ATTACHMENT_CHOICE_TAKE_PHOTO:
563 getPreferences().edit().putString("recently_used_quick_action", "photo").apply();
564 break;
565 case ATTACHMENT_CHOICE_CHOOSE_IMAGE:
566 getPreferences().edit().putString("recently_used_quick_action", "picture").apply();
567 break;
568 }
569 final Conversation conversation = getSelectedConversation();
570 final int encryption = conversation.getNextEncryption();
571 final int mode = conversation.getMode();
572 if (encryption == Message.ENCRYPTION_PGP) {
573 if (hasPgp()) {
574 if (mode == Conversation.MODE_SINGLE && conversation.getContact().getPgpKeyId() != 0) {
575 xmppConnectionService.getPgpEngine().hasKey(
576 conversation.getContact(),
577 new UiCallback<Contact>() {
578
579 @Override
580 public void userInputRequried(PendingIntent pi, Contact contact) {
581 ConversationActivity.this.runIntent(pi, attachmentChoice);
582 }
583
584 @Override
585 public void success(Contact contact) {
586 selectPresenceToAttachFile(attachmentChoice, encryption);
587 }
588
589 @Override
590 public void error(int error, Contact contact) {
591 replaceToast(getString(error));
592 }
593 });
594 } else if (mode == Conversation.MODE_MULTI && conversation.getMucOptions().pgpKeysInUse()) {
595 if (!conversation.getMucOptions().everybodyHasKeys()) {
596 Toast warning = Toast
597 .makeText(this,
598 R.string.missing_public_keys,
599 Toast.LENGTH_LONG);
600 warning.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
601 warning.show();
602 }
603 selectPresenceToAttachFile(attachmentChoice, encryption);
604 } else {
605 final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
606 .findFragmentByTag("conversation");
607 if (fragment != null) {
608 fragment.showNoPGPKeyDialog(false,
609 new OnClickListener() {
610
611 @Override
612 public void onClick(DialogInterface dialog,
613 int which) {
614 conversation
615 .setNextEncryption(Message.ENCRYPTION_NONE);
616 xmppConnectionService.databaseBackend
617 .updateConversation(conversation);
618 selectPresenceToAttachFile(attachmentChoice, Message.ENCRYPTION_NONE);
619 }
620 });
621 }
622 }
623 } else {
624 showInstallPgpDialog();
625 }
626 } else {
627 if (encryption != Message.ENCRYPTION_AXOLOTL || !trustKeysIfNeeded(REQUEST_TRUST_KEYS_MENU, attachmentChoice)) {
628 selectPresenceToAttachFile(attachmentChoice, encryption);
629 }
630 }
631 }
632
633 @Override
634 public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
635 if (grantResults.length > 0)
636 if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
637 if (requestCode == REQUEST_START_DOWNLOAD) {
638 if (this.mPendingDownloadableMessage != null) {
639 startDownloadable(this.mPendingDownloadableMessage);
640 }
641 } else {
642 attachFile(requestCode);
643 }
644 } else {
645 Toast.makeText(this, R.string.no_storage_permission, Toast.LENGTH_SHORT).show();
646 }
647 }
648
649 public void startDownloadable(Message message) {
650 if (!hasStoragePermission(ConversationActivity.REQUEST_START_DOWNLOAD)) {
651 this.mPendingDownloadableMessage = message;
652 return;
653 }
654 Transferable transferable = message.getTransferable();
655 if (transferable != null) {
656 if (!transferable.start()) {
657 Toast.makeText(this, R.string.not_connected_try_again, Toast.LENGTH_SHORT).show();
658 }
659 } else if (message.treatAsDownloadable() != Message.Decision.NEVER) {
660 xmppConnectionService.getHttpConnectionManager().createNewDownloadConnection(message, true);
661 }
662 }
663
664 @Override
665 public boolean onOptionsItemSelected(final MenuItem item) {
666 if (item.getItemId() == android.R.id.home) {
667 showConversationsOverview();
668 return true;
669 } else if (item.getItemId() == R.id.action_add) {
670 startActivity(new Intent(this, StartConversationActivity.class));
671 return true;
672 } else if (getSelectedConversation() != null) {
673 switch (item.getItemId()) {
674 case R.id.action_attach_file:
675 attachFileDialog();
676 break;
677 case R.id.action_archive:
678 this.endConversation(getSelectedConversation());
679 break;
680 case R.id.action_contact_details:
681 switchToContactDetails(getSelectedConversation().getContact());
682 break;
683 case R.id.action_muc_details:
684 Intent intent = new Intent(this,
685 ConferenceDetailsActivity.class);
686 intent.setAction(ConferenceDetailsActivity.ACTION_VIEW_MUC);
687 intent.putExtra("uuid", getSelectedConversation().getUuid());
688 startActivity(intent);
689 break;
690 case R.id.action_invite:
691 inviteToConversation(getSelectedConversation());
692 break;
693 case R.id.action_security:
694 selectEncryptionDialog(getSelectedConversation());
695 break;
696 case R.id.action_clear_history:
697 clearHistoryDialog(getSelectedConversation());
698 break;
699 case R.id.action_mute:
700 muteConversationDialog(getSelectedConversation());
701 break;
702 case R.id.action_unmute:
703 unmuteConversation(getSelectedConversation());
704 break;
705 case R.id.action_block:
706 BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
707 break;
708 case R.id.action_unblock:
709 BlockContactDialog.show(this, xmppConnectionService, getSelectedConversation());
710 break;
711 default:
712 break;
713 }
714 return super.onOptionsItemSelected(item);
715 } else {
716 return super.onOptionsItemSelected(item);
717 }
718 }
719
720 public void endConversation(Conversation conversation) {
721 endConversation(conversation, true, true);
722 }
723
724 public void endConversation(Conversation conversation, boolean showOverview, boolean reinit) {
725 if (showOverview) {
726 showConversationsOverview();
727 }
728 xmppConnectionService.archiveConversation(conversation);
729 if (reinit) {
730 if (conversationList.size() > 0) {
731 setSelectedConversation(conversationList.get(0));
732 this.mConversationFragment.reInit(getSelectedConversation());
733 } else {
734 setSelectedConversation(null);
735 if (mRedirected.compareAndSet(false, true)) {
736 Intent intent = new Intent(this, StartConversationActivity.class);
737 intent.putExtra("init", true);
738 startActivity(intent);
739 finish();
740 }
741 }
742 }
743 }
744
745 @SuppressLint("InflateParams")
746 protected void clearHistoryDialog(final Conversation conversation) {
747 AlertDialog.Builder builder = new AlertDialog.Builder(this);
748 builder.setTitle(getString(R.string.clear_conversation_history));
749 View dialogView = getLayoutInflater().inflate(
750 R.layout.dialog_clear_history, null);
751 final CheckBox endConversationCheckBox = (CheckBox) dialogView
752 .findViewById(R.id.end_conversation_checkbox);
753 builder.setView(dialogView);
754 builder.setNegativeButton(getString(R.string.cancel), null);
755 builder.setPositiveButton(getString(R.string.delete_messages),
756 new OnClickListener() {
757
758 @Override
759 public void onClick(DialogInterface dialog, int which) {
760 ConversationActivity.this.xmppConnectionService.clearConversationHistory(conversation);
761 if (endConversationCheckBox.isChecked()) {
762 endConversation(conversation);
763 } else {
764 updateConversationList();
765 ConversationActivity.this.mConversationFragment.updateMessages();
766 }
767 }
768 });
769 builder.create().show();
770 }
771
772 protected void attachFileDialog() {
773 View menuAttachFile = findViewById(R.id.action_attach_file);
774 if (menuAttachFile == null) {
775 return;
776 }
777 PopupMenu attachFilePopup = new PopupMenu(this, menuAttachFile);
778 attachFilePopup.inflate(R.menu.attachment_choices);
779 if (new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION).resolveActivity(getPackageManager()) == null) {
780 attachFilePopup.getMenu().findItem(R.id.attach_record_voice).setVisible(false);
781 }
782 if (new Intent("eu.siacs.conversations.location.request").resolveActivity(getPackageManager()) == null) {
783 attachFilePopup.getMenu().findItem(R.id.attach_location).setVisible(false);
784 }
785 attachFilePopup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
786
787 @Override
788 public boolean onMenuItemClick(MenuItem item) {
789 switch (item.getItemId()) {
790 case R.id.attach_choose_picture:
791 attachFile(ATTACHMENT_CHOICE_CHOOSE_IMAGE);
792 break;
793 case R.id.attach_take_picture:
794 attachFile(ATTACHMENT_CHOICE_TAKE_PHOTO);
795 break;
796 case R.id.attach_choose_file:
797 attachFile(ATTACHMENT_CHOICE_CHOOSE_FILE);
798 break;
799 case R.id.attach_record_voice:
800 attachFile(ATTACHMENT_CHOICE_RECORD_VOICE);
801 break;
802 case R.id.attach_location:
803 attachFile(ATTACHMENT_CHOICE_LOCATION);
804 break;
805 }
806 return false;
807 }
808 });
809 attachFilePopup.show();
810 }
811
812 public void verifyOtrSessionDialog(final Conversation conversation, View view) {
813 if (!conversation.hasValidOtrSession() || conversation.getOtrSession().getSessionStatus() != SessionStatus.ENCRYPTED) {
814 Toast.makeText(this, R.string.otr_session_not_started, Toast.LENGTH_LONG).show();
815 return;
816 }
817 if (view == null) {
818 return;
819 }
820 PopupMenu popup = new PopupMenu(this, view);
821 popup.inflate(R.menu.verification_choices);
822 popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
823 @Override
824 public boolean onMenuItemClick(MenuItem menuItem) {
825 Intent intent = new Intent(ConversationActivity.this, VerifyOTRActivity.class);
826 intent.setAction(VerifyOTRActivity.ACTION_VERIFY_CONTACT);
827 intent.putExtra("contact", conversation.getContact().getJid().toBareJid().toString());
828 intent.putExtra(EXTRA_ACCOUNT, conversation.getAccount().getJid().toBareJid().toString());
829 switch (menuItem.getItemId()) {
830 case R.id.scan_fingerprint:
831 intent.putExtra("mode", VerifyOTRActivity.MODE_SCAN_FINGERPRINT);
832 break;
833 case R.id.ask_question:
834 intent.putExtra("mode", VerifyOTRActivity.MODE_ASK_QUESTION);
835 break;
836 case R.id.manual_verification:
837 intent.putExtra("mode", VerifyOTRActivity.MODE_MANUAL_VERIFICATION);
838 break;
839 }
840 startActivity(intent);
841 return true;
842 }
843 });
844 popup.show();
845 }
846
847 protected void selectEncryptionDialog(final Conversation conversation) {
848 View menuItemView = findViewById(R.id.action_security);
849 if (menuItemView == null) {
850 return;
851 }
852 PopupMenu popup = new PopupMenu(this, menuItemView);
853 final ConversationFragment fragment = (ConversationFragment) getFragmentManager()
854 .findFragmentByTag("conversation");
855 if (fragment != null) {
856 popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
857
858 @Override
859 public boolean onMenuItemClick(MenuItem item) {
860 switch (item.getItemId()) {
861 case R.id.encryption_choice_none:
862 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
863 item.setChecked(true);
864 break;
865 case R.id.encryption_choice_otr:
866 conversation.setNextEncryption(Message.ENCRYPTION_OTR);
867 item.setChecked(true);
868 break;
869 case R.id.encryption_choice_pgp:
870 if (hasPgp()) {
871 if (conversation.getAccount().getPgpSignature() != null) {
872 conversation.setNextEncryption(Message.ENCRYPTION_PGP);
873 item.setChecked(true);
874 } else {
875 announcePgp(conversation.getAccount(), conversation, onOpenPGPKeyPublished);
876 }
877 } else {
878 showInstallPgpDialog();
879 }
880 break;
881 case R.id.encryption_choice_axolotl:
882 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(conversation.getAccount())
883 + "Enabled axolotl for Contact " + conversation.getContact().getJid());
884 conversation.setNextEncryption(Message.ENCRYPTION_AXOLOTL);
885 item.setChecked(true);
886 break;
887 default:
888 conversation.setNextEncryption(Message.ENCRYPTION_NONE);
889 break;
890 }
891 xmppConnectionService.databaseBackend.updateConversation(conversation);
892 fragment.updateChatMsgHint();
893 invalidateOptionsMenu();
894 refreshUi();
895 return true;
896 }
897 });
898 popup.inflate(R.menu.encryption_choices);
899 MenuItem otr = popup.getMenu().findItem(R.id.encryption_choice_otr);
900 MenuItem none = popup.getMenu().findItem(R.id.encryption_choice_none);
901 MenuItem pgp = popup.getMenu().findItem(R.id.encryption_choice_pgp);
902 MenuItem axolotl = popup.getMenu().findItem(R.id.encryption_choice_axolotl);
903 pgp.setVisible(Config.supportOpenPgp());
904 none.setVisible(Config.supportUnencrypted() || conversation.getMode() == Conversation.MODE_MULTI);
905 otr.setVisible(Config.supportOtr());
906 axolotl.setVisible(Config.supportOmemo());
907 if (conversation.getMode() == Conversation.MODE_MULTI) {
908 otr.setVisible(false);
909 }
910 if (!conversation.getAccount().getAxolotlService().isConversationAxolotlCapable(conversation)) {
911 axolotl.setEnabled(false);
912 }
913 switch (conversation.getNextEncryption()) {
914 case Message.ENCRYPTION_NONE:
915 none.setChecked(true);
916 break;
917 case Message.ENCRYPTION_OTR:
918 otr.setChecked(true);
919 break;
920 case Message.ENCRYPTION_PGP:
921 pgp.setChecked(true);
922 break;
923 case Message.ENCRYPTION_AXOLOTL:
924 axolotl.setChecked(true);
925 break;
926 default:
927 none.setChecked(true);
928 break;
929 }
930 popup.show();
931 }
932 }
933
934 protected void muteConversationDialog(final Conversation conversation) {
935 AlertDialog.Builder builder = new AlertDialog.Builder(this);
936 builder.setTitle(R.string.disable_notifications);
937 final int[] durations = getResources().getIntArray(R.array.mute_options_durations);
938 builder.setItems(R.array.mute_options_descriptions,
939 new OnClickListener() {
940
941 @Override
942 public void onClick(final DialogInterface dialog, final int which) {
943 final long till;
944 if (durations[which] == -1) {
945 till = Long.MAX_VALUE;
946 } else {
947 till = System.currentTimeMillis() + (durations[which] * 1000);
948 }
949 conversation.setMutedTill(till);
950 ConversationActivity.this.xmppConnectionService.databaseBackend
951 .updateConversation(conversation);
952 updateConversationList();
953 ConversationActivity.this.mConversationFragment.updateMessages();
954 invalidateOptionsMenu();
955 }
956 });
957 builder.create().show();
958 }
959
960 public void unmuteConversation(final Conversation conversation) {
961 conversation.setMutedTill(0);
962 this.xmppConnectionService.databaseBackend.updateConversation(conversation);
963 updateConversationList();
964 ConversationActivity.this.mConversationFragment.updateMessages();
965 invalidateOptionsMenu();
966 }
967
968 @Override
969 public void onBackPressed() {
970 if (!isConversationsOverviewVisable()) {
971 showConversationsOverview();
972 } else {
973 moveTaskToBack(true);
974 }
975 }
976
977 @Override
978 public boolean onKeyUp(int key, KeyEvent event) {
979 int rotation = getWindowManager().getDefaultDisplay().getRotation();
980 final int upKey;
981 final int downKey;
982 switch (rotation) {
983 case Surface.ROTATION_90:
984 upKey = KeyEvent.KEYCODE_DPAD_LEFT;
985 downKey = KeyEvent.KEYCODE_DPAD_RIGHT;
986 break;
987 case Surface.ROTATION_180:
988 upKey = KeyEvent.KEYCODE_DPAD_DOWN;
989 downKey = KeyEvent.KEYCODE_DPAD_UP;
990 break;
991 case Surface.ROTATION_270:
992 upKey = KeyEvent.KEYCODE_DPAD_RIGHT;
993 downKey = KeyEvent.KEYCODE_DPAD_LEFT;
994 break;
995 default:
996 upKey = KeyEvent.KEYCODE_DPAD_UP;
997 downKey = KeyEvent.KEYCODE_DPAD_DOWN;
998 }
999 final boolean modifier = event.isCtrlPressed() || (event.getMetaState() & KeyEvent.META_ALT_LEFT_ON) != 0;
1000 if (modifier && key == KeyEvent.KEYCODE_TAB && isConversationsOverviewHideable()) {
1001 toggleConversationsOverview();
1002 return true;
1003 } else if (modifier && key == KeyEvent.KEYCODE_SPACE) {
1004 startActivity(new Intent(this, StartConversationActivity.class));
1005 return true;
1006 } else if (modifier && key == downKey) {
1007 if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1008 showConversationsOverview();
1009 ;
1010 }
1011 return selectDownConversation();
1012 } else if (modifier && key == upKey) {
1013 if (isConversationsOverviewHideable() && !isConversationsOverviewVisable()) {
1014 showConversationsOverview();
1015 }
1016 return selectUpConversation();
1017 } else if (modifier && key == KeyEvent.KEYCODE_1) {
1018 return openConversationByIndex(0);
1019 } else if (modifier && key == KeyEvent.KEYCODE_2) {
1020 return openConversationByIndex(1);
1021 } else if (modifier && key == KeyEvent.KEYCODE_3) {
1022 return openConversationByIndex(2);
1023 } else if (modifier && key == KeyEvent.KEYCODE_4) {
1024 return openConversationByIndex(3);
1025 } else if (modifier && key == KeyEvent.KEYCODE_5) {
1026 return openConversationByIndex(4);
1027 } else if (modifier && key == KeyEvent.KEYCODE_6) {
1028 return openConversationByIndex(5);
1029 } else if (modifier && key == KeyEvent.KEYCODE_7) {
1030 return openConversationByIndex(6);
1031 } else if (modifier && key == KeyEvent.KEYCODE_8) {
1032 return openConversationByIndex(7);
1033 } else if (modifier && key == KeyEvent.KEYCODE_9) {
1034 return openConversationByIndex(8);
1035 } else if (modifier && key == KeyEvent.KEYCODE_0) {
1036 return openConversationByIndex(9);
1037 } else {
1038 return super.onKeyUp(key, event);
1039 }
1040 }
1041
1042 private void toggleConversationsOverview() {
1043 if (isConversationsOverviewVisable()) {
1044 hideConversationsOverview();
1045 if (mConversationFragment != null) {
1046 mConversationFragment.setFocusOnInputField();
1047 }
1048 } else {
1049 showConversationsOverview();
1050 }
1051 }
1052
1053 private boolean selectUpConversation() {
1054 if (this.mSelectedConversation != null) {
1055 int index = this.conversationList.indexOf(this.mSelectedConversation);
1056 if (index > 0) {
1057 return openConversationByIndex(index - 1);
1058 }
1059 }
1060 return false;
1061 }
1062
1063 private boolean selectDownConversation() {
1064 if (this.mSelectedConversation != null) {
1065 int index = this.conversationList.indexOf(this.mSelectedConversation);
1066 if (index != -1 && index < this.conversationList.size() - 1) {
1067 return openConversationByIndex(index + 1);
1068 }
1069 }
1070 return false;
1071 }
1072
1073 private boolean openConversationByIndex(int index) {
1074 try {
1075 this.conversationWasSelectedByKeyboard = true;
1076 setSelectedConversation(this.conversationList.get(index));
1077 this.mConversationFragment.reInit(getSelectedConversation());
1078 if (index > listView.getLastVisiblePosition() - 1 || index < listView.getFirstVisiblePosition() + 1) {
1079 this.listView.setSelection(index);
1080 }
1081 openConversation();
1082 return true;
1083 } catch (IndexOutOfBoundsException e) {
1084 return false;
1085 }
1086 }
1087
1088 @Override
1089 protected void onNewIntent(final Intent intent) {
1090 if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1091 mOpenConversation = null;
1092 if (xmppConnectionServiceBound) {
1093 handleViewConversationIntent(intent);
1094 intent.setAction(Intent.ACTION_MAIN);
1095 } else {
1096 setIntent(intent);
1097 }
1098 }
1099 }
1100
1101 @Override
1102 public void onStart() {
1103 super.onStart();
1104 this.mRedirected.set(false);
1105 if (this.xmppConnectionServiceBound) {
1106 this.onBackendConnected();
1107 }
1108 if (conversationList.size() >= 1) {
1109 this.onConversationUpdate();
1110 }
1111 }
1112
1113 @Override
1114 public void onPause() {
1115 listView.discardUndo();
1116 super.onPause();
1117 this.mActivityPaused = true;
1118 }
1119
1120 @Override
1121 public void onResume() {
1122 super.onResume();
1123 final int theme = findTheme();
1124 final boolean usingEnterKey = usingEnterKey();
1125 if (this.mTheme != theme || usingEnterKey != mUsingEnterKey) {
1126 recreate();
1127 }
1128 this.mActivityPaused = false;
1129
1130 if (!isConversationsOverviewVisable() || !isConversationsOverviewHideable()) {
1131 sendReadMarkerIfNecessary(getSelectedConversation());
1132 }
1133
1134 }
1135
1136 @Override
1137 public void onSaveInstanceState(final Bundle savedInstanceState) {
1138 Conversation conversation = getSelectedConversation();
1139 if (conversation != null) {
1140 savedInstanceState.putString(STATE_OPEN_CONVERSATION, conversation.getUuid());
1141 Pair<Integer,Integer> scrollPosition = mConversationFragment.getScrollPosition();
1142 if (scrollPosition != null) {
1143 savedInstanceState.putInt(STATE_FIRST_VISIBLE, scrollPosition.first);
1144 savedInstanceState.putInt(STATE_OFFSET_FROM_TOP, scrollPosition.second);
1145 }
1146 } else {
1147 savedInstanceState.remove(STATE_OPEN_CONVERSATION);
1148 }
1149 savedInstanceState.putBoolean(STATE_PANEL_OPEN, isConversationsOverviewVisable());
1150 if (this.mPendingImageUris.size() >= 1) {
1151 Log.d(Config.LOGTAG,"ConversationsActivity.onSaveInstanceState() - saving pending image uri");
1152 savedInstanceState.putString(STATE_PENDING_URI, this.mPendingImageUris.get(0).toString());
1153 } else {
1154 savedInstanceState.remove(STATE_PENDING_URI);
1155 }
1156 super.onSaveInstanceState(savedInstanceState);
1157 }
1158
1159 private void clearPending() {
1160 mPendingImageUris.clear();
1161 mPendingFileUris.clear();
1162 mPendingGeoUri = null;
1163 mPostponedActivityResult = null;
1164 }
1165
1166 @Override
1167 void onBackendConnected() {
1168 this.xmppConnectionService.getNotificationService().setIsInForeground(true);
1169 updateConversationList();
1170
1171 if (mPendingConferenceInvite != null) {
1172 if (mPendingConferenceInvite.execute(this)) {
1173 mToast = Toast.makeText(this, R.string.creating_conference, Toast.LENGTH_LONG);
1174 mToast.show();
1175 }
1176 mPendingConferenceInvite = null;
1177 }
1178
1179 final Intent intent = getIntent();
1180
1181 if (xmppConnectionService.getAccounts().size() == 0) {
1182 if (mRedirected.compareAndSet(false, true)) {
1183 if (Config.X509_VERIFICATION) {
1184 startActivity(new Intent(this, ManageAccountActivity.class));
1185 } else if (Config.MAGIC_CREATE_DOMAIN != null) {
1186 startActivity(new Intent(this, WelcomeActivity.class));
1187 } else {
1188 Intent editAccount = new Intent(this, EditAccountActivity.class);
1189 editAccount.putExtra("init",true);
1190 startActivity(editAccount);
1191 }
1192 finish();
1193 }
1194 } else if (conversationList.size() <= 0) {
1195 if (mRedirected.compareAndSet(false, true)) {
1196 Account pendingAccount = xmppConnectionService.getPendingAccount();
1197 if (pendingAccount == null) {
1198 Intent startConversationActivity = new Intent(this, StartConversationActivity.class);
1199 intent.putExtra("init", true);
1200 startActivity(startConversationActivity);
1201 } else {
1202 switchToAccount(pendingAccount, true);
1203 }
1204 finish();
1205 }
1206 } else if (selectConversationByUuid(mOpenConversation)) {
1207 if (mPanelOpen) {
1208 showConversationsOverview();
1209 } else {
1210 if (isConversationsOverviewHideable()) {
1211 openConversation();
1212 updateActionBarTitle(true);
1213 }
1214 }
1215 if (this.mConversationFragment.reInit(getSelectedConversation())) {
1216 Log.d(Config.LOGTAG,"setting scroll position on fragment");
1217 this.mConversationFragment.setScrollPosition(mScrollPosition);
1218 }
1219 mOpenConversation = null;
1220 } else if (intent != null && ACTION_VIEW_CONVERSATION.equals(intent.getAction())) {
1221 clearPending();
1222 handleViewConversationIntent(intent);
1223 intent.setAction(Intent.ACTION_MAIN);
1224 } else if (getSelectedConversation() == null) {
1225 showConversationsOverview();
1226 clearPending();
1227 setSelectedConversation(conversationList.get(0));
1228 this.mConversationFragment.reInit(getSelectedConversation());
1229 } else {
1230 this.mConversationFragment.messageListAdapter.updatePreferences();
1231 this.mConversationFragment.messagesView.invalidateViews();
1232 this.mConversationFragment.setupIme();
1233 }
1234
1235 if (this.mPostponedActivityResult != null) {
1236 this.onActivityResult(mPostponedActivityResult.first, RESULT_OK, mPostponedActivityResult.second);
1237 }
1238
1239 final boolean stopping;
1240 if (Build.VERSION.SDK_INT >= 17) {
1241 stopping = isFinishing() || isDestroyed();
1242 } else {
1243 stopping = isFinishing();
1244 }
1245
1246 if (!forbidProcessingPendings) {
1247 for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1248 Uri foo = i.next();
1249 Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching image to conversations. stopping="+Boolean.toString(stopping));
1250 attachImageToConversation(getSelectedConversation(), foo);
1251 }
1252
1253 for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1254 Log.d(Config.LOGTAG,"ConversationsActivity.onBackendConnected() - attaching file to conversations. stopping="+Boolean.toString(stopping));
1255 attachFileToConversation(getSelectedConversation(), i.next());
1256 }
1257
1258 if (mPendingGeoUri != null) {
1259 attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1260 mPendingGeoUri = null;
1261 }
1262 }
1263 forbidProcessingPendings = false;
1264
1265 if (!ExceptionHelper.checkForCrash(this, this.xmppConnectionService)) {
1266 openBatteryOptimizationDialogIfNeeded();
1267 }
1268 }
1269
1270 private void handleViewConversationIntent(final Intent intent) {
1271 final String uuid = intent.getStringExtra(CONVERSATION);
1272 final String downloadUuid = intent.getStringExtra(EXTRA_DOWNLOAD_UUID);
1273 final String text = intent.getStringExtra(TEXT);
1274 final String nick = intent.getStringExtra(NICK);
1275 final boolean pm = intent.getBooleanExtra(PRIVATE_MESSAGE, false);
1276 if (selectConversationByUuid(uuid)) {
1277 this.mConversationFragment.reInit(getSelectedConversation());
1278 if (nick != null) {
1279 if (pm) {
1280 Jid jid = getSelectedConversation().getJid();
1281 try {
1282 Jid next = Jid.fromParts(jid.getLocalpart(), jid.getDomainpart(), nick);
1283 this.mConversationFragment.privateMessageWith(next);
1284 } catch (final InvalidJidException ignored) {
1285 //do nothing
1286 }
1287 } else {
1288 this.mConversationFragment.highlightInConference(nick);
1289 }
1290 } else {
1291 this.mConversationFragment.appendText(text);
1292 }
1293 hideConversationsOverview();
1294 openConversation();
1295 if (mContentView instanceof SlidingPaneLayout) {
1296 updateActionBarTitle(true); //fixes bug where slp isn't properly closed yet
1297 }
1298 if (downloadUuid != null) {
1299 final Message message = mSelectedConversation.findMessageWithFileAndUuid(downloadUuid);
1300 if (message != null) {
1301 startDownloadable(message);
1302 }
1303 }
1304 }
1305 }
1306
1307 private boolean selectConversationByUuid(String uuid) {
1308 if (uuid == null) {
1309 return false;
1310 }
1311 for (Conversation aConversationList : conversationList) {
1312 if (aConversationList.getUuid().equals(uuid)) {
1313 setSelectedConversation(aConversationList);
1314 return true;
1315 }
1316 }
1317 return false;
1318 }
1319
1320 @Override
1321 protected void unregisterListeners() {
1322 super.unregisterListeners();
1323 xmppConnectionService.getNotificationService().setOpenConversation(null);
1324 }
1325
1326 @SuppressLint("NewApi")
1327 private static List<Uri> extractUriFromIntent(final Intent intent) {
1328 List<Uri> uris = new ArrayList<>();
1329 if (intent == null) {
1330 return uris;
1331 }
1332 Uri uri = intent.getData();
1333 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && uri == null) {
1334 final ClipData clipData = intent.getClipData();
1335 if (clipData != null) {
1336 for (int i = 0; i < clipData.getItemCount(); ++i) {
1337 uris.add(clipData.getItemAt(i).getUri());
1338 }
1339 }
1340 } else {
1341 uris.add(uri);
1342 }
1343 return uris;
1344 }
1345
1346 @Override
1347 protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
1348 super.onActivityResult(requestCode, resultCode, data);
1349 if (resultCode == RESULT_OK) {
1350 if (requestCode == REQUEST_DECRYPT_PGP) {
1351 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1352 } else if (requestCode == REQUEST_CHOOSE_PGP_ID) {
1353 // the user chose OpenPGP for encryption and selected his key in the PGP provider
1354 if (xmppConnectionServiceBound) {
1355 if (data.getExtras().containsKey(OpenPgpApi.EXTRA_SIGN_KEY_ID)) {
1356 // associate selected PGP keyId with the account
1357 mSelectedConversation.getAccount().setPgpSignId(data.getExtras().getLong(OpenPgpApi.EXTRA_SIGN_KEY_ID));
1358 // we need to announce the key as described in XEP-027
1359 announcePgp(mSelectedConversation.getAccount(), null, onOpenPGPKeyPublished);
1360 } else {
1361 choosePgpSignId(mSelectedConversation.getAccount());
1362 }
1363 this.mPostponedActivityResult = null;
1364 } else {
1365 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1366 }
1367 } else if (requestCode == REQUEST_ANNOUNCE_PGP) {
1368 if (xmppConnectionServiceBound) {
1369 announcePgp(mSelectedConversation.getAccount(), mSelectedConversation, onOpenPGPKeyPublished);
1370 this.mPostponedActivityResult = null;
1371 } else {
1372 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1373 }
1374 } else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_IMAGE) {
1375 mPendingImageUris.clear();
1376 mPendingImageUris.addAll(extractUriFromIntent(data));
1377 if (xmppConnectionServiceBound) {
1378 for (Iterator<Uri> i = mPendingImageUris.iterator(); i.hasNext(); i.remove()) {
1379 Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. CHOOSE_IMAGE");
1380 attachImageToConversation(getSelectedConversation(), i.next());
1381 }
1382 }
1383 } else if (requestCode == ATTACHMENT_CHOICE_CHOOSE_FILE || requestCode == ATTACHMENT_CHOICE_RECORD_VOICE) {
1384 final List<Uri> uris = extractUriFromIntent(data);
1385 final Conversation c = getSelectedConversation();
1386 final OnPresenceSelected callback = new OnPresenceSelected() {
1387 @Override
1388 public void onPresenceSelected() {
1389 mPendingFileUris.clear();
1390 mPendingFileUris.addAll(uris);
1391 if (xmppConnectionServiceBound) {
1392 for (Iterator<Uri> i = mPendingFileUris.iterator(); i.hasNext(); i.remove()) {
1393 Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching file to conversations. CHOOSE_FILE/RECORD_VOICE");
1394 attachFileToConversation(c, i.next());
1395 }
1396 }
1397 }
1398 };
1399 if (c == null || c.getMode() == Conversation.MODE_MULTI
1400 || FileBackend.allFilesUnderSize(this, uris, getMaxHttpUploadSize(c))
1401 || c.getNextEncryption() == Message.ENCRYPTION_OTR) {
1402 callback.onPresenceSelected();
1403 } else {
1404 selectPresence(c, callback);
1405 }
1406 } else if (requestCode == ATTACHMENT_CHOICE_TAKE_PHOTO) {
1407 if (mPendingImageUris.size() == 1) {
1408 Uri uri = FileBackend.getIndexableTakePhotoUri(mPendingImageUris.get(0));
1409 mPendingImageUris.set(0, uri);
1410 if (xmppConnectionServiceBound) {
1411 Log.d(Config.LOGTAG,"ConversationsActivity.onActivityResult() - attaching image to conversations. TAKE_PHOTO");
1412 attachImageToConversation(getSelectedConversation(), uri);
1413 mPendingImageUris.clear();
1414 }
1415 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
1416 intent.setData(uri);
1417 sendBroadcast(intent);
1418 } else {
1419 mPendingImageUris.clear();
1420 }
1421 } else if (requestCode == ATTACHMENT_CHOICE_LOCATION) {
1422 double latitude = data.getDoubleExtra("latitude", 0);
1423 double longitude = data.getDoubleExtra("longitude", 0);
1424 this.mPendingGeoUri = Uri.parse("geo:" + String.valueOf(latitude) + "," + String.valueOf(longitude));
1425 if (xmppConnectionServiceBound) {
1426 attachLocationToConversation(getSelectedConversation(), mPendingGeoUri);
1427 this.mPendingGeoUri = null;
1428 }
1429 } else if (requestCode == REQUEST_TRUST_KEYS_TEXT || requestCode == REQUEST_TRUST_KEYS_MENU) {
1430 this.forbidProcessingPendings = !xmppConnectionServiceBound;
1431 if (xmppConnectionServiceBound) {
1432 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1433 this.mPostponedActivityResult = null;
1434 } else {
1435 this.mPostponedActivityResult = new Pair<>(requestCode, data);
1436 }
1437
1438 }
1439 } else {
1440 mPendingImageUris.clear();
1441 mPendingFileUris.clear();
1442 if (requestCode == ConversationActivity.REQUEST_DECRYPT_PGP) {
1443 mConversationFragment.onActivityResult(requestCode, resultCode, data);
1444 }
1445 if (requestCode == REQUEST_BATTERY_OP) {
1446 setNeverAskForBatteryOptimizationsAgain();
1447 }
1448 }
1449 }
1450
1451 private long getMaxHttpUploadSize(Conversation conversation) {
1452 return conversation.getAccount().getXmppConnection().getFeatures().getMaxHttpUploadSize();
1453 }
1454
1455 private void setNeverAskForBatteryOptimizationsAgain() {
1456 getPreferences().edit().putBoolean("show_battery_optimization", false).commit();
1457 }
1458
1459 private void openBatteryOptimizationDialogIfNeeded() {
1460 if (hasAccountWithoutPush()
1461 && isOptimizingBattery()
1462 && getPreferences().getBoolean("show_battery_optimization", true)) {
1463 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1464 builder.setTitle(R.string.battery_optimizations_enabled);
1465 builder.setMessage(R.string.battery_optimizations_enabled_dialog);
1466 builder.setPositiveButton(R.string.next, new OnClickListener() {
1467 @Override
1468 public void onClick(DialogInterface dialog, int which) {
1469 Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
1470 Uri uri = Uri.parse("package:" + getPackageName());
1471 intent.setData(uri);
1472 try {
1473 startActivityForResult(intent, REQUEST_BATTERY_OP);
1474 } catch (ActivityNotFoundException e) {
1475 Toast.makeText(ConversationActivity.this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
1476 }
1477 }
1478 });
1479 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
1480 builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
1481 @Override
1482 public void onDismiss(DialogInterface dialog) {
1483 setNeverAskForBatteryOptimizationsAgain();
1484 }
1485 });
1486 }
1487 builder.create().show();
1488 }
1489 }
1490
1491 private boolean hasAccountWithoutPush() {
1492 for(Account account : xmppConnectionService.getAccounts()) {
1493 if (account.getStatus() != Account.State.DISABLED
1494 && !xmppConnectionService.getPushManagementService().available(account)) {
1495 return true;
1496 }
1497 }
1498 return false;
1499 }
1500
1501 private void attachLocationToConversation(Conversation conversation, Uri uri) {
1502 if (conversation == null) {
1503 return;
1504 }
1505 xmppConnectionService.attachLocationToConversation(conversation,uri, new UiCallback<Message>() {
1506
1507 @Override
1508 public void success(Message message) {
1509 xmppConnectionService.sendMessage(message);
1510 }
1511
1512 @Override
1513 public void error(int errorCode, Message object) {
1514
1515 }
1516
1517 @Override
1518 public void userInputRequried(PendingIntent pi, Message object) {
1519
1520 }
1521 });
1522 }
1523
1524 private void attachFileToConversation(Conversation conversation, Uri uri) {
1525 if (conversation == null) {
1526 return;
1527 }
1528 final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_file), Toast.LENGTH_LONG);
1529 prepareFileToast.show();
1530 xmppConnectionService.attachFileToConversation(conversation, uri, new UiCallback<Message>() {
1531 @Override
1532 public void success(Message message) {
1533 hidePrepareFileToast(prepareFileToast);
1534 xmppConnectionService.sendMessage(message);
1535 }
1536
1537 @Override
1538 public void error(final int errorCode, Message message) {
1539 hidePrepareFileToast(prepareFileToast);
1540 runOnUiThread(new Runnable() {
1541 @Override
1542 public void run() {
1543 replaceToast(getString(errorCode));
1544 }
1545 });
1546
1547 }
1548
1549 @Override
1550 public void userInputRequried(PendingIntent pi, Message message) {
1551 hidePrepareFileToast(prepareFileToast);
1552 }
1553 });
1554 }
1555
1556 private void attachImageToConversation(Conversation conversation, Uri uri) {
1557 if (conversation == null) {
1558 return;
1559 }
1560 final Toast prepareFileToast = Toast.makeText(getApplicationContext(),getText(R.string.preparing_image), Toast.LENGTH_LONG);
1561 prepareFileToast.show();
1562 xmppConnectionService.attachImageToConversation(conversation, uri,
1563 new UiCallback<Message>() {
1564
1565 @Override
1566 public void userInputRequried(PendingIntent pi, Message object) {
1567 hidePrepareFileToast(prepareFileToast);
1568 }
1569
1570 @Override
1571 public void success(Message message) {
1572 hidePrepareFileToast(prepareFileToast);
1573 xmppConnectionService.sendMessage(message);
1574 }
1575
1576 @Override
1577 public void error(final int error, Message message) {
1578 hidePrepareFileToast(prepareFileToast);
1579 runOnUiThread(new Runnable() {
1580 @Override
1581 public void run() {
1582 replaceToast(getString(error));
1583 }
1584 });
1585 }
1586 });
1587 }
1588
1589 private void hidePrepareFileToast(final Toast prepareFileToast) {
1590 if (prepareFileToast != null) {
1591 runOnUiThread(new Runnable() {
1592
1593 @Override
1594 public void run() {
1595 prepareFileToast.cancel();
1596 }
1597 });
1598 }
1599 }
1600
1601 public void updateConversationList() {
1602 xmppConnectionService
1603 .populateWithOrderedConversations(conversationList);
1604 if (swipedConversation != null) {
1605 if (swipedConversation.isRead()) {
1606 conversationList.remove(swipedConversation);
1607 } else {
1608 listView.discardUndo();
1609 }
1610 }
1611 listAdapter.notifyDataSetChanged();
1612 }
1613
1614 public void runIntent(PendingIntent pi, int requestCode) {
1615 try {
1616 this.startIntentSenderForResult(pi.getIntentSender(), requestCode,
1617 null, 0, 0, 0);
1618 } catch (final SendIntentException ignored) {
1619 }
1620 }
1621
1622 public void encryptTextMessage(Message message) {
1623 xmppConnectionService.getPgpEngine().encrypt(message,
1624 new UiCallback<Message>() {
1625
1626 @Override
1627 public void userInputRequried(PendingIntent pi,Message message) {
1628 ConversationActivity.this.runIntent(pi,ConversationActivity.REQUEST_SEND_MESSAGE);
1629 }
1630
1631 @Override
1632 public void success(Message message) {
1633 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
1634 xmppConnectionService.sendMessage(message);
1635 if (mConversationFragment != null) {
1636 mConversationFragment.messageSent();
1637 }
1638 }
1639
1640 @Override
1641 public void error(final int error, Message message) {
1642 runOnUiThread(new Runnable() {
1643 @Override
1644 public void run() {
1645 Toast.makeText(ConversationActivity.this,
1646 R.string.unable_to_connect_to_keychain,
1647 Toast.LENGTH_SHORT
1648 ).show();
1649 }
1650 });
1651 }
1652 });
1653 }
1654
1655 public boolean useSendButtonToIndicateStatus() {
1656 return getPreferences().getBoolean("send_button_status", false);
1657 }
1658
1659 public boolean indicateReceived() {
1660 return getPreferences().getBoolean("indicate_received", false);
1661 }
1662
1663 public boolean useGreenBackground() {
1664 return getPreferences().getBoolean("use_green_background",true);
1665 }
1666
1667 protected boolean trustKeysIfNeeded(int requestCode) {
1668 return trustKeysIfNeeded(requestCode, ATTACHMENT_CHOICE_INVALID);
1669 }
1670
1671 protected boolean trustKeysIfNeeded(int requestCode, int attachmentChoice) {
1672 AxolotlService axolotlService = mSelectedConversation.getAccount().getAxolotlService();
1673 final List<Jid> targets = axolotlService.getCryptoTargets(mSelectedConversation);
1674 boolean hasUnaccepted = !mSelectedConversation.getAcceptedCryptoTargets().containsAll(targets);
1675 boolean hasUndecidedOwn = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED).isEmpty();
1676 boolean hasUndecidedContacts = !axolotlService.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED, targets).isEmpty();
1677 boolean hasPendingKeys = !axolotlService.findDevicesWithoutSession(mSelectedConversation).isEmpty();
1678 boolean hasNoTrustedKeys = axolotlService.anyTargetHasNoTrustedKeys(targets);
1679 if(hasUndecidedOwn || hasUndecidedContacts || hasPendingKeys || hasNoTrustedKeys || hasUnaccepted) {
1680 axolotlService.createSessionsIfNeeded(mSelectedConversation);
1681 Intent intent = new Intent(getApplicationContext(), TrustKeysActivity.class);
1682 String[] contacts = new String[targets.size()];
1683 for(int i = 0; i < contacts.length; ++i) {
1684 contacts[i] = targets.get(i).toString();
1685 }
1686 intent.putExtra("contacts", contacts);
1687 intent.putExtra(EXTRA_ACCOUNT, mSelectedConversation.getAccount().getJid().toBareJid().toString());
1688 intent.putExtra("choice", attachmentChoice);
1689 intent.putExtra("conversation",mSelectedConversation.getUuid());
1690 startActivityForResult(intent, requestCode);
1691 return true;
1692 } else {
1693 return false;
1694 }
1695 }
1696
1697 @Override
1698 protected void refreshUiReal() {
1699 updateConversationList();
1700 if (conversationList.size() > 0) {
1701 if (!this.mConversationFragment.isAdded()) {
1702 Log.d(Config.LOGTAG,"fragment NOT added to activity. detached="+Boolean.toString(mConversationFragment.isDetached()));
1703 }
1704 ConversationActivity.this.mConversationFragment.updateMessages();
1705 updateActionBarTitle();
1706 invalidateOptionsMenu();
1707 } else {
1708 Log.d(Config.LOGTAG,"not updating conversations fragment because conversations list size was 0");
1709 }
1710 }
1711
1712 @Override
1713 public void onAccountUpdate() {
1714 this.refreshUi();
1715 }
1716
1717 @Override
1718 public void onConversationUpdate() {
1719 this.refreshUi();
1720 }
1721
1722 @Override
1723 public void onRosterUpdate() {
1724 this.refreshUi();
1725 }
1726
1727 @Override
1728 public void OnUpdateBlocklist(Status status) {
1729 this.refreshUi();
1730 }
1731
1732 public void unblockConversation(final Blockable conversation) {
1733 xmppConnectionService.sendUnblockRequest(conversation);
1734 }
1735
1736 public boolean enterIsSend() {
1737 return getPreferences().getBoolean("enter_is_send",false);
1738 }
1739
1740 @Override
1741 public void onShowErrorToast(final int resId) {
1742 runOnUiThread(new Runnable() {
1743 @Override
1744 public void run() {
1745 Toast.makeText(ConversationActivity.this,resId,Toast.LENGTH_SHORT).show();
1746 }
1747 });
1748 }
1749
1750 public boolean highlightSelectedConversations() {
1751 return !isConversationsOverviewHideable() || this.conversationWasSelectedByKeyboard;
1752 }
1753
1754 public void setMessagesLoaded() {
1755 if (mConversationFragment != null) {
1756 mConversationFragment.setMessagesLoaded();
1757 mConversationFragment.updateMessages();
1758 }
1759 }
1760}