ConversationActivity.java

  1/*
  2 * Copyright (c) 2018, Daniel Gultsch All rights reserved.
  3 *
  4 * Redistribution and use in source and binary forms, with or without modification,
  5 * are permitted provided that the following conditions are met:
  6 *
  7 * 1. Redistributions of source code must retain the above copyright notice, this
  8 * list of conditions and the following disclaimer.
  9 *
 10 * 2. Redistributions in binary form must reproduce the above copyright notice,
 11 * this list of conditions and the following disclaimer in the documentation and/or
 12 * other materials provided with the distribution.
 13 *
 14 * 3. Neither the name of the copyright holder nor the names of its contributors
 15 * may be used to endorse or promote products derived from this software without
 16 * specific prior written permission.
 17 *
 18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 21 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 25 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 27 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 28 */
 29
 30package eu.siacs.conversations.ui;
 31
 32
 33import android.annotation.SuppressLint;
 34import android.app.Fragment;
 35import android.app.FragmentManager;
 36import android.app.FragmentTransaction;
 37import android.content.ActivityNotFoundException;
 38import android.content.Context;
 39import android.content.Intent;
 40import android.databinding.DataBindingUtil;
 41import android.net.Uri;
 42import android.os.Build;
 43import android.os.Bundle;
 44import android.provider.Settings;
 45import android.support.annotation.IdRes;
 46import android.support.v7.app.ActionBar;
 47import android.support.v7.app.AlertDialog;
 48import android.util.Log;
 49import android.view.Menu;
 50import android.view.MenuItem;
 51import android.widget.Toast;
 52
 53import java.util.concurrent.atomic.AtomicBoolean;
 54
 55import eu.siacs.conversations.Config;
 56import eu.siacs.conversations.R;
 57import eu.siacs.conversations.databinding.ActivityConversationsBinding;
 58import eu.siacs.conversations.entities.Account;
 59import eu.siacs.conversations.entities.Conversation;
 60import eu.siacs.conversations.services.XmppConnectionService;
 61import eu.siacs.conversations.ui.interfaces.OnConversationArchived;
 62import eu.siacs.conversations.ui.interfaces.OnConversationRead;
 63import eu.siacs.conversations.ui.interfaces.OnConversationSelected;
 64import eu.siacs.conversations.ui.interfaces.OnConversationsListItemUpdated;
 65import eu.siacs.conversations.ui.service.EmojiService;
 66import eu.siacs.conversations.ui.util.PendingItem;
 67import eu.siacs.conversations.utils.ExceptionHelper;
 68import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 69
 70import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;
 71
 72public class ConversationActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast {
 73
 74	public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
 75	public static final String EXTRA_CONVERSATION = "conversationUuid";
 76	public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
 77	public static final String EXTRA_TEXT = "text";
 78	public static final String EXTRA_NICK = "nick";
 79	public static final String EXTRA_IS_PRIVATE_MESSAGE = "pm";
 80
 81
 82	//secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment
 83	private static final @IdRes
 84	int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};
 85	private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
 86	private ActivityConversationsBinding binding;
 87	private boolean mActivityPaused = true;
 88	private AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);
 89
 90	private static boolean isViewIntent(Intent i) {
 91		return i != null && ACTION_VIEW_CONVERSATION.equals(i.getAction()) && i.hasExtra(EXTRA_CONVERSATION);
 92	}
 93
 94	private static Intent createLauncherIntent(Context context) {
 95		final Intent intent = new Intent(context, ConversationActivity.class);
 96		intent.setAction(Intent.ACTION_MAIN);
 97		intent.addCategory(Intent.CATEGORY_LAUNCHER);
 98		return intent;
 99	}
100
101	@Override
102	protected void refreshUiReal() {
103		for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
104			refreshFragment(id);
105		}
106	}
107
108	@Override
109	void onBackendConnected() {
110		if (performRedirectIfNecessary(true)) {
111			return;
112		}
113		xmppConnectionService.getNotificationService().setIsInForeground(true);
114		Intent intent = pendingViewIntent.pop();
115		if (intent != null) {
116			if (processViewIntent(intent)) {
117				if (binding.secondaryFragment != null) {
118					notifyFragmentOfBackendConnected(R.id.main_fragment);
119				}
120				invalidateActionBarTitle();
121				return;
122			}
123		}
124		for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
125			notifyFragmentOfBackendConnected(id);
126		}
127		invalidateActionBarTitle();
128		if (binding.secondaryFragment != null && ConversationFragment.getConversation(this) == null) {
129			Conversation conversation = ConversationsOverviewFragment.getSuggestion(this);
130			if (conversation != null) {
131				openConversation(conversation, null);
132			}
133		}
134		showDialogsIfMainIsOverview();
135	}
136
137	private boolean performRedirectIfNecessary(boolean noAnimation) {
138		return performRedirectIfNecessary(null, noAnimation);
139	}
140
141	private boolean performRedirectIfNecessary(final Conversation ignore, final boolean noAnimation) {
142		if (xmppConnectionService == null) {
143			return false;
144		}
145		boolean isConversationsListEmpty = xmppConnectionService.isConversationsListEmpty(ignore);
146		if (isConversationsListEmpty && mRedirectInProcess.compareAndSet(false, true)) {
147			final Intent intent = getRedirectionIntent(noAnimation);
148			runOnUiThread(() -> {
149				startActivity(intent);
150				if (noAnimation) {
151					overridePendingTransition(0, 0);
152				}
153			});
154		}
155		return mRedirectInProcess.get();
156	}
157
158	private Intent getRedirectionIntent(boolean noAnimation) {
159		Account pendingAccount = xmppConnectionService.getPendingAccount();
160		Intent intent;
161		if (pendingAccount != null) {
162			intent = new Intent(this, EditAccountActivity.class);
163			intent.putExtra("jid", pendingAccount.getJid().toBareJid().toString());
164		} else {
165			if (xmppConnectionService.getAccounts().size() == 0) {
166				if (Config.X509_VERIFICATION) {
167					intent = new Intent(this, ManageAccountActivity.class);
168				} else if (Config.MAGIC_CREATE_DOMAIN != null) {
169					intent = new Intent(this, WelcomeActivity.class);
170					WelcomeActivity.addInviteUri(intent, getIntent());
171				} else {
172					intent = new Intent(this, EditAccountActivity.class);
173				}
174			} else {
175				intent = new Intent(this, StartConversationActivity.class);
176			}
177		}
178		intent.putExtra("init", true);
179		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
180		if (noAnimation) {
181			intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
182		}
183		return intent;
184	}
185
186	private void showDialogsIfMainIsOverview() {
187		Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
188		if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
189			if (ExceptionHelper.checkForCrash(this, this.xmppConnectionService)) {
190				return;
191			}
192			openBatteryOptimizationDialogIfNeeded();
193		}
194	}
195
196	private String getBatteryOptimizationPreferenceKey() {
197		@SuppressLint("HardwareIds") String device = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
198		return "show_battery_optimization" + (device == null ? "" : device);
199	}
200
201	private void setNeverAskForBatteryOptimizationsAgain() {
202		getPreferences().edit().putBoolean(getBatteryOptimizationPreferenceKey(), false).apply();
203	}
204
205	private void openBatteryOptimizationDialogIfNeeded() {
206		if (hasAccountWithoutPush()
207				&& isOptimizingBattery()
208				&& getPreferences().getBoolean(getBatteryOptimizationPreferenceKey(), true)) {
209			AlertDialog.Builder builder = new AlertDialog.Builder(this);
210			builder.setTitle(R.string.battery_optimizations_enabled);
211			builder.setMessage(R.string.battery_optimizations_enabled_dialog);
212			builder.setPositiveButton(R.string.next, (dialog, which) -> {
213				Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
214				Uri uri = Uri.parse("package:" + getPackageName());
215				intent.setData(uri);
216				try {
217					startActivityForResult(intent, REQUEST_BATTERY_OP);
218				} catch (ActivityNotFoundException e) {
219					Toast.makeText(this, R.string.device_does_not_support_battery_op, Toast.LENGTH_SHORT).show();
220				}
221			});
222			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
223				builder.setOnDismissListener(dialog -> setNeverAskForBatteryOptimizationsAgain());
224			}
225			AlertDialog dialog = builder.create();
226			dialog.setCanceledOnTouchOutside(false);
227			dialog.show();
228		}
229	}
230
231	private boolean hasAccountWithoutPush() {
232		for (Account account : xmppConnectionService.getAccounts()) {
233			if (account.getStatus() == Account.State.ONLINE && !xmppConnectionService.getPushManagementService().available(account)) {
234				return true;
235			}
236		}
237		return false;
238	}
239
240	private void notifyFragmentOfBackendConnected(@IdRes int id) {
241		final Fragment fragment = getFragmentManager().findFragmentById(id);
242		if (fragment != null && fragment instanceof XmppFragment) {
243			((XmppFragment) fragment).onBackendConnected();
244		}
245	}
246
247	private void refreshFragment(@IdRes int id) {
248		final Fragment fragment = getFragmentManager().findFragmentById(id);
249		if (fragment != null && fragment instanceof XmppFragment) {
250			((XmppFragment) fragment).refresh();
251		}
252	}
253
254	private boolean processViewIntent(Intent intent) {
255		Log.d(Config.LOGTAG,"process view intent");
256		String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
257		Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
258		if (conversation == null) {
259			Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
260			return false;
261		}
262		openConversation(conversation, intent.getExtras());
263		return true;
264	}
265
266	@Override
267	public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
268		UriHandlerActivity.onRequestPermissionResult(this, requestCode, grantResults);
269	}
270
271	@Override
272	public void onActivityResult(int requestCode, int resultCode, final Intent data) {
273		if (resultCode == RESULT_OK) {
274			handlePositiveActivityResult(requestCode, data);
275		} else {
276			handleNegativeActivityResult(requestCode);
277		}
278	}
279
280	private void handleNegativeActivityResult(int requestCode) {
281		switch (requestCode) {
282			case REQUEST_DECRYPT_PGP:
283				Conversation conversation = ConversationFragment.getConversationReliable(this);
284				if (conversation == null) {
285					break;
286				}
287				conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
288				break;
289			case REQUEST_BATTERY_OP:
290				setNeverAskForBatteryOptimizationsAgain();
291				break;
292		}
293	}
294
295	private void handlePositiveActivityResult(int requestCode, final Intent data) {
296		switch (requestCode) {
297			case REQUEST_DECRYPT_PGP:
298				Conversation conversation = ConversationFragment.getConversationReliable(this);
299				if (conversation == null) {
300					break;
301				}
302				conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
303				break;
304		}
305	}
306
307	@Override
308	protected void onCreate(final Bundle savedInstanceState) {
309		super.onCreate(savedInstanceState);
310		new EmojiService(this).init();
311		this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
312		this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
313		this.getFragmentManager().addOnBackStackChangedListener(this::showDialogsIfMainIsOverview);
314		this.initializeFragments();
315		this.invalidateActionBarTitle();
316		final Intent intent;
317		if (savedInstanceState == null) {
318			intent = getIntent();
319		} else {
320			intent = savedInstanceState.getParcelable("intent");
321		}
322		if (isViewIntent(intent)) {
323			pendingViewIntent.push(intent);
324			setIntent(createLauncherIntent(this));
325		}
326	}
327
328	@Override
329	public boolean onCreateOptionsMenu(Menu menu) {
330		getMenuInflater().inflate(R.menu.activity_conversations, menu);
331		MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
332		if (qrCodeScanMenuItem != null) {
333			Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
334			boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
335					&& fragment != null
336					&& fragment instanceof ConversationsOverviewFragment;
337			qrCodeScanMenuItem.setVisible(visible);
338		}
339		return super.onCreateOptionsMenu(menu);
340	}
341
342	@Override
343	public void onConversationSelected(Conversation conversation) {
344		openConversation(conversation, null);
345	}
346
347	private void openConversation(Conversation conversation, Bundle extras) {
348		ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment);
349		final boolean mainNeedsRefresh;
350		if (conversationFragment == null) {
351			mainNeedsRefresh = false;
352			Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
353			if (mainFragment != null && mainFragment instanceof ConversationFragment) {
354				conversationFragment = (ConversationFragment) mainFragment;
355			} else {
356				conversationFragment = new ConversationFragment();
357				FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
358				fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
359				fragmentTransaction.addToBackStack(null);
360				fragmentTransaction.commit();
361			}
362		} else {
363			mainNeedsRefresh = true;
364		}
365		conversationFragment.reInit(conversation, extras);
366		if (mainNeedsRefresh) {
367			refreshFragment(R.id.main_fragment);
368		} else {
369			invalidateActionBarTitle();
370		}
371	}
372
373	@Override
374	public boolean onOptionsItemSelected(MenuItem item) {
375		switch (item.getItemId()) {
376			case android.R.id.home:
377				FragmentManager fm = getFragmentManager();
378				if (fm.getBackStackEntryCount() > 0) {
379					fm.popBackStack();
380					return true;
381				}
382				break;
383			case R.id.action_scan_qr_code:
384				UriHandlerActivity.scan(this);
385				return true;
386		}
387		return super.onOptionsItemSelected(item);
388	}
389
390	@Override
391	public void onSaveInstanceState(Bundle savedInstanceState) {
392		savedInstanceState.putParcelable("intent", getIntent());
393		super.onSaveInstanceState(savedInstanceState);
394	}
395
396	@Override
397	protected void onStart() {
398		final int theme = findTheme();
399		if (this.mTheme != theme) {
400			recreate();
401		}
402		mRedirectInProcess.set(false);
403		super.onStart();
404	}
405
406	@Override
407	protected void onNewIntent(final Intent intent) {
408		if (isViewIntent(intent)) {
409			if (xmppConnectionService != null) {
410				processViewIntent(intent);
411			} else {
412				pendingViewIntent.push(intent);
413			}
414		}
415	}
416
417	@Override
418	public void onPause() {
419		this.mActivityPaused = true;
420		super.onPause();
421	}
422
423	@Override
424	public void onResume() {
425		super.onResume();
426		this.mActivityPaused = false;
427	}
428
429	private void initializeFragments() {
430		FragmentTransaction transaction = getFragmentManager().beginTransaction();
431		Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
432		Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
433		if (mainFragment != null) {
434			Log.d(Config.LOGTAG, "initializeFragment(). main fragment exists");
435			if (binding.secondaryFragment != null) {
436				if (mainFragment instanceof ConversationFragment) {
437					Log.d(Config.LOGTAG, "gained secondary fragment. moving...");
438					getFragmentManager().popBackStack();
439					transaction.remove(mainFragment);
440					transaction.commit();
441					getFragmentManager().executePendingTransactions();
442					transaction = getFragmentManager().beginTransaction();
443					transaction.replace(R.id.secondary_fragment, mainFragment);
444					transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
445					transaction.commit();
446					return;
447				}
448			} else {
449				if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
450					Log.d(Config.LOGTAG, "lost secondary fragment. moving...");
451					transaction.remove(secondaryFragment);
452					transaction.commit();
453					getFragmentManager().executePendingTransactions();
454					transaction = getFragmentManager().beginTransaction();
455					transaction.replace(R.id.main_fragment, secondaryFragment);
456					transaction.addToBackStack(null);
457					transaction.commit();
458					return;
459				}
460			}
461		} else {
462			transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
463		}
464		if (binding.secondaryFragment != null && secondaryFragment == null) {
465			transaction.replace(R.id.secondary_fragment, new ConversationFragment());
466		}
467		transaction.commit();
468	}
469
470	private void invalidateActionBarTitle() {
471		final ActionBar actionBar = getSupportActionBar();
472		if (actionBar != null) {
473			Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
474			if (mainFragment != null && mainFragment instanceof ConversationFragment) {
475				final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
476				if (conversation != null) {
477					actionBar.setTitle(conversation.getName());
478					actionBar.setDisplayHomeAsUpEnabled(true);
479					return;
480				}
481			}
482			actionBar.setTitle(R.string.app_name);
483			actionBar.setDisplayHomeAsUpEnabled(false);
484		}
485	}
486
487	@Override
488	public void onConversationArchived(Conversation conversation) {
489		if (performRedirectIfNecessary(conversation, false)) {
490			return;
491		}
492		Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
493		if (mainFragment != null && mainFragment instanceof ConversationFragment) {
494			getFragmentManager().popBackStack();
495			return;
496		}
497		Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
498		if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
499			if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
500				Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
501				if (suggestion != null) {
502					openConversation(suggestion, null);
503					return;
504				}
505			}
506		}
507	}
508
509	@Override
510	public void onConversationsListItemUpdated() {
511		Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
512		if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
513			((ConversationsOverviewFragment) fragment).refresh();
514		}
515	}
516
517	@Override
518	public void onConversationRead(Conversation conversation) {
519		if (!mActivityPaused && pendingViewIntent.peek() == null) {
520			xmppConnectionService.sendReadMarker(conversation);
521		} else {
522			Log.d(Config.LOGTAG,"ignoring read callback. mActivityPaused="+Boolean.toString(mActivityPaused));
523		}
524	}
525
526	@Override
527	public void onAccountUpdate() {
528		this.refreshUi();
529	}
530
531	@Override
532	public void onConversationUpdate() {
533		if (performRedirectIfNecessary(false)) {
534			return;
535		}
536		this.refreshUi();
537	}
538
539	@Override
540	public void onRosterUpdate() {
541		this.refreshUi();
542	}
543
544	@Override
545	public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
546		this.refreshUi();
547	}
548
549	@Override
550	public void onShowErrorToast(int resId) {
551		runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
552	}
553}