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.app.Fragment;
 34import android.app.FragmentManager;
 35import android.app.FragmentTransaction;
 36import android.content.Context;
 37import android.content.Intent;
 38import android.databinding.DataBindingUtil;
 39import android.os.Bundle;
 40import android.support.annotation.IdRes;
 41import android.support.v7.app.ActionBar;
 42import android.util.Log;
 43import android.view.Menu;
 44import android.view.MenuItem;
 45import android.widget.Toast;
 46
 47import java.util.concurrent.atomic.AtomicBoolean;
 48
 49import eu.siacs.conversations.Config;
 50import eu.siacs.conversations.R;
 51import eu.siacs.conversations.databinding.ActivityConversationsBinding;
 52import eu.siacs.conversations.entities.Account;
 53import eu.siacs.conversations.entities.Conversation;
 54import eu.siacs.conversations.services.XmppConnectionService;
 55import eu.siacs.conversations.ui.interfaces.OnConversationArchived;
 56import eu.siacs.conversations.ui.interfaces.OnConversationRead;
 57import eu.siacs.conversations.ui.interfaces.OnConversationSelected;
 58import eu.siacs.conversations.ui.interfaces.OnConversationsListItemUpdated;
 59import eu.siacs.conversations.ui.service.EmojiService;
 60import eu.siacs.conversations.ui.util.PendingItem;
 61import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
 62
 63import static eu.siacs.conversations.ui.ConversationFragment.REQUEST_DECRYPT_PGP;
 64
 65public class ConversationActivity extends XmppActivity implements OnConversationSelected, OnConversationArchived, OnConversationsListItemUpdated, OnConversationRead, XmppConnectionService.OnAccountUpdate, XmppConnectionService.OnConversationUpdate, XmppConnectionService.OnRosterUpdate, OnUpdateBlocklist, XmppConnectionService.OnShowErrorToast {
 66
 67	public static final String ACTION_VIEW_CONVERSATION = "eu.siacs.conversations.action.VIEW";
 68	public static final String EXTRA_CONVERSATION = "conversationUuid";
 69	public static final String EXTRA_DOWNLOAD_UUID = "eu.siacs.conversations.download_uuid";
 70	public static final String EXTRA_TEXT = "text";
 71	public static final String EXTRA_NICK = "nick";
 72	public static final String EXTRA_IS_PRIVATE_MESSAGE = "pm";
 73
 74
 75	//secondary fragment (when holding the conversation, must be initialized before refreshing the overview fragment
 76	private static final @IdRes
 77	int[] FRAGMENT_ID_NOTIFICATION_ORDER = {R.id.secondary_fragment, R.id.main_fragment};
 78	private final PendingItem<Intent> pendingViewIntent = new PendingItem<>();
 79	private ActivityConversationsBinding binding;
 80	private boolean mActivityPaused = true;
 81	private AtomicBoolean mRedirectInProcess = new AtomicBoolean(false);
 82
 83	private static boolean isViewIntent(Intent i) {
 84		return i != null && ACTION_VIEW_CONVERSATION.equals(i.getAction()) && i.hasExtra(EXTRA_CONVERSATION);
 85	}
 86
 87	private static Intent createLauncherIntent(Context context) {
 88		final Intent intent = new Intent(context, ConversationActivity.class);
 89		intent.setAction(Intent.ACTION_MAIN);
 90		intent.addCategory(Intent.CATEGORY_LAUNCHER);
 91		return intent;
 92	}
 93
 94	@Override
 95	protected void refreshUiReal() {
 96		for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
 97			refreshFragment(id);
 98		}
 99	}
100
101	@Override
102	void onBackendConnected() {
103		if (performRedirectIfNecessary(true)) {
104			return;
105		}
106		for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
107			notifyFragmentOfBackendConnected(id);
108		}
109		invalidateActionBarTitle();
110		xmppConnectionService.getNotificationService().setIsInForeground(true);
111		Intent intent = pendingViewIntent.pop();
112		if (intent != null) {
113			if (processViewIntent(intent)) {
114				return;
115			}
116		}
117		if (binding.secondaryFragment != null && ConversationFragment.getConversation(this) == null) {
118			Conversation conversation = ConversationsOverviewFragment.getSuggestion(this);
119			if (conversation != null) {
120				openConversation(conversation, null);
121			}
122		}
123	}
124
125	private boolean performRedirectIfNecessary(boolean noAnimation) {
126		return performRedirectIfNecessary(null, noAnimation);
127	}
128
129	private boolean performRedirectIfNecessary(final Conversation ignore, final boolean noAnimation) {
130		if (xmppConnectionService == null) {
131			return false;
132		}
133		boolean isConversationsListEmpty = xmppConnectionService.isConversationsListEmpty(ignore);
134		if (isConversationsListEmpty && mRedirectInProcess.compareAndSet(false, true)) {
135			final Intent intent = getRedirectionIntent(noAnimation);
136			runOnUiThread(() -> {
137				startActivity(intent);
138				if (noAnimation) {
139					overridePendingTransition(0, 0);
140				}
141			});
142		}
143		return mRedirectInProcess.get();
144	}
145
146	private Intent getRedirectionIntent(boolean noAnimation) {
147		Account pendingAccount = xmppConnectionService.getPendingAccount();
148		Intent intent;
149		if (pendingAccount != null) {
150			intent = new Intent(this, EditAccountActivity.class);
151			intent.putExtra("jid", pendingAccount.getJid().toBareJid().toString());
152		} else {
153			if (xmppConnectionService.getAccounts().size() == 0) {
154				if (Config.X509_VERIFICATION) {
155					intent = new Intent(this, ManageAccountActivity.class);
156				} else if (Config.MAGIC_CREATE_DOMAIN != null) {
157					intent = new Intent(this, WelcomeActivity.class);
158					WelcomeActivity.addInviteUri(intent, getIntent());
159				} else {
160					intent = new Intent(this, EditAccountActivity.class);
161				}
162			} else {
163				intent = new Intent(this, StartConversationActivity.class);
164			}
165		}
166		intent.putExtra("init", true);
167		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
168		if (noAnimation) {
169			intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
170		}
171		return intent;
172	}
173
174	private void notifyFragmentOfBackendConnected(@IdRes int id) {
175		final Fragment fragment = getFragmentManager().findFragmentById(id);
176		if (fragment != null && fragment instanceof XmppFragment) {
177			((XmppFragment) fragment).onBackendConnected();
178		}
179	}
180
181	private void refreshFragment(@IdRes int id) {
182		final Fragment fragment = getFragmentManager().findFragmentById(id);
183		if (fragment != null && fragment instanceof XmppFragment) {
184			((XmppFragment) fragment).refresh();
185		}
186	}
187
188	private boolean processViewIntent(Intent intent) {
189		String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
190		Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
191		if (conversation == null) {
192			Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
193			return false;
194		}
195		openConversation(conversation, intent.getExtras());
196		return true;
197	}
198
199	@Override
200	public void onActivityResult(int requestCode, int resultCode, final Intent data) {
201		Log.d(Config.LOGTAG,"on activity result");
202		if (resultCode == RESULT_OK) {
203			handlePositiveActivityResult(requestCode, data);
204		} else {
205			handleNegativeActivityResult(requestCode);
206		}
207	}
208
209	private void handleNegativeActivityResult(int requestCode) {
210		switch (requestCode) {
211			case REQUEST_DECRYPT_PGP:
212				Conversation conversation = ConversationFragment.getConversationReliable(this);
213				if (conversation == null) {
214					break;
215				}
216				conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
217				break;
218		}
219	}
220
221	private void handlePositiveActivityResult(int requestCode, final Intent data) {
222		switch (requestCode) {
223			case REQUEST_DECRYPT_PGP:
224				Conversation conversation = ConversationFragment.getConversationReliable(this);
225				if (conversation == null) {
226					break;
227				}
228				conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
229				break;
230		}
231	}
232
233	@Override
234	protected void onCreate(final Bundle savedInstanceState) {
235		super.onCreate(savedInstanceState);
236		new EmojiService(this).init();
237		this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
238		this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
239		this.initializeFragments();
240		this.invalidateActionBarTitle();
241		final Intent intent = getIntent();
242		if (isViewIntent(intent)) {
243			pendingViewIntent.push(intent);
244			setIntent(createLauncherIntent(this));
245		}
246	}
247
248	@Override
249	public boolean onCreateOptionsMenu(Menu menu) {
250		getMenuInflater().inflate(R.menu.activity_conversations, menu);
251		MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
252		if (qrCodeScanMenuItem != null) {
253			Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
254			boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
255					&& fragment != null
256					&& fragment instanceof ConversationsOverviewFragment;
257			qrCodeScanMenuItem.setVisible(visible);
258		}
259		return super.onCreateOptionsMenu(menu);
260	}
261
262	@Override
263	public void onConversationSelected(Conversation conversation) {
264		openConversation(conversation, null);
265	}
266
267	private void openConversation(Conversation conversation, Bundle extras) {
268		ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment);
269		final boolean mainNeedsRefresh;
270		if (conversationFragment == null) {
271			mainNeedsRefresh = false;
272			Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
273			if (mainFragment != null && mainFragment instanceof ConversationFragment) {
274				conversationFragment = (ConversationFragment) mainFragment;
275			} else {
276				conversationFragment = new ConversationFragment();
277				FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
278				fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
279				fragmentTransaction.addToBackStack(null);
280				fragmentTransaction.commit();
281			}
282		} else {
283			mainNeedsRefresh = true;
284		}
285		conversationFragment.reInit(conversation, extras);
286		if (mainNeedsRefresh) {
287			refreshFragment(R.id.main_fragment);
288		} else {
289			invalidateActionBarTitle();
290		}
291	}
292
293	@Override
294	public boolean onOptionsItemSelected(MenuItem item) {
295		switch (item.getItemId()) {
296			case android.R.id.home:
297				FragmentManager fm = getFragmentManager();
298				if (fm.getBackStackEntryCount() > 0) {
299					fm.popBackStack();
300					return true;
301				}
302				break;
303			case R.id.action_scan_qr_code:
304				UriHandlerActivity.scan(this);
305				return true;
306		}
307		return super.onOptionsItemSelected(item);
308	}
309
310	@Override
311	protected void onStart() {
312		final int theme = findTheme();
313		if (this.mTheme != theme) {
314			recreate();
315		}
316		mRedirectInProcess.set(false);
317		super.onStart();
318	}
319
320	@Override
321	protected void onNewIntent(final Intent intent) {
322		if (isViewIntent(intent)) {
323			if (xmppConnectionService != null) {
324				processViewIntent(intent);
325			} else {
326				pendingViewIntent.push(intent);
327			}
328		}
329	}
330
331	@Override
332	public void onPause() {
333		this.mActivityPaused = true;
334		super.onPause();
335	}
336
337	@Override
338	public void onResume() {
339		super.onResume();
340		this.mActivityPaused = false;
341	}
342
343	private void initializeFragments() {
344		FragmentTransaction transaction = getFragmentManager().beginTransaction();
345		Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
346		Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
347		if (mainFragment != null) {
348			Log.d(Config.LOGTAG, "initializeFragment(). main fragment exists");
349			if (binding.secondaryFragment != null) {
350				if (mainFragment instanceof ConversationFragment) {
351					Log.d(Config.LOGTAG, "gained secondary fragment. moving...");
352					getFragmentManager().popBackStack();
353					transaction.remove(mainFragment);
354					transaction.commit();
355					getFragmentManager().executePendingTransactions();
356					transaction = getFragmentManager().beginTransaction();
357					transaction.replace(R.id.secondary_fragment, mainFragment);
358					transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
359					transaction.commit();
360					return;
361				}
362			} else {
363				if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
364					Log.d(Config.LOGTAG, "lost secondary fragment. moving...");
365					transaction.remove(secondaryFragment);
366					transaction.commit();
367					getFragmentManager().executePendingTransactions();
368					transaction = getFragmentManager().beginTransaction();
369					transaction.replace(R.id.main_fragment, secondaryFragment);
370					transaction.addToBackStack(null);
371					transaction.commit();
372					return;
373				}
374			}
375		} else {
376			transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
377		}
378		if (binding.secondaryFragment != null && secondaryFragment == null) {
379			transaction.replace(R.id.secondary_fragment, new ConversationFragment());
380		}
381		transaction.commit();
382	}
383
384	private void invalidateActionBarTitle() {
385		final ActionBar actionBar = getSupportActionBar();
386		if (actionBar != null) {
387			Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
388			if (mainFragment != null && mainFragment instanceof ConversationFragment) {
389				final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
390				if (conversation != null) {
391					actionBar.setTitle(conversation.getName());
392					actionBar.setDisplayHomeAsUpEnabled(true);
393					return;
394				}
395			}
396			actionBar.setTitle(R.string.app_name);
397			actionBar.setDisplayHomeAsUpEnabled(false);
398		}
399	}
400
401	@Override
402	public void onConversationArchived(Conversation conversation) {
403		if (performRedirectIfNecessary(conversation, false)) {
404			return;
405		}
406		Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
407		if (mainFragment != null && mainFragment instanceof ConversationFragment) {
408			getFragmentManager().popBackStack();
409			return;
410		}
411		Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
412		if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
413			if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
414				Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
415				if (suggestion != null) {
416					openConversation(suggestion, null);
417					return;
418				}
419			}
420		}
421	}
422
423	@Override
424	public void onConversationsListItemUpdated() {
425		Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
426		if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
427			((ConversationsOverviewFragment) fragment).refresh();
428		}
429	}
430
431	@Override
432	public void onConversationRead(Conversation conversation) {
433		if (!mActivityPaused && pendingViewIntent.peek() == null) {
434			xmppConnectionService.sendReadMarker(conversation);
435		}
436	}
437
438	@Override
439	public void onAccountUpdate() {
440		this.refreshUi();
441	}
442
443	@Override
444	public void onConversationUpdate() {
445		if (performRedirectIfNecessary(false)) {
446			return;
447		}
448		this.refreshUi();
449	}
450
451	@Override
452	public void onRosterUpdate() {
453		this.refreshUi();
454	}
455
456	@Override
457	public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
458		this.refreshUi();
459	}
460
461	@Override
462	public void onShowErrorToast(int resId) {
463		runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
464	}
465}