FairEmail/app/src/main/java/eu/faircode/email/FragmentBase.java

760 lines
29 KiB
Java
Raw Normal View History

package eu.faircode.email;
2018-08-14 05:53:24 +00:00
/*
This file is part of FairEmail.
FairEmail is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2018-10-29 10:46:49 +00:00
FairEmail is distributed in the hope that it will be useful,
2018-08-14 05:53:24 +00:00
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
2018-10-29 10:46:49 +00:00
along with FairEmail. If not, see <http://www.gnu.org/licenses/>.
2018-08-14 05:53:24 +00:00
2023-01-01 07:52:55 +00:00
Copyright 2018-2023 by Marcel Bokhorst (M66B)
2018-08-14 05:53:24 +00:00
*/
2021-08-07 06:11:34 +00:00
import static android.app.ActionBar.DISPLAY_SHOW_CUSTOM;
import static android.app.Activity.RESULT_OK;
2022-09-30 08:46:09 +00:00
import android.app.Activity;
2020-01-05 14:33:47 +00:00
import android.app.RecoverableSecurityException;
2018-12-09 17:49:52 +00:00
import android.content.Context;
2020-01-05 14:33:47 +00:00
import android.content.DialogInterface;
2019-06-30 14:55:15 +00:00
import android.content.Intent;
2020-01-05 14:33:47 +00:00
import android.content.IntentSender;
import android.content.SharedPreferences;
2022-09-30 08:46:09 +00:00
import android.content.pm.ActivityInfo;
2020-06-14 16:34:13 +00:00
import android.content.pm.PackageManager;
2018-08-11 16:13:22 +00:00
import android.content.res.Configuration;
2021-06-23 14:52:11 +00:00
import android.graphics.Rect;
2019-09-22 08:29:59 +00:00
import android.net.Uri;
2020-01-05 14:33:47 +00:00
import android.os.Build;
2018-08-11 16:13:22 +00:00
import android.os.Bundle;
2020-08-23 15:34:14 +00:00
import android.os.Handler;
2019-09-22 08:29:59 +00:00
import android.text.TextUtils;
2018-08-12 17:51:57 +00:00
import android.view.LayoutInflater;
2022-08-08 19:26:38 +00:00
import android.view.Menu;
import android.view.MenuInflater;
2022-06-15 09:55:03 +00:00
import android.view.MenuItem;
2018-08-06 08:39:28 +00:00
import android.view.View;
2018-08-12 17:51:57 +00:00
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
2020-06-13 07:42:54 +00:00
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
2022-06-15 14:30:50 +00:00
import androidx.activity.OnBackPressedCallback;
2020-09-17 14:22:42 +00:00
import androidx.annotation.NonNull;
2019-06-30 14:55:15 +00:00
import androidx.annotation.Nullable;
2020-01-05 14:33:47 +00:00
import androidx.annotation.RequiresApi;
2018-08-08 06:55:47 +00:00
import androidx.appcompat.app.ActionBar;
2020-01-05 14:33:47 +00:00
import androidx.appcompat.app.AlertDialog;
2018-08-08 06:55:47 +00:00
import androidx.appcompat.app.AppCompatActivity;
2019-09-22 08:29:59 +00:00
import androidx.documentfile.provider.DocumentFile;
2018-08-08 06:55:47 +00:00
import androidx.fragment.app.Fragment;
2021-04-27 15:06:37 +00:00
import androidx.fragment.app.FragmentActivity;
2020-09-17 14:22:42 +00:00
import androidx.fragment.app.FragmentResultListener;
2018-08-22 05:18:31 +00:00
import androidx.lifecycle.Lifecycle;
2022-06-15 14:30:50 +00:00
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
2022-06-15 14:30:50 +00:00
import androidx.lifecycle.OnLifecycleEvent;
import androidx.preference.PreferenceManager;
2019-09-22 08:29:59 +00:00
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
2019-05-11 20:10:49 +00:00
import java.util.HashMap;
2019-09-22 08:29:59 +00:00
import java.util.List;
2019-05-11 20:10:49 +00:00
import java.util.Map;
2019-01-15 17:41:55 +00:00
public class FragmentBase extends Fragment {
private CharSequence count = null;
2021-11-08 09:15:48 +00:00
private CharSequence title = null;
private CharSequence subtitle = " ";
2018-08-22 05:18:31 +00:00
private boolean finish = false;
2020-06-02 13:25:30 +00:00
private boolean finished = false;
2021-07-08 13:34:02 +00:00
private int scrollToResid = 0;
private int scrollToOffset = 0;
2019-09-22 08:29:59 +00:00
2022-09-30 08:46:09 +00:00
private Integer orientation = null;
2019-09-22 08:29:59 +00:00
private static final int REQUEST_ATTACHMENT = 51;
private static final int REQUEST_ATTACHMENTS = 52;
2020-01-05 14:33:47 +00:00
private static final int REQUEST_RECOVERABLE_PERMISSION = 53;
2019-09-22 08:29:59 +00:00
2022-03-19 07:12:46 +00:00
static final int REQUEST_PERMISSIONS = 1000;
2022-02-20 09:20:44 +00:00
protected ActionBar getSupportActionBar() {
FragmentActivity activity = getActivity();
if (activity instanceof ActivityBase)
return ((ActivityBase) activity).getSupportActionBar();
else
return null;
}
2023-01-08 07:11:32 +00:00
protected boolean isActionBarShown() {
FragmentActivity activity = getActivity();
if (activity instanceof ActivityBase)
return ((ActivityBase) activity).isActionBarShown();
else
return false;
}
2023-01-07 10:26:19 +00:00
protected void showActionBar(boolean show) {
FragmentActivity activity = getActivity();
if (activity instanceof ActivityBase)
((ActivityBase) activity).showActionBar(show);
}
protected void setCount(String count) {
this.count = count;
updateSubtitle();
}
2019-08-18 08:03:14 +00:00
protected void setTitle(int resid) {
setTitle(getString(resid));
}
2021-11-08 09:15:48 +00:00
protected void setTitle(CharSequence title) {
2019-08-18 08:03:14 +00:00
this.title = title;
updateSubtitle();
}
protected void setSubtitle(int resid) {
setSubtitle(getString(resid));
}
2021-11-08 09:15:48 +00:00
protected void setSubtitle(CharSequence subtitle) {
this.subtitle = subtitle;
updateSubtitle();
}
protected void setActionBarListener(final LifecycleOwner owner, final View.OnClickListener listener) {
final AppCompatActivity activity = (AppCompatActivity) getActivity();
if (activity == null)
return;
final ActionBar actionbar = activity.getSupportActionBar();
if (actionbar == null)
return;
if ((actionbar.getDisplayOptions() & DISPLAY_SHOW_CUSTOM) == 0)
return;
final View custom = actionbar.getCustomView();
if (custom == null)
return;
owner.getLifecycle().addObserver(new LifecycleObserver() {
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public void onAny() {
Lifecycle.State state = owner.getLifecycle().getCurrentState();
custom.setOnClickListener(state.isAtLeast(Lifecycle.State.STARTED) ? listener : null);
if (Lifecycle.State.DESTROYED.equals(state))
owner.getLifecycle().removeObserver(this);
}
});
}
2022-08-08 19:26:38 +00:00
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
onPrepareOptionsMenu(menu);
}
2021-11-03 17:28:51 +00:00
void invalidateOptionsMenu() {
FragmentActivity activity = getActivity();
if (activity != null)
activity.invalidateOptionsMenu();
}
2021-07-08 13:34:02 +00:00
void scrollTo(int resid, int offset) {
scrollToResid = resid;
scrollToOffset = offset;
2020-06-13 07:42:54 +00:00
scrollTo();
}
private void scrollTo() {
2021-07-08 13:34:02 +00:00
if (scrollToResid == 0)
2020-06-13 07:42:54 +00:00
return;
View view = getView();
if (view == null)
return;
final ScrollView scroll = view.findViewById(R.id.scroll);
if (scroll == null)
return;
2021-07-08 13:34:02 +00:00
final View child = scroll.findViewById(scrollToResid);
2020-06-13 07:42:54 +00:00
if (child == null)
return;
2021-07-08 13:34:02 +00:00
scrollToResid = 0;
final int dy = Helper.dp2pixels(scroll.getContext(), scrollToOffset);
2020-06-13 07:42:54 +00:00
scroll.post(new Runnable() {
@Override
public void run() {
try {
Rect rect = new Rect();
child.getDrawingRect(rect);
scroll.offsetDescendantRectToMyCoords(child, rect);
int y = rect.top - scroll.getPaddingTop() + dy;
if (y < 0)
y = 0;
scroll.scrollTo(0, y);
} catch (Throwable ex) {
Log.e(ex);
}
2020-06-13 07:42:54 +00:00
}
});
}
@Override
public void startActivity(Intent intent) {
try {
2020-09-26 05:43:07 +00:00
Log.i("Start intent=" + intent);
Log.logExtras(intent);
super.startActivity(intent);
2020-07-03 15:49:01 +00:00
} catch (Throwable ex) {
2022-01-16 07:43:56 +00:00
Helper.reportNoViewer(getContext(), intent, ex);
}
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
try {
2020-09-26 05:43:07 +00:00
Log.i("Start intent=" + intent + " request=" + requestCode);
Log.logExtras(intent);
super.startActivityForResult(intent, requestCode);
2020-07-03 15:49:01 +00:00
} catch (Throwable ex) {
2022-01-16 07:43:56 +00:00
Helper.reportNoViewer(getContext(), intent, ex);
}
}
2018-08-22 05:18:31 +00:00
protected void finish() {
2020-06-02 13:25:30 +00:00
if (finished)
return;
finished = true;
if (getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED))
2022-06-14 11:55:15 +00:00
getParentFragmentManager().popBackStack();
2018-08-22 05:18:31 +00:00
else
finish = true;
}
2018-08-24 06:43:05 +00:00
@Override
public void onSaveInstanceState(Bundle outState) {
2019-12-07 16:02:42 +00:00
Log.d("Save instance " + this);
2019-04-11 07:47:49 +00:00
int before = Helper.getSize(outState);
2021-11-08 09:15:48 +00:00
outState.putCharSequence("fair:title", title);
outState.putCharSequence("fair:subtitle", subtitle);
2019-04-11 17:30:39 +00:00
super.onSaveInstanceState(outState);
2019-04-11 07:47:49 +00:00
int after = Helper.getSize(outState);
2019-12-07 16:02:42 +00:00
Log.d("Saved instance " + this + " size=" + before + "/" + after);
2019-05-11 20:10:49 +00:00
Map<String, String> crumb = new HashMap<>();
crumb.put("name", this.getClass().getName());
crumb.put("before", Integer.toString(before));
crumb.put("after", Integer.toString(after));
2019-08-11 08:18:37 +00:00
for (String key : outState.keySet()) {
Object value = outState.get(key);
crumb.put(key, value == null ? "" : value.getClass().getName());
}
2019-08-12 11:07:14 +00:00
Log.breadcrumb("onSaveInstanceState", crumb);
2019-05-11 20:10:49 +00:00
2019-04-11 07:47:49 +00:00
for (String key : outState.keySet())
2019-12-07 16:02:42 +00:00
Log.d("Saved " + this + " " + key + "=" + outState.get(key));
2018-08-24 06:43:05 +00:00
}
2020-09-17 20:40:38 +00:00
public String getRequestKey() {
2021-12-26 19:39:58 +00:00
return Helper.getRequestKey(this);
2020-09-17 20:40:38 +00:00
}
2018-08-11 16:13:22 +00:00
@Override
public void onCreate(Bundle savedInstanceState) {
2018-12-24 12:27:45 +00:00
Log.i("Create " + this + " saved=" + (savedInstanceState != null));
2018-08-11 16:13:22 +00:00
super.onCreate(savedInstanceState);
2020-09-17 15:04:00 +00:00
2021-10-31 18:10:36 +00:00
if (savedInstanceState == null) {
Bundle args = getArguments();
2022-02-18 14:16:09 +00:00
if (args == null && !isStateSaved())
2021-10-31 18:10:36 +00:00
setArguments(new Bundle());
} else {
2021-11-08 09:15:48 +00:00
title = savedInstanceState.getCharSequence("fair:title");
subtitle = savedInstanceState.getCharSequence("fair:subtitle");
2020-09-17 20:40:38 +00:00
}
2020-09-17 14:22:42 +00:00
2020-09-17 15:04:00 +00:00
// https://developer.android.com/training/basics/fragments/pass-data-between
2021-12-26 08:13:33 +00:00
String requestKey = getRequestKey();
if (!BuildConfig.PLAY_STORE_RELEASE)
2022-06-14 10:51:29 +00:00
EntityLog.log(getContext(), "Listening key=" + requestKey);
2021-12-26 08:13:33 +00:00
getParentFragmentManager().setFragmentResultListener(requestKey, this, new FragmentResultListener() {
2020-09-17 14:22:42 +00:00
@Override
public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) {
2020-10-02 10:16:25 +00:00
try {
result.setClassLoader(ApplicationEx.class.getClassLoader());
2020-10-02 10:16:25 +00:00
int requestCode = result.getInt("requestCode");
int resultCode = result.getInt("resultCode");
2021-12-26 08:13:33 +00:00
EntityLog.log(getContext(), "Received key=" + requestKey +
" request=" + requestCode +
" result=" + resultCode);
2020-10-02 10:16:25 +00:00
Intent data = new Intent();
data.putExtra("args", result);
onActivityResult(requestCode, resultCode, data);
} catch (Throwable ex) {
2021-12-26 08:13:33 +00:00
Log.e(ex);
2020-10-02 10:16:25 +00:00
/*
android.os.BadParcelableException: ClassNotFoundException when unmarshalling: eu.faircode.email.FragmentMessages$MessageTarget
at android.os.Parcel.readParcelableCreator(Parcel.java:2839)
at android.os.Parcel.readParcelable(Parcel.java:2765)
at android.os.Parcel.readValue(Parcel.java:2668)
at android.os.Parcel.readListInternal(Parcel.java:3098)
at android.os.Parcel.readArrayList(Parcel.java:2319)
at android.os.Parcel.readValue(Parcel.java:2689)
at android.os.Parcel.readArrayMapInternal(Parcel.java:3037)
at android.os.BaseBundle.initializeFromParcelLocked(BaseBundle.java:288)
at android.os.BaseBundle.unparcel(BaseBundle.java:232)
at android.os.BaseBundle.getInt(BaseBundle.java:1017)
*/
}
2020-09-17 14:22:42 +00:00
}
});
2020-09-17 15:04:00 +00:00
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("Create view " + this + (savedInstanceState != null));
return super.onCreateView(inflater, container, savedInstanceState);
}
2020-09-17 14:22:42 +00:00
2020-09-17 15:04:00 +00:00
@Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d("Activity " + this + " saved=" + (savedInstanceState != null));
super.onActivityCreated(savedInstanceState);
2020-06-13 07:42:54 +00:00
scrollTo();
2018-08-11 16:13:22 +00:00
}
@Override
public void onResume() {
2019-12-07 16:02:42 +00:00
Log.d("Resume " + this);
super.onResume();
updateSubtitle();
2018-08-22 05:18:31 +00:00
if (finish) {
2019-10-12 15:16:53 +00:00
getParentFragmentManager().popBackStack();
2018-08-22 05:18:31 +00:00
finish = false;
}
}
2018-08-11 16:13:22 +00:00
@Override
public void onPause() {
2019-12-07 16:02:42 +00:00
Log.d("Pause " + this);
2018-08-11 16:13:22 +00:00
super.onPause();
}
2022-06-15 09:55:03 +00:00
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
FragmentActivity activity = getActivity();
if (activity != null) {
activity.getOnBackPressedDispatcher().onBackPressed();
return true;
}
}
return super.onOptionsItemSelected(item);
}
2019-06-30 14:55:15 +00:00
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
2021-12-06 07:12:40 +00:00
EntityLog.log(getContext(), "Result class=" + this.getClass().getSimpleName() +
" action=" + (data == null ? null : data.getAction()) +
" request=" + requestCode +
" result=" + resultCode + " ok=" + (resultCode == RESULT_OK) +
" data=" + (data == null ? null : data.getData()) +
(data == null ? "" : " " + TextUtils.join(" ", Log.getExtras(data.getExtras()))));
2019-06-30 14:55:15 +00:00
super.onActivityResult(requestCode, resultCode, data);
2019-09-22 08:29:59 +00:00
try {
switch (requestCode) {
case REQUEST_ATTACHMENT:
if (resultCode == RESULT_OK && data != null)
onSaveAttachment(data);
break;
case REQUEST_ATTACHMENTS:
if (resultCode == RESULT_OK && data != null)
onSaveAttachments(data);
break;
}
} catch (Throwable ex) {
Log.e(ex);
}
2019-06-30 14:55:15 +00:00
}
@Override
public void onDetach() {
2019-12-07 16:02:42 +00:00
Log.d("Detach " + this);
super.onDetach();
2021-03-10 11:01:25 +00:00
try {
2021-04-27 15:06:37 +00:00
FragmentActivity activity = getActivity();
if (activity != null) {
2022-06-12 09:38:16 +00:00
InputMethodManager imm = Helper.getSystemService(activity, InputMethodManager.class);
2021-04-27 15:06:37 +00:00
View focused = activity.getCurrentFocus();
if (imm != null && focused != null)
imm.hideSoftInputFromWindow(focused.getWindowToken(), 0);
2021-04-27 15:06:37 +00:00
}
2021-03-10 11:01:25 +00:00
} catch (Throwable ex) {
Log.w(ex);
/*
Caused by: java.lang.NullPointerException: Attempt to read from field 'com.android.internal.view.IInputMethodClient com.android.server.inputmethod.InputMethodManagerService$ClientState.client' on a null object reference
at android.os.Parcel.createException(Parcel.java:2077)
at android.os.Parcel.readException(Parcel.java:2039)
at android.os.Parcel.readException(Parcel.java:1987)
at com.android.internal.view.IInputMethodManager$Stub$Proxy.hideSoftInput(IInputMethodManager.java:615)
at android.view.inputmethod.InputMethodManager.hideSoftInputFromWindow(InputMethodManager.java:1523)
at android.view.inputmethod.InputMethodManager.hideSoftInputFromWindow(InputMethodManager.java:1485)
at eu.faircode.email.FragmentBase.onDetach(SourceFile:5)
at androidx.fragment.app.Fragment.performDetach(SourceFile:3)
*/
}
}
2018-08-11 16:13:22 +00:00
@Override
public void onConfigurationChanged(Configuration newConfig) {
2019-12-07 16:02:42 +00:00
Log.d("Config " + this);
2018-08-11 16:13:22 +00:00
super.onConfigurationChanged(newConfig);
}
@Override
public void onDestroy() {
2018-12-24 12:27:45 +00:00
Log.i("Destroy " + this);
2022-09-30 08:46:09 +00:00
if (orientation != null) {
Activity activity = getActivity();
if (activity != null)
activity.setRequestedOrientation(orientation);
}
2018-08-11 16:13:22 +00:00
super.onDestroy();
}
2022-09-30 08:46:09 +00:00
protected void lockOrientation() {
Activity activity = getActivity();
if (activity != null) {
orientation = activity.getRequestedOrientation();
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
}
}
2018-12-29 07:24:43 +00:00
@Override
public void setHasOptionsMenu(boolean hasMenu) {
super.setHasOptionsMenu(!isPane() && hasMenu);
}
private void updateSubtitle() {
AppCompatActivity activity = (AppCompatActivity) getActivity();
2018-12-29 07:24:43 +00:00
if (activity != null && !isPane()) {
ActionBar actionbar = activity.getSupportActionBar();
if (actionbar != null)
if ((actionbar.getDisplayOptions() & DISPLAY_SHOW_CUSTOM) == 0) {
actionbar.setTitle(title == null ? getString(R.string.app_name) : title);
actionbar.setSubtitle(subtitle);
} else {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
boolean list_count = prefs.getBoolean("list_count", false);
View custom = actionbar.getCustomView();
TextView tvCount = custom.findViewById(R.id.count);
TextView tvTitle = custom.findViewById(R.id.title);
TextView tvSubtitle = custom.findViewById(R.id.subtitle);
if (tvCount != null) {
tvCount.setText(count);
tvCount.setVisibility(!list_count || TextUtils.isEmpty(count)
? View.GONE : View.VISIBLE);
}
2021-02-17 11:04:00 +00:00
if (tvTitle != null)
tvTitle.setText(title == null ? getString(R.string.app_name) : title);
if (tvSubtitle != null)
tvSubtitle.setText(subtitle);
}
}
}
2018-12-29 07:24:43 +00:00
2022-06-15 14:30:50 +00:00
protected void setBackPressedCallback(OnBackPressedCallback backPressedCallback) {
FragmentActivity activity = getActivity();
if (activity == null)
return;
2022-06-15 20:20:02 +00:00
backPressedCallback.setEnabled(true);
2022-06-15 14:30:50 +00:00
getViewLifecycleOwner().getLifecycle().addObserver(new LifecycleObserver() {
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public void onAny() {
Lifecycle.State state = getViewLifecycleOwner().getLifecycle().getCurrentState();
2022-06-15 20:20:02 +00:00
if (state.isAtLeast(Lifecycle.State.STARTED))
activity.getOnBackPressedDispatcher().addCallback(backPressedCallback);
else
2022-06-15 14:30:50 +00:00
backPressedCallback.remove();
}
});
}
2018-12-29 07:24:43 +00:00
private boolean isPane() {
Bundle args = getArguments();
return (args != null && args.getBoolean("pane"));
}
2019-02-07 09:02:40 +00:00
boolean hasPermission(String name) {
ActivityBase activity = (ActivityBase) getActivity();
if (activity == null)
return false;
return activity.hasPermission(name);
}
2019-04-17 17:26:39 +00:00
2020-01-30 19:52:18 +00:00
void addKeyPressedListener(ActivityBase.IKeyPressedListener listener) {
((ActivityBase) getActivity()).addKeyPressedListener(listener, getViewLifecycleOwner());
2019-04-17 17:26:39 +00:00
}
2019-04-29 18:26:29 +00:00
void addBillingListener(ActivityBilling.IBillingListener listener) {
((ActivityBilling) getActivity()).addBillingListener(listener, getViewLifecycleOwner());
}
2019-09-22 08:29:59 +00:00
2023-02-03 18:20:54 +00:00
protected void onStoreAttachment(EntityAttachment attachment) {
getArguments().putLong("selected_attachment", attachment.id);
Log.i("Save attachment id=" + attachment.id);
2020-09-26 05:43:07 +00:00
2023-01-27 08:56:32 +00:00
final Context context = getContext();
2019-09-22 08:29:59 +00:00
Intent create = new Intent(Intent.ACTION_CREATE_DOCUMENT);
create.addCategory(Intent.CATEGORY_OPENABLE);
2023-02-03 18:20:54 +00:00
create.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
create.setType(attachment.getMimeType());
2023-02-03 18:20:54 +00:00
create.putExtra(Intent.EXTRA_TITLE, attachment.name);
2023-01-27 08:56:32 +00:00
Helper.openAdvanced(context, create);
PackageManager pm = context.getPackageManager();
2023-12-06 10:06:33 +00:00
if (create.resolveActivity(pm) == null) // system whitelisted
Log.unexpectedError(getParentFragmentManager(),
new IllegalArgumentException(context.getString(R.string.title_no_saf)), 25);
else
2023-01-27 08:56:32 +00:00
startActivityForResult(Helper.getChooser(context, create), REQUEST_ATTACHMENT);
2019-09-22 08:29:59 +00:00
}
2023-02-03 18:20:54 +00:00
protected void onStoreAttachments(long message) {
2021-04-17 12:29:53 +00:00
getArguments().putLong("selected_message", message);
2020-09-26 05:43:07 +00:00
Log.i("Save attachments message=" + message);
2023-01-27 08:56:32 +00:00
final Context context = getContext();
2019-09-22 08:29:59 +00:00
Intent tree = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
2023-01-27 08:56:32 +00:00
Helper.openAdvanced(context, tree);
PackageManager pm = context.getPackageManager();
2023-12-06 10:06:33 +00:00
if (tree.resolveActivity(pm) == null) // system whitelisted
Log.unexpectedError(getParentFragmentManager(),
new IllegalArgumentException(context.getString(R.string.title_no_saf)), 25);
else
2023-01-27 08:56:32 +00:00
startActivityForResult(Helper.getChooser(context, tree), REQUEST_ATTACHMENTS);
2019-09-22 08:29:59 +00:00
}
private void onSaveAttachment(Intent data) {
2021-04-17 12:29:53 +00:00
long attachment = getArguments().getLong("selected_attachment", -1L);
2019-09-22 08:29:59 +00:00
Bundle args = new Bundle();
args.putLong("id", attachment);
args.putParcelable("uri", data.getData());
new SimpleTask<Void>() {
@Override
protected Void onExecute(Context context, Bundle args) throws Throwable {
long id = args.getLong("id");
Uri uri = args.getParcelable("uri");
2021-08-07 06:11:34 +00:00
if (uri == null)
throw new FileNotFoundException();
2019-11-03 19:07:26 +00:00
if (!"content".equals(uri.getScheme())) {
2019-09-22 08:29:59 +00:00
Log.w("Save attachment uri=" + uri);
throw new IllegalArgumentException(context.getString(R.string.title_no_stream));
}
DB db = DB.getInstance(context);
EntityAttachment attachment = db.attachment().getAttachment(id);
if (attachment == null)
return null;
File file = attachment.getFile(context);
OutputStream os = null;
InputStream is = null;
try {
2020-09-27 15:24:32 +00:00
os = context.getContentResolver().openOutputStream(uri);
2019-09-22 08:29:59 +00:00
is = new FileInputStream(file);
2022-03-27 11:43:45 +00:00
if (os == null)
throw new FileNotFoundException(uri.toString());
2019-09-22 08:29:59 +00:00
byte[] buffer = new byte[Helper.BUFFER_SIZE];
int read;
while ((read = is.read(buffer)) != -1)
os.write(buffer, 0, read);
} finally {
try {
if (os != null)
os.close();
} catch (Throwable ex) {
Log.w(ex);
}
try {
if (is != null)
is.close();
} catch (Throwable ex) {
Log.w(ex);
}
}
return null;
}
@Override
protected void onExecuted(Bundle args, Void data) {
ToastEx.makeText(getContext(), R.string.title_attachment_saved, Toast.LENGTH_LONG).show();
}
@Override
protected void onException(Bundle args, Throwable ex) {
2020-02-20 10:43:08 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
2020-01-21 07:16:56 +00:00
if (ex instanceof RecoverableSecurityException) {
handle((RecoverableSecurityException) ex);
return;
}
2023-12-06 16:06:46 +00:00
boolean report = !(ex instanceof IllegalArgumentException ||
2020-02-20 10:45:34 +00:00
ex instanceof FileNotFoundException ||
2023-12-06 16:06:46 +00:00
ex instanceof SecurityException);
Log.unexpectedError(getParentFragmentManager(), ex, report);
2019-09-22 08:29:59 +00:00
}
}.execute(this, args, "attachment:save");
}
private void onSaveAttachments(Intent data) {
2021-04-17 12:29:53 +00:00
long message = getArguments().getLong("selected_message", -1L);
2019-09-22 08:29:59 +00:00
Bundle args = new Bundle();
args.putLong("id", message);
args.putParcelable("uri", data.getData());
new SimpleTask<Void>() {
@Override
protected Void onExecute(Context context, Bundle args) throws Throwable {
long id = args.getLong("id");
Uri uri = args.getParcelable("uri");
2021-08-07 06:11:34 +00:00
if (uri == null)
throw new FileNotFoundException();
2020-02-20 10:45:34 +00:00
if (!"content".equals(uri.getScheme())) {
Log.w("Save attachment uri=" + uri);
throw new IllegalArgumentException(context.getString(R.string.title_no_stream));
}
2019-09-22 08:29:59 +00:00
DB db = DB.getInstance(context);
DocumentFile tree = DocumentFile.fromTreeUri(context, uri);
List<EntityAttachment> attachments = db.attachment().getAttachments(id);
for (EntityAttachment attachment : attachments)
if (attachment.subsequence == null) {
File file = attachment.getFile(context);
String name = Helper.sanitizeFilename(attachment.name);
if (TextUtils.isEmpty(name))
name = Long.toString(attachment.id);
DocumentFile document = tree.createFile(attachment.getMimeType(), name);
if (document == null)
throw new FileNotFoundException("Could not save " + uri + ":" + name);
OutputStream os = null;
InputStream is = null;
2019-09-22 08:29:59 +00:00
try {
os = context.getContentResolver().openOutputStream(document.getUri());
is = new FileInputStream(file);
2022-03-27 11:43:45 +00:00
if (os == null)
throw new FileNotFoundException(uri.toString());
byte[] buffer = new byte[Helper.BUFFER_SIZE];
int read;
while ((read = is.read(buffer)) != -1)
os.write(buffer, 0, read);
} finally {
try {
if (os != null)
os.close();
} catch (Throwable ex) {
Log.w(ex);
}
try {
if (is != null)
is.close();
} catch (Throwable ex) {
Log.w(ex);
}
2019-09-22 08:29:59 +00:00
}
}
return null;
}
@Override
protected void onExecuted(Bundle args, Void data) {
ToastEx.makeText(getContext(), R.string.title_attachments_saved, Toast.LENGTH_LONG).show();
}
@Override
protected void onException(Bundle args, Throwable ex) {
2020-10-05 06:11:01 +00:00
Log.w(ex);
2020-02-20 10:43:08 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
2020-01-21 07:16:56 +00:00
if (ex instanceof RecoverableSecurityException) {
handle((RecoverableSecurityException) ex);
return;
}
2023-12-06 16:06:46 +00:00
boolean report = !(ex instanceof IllegalArgumentException ||
2020-02-20 10:45:34 +00:00
ex instanceof FileNotFoundException ||
2023-12-06 16:06:46 +00:00
ex instanceof SecurityException);
Log.unexpectedError(getParentFragmentManager(), ex, report);
2019-09-22 08:29:59 +00:00
}
}.execute(this, args, "attachments:save");
}
2020-01-05 14:33:47 +00:00
2020-02-20 10:43:08 +00:00
@RequiresApi(api = Build.VERSION_CODES.Q)
2020-01-05 14:33:47 +00:00
private void handle(RecoverableSecurityException ex) {
new AlertDialog.Builder(getContext())
.setMessage(ex.getMessage())
.setPositiveButton(ex.getUserAction().getTitle(), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
startIntentSenderForResult(
ex.getUserAction().getActionIntent().getIntentSender(),
REQUEST_RECOVERABLE_PERMISSION,
2023-06-28 10:42:56 +00:00
null, 0, 0, 0,
Helper.getBackgroundActivityOptions());
2020-01-05 14:33:47 +00:00
} catch (IntentSender.SendIntentException ex) {
Log.w(ex);
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
2020-08-23 15:34:14 +00:00
Handler getMainHandler() {
return ApplicationEx.getMainHandler();
}
}