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

891 lines
34 KiB
Java
Raw Normal View History

2018-08-02 13:33:06 +00:00
package eu.faircode.email;
/*
2018-08-14 05:53:24 +00:00
This file is part of FairEmail.
2018-08-02 13:33:06 +00:00
2018-08-14 05:53:24 +00:00
FairEmail is free software: you can redistribute it and/or modify
2018-08-02 13:33:06 +00:00
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-02 13:33:06 +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-02 13:33:06 +00:00
2018-12-31 08:04:33 +00:00
Copyright 2018-2019 by Marcel Bokhorst (M66B)
2018-08-02 13:33:06 +00:00
*/
2019-07-12 17:33:40 +00:00
import android.annotation.SuppressLint;
import android.app.Dialog;
2018-11-08 19:51:38 +00:00
import android.content.ActivityNotFoundException;
2018-08-02 13:33:06 +00:00
import android.content.Context;
2018-12-01 12:17:33 +00:00
import android.content.DialogInterface;
import android.content.Intent;
2019-07-10 15:58:26 +00:00
import android.content.SharedPreferences;
2018-09-27 06:44:02 +00:00
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
2018-12-23 13:34:42 +00:00
import android.content.pm.ResolveInfo;
2018-08-06 15:07:46 +00:00
import android.content.res.TypedArray;
2019-01-29 13:29:39 +00:00
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
2019-06-22 12:41:02 +00:00
import android.graphics.Matrix;
2019-07-12 17:33:40 +00:00
import android.hardware.biometrics.BiometricManager;
import android.hardware.fingerprint.FingerprintManager;
2018-09-19 11:03:44 +00:00
import android.net.Uri;
2019-07-12 17:33:40 +00:00
import android.os.Build;
2018-12-01 12:17:33 +00:00
import android.os.Bundle;
2019-07-10 15:58:26 +00:00
import android.os.Handler;
2019-04-11 07:47:49 +00:00
import android.os.Parcel;
2019-05-13 06:02:56 +00:00
import android.text.Spannable;
import android.text.Spanned;
import android.text.format.DateUtils;
import android.text.format.Time;
2019-05-13 12:29:52 +00:00
import android.util.TypedValue;
2018-08-13 13:53:46 +00:00
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
2019-01-27 17:48:41 +00:00
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
2018-08-13 13:53:46 +00:00
import android.widget.ImageView;
import android.widget.Spinner;
2019-06-28 19:22:20 +00:00
import android.widget.TextView;
2018-11-08 19:51:38 +00:00
import android.widget.Toast;
2018-08-02 13:33:06 +00:00
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
2019-07-10 15:58:26 +00:00
import androidx.biometric.BiometricPrompt;
import androidx.browser.customtabs.CustomTabsIntent;
2019-05-16 06:13:18 +00:00
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
2019-06-22 12:41:02 +00:00
import androidx.exifinterface.media.ExifInterface;
2019-07-10 15:58:26 +00:00
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.preference.PreferenceManager;
2018-08-13 13:53:46 +00:00
import com.google.android.material.bottomnavigation.BottomNavigationView;
2019-06-27 07:18:57 +00:00
import com.sun.mail.iap.ConnectionException;
2019-07-21 07:50:35 +00:00
import com.sun.mail.util.FolderClosedIOException;
2018-08-13 13:53:46 +00:00
2019-01-16 13:42:17 +00:00
import java.io.BufferedInputStream;
2018-12-24 10:47:21 +00:00
import java.io.BufferedOutputStream;
2019-01-21 16:45:05 +00:00
import java.io.BufferedWriter;
2019-07-06 11:02:32 +00:00
import java.io.ByteArrayOutputStream;
2018-08-23 18:58:21 +00:00
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
2019-01-21 16:45:05 +00:00
import java.io.FileWriter;
2018-08-02 17:07:02 +00:00
import java.io.IOException;
2018-08-23 18:58:21 +00:00
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
2018-08-25 11:27:54 +00:00
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
2018-12-24 10:47:21 +00:00
import java.text.DateFormat;
import java.text.DecimalFormat;
2018-12-24 10:47:21 +00:00
import java.text.SimpleDateFormat;
import java.util.ArrayList;
2019-07-10 15:58:26 +00:00
import java.util.Date;
import java.util.List;
import java.util.Locale;
2019-02-26 10:05:21 +00:00
import java.util.Objects;
2019-03-18 10:51:47 +00:00
import java.util.Set;
2019-07-10 15:58:26 +00:00
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
2018-09-04 07:02:54 +00:00
import java.util.concurrent.ThreadFactory;
2019-06-07 06:07:40 +00:00
import java.util.concurrent.atomic.AtomicInteger;
2019-02-21 09:34:43 +00:00
import javax.mail.FolderClosedException;
import javax.mail.MessageRemovedException;
2018-08-02 17:07:02 +00:00
2018-09-04 07:02:54 +00:00
import static android.os.Process.THREAD_PRIORITY_BACKGROUND;
2018-12-23 13:34:42 +00:00
import static androidx.browser.customtabs.CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION;
2018-09-04 07:02:54 +00:00
2018-08-02 13:33:06 +00:00
public class Helper {
2019-02-15 07:51:14 +00:00
static final int NOTIFICATION_SYNCHRONIZE = 1;
static final int NOTIFICATION_SEND = 2;
static final int NOTIFICATION_EXTERNAL = 3;
static final int NOTIFICATION_UPDATE = 4;
2019-02-15 07:51:14 +00:00
2019-01-17 10:53:29 +00:00
static final float LOW_LIGHT = 0.6f;
2019-07-12 14:57:56 +00:00
static final String FAQ_URI = "https://github.com/M66B/FairEmail/blob/master/FAQ.md";
2019-06-08 19:50:17 +00:00
static final String XDA_URI = "https://forum.xda-developers.com/android/apps-games/source-email-t3824168";
2019-02-07 19:51:50 +00:00
2018-09-04 07:02:54 +00:00
static ThreadFactory backgroundThreadFactory = new ThreadFactory() {
2019-06-07 06:07:40 +00:00
private final AtomicInteger threadId = new AtomicInteger();
2018-09-04 07:02:54 +00:00
@Override
public Thread newThread(@NonNull Runnable runnable) {
Thread thread = new Thread(runnable);
thread.setName("FairEmail_bg_" + threadId.getAndIncrement());
2018-09-04 07:02:54 +00:00
thread.setPriority(THREAD_PRIORITY_BACKGROUND);
return thread;
}
};
static ThreadFactory foregroundThreadFactory = new ThreadFactory() {
private final AtomicInteger threadId = new AtomicInteger();
@Override
public Thread newThread(@NonNull Runnable runnable) {
Thread thread = new Thread(runnable);
thread.setName("FairEmail_fg_" + threadId.getAndIncrement());
return thread;
}
};
2019-07-11 05:52:06 +00:00
private final static ExecutorService executor = Executors.newSingleThreadExecutor();
2019-07-10 15:58:26 +00:00
2019-05-12 17:14:34 +00:00
// Features
2019-02-07 09:02:40 +00:00
static boolean hasPermission(Context context, String name) {
return (ContextCompat.checkSelfPermission(context, name) == PackageManager.PERMISSION_GRANTED);
}
2019-05-12 17:14:34 +00:00
static boolean hasCustomTabs(Context context, Uri uri) {
PackageManager pm = context.getPackageManager();
Intent view = new Intent(Intent.ACTION_VIEW, uri);
for (ResolveInfo info : pm.queryIntentActivities(view, 0)) {
Intent intent = new Intent();
intent.setAction(ACTION_CUSTOM_TABS_CONNECTION);
intent.setPackage(info.activityInfo.packageName);
if (pm.resolveService(intent, 0) != null)
return true;
}
return false;
}
static boolean hasWebView(Context context) {
PackageManager pm = context.getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_WEBVIEW))
try {
new WebView(context);
return true;
} catch (Throwable ex) {
return false;
}
else
return false;
}
static boolean canPrint(Context context) {
PackageManager pm = context.getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_PRINTING);
}
// View
static Intent getChooser(Context context, Intent intent) {
PackageManager pm = context.getPackageManager();
if (pm.queryIntentActivities(intent, 0).size() == 1)
return intent;
else
return Intent.createChooser(intent, context.getString(R.string.title_select_app));
}
2019-07-01 18:34:02 +00:00
static void view(Context context, Intent intent) {
Uri uri = intent.getData();
if ("http".equals(uri.getScheme()) || "https".equals(uri.getScheme()))
2019-07-01 18:34:02 +00:00
view(context, intent.getData(), false);
else
context.startActivity(intent);
}
2019-07-01 18:34:02 +00:00
static void view(Context context, Uri uri, boolean browse) {
2018-12-24 12:27:45 +00:00
Log.i("View=" + uri);
2018-12-23 13:34:42 +00:00
if (!hasCustomTabs(context, uri))
browse = true;
if (browse) {
Intent view = new Intent(Intent.ACTION_VIEW, uri);
2018-12-30 10:56:04 +00:00
context.startActivity(getChooser(context, view));
2018-12-23 13:34:42 +00:00
} else {
// https://developer.chrome.com/multidevice/android/customtabs
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
2019-01-27 12:24:37 +00:00
builder.setToolbarColor(resolveColor(context, R.attr.colorPrimary));
2018-12-23 13:34:42 +00:00
CustomTabsIntent customTabsIntent = builder.build();
try {
customTabsIntent.launchUrl(context, uri);
} catch (ActivityNotFoundException ex) {
2019-02-19 16:14:07 +00:00
Log.w(ex);
2019-07-13 06:58:56 +00:00
ToastEx.makeText(context, context.getString(R.string.title_no_viewer, uri.toString()), Toast.LENGTH_LONG).show();
2018-12-23 13:34:42 +00:00
} catch (Throwable ex) {
2018-12-24 12:41:38 +00:00
Log.e(ex);
2019-07-13 06:58:56 +00:00
ToastEx.makeText(context, Helper.formatThrowable(ex, false), Toast.LENGTH_LONG).show();
2018-12-23 13:34:42 +00:00
}
}
}
2019-01-14 10:29:47 +00:00
static Intent getIntentFAQ() {
Intent intent = new Intent(Intent.ACTION_VIEW);
2019-02-07 19:51:50 +00:00
intent.setData(Uri.parse(Helper.FAQ_URI));
2019-01-14 10:29:47 +00:00
return intent;
}
2018-10-29 15:47:27 +00:00
static Intent getIntentOpenKeychain() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://f-droid.org/en/packages/org.sufficientlysecure.keychain/"));
return intent;
}
static Intent getIntentIssue(Context context) {
if (BuildConfig.BETA_RELEASE) {
2019-06-08 19:50:17 +00:00
String version = BuildConfig.VERSION_NAME + "/" +
(Helper.hasValidFingerprint(context) ? "1" : "3") +
2019-07-22 15:19:18 +00:00
(BuildConfig.PLAY_STORE_RELEASE ? "p" : "") +
(BuildConfig.DEBUG ? "d" : "") +
2019-06-08 19:50:17 +00:00
(Helper.isPro(context) ? "+" : "");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setPackage(BuildConfig.APPLICATION_ID);
intent.setType("text/plain");
try {
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{Log.myAddress().getAddress()});
} catch (UnsupportedEncodingException ex) {
Log.w(ex);
}
intent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.title_issue_subject, version));
return intent;
} else
return new Intent(Intent.ACTION_VIEW, Uri.parse(XDA_URI));
}
2019-05-12 17:14:34 +00:00
// Graphics
2018-12-30 14:35:19 +00:00
static int dp2pixels(Context context, int dp) {
2018-12-29 07:40:12 +00:00
float scale = context.getResources().getDisplayMetrics().density;
return Math.round(dp * scale);
}
2018-12-30 14:35:19 +00:00
static float getTextSize(Context context, int zoom) {
2018-12-30 14:34:14 +00:00
TypedArray ta = null;
try {
if (zoom == 0)
ta = context.obtainStyledAttributes(
R.style.TextAppearance_AppCompat_Small, new int[]{android.R.attr.textSize});
else if (zoom == 2)
ta = context.obtainStyledAttributes(
R.style.TextAppearance_AppCompat_Large, new int[]{android.R.attr.textSize});
else
ta = context.obtainStyledAttributes(
R.style.TextAppearance_AppCompat_Medium, new int[]{android.R.attr.textSize});
2018-12-30 16:17:22 +00:00
return ta.getDimension(0, 0);
2018-12-30 14:34:14 +00:00
} finally {
if (ta != null)
ta.recycle();
}
}
2018-08-02 13:33:06 +00:00
static int resolveColor(Context context, int attr) {
2018-08-06 15:07:46 +00:00
int[] attrs = new int[]{attr};
TypedArray a = context.getTheme().obtainStyledAttributes(attrs);
int color = a.getColor(0, 0xFF0000);
a.recycle();
return color;
2018-08-02 13:33:06 +00:00
}
static void setViewsEnabled(ViewGroup view, boolean enabled) {
for (int i = 0; i < view.getChildCount(); i++) {
View child = view.getChildAt(i);
if (child instanceof Spinner ||
child instanceof EditText ||
child instanceof CheckBox ||
child instanceof ImageView /* =ImageButton */ ||
(child instanceof Button && "disable".equals(child.getTag())))
child.setEnabled(enabled);
2018-08-13 13:53:46 +00:00
if (child instanceof BottomNavigationView) {
Menu menu = ((BottomNavigationView) child).getMenu();
menu.setGroupEnabled(0, enabled);
} else if (child instanceof ViewGroup)
setViewsEnabled((ViewGroup) child, enabled);
}
}
2019-05-16 06:13:18 +00:00
static void hide(View view) {
view.setPadding(0, 0, 0, 0);
ViewGroup.LayoutParams lparam = view.getLayoutParams();
lparam.width = 0;
lparam.height = 0;
if (lparam instanceof ConstraintLayout.LayoutParams)
((ConstraintLayout.LayoutParams) lparam).setMargins(0, 0, 0, 0);
view.setLayoutParams(lparam);
}
2019-05-13 12:29:52 +00:00
static boolean isDarkTheme(Context context) {
TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(R.attr.themeName, tv, true);
return (tv.string != null && !"light".contentEquals(tv.string));
}
2019-05-12 17:14:34 +00:00
// Formatting
static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
return new DecimalFormat("@@").format(bytes / Math.pow(unit, exp)) + " " + pre + "B";
}
2019-07-15 19:28:25 +00:00
// https://issuetracker.google.com/issues/37054851
static DateFormat getTimeInstance(Context context) {
return Helper.getTimeInstance(context, SimpleDateFormat.MEDIUM);
}
static DateFormat getDateInstance(Context context) {
return SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM);
}
2019-05-12 17:14:34 +00:00
static DateFormat getTimeInstance(Context context, int style) {
if (context != null &&
(style == SimpleDateFormat.SHORT || style == SimpleDateFormat.MEDIUM)) {
Locale locale = Locale.getDefault();
boolean is24Hour = android.text.format.DateFormat.is24HourFormat(context);
String skeleton = (is24Hour ? "Hm" : "hm");
if (style == SimpleDateFormat.MEDIUM)
skeleton += "s";
String pattern = android.text.format.DateFormat.getBestDateTimePattern(locale, skeleton);
return new SimpleDateFormat(pattern, locale);
} else
return SimpleDateFormat.getTimeInstance(style);
}
2019-07-15 19:28:25 +00:00
static DateFormat getDateTimeInstance(Context context) {
return Helper.getDateTimeInstance(context, SimpleDateFormat.MEDIUM, SimpleDateFormat.MEDIUM);
}
static DateFormat getDateTimeInstance(Context context, int dateStyle, int timeStyle) {
// TODO fix time format
return SimpleDateFormat.getDateTimeInstance(dateStyle, timeStyle);
}
2019-05-12 17:14:34 +00:00
static CharSequence getRelativeTimeSpanString(Context context, long millis) {
long now = System.currentTimeMillis();
long span = Math.abs(now - millis);
Time nowTime = new Time();
Time thenTime = new Time();
nowTime.set(now);
thenTime.set(millis);
if (span < DateUtils.DAY_IN_MILLIS && nowTime.weekDay == thenTime.weekDay)
return getTimeInstance(context, SimpleDateFormat.SHORT).format(millis);
else
return DateUtils.getRelativeTimeSpanString(context, millis);
}
static String ellipsize(String text, int maxLen) {
if (text == null || text.length() < maxLen) {
return text;
}
return text.substring(0, maxLen) + "...";
}
2019-05-13 06:02:56 +00:00
static void clearComposingText(Spannable text) {
Object[] spans = text.getSpans(0, text.length(), Object.class);
for (Object span : spans)
if ((text.getSpanFlags(span) & Spanned.SPAN_COMPOSING) != 0)
text.removeSpan(span);
}
2019-07-19 06:27:44 +00:00
static String localizeFolderType(Context context, String type) {
int resid = context.getResources().getIdentifier(
"title_folder_" + type.toLowerCase(),
"string",
context.getPackageName());
return (resid > 0 ? context.getString(resid) : type);
}
2018-08-02 13:33:06 +00:00
static String localizeFolderName(Context context, String name) {
2019-02-02 07:28:14 +00:00
if (name != null && "INBOX".equals(name.toUpperCase()))
2018-08-02 13:33:06 +00:00
return context.getString(R.string.title_folder_inbox);
else if ("OUTBOX".equals(name))
return context.getString(R.string.title_folder_outbox);
else
return name;
}
static String formatThrowable(Throwable ex) {
2019-06-26 14:51:29 +00:00
return formatThrowable(ex, true);
2019-01-23 08:44:25 +00:00
}
2019-06-26 14:51:29 +00:00
static String formatThrowable(Throwable ex, boolean santize) {
return formatThrowable(ex, " ", santize);
}
static String formatThrowable(Throwable ex, String separator, boolean sanitize) {
if (sanitize) {
if (ex instanceof MessageRemovedException)
return null;
2019-06-26 14:51:29 +00:00
if (ex instanceof IOException &&
ex.getCause() instanceof MessageRemovedException)
return null;
2019-06-27 07:18:57 +00:00
if (ex instanceof ConnectionException)
return null;
2019-07-21 07:50:35 +00:00
if (ex instanceof FolderClosedException || ex instanceof FolderClosedIOException)
2019-06-26 14:51:29 +00:00
return null;
2019-06-26 14:51:29 +00:00
if (ex instanceof IllegalStateException &&
("Not connected".equals(ex.getMessage()) ||
"This operation is not allowed on a closed folder".equals(ex.getMessage())))
return null;
2019-02-21 09:34:43 +00:00
2019-06-26 14:51:29 +00:00
if (ex instanceof Core.AlertException)
return ex.getMessage();
}
2019-06-24 06:45:55 +00:00
2018-08-02 13:33:06 +00:00
StringBuilder sb = new StringBuilder();
2019-02-20 08:20:07 +00:00
if (BuildConfig.DEBUG)
sb.append(ex.toString());
else
sb.append(ex.getMessage() == null ? ex.getClass().getName() : ex.getMessage());
2018-12-08 16:27:50 +00:00
2018-08-02 13:33:06 +00:00
Throwable cause = ex.getCause();
while (cause != null) {
2019-02-20 08:20:07 +00:00
if (BuildConfig.DEBUG)
sb.append(separator).append(cause.toString());
else
sb.append(separator).append(cause.getMessage() == null ? cause.getClass().getName() : cause.getMessage());
2018-08-02 13:33:06 +00:00
cause = cause.getCause();
}
2018-12-08 16:27:50 +00:00
2018-08-02 13:33:06 +00:00
return sb.toString();
}
2018-08-02 17:07:02 +00:00
static void unexpectedError(FragmentManager manager, final Throwable ex) {
Bundle args = new Bundle();
args.putSerializable("ex", ex);
FragmentDialogUnexpected fragment = new FragmentDialogUnexpected();
fragment.setArguments(args);
fragment.show(manager, "error:unexpected");
}
public static class FragmentDialogUnexpected extends DialogFragmentEx {
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
final Throwable ex = (Throwable) getArguments().getSerializable("ex");
return new AlertDialog.Builder(getContext())
2018-12-01 09:58:19 +00:00
.setTitle(R.string.title_unexpected_error)
.setMessage(Helper.formatThrowable(ex, false))
2018-12-01 09:58:19 +00:00
.setPositiveButton(android.R.string.cancel, null)
2018-12-01 12:17:33 +00:00
.setNeutralButton(R.string.title_report, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Dialog will be dismissed
final Context context = getContext();
2018-12-01 12:17:33 +00:00
new SimpleTask<Long>() {
@Override
2018-12-31 07:03:48 +00:00
protected Long onExecute(Context context, Bundle args) throws Throwable {
2019-05-12 17:14:34 +00:00
return Log.getDebugInfo(context, R.string.title_crash_info_remark, ex, null).id;
2018-12-01 12:17:33 +00:00
}
@Override
2018-12-31 07:03:48 +00:00
protected void onExecuted(Bundle args, Long id) {
context.startActivity(new Intent(context, ActivityCompose.class)
.putExtra("action", "edit")
.putExtra("id", id));
2018-12-01 12:17:33 +00:00
}
@Override
protected void onException(Bundle args, Throwable ex) {
2018-12-24 10:47:21 +00:00
if (ex instanceof IllegalArgumentException)
2019-07-13 06:58:56 +00:00
ToastEx.makeText(context, ex.getMessage(), Toast.LENGTH_LONG).show();
2018-12-24 10:47:21 +00:00
else
2019-07-13 06:58:56 +00:00
ToastEx.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
2018-12-01 12:17:33 +00:00
}
}.execute(context, getActivity(), new Bundle(), "error:unexpected");
2018-12-01 12:17:33 +00:00
}
})
.create();
}
2018-12-24 10:47:21 +00:00
}
2019-05-12 17:14:34 +00:00
// Files
2018-12-24 10:47:21 +00:00
2019-05-12 17:14:34 +00:00
static String sanitizeFilename(String name) {
2019-06-23 12:27:14 +00:00
if (name == null)
return null;
2019-06-29 13:41:16 +00:00
return name.replaceAll("[?:\"*|/\\\\<>]", "_");
2018-08-03 19:12:19 +00:00
}
2019-05-12 17:14:34 +00:00
static String getExtension(String filename) {
if (filename == null)
return null;
int index = filename.lastIndexOf(".");
if (index < 0)
return null;
return filename.substring(index + 1);
}
2018-08-23 14:36:19 +00:00
2019-01-21 16:45:05 +00:00
static void writeText(File file, String content) throws IOException {
2019-02-22 15:59:23 +00:00
try (BufferedWriter out = new BufferedWriter(new FileWriter(file))) {
2019-01-21 16:45:05 +00:00
out.write(content == null ? "" : content);
}
}
2019-07-06 11:02:32 +00:00
static String readStream(InputStream is, String charset) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[16384];
for (int len = is.read(buffer); len != -1; len = is.read(buffer))
os.write(buffer, 0, len);
return new String(os.toByteArray(), charset);
}
2019-01-21 16:45:05 +00:00
static String readText(File file) throws IOException {
try (FileInputStream in = new FileInputStream(file)) {
2019-07-06 11:02:32 +00:00
return readStream(in, "UTF-8");
2019-01-21 16:45:05 +00:00
}
}
2018-08-23 18:58:21 +00:00
static void copy(File src, File dst) throws IOException {
2019-02-22 15:59:23 +00:00
try (InputStream in = new BufferedInputStream(new FileInputStream(src))) {
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(dst))) {
2018-08-23 18:58:21 +00:00
byte[] buf = new byte[4096];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
}
}
}
2018-08-25 11:27:54 +00:00
2019-05-12 17:14:34 +00:00
static Bitmap decodeImage(File file, int scaleToPixels) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), options);
2018-09-20 15:03:07 +00:00
2019-05-12 17:14:34 +00:00
int factor = 1;
while (options.outWidth / factor > scaleToPixels)
factor *= 2;
2019-06-22 12:49:02 +00:00
Matrix rotation = null;
try {
rotation = Helper.getImageRotation(file);
} catch (IOException ex) {
Log.w(ex);
}
if (factor > 1 || rotation != null) {
2019-05-12 17:14:34 +00:00
Log.i("Decode image factor=" + factor);
options.inJustDecodeBounds = false;
options.inSampleSize = factor;
2019-06-22 12:49:02 +00:00
Bitmap scaled = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
if (rotation != null) {
Bitmap rotated = Bitmap.createBitmap(scaled, 0, 0, scaled.getWidth(), scaled.getHeight(), rotation, true);
scaled.recycle();
scaled = rotated;
}
return scaled;
2019-05-12 17:14:34 +00:00
}
return BitmapFactory.decodeFile(file.getAbsolutePath());
2018-08-25 11:27:54 +00:00
}
2019-06-22 12:41:02 +00:00
static Matrix getImageRotation(File file) throws IOException {
ExifInterface exif = new ExifInterface(file.getAbsolutePath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return null;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
return matrix;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
return matrix;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
return matrix;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
return matrix;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
return matrix;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
return matrix;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
return matrix;
default:
return null;
}
}
2019-05-12 17:14:34 +00:00
// Cryptography
2018-08-25 11:27:54 +00:00
static String sha256(String data) throws NoSuchAlgorithmException {
return sha256(data.getBytes());
}
static String sha256(byte[] data) throws NoSuchAlgorithmException {
byte[] bytes = MessageDigest.getInstance("SHA-256").digest(data);
StringBuilder sb = new StringBuilder();
for (byte b : bytes)
sb.append(String.format("%02x", b));
return sb.toString();
}
2018-08-25 13:32:52 +00:00
2019-07-11 05:52:06 +00:00
static String getFingerprint(Context context) {
2018-09-27 06:44:02 +00:00
try {
PackageManager pm = context.getPackageManager();
String pkg = context.getPackageName();
PackageInfo info = pm.getPackageInfo(pkg, PackageManager.GET_SIGNATURES);
byte[] cert = info.signatures[0].toByteArray();
MessageDigest digest = MessageDigest.getInstance("SHA1");
byte[] bytes = digest.digest(cert);
StringBuilder sb = new StringBuilder();
for (byte b : bytes)
sb.append(Integer.toString(b & 0xff, 16).toUpperCase());
return sb.toString();
} catch (Throwable ex) {
2018-12-24 12:27:45 +00:00
Log.e(ex);
2018-09-27 06:44:02 +00:00
return null;
}
}
2019-07-11 05:52:06 +00:00
static boolean hasValidFingerprint(Context context) {
2018-09-27 06:44:02 +00:00
String signed = getFingerprint(context);
String expected = context.getString(R.string.fingerprint);
2019-02-26 10:05:21 +00:00
return Objects.equals(signed, expected);
2018-09-27 06:44:02 +00:00
}
2019-07-12 17:33:40 +00:00
static boolean canAuthenticate(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
return false;
else if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q) {
2019-07-18 17:40:47 +00:00
if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT))
return false;
2019-07-12 17:33:40 +00:00
FingerprintManager fpm = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
return (fpm != null && fpm.isHardwareDetected() && fpm.hasEnrolledFingerprints());
} else {
@SuppressLint("WrongConstant")
BiometricManager bm = (BiometricManager) context.getSystemService(Context.BIOMETRIC_SERVICE);
return (bm != null && bm.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS);
}
}
static boolean hasAuthentication(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getBoolean("biometrics", false);
}
2019-07-10 15:58:26 +00:00
static boolean shouldAuthenticate(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean biometrics = prefs.getBoolean("biometrics", false);
long biometrics_timeout = prefs.getInt("biometrics_timeout", 2) * 60 * 1000L;
2019-07-10 15:58:26 +00:00
2019-07-10 17:58:02 +00:00
if (biometrics) {
long now = new Date().getTime();
long last_authentication = prefs.getLong("last_authentication", 0);
Log.i("Authentication valid until=" + new Date(last_authentication + biometrics_timeout));
2019-07-10 17:58:02 +00:00
if (last_authentication + biometrics_timeout < now)
2019-07-10 17:58:02 +00:00
return true;
2019-07-10 15:58:26 +00:00
2019-07-10 17:58:02 +00:00
prefs.edit().putLong("last_authentication", now).apply();
}
2019-07-10 15:58:26 +00:00
2019-07-10 17:58:02 +00:00
return false;
2019-07-10 15:58:26 +00:00
}
static void authenticate(final FragmentActivity activity,
Boolean enabled, final
Runnable authenticated, final Runnable cancelled) {
final Handler handler = new Handler();
BiometricPrompt.PromptInfo.Builder info = new BiometricPrompt.PromptInfo.Builder()
.setTitle(activity.getString(enabled == null ? R.string.app_name : R.string.title_setup_biometrics))
.setNegativeButtonText(activity.getString(android.R.string.cancel));
2019-07-11 05:34:56 +00:00
info.setSubtitle(activity.getString(enabled == null ? R.string.title_setup_biometrics_unlock
: enabled
? R.string.title_setup_biometrics_disable
: R.string.title_setup_biometrics_enable));
2019-07-10 15:58:26 +00:00
BiometricPrompt prompt = new BiometricPrompt(activity, executor,
new BiometricPrompt.AuthenticationCallback() {
@Override
public void onAuthenticationError(final int errorCode, @NonNull final CharSequence errString) {
Log.w("Biometric error " + errorCode + ": " + errString);
handler.post(new Runnable() {
@Override
public void run() {
if (errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON ||
errorCode == BiometricPrompt.ERROR_CANCELED ||
errorCode == BiometricPrompt.ERROR_USER_CANCELED)
cancelled.run();
else
2019-07-13 06:58:56 +00:00
ToastEx.makeText(activity,
2019-07-10 15:58:26 +00:00
errString + " (" + errorCode + ")",
Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) {
Log.i("Biometric succeeded");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
prefs.edit().putLong("last_authentication", new Date().getTime()).apply();
handler.post(new Runnable() {
@Override
public void run() {
authenticated.run();
}
});
}
@Override
public void onAuthenticationFailed() {
Log.w("Biometric failed");
handler.post(new Runnable() {
@Override
public void run() {
2019-07-13 06:58:56 +00:00
ToastEx.makeText(activity,
2019-07-10 15:58:26 +00:00
R.string.title_unexpected_error,
Toast.LENGTH_LONG).show();
cancelled.run();
}
});
}
});
prompt.authenticate(info.build());
}
2019-07-11 06:13:49 +00:00
static void clearAuthentication(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().remove("last_authentication").apply();
}
2019-05-12 17:14:34 +00:00
// Miscellaneous
static String sanitizeKeyword(String keyword) {
// https://tools.ietf.org/html/rfc3501
StringBuilder sb = new StringBuilder();
for (int i = 0; i < keyword.length(); i++) {
// flag-keyword = atom
// atom = 1*ATOM-CHAR
// ATOM-CHAR = <any CHAR except atom-specials>
char kar = keyword.charAt(i);
// atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards / quoted-specials / resp-specials
if (kar == '(' || kar == ')' || kar == '{' || kar == ' ' || Character.isISOControl(kar))
continue;
// list-wildcards = "%" / "*"
if (kar == '%' || kar == '*')
continue;
// quoted-specials = DQUOTE / "\"
if (kar == '"' || kar == '\\')
continue;
// resp-specials = "]"
if (kar == ']')
continue;
sb.append(kar);
}
return sb.toString();
}
static boolean isPlayStoreInstall(Context context) {
return BuildConfig.PLAY_STORE_RELEASE;
}
2018-09-17 06:15:54 +00:00
static boolean isPro(Context context) {
2018-09-22 05:36:24 +00:00
if (false && BuildConfig.DEBUG)
2018-09-17 06:15:54 +00:00
return true;
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean("pro", false);
}
2019-07-02 05:53:58 +00:00
static void linkPro(final TextView tv) {
if (isPro(tv.getContext()) && !BuildConfig.DEBUG)
2019-07-13 09:42:42 +00:00
hide(tv);
else {
final Intent pro = new Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.PRO_FEATURES_URI));
PackageManager pm = tv.getContext().getPackageManager();
if (pro.resolveActivity(pm) != null) {
tv.getPaint().setUnderlineText(true);
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tv.getContext().startActivity(pro);
}
});
}
2019-07-02 05:53:58 +00:00
}
2019-06-28 19:22:20 +00:00
}
2019-07-11 05:52:06 +00:00
static <T> List<List<T>> chunkList(List<T> list, int size) {
2019-05-22 11:17:42 +00:00
List<List<T>> result = new ArrayList<>(list.size() / size);
for (int i = 0; i < list.size(); i += size)
result.add(list.subList(i, i + size < list.size() ? i + size : list.size()));
return result;
}
static long[] toLongArray(List<Long> list) {
long[] result = new long[list.size()];
for (int i = 0; i < list.size(); i++)
result[i] = list.get(i);
return result;
}
2019-03-18 10:51:47 +00:00
static long[] toLongArray(Set<Long> set) {
long[] result = new long[set.size()];
int i = 0;
for (Long value : set)
result[i++] = value;
return result;
}
static List<Long> fromLongArray(long[] array) {
List<Long> result = new ArrayList<>();
for (int i = 0; i < array.length; i++)
result.add(array[i]);
return result;
}
2018-11-25 12:34:08 +00:00
static boolean equal(String[] a1, String[] a2) {
if (a1.length != a2.length)
return false;
for (int i = 0; i < a1.length; i++)
if (!a1[i].equals(a2[i]))
return false;
return true;
}
2018-11-26 11:42:06 +00:00
2019-04-11 07:47:49 +00:00
static int getSize(Bundle bundle) {
Parcel p = Parcel.obtain();
bundle.writeToParcel(p, 0);
return p.dataSize();
}
2018-08-02 13:33:06 +00:00
}