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		if (ConversationFragment.getConversation(this) == conversation) {
345			Log.d(Config.LOGTAG,"ignore onConversationSelected() because conversation is already open");
346		}
347		openConversation(conversation, null);
348	}
349
350	private void openConversation(Conversation conversation, Bundle extras) {
351		ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment);
352		final boolean mainNeedsRefresh;
353		if (conversationFragment == null) {
354			mainNeedsRefresh = false;
355			Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
356			if (mainFragment != null && mainFragment instanceof ConversationFragment) {
357				conversationFragment = (ConversationFragment) mainFragment;
358			} else {
359				conversationFragment = new ConversationFragment();
360				FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
361				fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
362				fragmentTransaction.addToBackStack(null);
363				fragmentTransaction.commit();
364			}
365		} else {
366			mainNeedsRefresh = true;
367		}
368		conversationFragment.reInit(conversation, extras);
369		if (mainNeedsRefresh) {
370			refreshFragment(R.id.main_fragment);
371		} else {
372			invalidateActionBarTitle();
373		}
374	}
375
376	@Override
377	public boolean onOptionsItemSelected(MenuItem item) {
378		switch (item.getItemId()) {
379			case android.R.id.home:
380				FragmentManager fm = getFragmentManager();
381				if (fm.getBackStackEntryCount() > 0) {
382					fm.popBackStack();
383					return true;
384				}
385				break;
386			case R.id.action_scan_qr_code:
387				UriHandlerActivity.scan(this);
388				return true;
389		}
390		return super.onOptionsItemSelected(item);
391	}
392
393	@Override
394	public void onSaveInstanceState(Bundle savedInstanceState) {
395		savedInstanceState.putParcelable("intent", getIntent());
396		super.onSaveInstanceState(savedInstanceState);
397	}
398
399	@Override
400	protected void onStart() {
401		final int theme = findTheme();
402		if (this.mTheme != theme) {
403			recreate();
404		}
405		mRedirectInProcess.set(false);
406		super.onStart();
407	}
408
409	@Override
410	protected void onNewIntent(final Intent intent) {
411		if (isViewIntent(intent)) {
412			if (xmppConnectionService != null) {
413				processViewIntent(intent);
414			} else {
415				pendingViewIntent.push(intent);
416			}
417		}
418		setIntent(createLauncherIntent(this));
419	}
420
421	@Override
422	public void onPause() {
423		this.mActivityPaused = true;
424		super.onPause();
425	}
426
427	@Override
428	public void onResume() {
429		super.onResume();
430		this.mActivityPaused = false;
431	}
432
433	private void initializeFragments() {
434		FragmentTransaction transaction = getFragmentManager().beginTransaction();
435		Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
436		Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
437		if (mainFragment != null) {
438			Log.d(Config.LOGTAG, "initializeFragment(). main fragment exists");
439			if (binding.secondaryFragment != null) {
440				if (mainFragment instanceof ConversationFragment) {
441					Log.d(Config.LOGTAG, "gained secondary fragment. moving...");
442					getFragmentManager().popBackStack();
443					transaction.remove(mainFragment);
444					transaction.commit();
445					getFragmentManager().executePendingTransactions();
446					transaction = getFragmentManager().beginTransaction();
447					transaction.replace(R.id.secondary_fragment, mainFragment);
448					transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
449					transaction.commit();
450					return;
451				}
452			} else {
453				if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
454					Log.d(Config.LOGTAG, "lost secondary fragment. moving...");
455					transaction.remove(secondaryFragment);
456					transaction.commit();
457					getFragmentManager().executePendingTransactions();
458					transaction = getFragmentManager().beginTransaction();
459					transaction.replace(R.id.main_fragment, secondaryFragment);
460					transaction.addToBackStack(null);
461					transaction.commit();
462					return;
463				}
464			}
465		} else {
466			transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
467		}
468		if (binding.secondaryFragment != null && secondaryFragment == null) {
469			transaction.replace(R.id.secondary_fragment, new ConversationFragment());
470		}
471		transaction.commit();
472	}
473
474	private void invalidateActionBarTitle() {
475		final ActionBar actionBar = getSupportActionBar();
476		if (actionBar != null) {
477			Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
478			if (mainFragment != null && mainFragment instanceof ConversationFragment) {
479				final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
480				if (conversation != null) {
481					actionBar.setTitle(conversation.getName());
482					actionBar.setDisplayHomeAsUpEnabled(true);
483					return;
484				}
485			}
486			actionBar.setTitle(R.string.app_name);
487			actionBar.setDisplayHomeAsUpEnabled(false);
488		}
489	}
490
491	@Override
492	public void onConversationArchived(Conversation conversation) {
493		if (performRedirectIfNecessary(conversation, false)) {
494			return;
495		}
496		Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
497		if (mainFragment != null && mainFragment instanceof ConversationFragment) {
498			getFragmentManager().popBackStack();
499			return;
500		}
501		Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
502		if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
503			if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
504				Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
505				if (suggestion != null) {
506					openConversation(suggestion, null);
507					return;
508				}
509			}
510		}
511	}
512
513	@Override
514	public void onConversationsListItemUpdated() {
515		Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
516		if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
517			((ConversationsOverviewFragment) fragment).refresh();
518		}
519	}
520
521	@Override
522	public void onConversationRead(Conversation conversation) {
523		if (!mActivityPaused && pendingViewIntent.peek() == null) {
524			xmppConnectionService.sendReadMarker(conversation);
525		} else {
526			Log.d(Config.LOGTAG,"ignoring read callback. mActivityPaused="+Boolean.toString(mActivityPaused));
527		}
528	}
529
530	@Override
531	public void onAccountUpdate() {
532		this.refreshUi();
533	}
534
535	@Override
536	public void onConversationUpdate() {
537		if (performRedirectIfNecessary(false)) {
538			return;
539		}
540		this.refreshUi();
541	}
542
543	@Override
544	public void onRosterUpdate() {
545		this.refreshUi();
546	}
547
548	@Override
549	public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
550		this.refreshUi();
551	}
552
553	@Override
554	public void onShowErrorToast(int resId) {
555		runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
556	}
557}