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 xmppConnectionService.getNotificationService().setIsInForeground(true);
107 Intent intent = pendingViewIntent.pop();
108 if (intent != null) {
109 if (processViewIntent(intent)) {
110 if (binding.secondaryFragment != null) {
111 notifyFragmentOfBackendConnected(R.id.main_fragment);
112 }
113 invalidateActionBarTitle();
114 return;
115 }
116 }
117 for (@IdRes int id : FRAGMENT_ID_NOTIFICATION_ORDER) {
118 notifyFragmentOfBackendConnected(id);
119 }
120 invalidateActionBarTitle();
121 if (binding.secondaryFragment != null && ConversationFragment.getConversation(this) == null) {
122 Conversation conversation = ConversationsOverviewFragment.getSuggestion(this);
123 if (conversation != null) {
124 openConversation(conversation, null);
125 }
126 }
127 }
128
129 private boolean performRedirectIfNecessary(boolean noAnimation) {
130 return performRedirectIfNecessary(null, noAnimation);
131 }
132
133 private boolean performRedirectIfNecessary(final Conversation ignore, final boolean noAnimation) {
134 if (xmppConnectionService == null) {
135 return false;
136 }
137 boolean isConversationsListEmpty = xmppConnectionService.isConversationsListEmpty(ignore);
138 if (isConversationsListEmpty && mRedirectInProcess.compareAndSet(false, true)) {
139 final Intent intent = getRedirectionIntent(noAnimation);
140 runOnUiThread(() -> {
141 startActivity(intent);
142 if (noAnimation) {
143 overridePendingTransition(0, 0);
144 }
145 });
146 }
147 return mRedirectInProcess.get();
148 }
149
150 private Intent getRedirectionIntent(boolean noAnimation) {
151 Account pendingAccount = xmppConnectionService.getPendingAccount();
152 Intent intent;
153 if (pendingAccount != null) {
154 intent = new Intent(this, EditAccountActivity.class);
155 intent.putExtra("jid", pendingAccount.getJid().toBareJid().toString());
156 } else {
157 if (xmppConnectionService.getAccounts().size() == 0) {
158 if (Config.X509_VERIFICATION) {
159 intent = new Intent(this, ManageAccountActivity.class);
160 } else if (Config.MAGIC_CREATE_DOMAIN != null) {
161 intent = new Intent(this, WelcomeActivity.class);
162 WelcomeActivity.addInviteUri(intent, getIntent());
163 } else {
164 intent = new Intent(this, EditAccountActivity.class);
165 }
166 } else {
167 intent = new Intent(this, StartConversationActivity.class);
168 }
169 }
170 intent.putExtra("init", true);
171 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
172 if (noAnimation) {
173 intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
174 }
175 return intent;
176 }
177
178 private void notifyFragmentOfBackendConnected(@IdRes int id) {
179 final Fragment fragment = getFragmentManager().findFragmentById(id);
180 if (fragment != null && fragment instanceof XmppFragment) {
181 ((XmppFragment) fragment).onBackendConnected();
182 }
183 }
184
185 private void refreshFragment(@IdRes int id) {
186 final Fragment fragment = getFragmentManager().findFragmentById(id);
187 if (fragment != null && fragment instanceof XmppFragment) {
188 ((XmppFragment) fragment).refresh();
189 }
190 }
191
192 private boolean processViewIntent(Intent intent) {
193 String uuid = intent.getStringExtra(EXTRA_CONVERSATION);
194 Conversation conversation = uuid != null ? xmppConnectionService.findConversationByUuid(uuid) : null;
195 if (conversation == null) {
196 Log.d(Config.LOGTAG, "unable to view conversation with uuid:" + uuid);
197 return false;
198 }
199 openConversation(conversation, intent.getExtras());
200 return true;
201 }
202
203 @Override
204 public void onActivityResult(int requestCode, int resultCode, final Intent data) {
205 Log.d(Config.LOGTAG,"on activity result");
206 if (resultCode == RESULT_OK) {
207 handlePositiveActivityResult(requestCode, data);
208 } else {
209 handleNegativeActivityResult(requestCode);
210 }
211 }
212
213 private void handleNegativeActivityResult(int requestCode) {
214 switch (requestCode) {
215 case REQUEST_DECRYPT_PGP:
216 Conversation conversation = ConversationFragment.getConversationReliable(this);
217 if (conversation == null) {
218 break;
219 }
220 conversation.getAccount().getPgpDecryptionService().giveUpCurrentDecryption();
221 break;
222 }
223 }
224
225 private void handlePositiveActivityResult(int requestCode, final Intent data) {
226 switch (requestCode) {
227 case REQUEST_DECRYPT_PGP:
228 Conversation conversation = ConversationFragment.getConversationReliable(this);
229 if (conversation == null) {
230 break;
231 }
232 conversation.getAccount().getPgpDecryptionService().continueDecryption(data);
233 break;
234 }
235 }
236
237 @Override
238 protected void onCreate(final Bundle savedInstanceState) {
239 super.onCreate(savedInstanceState);
240 new EmojiService(this).init();
241 this.binding = DataBindingUtil.setContentView(this, R.layout.activity_conversations);
242 this.getFragmentManager().addOnBackStackChangedListener(this::invalidateActionBarTitle);
243 this.initializeFragments();
244 this.invalidateActionBarTitle();
245 final Intent intent = getIntent();
246 if (isViewIntent(intent)) {
247 pendingViewIntent.push(intent);
248 setIntent(createLauncherIntent(this));
249 }
250 }
251
252 @Override
253 public boolean onCreateOptionsMenu(Menu menu) {
254 getMenuInflater().inflate(R.menu.activity_conversations, menu);
255 MenuItem qrCodeScanMenuItem = menu.findItem(R.id.action_scan_qr_code);
256 if (qrCodeScanMenuItem != null) {
257 Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
258 boolean visible = getResources().getBoolean(R.bool.show_qr_code_scan)
259 && fragment != null
260 && fragment instanceof ConversationsOverviewFragment;
261 qrCodeScanMenuItem.setVisible(visible);
262 }
263 return super.onCreateOptionsMenu(menu);
264 }
265
266 @Override
267 public void onConversationSelected(Conversation conversation) {
268 openConversation(conversation, null);
269 }
270
271 private void openConversation(Conversation conversation, Bundle extras) {
272 ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment);
273 final boolean mainNeedsRefresh;
274 if (conversationFragment == null) {
275 mainNeedsRefresh = false;
276 Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
277 if (mainFragment != null && mainFragment instanceof ConversationFragment) {
278 conversationFragment = (ConversationFragment) mainFragment;
279 } else {
280 conversationFragment = new ConversationFragment();
281 FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
282 fragmentTransaction.replace(R.id.main_fragment, conversationFragment);
283 fragmentTransaction.addToBackStack(null);
284 fragmentTransaction.commit();
285 }
286 } else {
287 mainNeedsRefresh = true;
288 }
289 conversationFragment.reInit(conversation, extras);
290 if (mainNeedsRefresh) {
291 refreshFragment(R.id.main_fragment);
292 } else {
293 invalidateActionBarTitle();
294 }
295 }
296
297 @Override
298 public boolean onOptionsItemSelected(MenuItem item) {
299 switch (item.getItemId()) {
300 case android.R.id.home:
301 FragmentManager fm = getFragmentManager();
302 if (fm.getBackStackEntryCount() > 0) {
303 fm.popBackStack();
304 return true;
305 }
306 break;
307 case R.id.action_scan_qr_code:
308 UriHandlerActivity.scan(this);
309 return true;
310 }
311 return super.onOptionsItemSelected(item);
312 }
313
314 @Override
315 protected void onStart() {
316 final int theme = findTheme();
317 if (this.mTheme != theme) {
318 recreate();
319 }
320 mRedirectInProcess.set(false);
321 super.onStart();
322 }
323
324 @Override
325 protected void onNewIntent(final Intent intent) {
326 if (isViewIntent(intent)) {
327 if (xmppConnectionService != null) {
328 processViewIntent(intent);
329 } else {
330 pendingViewIntent.push(intent);
331 }
332 }
333 }
334
335 @Override
336 public void onPause() {
337 this.mActivityPaused = true;
338 super.onPause();
339 }
340
341 @Override
342 public void onResume() {
343 super.onResume();
344 this.mActivityPaused = false;
345 }
346
347 private void initializeFragments() {
348 FragmentTransaction transaction = getFragmentManager().beginTransaction();
349 Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
350 Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
351 if (mainFragment != null) {
352 Log.d(Config.LOGTAG, "initializeFragment(). main fragment exists");
353 if (binding.secondaryFragment != null) {
354 if (mainFragment instanceof ConversationFragment) {
355 Log.d(Config.LOGTAG, "gained secondary fragment. moving...");
356 getFragmentManager().popBackStack();
357 transaction.remove(mainFragment);
358 transaction.commit();
359 getFragmentManager().executePendingTransactions();
360 transaction = getFragmentManager().beginTransaction();
361 transaction.replace(R.id.secondary_fragment, mainFragment);
362 transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
363 transaction.commit();
364 return;
365 }
366 } else {
367 if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
368 Log.d(Config.LOGTAG, "lost secondary fragment. moving...");
369 transaction.remove(secondaryFragment);
370 transaction.commit();
371 getFragmentManager().executePendingTransactions();
372 transaction = getFragmentManager().beginTransaction();
373 transaction.replace(R.id.main_fragment, secondaryFragment);
374 transaction.addToBackStack(null);
375 transaction.commit();
376 return;
377 }
378 }
379 } else {
380 transaction.replace(R.id.main_fragment, new ConversationsOverviewFragment());
381 }
382 if (binding.secondaryFragment != null && secondaryFragment == null) {
383 transaction.replace(R.id.secondary_fragment, new ConversationFragment());
384 }
385 transaction.commit();
386 }
387
388 private void invalidateActionBarTitle() {
389 final ActionBar actionBar = getSupportActionBar();
390 if (actionBar != null) {
391 Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
392 if (mainFragment != null && mainFragment instanceof ConversationFragment) {
393 final Conversation conversation = ((ConversationFragment) mainFragment).getConversation();
394 if (conversation != null) {
395 actionBar.setTitle(conversation.getName());
396 actionBar.setDisplayHomeAsUpEnabled(true);
397 return;
398 }
399 }
400 actionBar.setTitle(R.string.app_name);
401 actionBar.setDisplayHomeAsUpEnabled(false);
402 }
403 }
404
405 @Override
406 public void onConversationArchived(Conversation conversation) {
407 if (performRedirectIfNecessary(conversation, false)) {
408 return;
409 }
410 Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment);
411 if (mainFragment != null && mainFragment instanceof ConversationFragment) {
412 getFragmentManager().popBackStack();
413 return;
414 }
415 Fragment secondaryFragment = getFragmentManager().findFragmentById(R.id.secondary_fragment);
416 if (secondaryFragment != null && secondaryFragment instanceof ConversationFragment) {
417 if (((ConversationFragment) secondaryFragment).getConversation() == conversation) {
418 Conversation suggestion = ConversationsOverviewFragment.getSuggestion(this, conversation);
419 if (suggestion != null) {
420 openConversation(suggestion, null);
421 return;
422 }
423 }
424 }
425 }
426
427 @Override
428 public void onConversationsListItemUpdated() {
429 Fragment fragment = getFragmentManager().findFragmentById(R.id.main_fragment);
430 if (fragment != null && fragment instanceof ConversationsOverviewFragment) {
431 ((ConversationsOverviewFragment) fragment).refresh();
432 }
433 }
434
435 @Override
436 public void onConversationRead(Conversation conversation) {
437 if (!mActivityPaused && pendingViewIntent.peek() == null) {
438 xmppConnectionService.sendReadMarker(conversation);
439 }
440 }
441
442 @Override
443 public void onAccountUpdate() {
444 this.refreshUi();
445 }
446
447 @Override
448 public void onConversationUpdate() {
449 if (performRedirectIfNecessary(false)) {
450 return;
451 }
452 this.refreshUi();
453 }
454
455 @Override
456 public void onRosterUpdate() {
457 this.refreshUi();
458 }
459
460 @Override
461 public void OnUpdateBlocklist(OnUpdateBlocklist.Status status) {
462 this.refreshUi();
463 }
464
465 @Override
466 public void onShowErrorToast(int resId) {
467 runOnUiThread(() -> Toast.makeText(this, resId, Toast.LENGTH_SHORT).show());
468 }
469}