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

2903 lines
117 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
2022-01-01 08:46:36 +00:00
Copyright 2018-2022 by Marcel Bokhorst (M66B)
2018-08-02 13:33:06 +00:00
*/
import static android.os.Process.THREAD_PRIORITY_BACKGROUND;
import static androidx.browser.customtabs.CustomTabsService.ACTION_CUSTOM_TABS_CONNECTION;
2019-12-12 12:34:04 +00:00
import android.Manifest;
2022-04-15 19:29:00 +00:00
import android.animation.Animator;
2021-12-31 14:56:30 +00:00
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
2019-12-05 14:18:53 +00:00
import android.app.Activity;
2021-02-02 16:43:46 +00:00
import android.app.ActivityManager;
2022-06-19 06:24:13 +00:00
import android.app.ApplicationExitInfo;
import android.app.KeyguardManager;
2021-10-02 05:37:00 +00:00
import android.app.UiModeManager;
2022-06-19 06:24:13 +00:00
import android.app.usage.UsageEvents;
2021-08-18 18:43:25 +00:00
import android.app.usage.UsageStatsManager;
2018-11-08 19:51:38 +00:00
import android.content.ActivityNotFoundException;
2020-02-26 10:19:19 +00:00
import android.content.ComponentName;
2020-07-19 16:06:57 +00:00
import android.content.ContentResolver;
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;
2022-06-10 14:53:14 +00:00
import android.content.pm.ApplicationInfo;
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;
2019-12-01 11:24:03 +00:00
import android.content.res.Configuration;
import android.content.res.Resources;
2018-08-06 15:07:46 +00:00
import android.content.res.TypedArray;
2021-12-11 15:37:56 +00:00
import android.graphics.Bitmap;
2018-09-19 11:03:44 +00:00
import android.net.Uri;
2020-10-31 09:27:42 +00:00
import android.os.BatteryManager;
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-10-19 19:53:19 +00:00
import android.os.Environment;
2019-12-01 11:24:03 +00:00
import android.os.LocaleList;
2019-04-11 07:47:49 +00:00
import android.os.Parcel;
2019-09-26 10:11:46 +00:00
import android.os.PowerManager;
2019-10-19 19:53:19 +00:00
import android.os.StatFs;
2022-04-30 20:05:28 +00:00
import android.os.storage.StorageManager;
2022-06-12 08:09:37 +00:00
import android.provider.Browser;
2020-07-19 16:06:57 +00:00
import android.provider.Settings;
2019-12-05 14:18:53 +00:00
import android.security.KeyChain;
import android.security.KeyChainAliasCallback;
import android.security.KeyChainException;
import android.text.Html;
2021-04-04 12:53:25 +00:00
import android.text.Layout;
import android.text.Spannable;
2019-10-20 10:17:04 +00:00
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.format.Time;
2021-12-30 14:33:09 +00:00
import android.util.DisplayMetrics;
2019-05-13 12:29:52 +00:00
import android.util.TypedValue;
2022-01-16 07:01:59 +00:00
import android.view.ActionMode;
2019-10-20 10:17:04 +00:00
import android.view.KeyEvent;
import android.view.LayoutInflater;
2018-08-13 13:53:46 +00:00
import android.view.Menu;
2022-01-16 07:01:59 +00:00
import android.view.MenuItem;
2021-04-04 12:53:25 +00:00
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
2021-12-11 14:45:58 +00:00
import android.view.ViewParent;
import android.view.accessibility.AccessibilityManager;
2019-10-20 10:17:04 +00:00
import android.view.inputmethod.EditorInfo;
2021-04-27 14:40:27 +00:00
import android.view.inputmethod.InputMethodManager;
2019-11-20 11:40:56 +00:00
import android.webkit.MimeTypeMap;
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;
2019-09-19 13:29:00 +00:00
import android.widget.RadioButton;
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-11-09 10:18:55 +00:00
import androidx.biometric.BiometricManager;
2019-07-10 15:58:26 +00:00
import androidx.biometric.BiometricPrompt;
2021-01-17 03:05:29 +00:00
import androidx.browser.customtabs.CustomTabColorSchemeParams;
2020-02-26 10:19:19 +00:00
import androidx.browser.customtabs.CustomTabsClient;
import androidx.browser.customtabs.CustomTabsIntent;
2019-05-16 06:13:18 +00:00
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
2020-01-08 08:06:30 +00:00
import androidx.core.content.FileProvider;
2022-06-12 11:19:38 +00:00
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
2021-12-26 19:39:58 +00:00
import androidx.fragment.app.Fragment;
2019-07-10 15:58:26 +00:00
import androidx.fragment.app.FragmentActivity;
2019-12-29 16:10:25 +00:00
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
2019-12-29 16:10:25 +00:00
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.preference.PreferenceManager;
2022-04-15 19:29:00 +00:00
import androidx.recyclerview.selection.SelectionTracker;
2019-12-02 06:37:09 +00:00
import androidx.recyclerview.widget.RecyclerView;
2022-04-17 10:14:39 +00:00
import androidx.viewpager.widget.PagerAdapter;
2018-08-13 13:53:46 +00:00
import com.google.android.material.bottomnavigation.BottomNavigationView;
2022-01-22 20:14:01 +00:00
import com.google.android.material.snackbar.Snackbar;
2018-08-13 13:53:46 +00:00
2020-06-19 18:44:19 +00:00
import org.openintents.openpgp.util.OpenPgpApi;
2020-01-25 09:49:59 +00:00
2022-04-30 19:30:22 +00:00
import java.io.ByteArrayInputStream;
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;
2022-03-18 16:22:25 +00:00
import java.io.FileNotFoundException;
2018-08-23 18:58:21 +00:00
import java.io.FileOutputStream;
2018-08-02 17:07:02 +00:00
import java.io.IOException;
2018-08-23 18:58:21 +00:00
import java.io.InputStream;
2019-11-30 11:50:39 +00:00
import java.io.OutputStream;
2020-01-05 08:27:34 +00:00
import java.io.UnsupportedEncodingException;
2021-12-26 19:39:58 +00:00
import java.lang.reflect.Field;
2021-08-29 19:18:09 +00:00
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
2021-01-20 19:00:44 +00:00
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
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;
2022-03-06 13:05:33 +00:00
import java.text.NumberFormat;
2018-12-24 10:47:21 +00:00
import java.text.SimpleDateFormat;
import java.util.ArrayList;
2020-07-20 12:50:10 +00:00
import java.util.Arrays;
2020-01-25 09:49:59 +00:00
import java.util.Comparator;
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-10-10 11:26:44 +00:00
import java.util.concurrent.BlockingQueue;
2020-01-25 09:49:59 +00:00
import java.util.concurrent.ExecutionException;
2019-07-10 15:58:26 +00:00
import java.util.concurrent.ExecutorService;
2019-10-10 11:26:44 +00:00
import java.util.concurrent.LinkedBlockingQueue;
2020-01-25 09:49:59 +00:00
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.RunnableFuture;
2019-10-10 11:26:44 +00:00
import java.util.concurrent.SynchronousQueue;
2018-09-04 07:02:54 +00:00
import java.util.concurrent.ThreadFactory;
2019-10-10 11:26:44 +00:00
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
2020-01-25 09:49:59 +00:00
import java.util.concurrent.TimeoutException;
2019-06-07 06:07:40 +00:00
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
2020-03-05 13:45:29 +00:00
import java.util.regex.Pattern;
2018-08-02 13:33:06 +00:00
public class Helper {
2022-06-10 14:53:14 +00:00
private static Integer targetSdk = null;
2022-02-14 09:38:07 +00:00
private static Boolean hasWebView = null;
2021-05-02 07:48:08 +00:00
private static Boolean hasPlayStore = null;
private static Boolean hasValidFingerprint = null;
2019-01-17 10:53:29 +00:00
static final float LOW_LIGHT = 0.6f;
2019-09-24 12:46:12 +00:00
static final int BUFFER_SIZE = 8192; // Same as in Files class
2021-01-25 09:05:22 +00:00
static final long MIN_REQUIRED_SPACE = 250 * 1024L * 1024L;
2021-08-29 19:18:09 +00:00
static final int MAX_REDIRECTS = 5; // https://www.freesoft.org/CIE/RFC/1945/46.htm
2021-10-30 09:10:24 +00:00
static final int AUTOLOCK_GRACE = 7; // seconds
static final long PIN_FAILURE_DELAY = 3; // seconds
2019-01-17 10:53:29 +00:00
2022-05-14 13:48:14 +00:00
static final String PGP_OPENKEYCHAIN_PACKAGE = "org.sufficientlysecure.keychain";
static final String PGP_BEGIN_MESSAGE = "-----BEGIN PGP MESSAGE-----";
static final String PGP_END_MESSAGE = "-----END PGP MESSAGE-----";
2022-06-03 08:47:12 +00:00
static final String PACKAGE_CHROME = "com.android.chrome";
static final String PACKAGE_WEBVIEW = "https://play.google.com/store/apps/details?id=com.google.android.webview";
2022-07-17 05:35:03 +00:00
static final String PRIVACY_URI = "https://github.com/M66B/FairEmail/blob/master/PRIVACY.md";
2022-07-17 06:02:13 +00:00
static final String TUTORIALS_URI = "https://github.com/M66B/FairEmail/tree/master/tutorials#main";
static final String XDA_URI = "https://forum.xda-developers.com/showthread.php?t=3824168";
2021-08-23 13:20:07 +00:00
static final String SUPPORT_URI = "https://contact.faircode.eu/";
static final String TEST_URI = "https://play.google.com/apps/testing/" + BuildConfig.APPLICATION_ID;
2021-07-16 16:39:06 +00:00
static final String BIMI_PRIVACY_URI = "https://datatracker.ietf.org/doc/html/draft-brotman-ietf-bimi-guidance-03#section-7.4";
2022-07-09 05:47:29 +00:00
static final String LT_PRIVACY_URI = "https://languagetool.org/legal/privacy";
2022-03-02 19:54:33 +00:00
static final String ID_COMMAND_URI = "https://datatracker.ietf.org/doc/html/rfc2971#section-3.1";
2022-03-13 13:39:19 +00:00
static final String AUTH_RESULTS_URI = "https://datatracker.ietf.org/doc/html/rfc7601";
2021-07-03 14:41:54 +00:00
static final String FAVICON_PRIVACY_URI = "https://en.wikipedia.org/wiki/Favicon";
2020-08-18 15:25:19 +00:00
static final String LICENSE_URI = "https://www.gnu.org/licenses/gpl-3.0.html";
2021-06-16 06:46:40 +00:00
static final String DONTKILL_URI = "https://dontkillmyapp.com/";
2021-10-27 12:44:21 +00:00
static final String URI_SUPPORT_RESET_OPEN = "https://support.google.com/pixelphone/answer/6271667";
static final String URI_SUPPORT_CONTACT_GROUP = "https://support.google.com/contacts/answer/30970";
2019-02-07 19:51:50 +00:00
2021-08-25 06:20:18 +00:00
// https://developer.android.com/distribute/marketing-tools/linking-to-google-play#PerformingSearch
private static final String PLAY_STORE_SEARCH = "https://play.google.com/store/search";
2021-10-14 17:53:53 +00:00
private static final String[] ROMAN_1000 = {"", "M", "MM", "MMM"};
private static final String[] ROMAN_100 = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
private static final String[] ROMAN_10 = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
private static final String[] ROMAN_1 = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
2022-02-16 09:13:45 +00:00
static final Pattern EMAIL_ADDRESS = Pattern.compile(
2022-03-05 07:12:36 +00:00
"[\\S&&[^\"@]]{1,256}" +
2020-03-05 13:45:29 +00:00
"\\@" +
2022-02-23 07:26:37 +00:00
"[\\p{L}0-9][\\p{L}0-9\\-\\_]{0,64}" +
2020-03-05 13:45:29 +00:00
"(" +
"\\." +
2022-02-16 16:54:18 +00:00
"[\\p{L}0-9][\\p{L}0-9\\-\\_]{0,25}" +
2020-03-05 13:45:29 +00:00
")+"
);
2020-04-23 15:56:02 +00:00
private static final ExecutorService executor = getBackgroundExecutor(1, "helper");
2020-01-25 09:49:59 +00:00
static ExecutorService getBackgroundExecutor(int threads, final String name) {
2019-10-10 11:26:44 +00:00
ThreadFactory factory = new ThreadFactory() {
private final AtomicInteger threadId = new AtomicInteger();
@Override
public Thread newThread(@NonNull Runnable runnable) {
Thread thread = new Thread(runnable);
thread.setName("FairEmail_bg_" + name + "_" + threadId.getAndIncrement());
thread.setPriority(THREAD_PRIORITY_BACKGROUND);
return thread;
}
};
if (threads == 0)
return new ThreadPoolExecutorEx(
2020-01-30 16:05:15 +00:00
name,
2019-10-10 11:26:44 +00:00
0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
factory);
2020-01-25 09:49:59 +00:00
else if (threads == 1)
return new ThreadPoolExecutorEx(
2020-01-30 16:05:15 +00:00
name,
2020-01-25 09:49:59 +00:00
threads, threads,
0L, TimeUnit.MILLISECONDS,
new PriorityBlockingQueue<Runnable>(10, new PriorityComparator()),
factory) {
private final AtomicLong sequenceId = new AtomicLong();
2020-01-25 09:49:59 +00:00
@Override
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
RunnableFuture<T> task = super.newTaskFor(runnable, value);
if (runnable instanceof PriorityRunnable)
return new PriorityFuture<T>(task,
((PriorityRunnable) runnable).getPriority(),
((PriorityRunnable) runnable).getOrder());
2020-01-25 09:49:59 +00:00
else
return new PriorityFuture<>(task, 0, sequenceId.getAndIncrement());
2020-01-25 09:49:59 +00:00
}
};
2019-10-10 11:26:44 +00:00
else
return new ThreadPoolExecutorEx(
2020-01-30 16:05:15 +00:00
name,
2019-10-10 11:26:44 +00:00
threads, threads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
factory);
}
private static class ThreadPoolExecutorEx extends ThreadPoolExecutor {
2020-04-05 12:10:19 +00:00
private String name;
2020-01-30 16:05:15 +00:00
public ThreadPoolExecutorEx(
String name,
int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
2019-10-10 11:26:44 +00:00
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
2020-01-30 16:05:15 +00:00
this.name = name;
2019-10-10 11:26:44 +00:00
}
2019-06-07 06:07:40 +00:00
2018-09-04 07:02:54 +00:00
@Override
2019-10-10 11:26:44 +00:00
protected void beforeExecute(Thread t, Runnable r) {
2019-12-07 16:02:42 +00:00
Log.d("Executing " + t.getName());
2018-09-04 07:02:54 +00:00
}
2020-04-05 12:10:19 +00:00
@Override
protected void afterExecute(Runnable r, Throwable t) {
Log.d("Executed " + name + " pending=" + getQueue().size());
}
2019-10-10 11:26:44 +00:00
}
2018-09-04 07:02:54 +00:00
2020-01-25 09:49:59 +00:00
private static class PriorityFuture<T> implements RunnableFuture<T> {
private int priority;
private long order;
2020-01-25 09:49:59 +00:00
private RunnableFuture<T> wrapped;
PriorityFuture(RunnableFuture<T> wrapped, int priority, long order) {
2020-01-25 09:49:59 +00:00
this.wrapped = wrapped;
this.priority = priority;
this.order = order;
2020-01-25 09:49:59 +00:00
}
public int getPriority() {
return this.priority;
2020-01-25 09:49:59 +00:00
}
public long getOrder() {
return this.order;
}
2020-01-25 09:49:59 +00:00
@Override
public void run() {
wrapped.run();
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return wrapped.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return wrapped.isCancelled();
}
@Override
public boolean isDone() {
return wrapped.isDone();
}
@Override
public T get() throws ExecutionException, InterruptedException {
return wrapped.get();
}
@Override
2020-09-10 09:14:51 +00:00
public T get(long timeout, @NonNull TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException {
2020-01-25 09:49:59 +00:00
return wrapped.get(timeout, unit);
}
}
private static class PriorityComparator implements Comparator<Runnable> {
@Override
public int compare(Runnable r1, Runnable r2) {
if (r1 instanceof PriorityFuture<?> && r2 instanceof PriorityFuture<?>) {
Integer p1 = ((PriorityFuture<?>) r1).getPriority();
Integer p2 = ((PriorityFuture<?>) r2).getPriority();
int p = p1.compareTo(p2);
if (p == 0) {
Long o1 = ((PriorityFuture<?>) r1).getOrder();
Long o2 = ((PriorityFuture<?>) r2).getOrder();
return o1.compareTo(o2);
} else
return p;
2020-01-25 09:49:59 +00:00
} else
return 0;
}
}
static class PriorityRunnable implements Runnable {
private int priority;
private long order;
2020-01-25 09:49:59 +00:00
int getPriority() {
return this.priority;
}
long getOrder() {
return this.order;
2020-01-25 09:49:59 +00:00
}
PriorityRunnable(int priority, long order) {
2020-01-25 09:49:59 +00:00
this.priority = priority;
this.order = order;
2020-01-25 09:49:59 +00:00
}
@Override
public void run() {
Log.i("Run priority=" + priority);
}
}
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-12-12 12:34:04 +00:00
static boolean hasPermissions(Context context, String[] permissions) {
for (String permission : permissions)
if (!hasPermission(context, permission))
return false;
return true;
}
2022-06-10 14:53:14 +00:00
static String[] getDesiredPermissions(Context context) {
List<String> permissions = new ArrayList<>();
permissions.add(Manifest.permission.READ_CONTACTS);
2022-06-11 17:30:05 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
2022-06-10 14:53:14 +00:00
permissions.add(Manifest.permission.POST_NOTIFICATIONS);
return permissions.toArray(new String[0]);
}
2019-12-12 12:34:04 +00:00
static String[] getOAuthPermissions() {
List<String> permissions = new ArrayList<>();
//permissions.add(Manifest.permission.READ_CONTACTS); // profile
2019-12-12 12:34:04 +00:00
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
permissions.add(Manifest.permission.GET_ACCOUNTS);
return permissions.toArray(new String[0]);
}
2022-06-15 13:36:29 +00:00
private static boolean hasCustomTabs(Context context, Uri uri, String pkg) {
2019-05-12 17:14:34 +00:00
PackageManager pm = context.getPackageManager();
Intent view = new Intent(Intent.ACTION_VIEW, uri);
2022-07-03 10:15:46 +00:00
int flags = (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ? 0 : PackageManager.MATCH_ALL);
List<ResolveInfo> ris = pm.queryIntentActivities(view, flags); // action whitelisted
2020-06-13 14:32:18 +00:00
for (ResolveInfo info : ris) {
2019-05-12 17:14:34 +00:00
Intent intent = new Intent();
intent.setAction(ACTION_CUSTOM_TABS_CONNECTION);
intent.setPackage(info.activityInfo.packageName);
2022-06-15 13:36:29 +00:00
if (pkg != null && !pkg.equals(info.activityInfo.packageName))
continue;
2019-05-12 17:14:34 +00:00
if (pm.resolveService(intent, 0) != null)
return true;
}
return false;
}
static boolean hasWebView(Context context) {
2022-02-14 09:38:07 +00:00
if (hasWebView == null)
hasWebView = _hasWebView(context);
return hasWebView;
}
private static boolean _hasWebView(Context context) {
2020-07-10 07:12:24 +00:00
try {
PackageManager pm = context.getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
2022-06-10 07:57:27 +00:00
WebView view = new WebView(context);
view.setOverScrollMode(View.OVER_SCROLL_NEVER);
2019-05-12 17:14:34 +00:00
return true;
2020-07-10 07:12:24 +00:00
} else
2019-05-12 17:14:34 +00:00
return false;
2020-07-10 07:12:24 +00:00
} catch (Throwable ex) {
/*
Caused by: java.lang.RuntimeException: Package manager has died
at android.app.ApplicationPackageManager.hasSystemFeature(ApplicationPackageManager.java:414)
at eu.faircode.email.Helper.hasWebView(SourceFile:375)
at eu.faircode.email.ApplicationEx.onCreate(SourceFile:110)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1014)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4751)
2022-06-09 10:30:37 +00:00
Chromium WebView package does not exist
android.webkit.WebViewFactory$MissingWebViewPackageException: Failed to load WebView provider: No WebView installed
at android.webkit.WebViewFactory.getWebViewContextAndSetProvider(WebViewFactory.java:428)
at android.webkit.WebViewFactory.getProviderClass(WebViewFactory.java:493)
at android.webkit.WebViewFactory.getProvider(WebViewFactory.java:348)
at android.webkit.WebView.getFactory(WebView.java:2594)
at android.webkit.WebView.ensureProviderCreated(WebView.java:2588)
at android.webkit.WebView.setOverScrollMode(WebView.java:2656)
at android.view.View.<init>(View.java:5325)
at android.view.View.<init>(View.java:5466)
at android.view.ViewGroup.<init>(ViewGroup.java:702)
at android.widget.AbsoluteLayout.<init>(AbsoluteLayout.java:56)
at android.webkit.WebView.<init>(WebView.java:421)
at android.webkit.WebView.<init>(WebView.java:363)
at android.webkit.WebView.<init>(WebView.java:345)
at android.webkit.WebView.<init>(WebView.java:332)
at android.webkit.WebView.<init>(WebView.java:322)
at eu.faircode.email.WebViewEx.<init>(SourceFile:1)
2020-07-10 07:12:24 +00:00
*/
2019-05-12 17:14:34 +00:00
return false;
2020-07-10 07:12:24 +00:00
}
2019-05-12 17:14:34 +00:00
}
static boolean canPrint(Context context) {
2021-05-02 07:25:07 +00:00
try {
PackageManager pm = context.getPackageManager();
return pm.hasSystemFeature(PackageManager.FEATURE_PRINTING);
} catch (Throwable ex) {
Log.e(ex);
return false;
}
2019-05-12 17:14:34 +00:00
}
2019-09-26 10:11:46 +00:00
static Boolean isIgnoringOptimizations(Context context) {
2022-03-20 08:47:12 +00:00
if (isArc())
return true;
2021-04-27 08:00:44 +00:00
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
return null;
2022-04-13 20:27:33 +00:00
PowerManager pm = Helper.getSystemService(context, PowerManager.class);
2021-04-27 08:00:44 +00:00
if (pm == null)
return null;
return pm.isIgnoringBatteryOptimizations(BuildConfig.APPLICATION_ID);
2019-09-26 10:11:46 +00:00
}
2020-11-04 14:15:08 +00:00
static Integer getBatteryLevel(Context context) {
try {
2022-04-13 20:27:33 +00:00
BatteryManager bm = Helper.getSystemService(context, BatteryManager.class);
2020-11-04 19:46:20 +00:00
if (bm == null)
return null;
2020-11-04 14:15:08 +00:00
return bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
} catch (Throwable ex) {
Log.e(ex);
return null;
}
}
2020-10-31 09:27:42 +00:00
static boolean isCharging(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
return false;
try {
2022-04-13 20:27:33 +00:00
BatteryManager bm = Helper.getSystemService(context, BatteryManager.class);
2020-11-04 19:46:20 +00:00
if (bm == null)
return false;
2020-10-31 09:27:42 +00:00
return bm.isCharging();
} catch (Throwable ex) {
Log.e(ex);
return false;
}
}
2019-09-26 10:11:46 +00:00
static boolean isPlayStoreInstall() {
return BuildConfig.PLAY_STORE_RELEASE;
}
2021-06-28 14:39:55 +00:00
static boolean isAmazonInstall() {
return BuildConfig.AMAZON_RELEASE;
}
2021-05-02 07:48:08 +00:00
static boolean hasPlayStore(Context context) {
if (hasPlayStore == null)
try {
PackageManager pm = context.getPackageManager();
pm.getPackageInfo("com.android.vending", 0);
hasPlayStore = true;
2021-05-02 16:33:48 +00:00
} catch (PackageManager.NameNotFoundException ex) {
Log.i(ex);
hasPlayStore = false;
2021-05-02 07:48:08 +00:00
} catch (Throwable ex) {
2021-05-02 16:33:48 +00:00
Log.e(ex);
2021-05-02 07:48:08 +00:00
hasPlayStore = false;
}
return hasPlayStore;
}
static boolean isSecure(Context context) {
2020-07-19 16:06:57 +00:00
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
ContentResolver resolver = context.getContentResolver();
2021-01-17 03:05:29 +00:00
int enabled = Settings.System.getInt(resolver, Settings.Secure.LOCK_PATTERN_ENABLED, 0);
2020-07-19 16:06:57 +00:00
return (enabled != 0);
} else {
2022-04-13 20:27:33 +00:00
KeyguardManager kgm = Helper.getSystemService(context, KeyguardManager.class);
2020-07-19 16:06:57 +00:00
return (kgm != null && kgm.isDeviceSecure());
}
} catch (Throwable ex) {
Log.e(ex);
return false;
}
}
static String getOpenKeychainPackage(Context context) {
2020-06-19 18:44:19 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
2022-05-14 13:48:14 +00:00
return prefs.getString("openpgp_provider", Helper.PGP_OPENKEYCHAIN_PACKAGE);
}
static boolean isOpenKeychainInstalled(Context context) {
String provider = getOpenKeychainPackage(context);
2020-06-19 18:44:19 +00:00
PackageManager pm = context.getPackageManager();
Intent intent = new Intent(OpenPgpApi.SERVICE_INTENT_2);
intent.setPackage(provider);
List<ResolveInfo> ris = pm.queryIntentServices(intent, 0);
2020-09-07 13:58:16 +00:00
return (ris != null && ris.size() > 0);
2020-06-19 18:44:19 +00:00
}
2021-11-14 10:14:25 +00:00
static boolean isInstalled(Context context, String pkg) {
try {
PackageManager pm = context.getPackageManager();
pm.getPackageInfo(pkg, 0);
return true;
} catch (Throwable ex) {
return false;
}
}
2020-12-11 12:46:14 +00:00
static boolean isComponentEnabled(Context context, Class<?> clazz) {
PackageManager pm = context.getPackageManager();
int state = pm.getComponentEnabledSetting(new ComponentName(context, clazz));
2021-01-07 07:05:47 +00:00
return (state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
2020-12-11 12:46:14 +00:00
}
2020-09-10 14:03:14 +00:00
static void enableComponent(Context context, Class<?> clazz, boolean whether) {
enableComponent(context, clazz.getName(), whether);
2020-09-10 13:57:33 +00:00
}
2020-09-10 14:03:14 +00:00
static void enableComponent(Context context, String name, boolean whether) {
2020-09-10 13:57:33 +00:00
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(
new ComponentName(context, name),
2020-09-10 14:03:14 +00:00
whether
2021-01-07 07:05:47 +00:00
? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
2020-09-10 13:57:33 +00:00
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
2021-01-17 08:56:37 +00:00
static void setKeyboardIncognitoMode(EditText view, Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
return;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean incognito_keyboard = prefs.getBoolean("incognito_keyboard", false);
if (incognito_keyboard)
try {
view.setImeOptions(view.getImeOptions() | EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING);
} catch (Throwable ex) {
Log.e(ex);
}
}
static boolean isAccessibilityEnabled(Context context) {
try {
2022-04-13 20:27:33 +00:00
AccessibilityManager am = Helper.getSystemService(context, AccessibilityManager.class);
return (am != null && am.isEnabled());
} catch (Throwable ex) {
Log.e(ex);
return false;
}
}
2021-08-18 18:43:25 +00:00
static String getStandbyBucketName(int bucket) {
switch (bucket) {
2022-02-01 07:28:03 +00:00
case 5:
return "exempted";
2021-08-18 18:43:25 +00:00
case UsageStatsManager.STANDBY_BUCKET_ACTIVE:
return "active";
case UsageStatsManager.STANDBY_BUCKET_WORKING_SET:
return "workingset";
case UsageStatsManager.STANDBY_BUCKET_FREQUENT:
return "frequent";
case UsageStatsManager.STANDBY_BUCKET_RARE:
return "rare";
case UsageStatsManager.STANDBY_BUCKET_RESTRICTED:
return "restricted";
default:
return Integer.toString(bucket);
}
}
2022-06-19 06:24:13 +00:00
static String getEventType(int type) {
switch (type) {
case UsageEvents.Event.ACTIVITY_PAUSED:
return "Activity/paused";
case UsageEvents.Event.ACTIVITY_RESUMED:
return "Activity/resumed";
case UsageEvents.Event.ACTIVITY_STOPPED:
return "Activity/stopped";
case UsageEvents.Event.CONFIGURATION_CHANGE:
return "Configuration/change";
case UsageEvents.Event.DEVICE_SHUTDOWN:
return "Device/shutdown";
case UsageEvents.Event.DEVICE_STARTUP:
return "Device/startup";
case UsageEvents.Event.FOREGROUND_SERVICE_START:
return "Foreground/start";
case UsageEvents.Event.FOREGROUND_SERVICE_STOP:
return "Foreground/stop";
case UsageEvents.Event.KEYGUARD_HIDDEN:
return "Keyguard/hidden";
case UsageEvents.Event.KEYGUARD_SHOWN:
return "Keyguard/shown";
case UsageEvents.Event.SCREEN_INTERACTIVE:
return "Screen/interactive";
case UsageEvents.Event.SCREEN_NON_INTERACTIVE:
return "Screen/non-interactive";
case UsageEvents.Event.SHORTCUT_INVOCATION:
return "Shortcut/invocation";
case UsageEvents.Event.STANDBY_BUCKET_CHANGED:
return "Bucket/changed";
case UsageEvents.Event.USER_INTERACTION:
return "User/interaction";
default:
return Integer.toString(type);
}
}
static String getExitReason(int reason) {
switch (reason) {
case ApplicationExitInfo.REASON_UNKNOWN:
return "Unknown";
case ApplicationExitInfo.REASON_EXIT_SELF:
return "ExitSelf";
case ApplicationExitInfo.REASON_SIGNALED:
return "Signaled";
case ApplicationExitInfo.REASON_LOW_MEMORY:
return "LowMemory";
case ApplicationExitInfo.REASON_CRASH:
return "Crash";
case ApplicationExitInfo.REASON_CRASH_NATIVE:
return "CrashNative";
case ApplicationExitInfo.REASON_ANR:
return "ANR";
case ApplicationExitInfo.REASON_INITIALIZATION_FAILURE:
return "InitializationFailure";
case ApplicationExitInfo.REASON_PERMISSION_CHANGE:
return "PermissionChange";
case ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE:
return "ExcessiveResourceUsage";
case ApplicationExitInfo.REASON_USER_REQUESTED:
return "UserRequested";
case ApplicationExitInfo.REASON_USER_STOPPED:
return "UserStopped";
case ApplicationExitInfo.REASON_DEPENDENCY_DIED:
return "DependencyDied";
case ApplicationExitInfo.REASON_OTHER:
return "Other";
default:
return Integer.toString(reason);
}
}
2022-04-13 20:27:33 +00:00
static <T extends Object> T getSystemService(Context context, Class<T> type) {
return ContextCompat.getSystemService(context.getApplicationContext(), type);
}
2019-05-12 17:14:34 +00:00
// View
2021-12-30 14:33:09 +00:00
static int getActionBarHeight(Context context) {
int actionBarHeight;
TypedValue tv = new TypedValue();
if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
return TypedValue.complexToDimensionPixelSize(tv.data, dm);
2021-12-30 14:49:39 +00:00
} else
return Helper.dp2pixels(context, 56);
}
static int getBottomNavigationHeight(Context context) {
int resid = context.getResources().getIdentifier("design_bottom_navigation_height", "dimen", context.getPackageName());
if (resid <= 0)
2021-12-30 14:33:09 +00:00
return Helper.dp2pixels(context, 56);
2021-12-30 14:49:39 +00:00
else
return context.getResources().getDimensionPixelSize(resid);
2021-12-30 14:33:09 +00:00
}
2021-12-31 14:56:30 +00:00
static ObjectAnimator getFabAnimator(View fab, LifecycleOwner owner) {
2022-04-13 08:39:05 +00:00
ObjectAnimator.AnimatorUpdateListener listener = new ObjectAnimator.AnimatorUpdateListener() {
2021-12-31 14:56:30 +00:00
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if (!owner.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED))
return;
2021-12-31 19:41:44 +00:00
fab.setScaleX((float) animation.getAnimatedValue());
fab.setScaleY((float) animation.getAnimatedValue());
2021-12-31 14:56:30 +00:00
}
2022-04-13 08:39:05 +00:00
};
ObjectAnimator animator = ObjectAnimator.ofFloat(fab, "alpha", 0.9f, 1.0f);
animator.setDuration(750L);
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.setRepeatMode(ValueAnimator.REVERSE);
animator.addUpdateListener(listener);
owner.getLifecycle().addObserver(new LifecycleObserver() {
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroyed() {
try {
animator.removeUpdateListener(listener);
owner.getLifecycle().removeObserver(this);
} catch (Throwable ex) {
Log.e(ex);
}
}
2021-12-31 14:56:30 +00:00
});
2022-04-13 08:39:05 +00:00
2021-12-31 14:56:30 +00:00
return animator;
}
2019-05-12 17:14:34 +00:00
static Intent getChooser(Context context, Intent intent) {
2020-06-14 16:34:13 +00:00
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
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));
} else
2019-05-12 17:14:34 +00:00
return intent;
}
2020-01-08 08:06:30 +00:00
static void share(Context context, File file, String type, String name) {
2022-02-12 18:29:55 +00:00
// https://developer.android.com/reference/androidx/core/content/FileProvider
Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, file);
share(context, uri, type, name);
}
static void share(Context context, Uri uri, String type, String name) {
2020-10-29 07:32:23 +00:00
try {
2022-02-12 18:29:55 +00:00
_share(context, uri, type, name);
2020-10-29 07:32:23 +00:00
} catch (Throwable ex) {
// java.lang.IllegalArgumentException: Failed to resolve canonical path for ...
Log.e(ex);
}
}
2022-02-12 18:29:55 +00:00
private static void _share(Context context, Uri uri, String type, String name) {
2021-06-28 06:15:01 +00:00
Log.i("uri=" + uri + " type=" + type);
2020-01-08 08:06:30 +00:00
// Build intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndTypeAndNormalize(uri, type);
2021-03-06 18:42:23 +00:00
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
2020-01-08 08:06:30 +00:00
if (!TextUtils.isEmpty(name))
intent.putExtra(Intent.EXTRA_TITLE, Helper.sanitizeFilename(name));
Log.i("Intent=" + intent + " type=" + type);
2020-06-14 16:34:13 +00:00
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
// Get targets
2020-08-30 12:55:26 +00:00
List<ResolveInfo> ris = null;
try {
PackageManager pm = context.getPackageManager();
2022-07-03 10:15:46 +00:00
int flags = (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ? 0 : PackageManager.MATCH_ALL);
ris = pm.queryIntentActivities(intent, flags);
2020-08-30 12:55:26 +00:00
for (ResolveInfo ri : ris) {
Log.i("Target=" + ri);
context.grantUriPermission(ri.activityInfo.packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
} catch (Throwable ex) {
Log.e(ex);
/*
java.lang.RuntimeException: Package manager has died
at android.app.ApplicationPackageManager.queryIntentActivitiesAsUser(ApplicationPackageManager.java:571)
at android.app.ApplicationPackageManager.queryIntentActivities(ApplicationPackageManager.java:557)
at eu.faircode.email.Helper.share(SourceFile:489)
*/
2020-06-14 16:34:13 +00:00
}
2020-01-08 08:06:30 +00:00
2020-06-14 16:34:13 +00:00
// Check if viewer available
2021-01-30 10:13:29 +00:00
if (ris == null || ris.size() == 0)
2020-10-18 07:33:25 +00:00
if (isTnef(type, null))
2020-06-14 16:34:13 +00:00
viewFAQ(context, 155);
2021-01-30 10:13:29 +00:00
else
2022-01-16 07:43:56 +00:00
reportNoViewer(context, intent, null);
2021-01-30 10:13:29 +00:00
else
2020-06-14 16:34:13 +00:00
context.startActivity(intent);
2020-10-17 09:44:47 +00:00
} else
context.startActivity(intent);
2020-01-08 08:06:30 +00:00
}
2020-10-18 07:33:25 +00:00
static boolean isTnef(String type, String name) {
2020-10-04 10:17:37 +00:00
// https://en.wikipedia.org/wiki/Transport_Neutral_Encapsulation_Format
2020-10-18 07:33:25 +00:00
if ("application/ms-tnef".equals(type) ||
"application/vnd.ms-tnef".equals(type))
return true;
if ("application/octet-stream".equals(type) &&
2021-09-13 19:15:14 +00:00
"winmail.dat".equalsIgnoreCase(name))
2020-10-18 07:33:25 +00:00
return true;
return false;
2020-10-04 10:17:37 +00:00
}
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
2020-06-14 16:34:13 +00:00
try {
context.startActivity(intent);
2022-01-16 07:43:56 +00:00
} catch (Throwable ex) {
reportNoViewer(context, intent, ex);
2020-06-14 16:34:13 +00:00
}
}
2019-07-01 18:34:02 +00:00
static void view(Context context, Uri uri, boolean browse) {
2021-09-07 08:10:02 +00:00
view(context, uri, null, browse, false);
2020-06-18 11:53:32 +00:00
}
static void view(Context context, Uri uri, boolean browse, boolean task) {
2021-09-07 08:10:02 +00:00
view(context, uri, null, browse, task);
}
static void view(Context context, Uri uri, String mimeType, boolean browse, boolean task) {
2020-10-30 10:59:28 +00:00
if (context == null) {
Log.e(new Throwable("view"));
return;
}
2022-06-15 13:36:29 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String open_with_pkg = prefs.getString("open_with_pkg", null);
2022-06-17 13:54:50 +00:00
boolean open_with_tabs = prefs.getBoolean("open_with_tabs", true);
2022-06-15 13:36:29 +00:00
2022-07-03 10:15:46 +00:00
Log.i("View=" + uri +
" browse=" + browse +
" task=" + task +
" pkg=" + open_with_pkg + ":" + open_with_tabs +
" isHyperLink=" + UriHelper.isHyperLink(uri) +
" isInstalled=" + isInstalled(context, open_with_pkg) +
" hasCustomTabs=" + hasCustomTabs(context, uri, open_with_pkg));
2022-06-17 13:54:50 +00:00
if (!UriHelper.isHyperLink(uri)) {
open_with_pkg = null;
open_with_tabs = false;
}
2022-06-15 13:36:29 +00:00
2022-07-14 06:23:17 +00:00
if (!"chooser".equals(open_with_pkg)) {
if (open_with_pkg != null && !isInstalled(context, open_with_pkg)) {
open_with_pkg = null;
open_with_tabs = false;
}
if (open_with_tabs && !hasCustomTabs(context, uri, open_with_pkg))
open_with_tabs = false;
2022-06-17 13:54:50 +00:00
}
2018-12-23 13:34:42 +00:00
2022-07-14 06:23:17 +00:00
Intent view = new Intent(Intent.ACTION_VIEW);
if (mimeType == null)
view.setData(uri);
else
view.setDataAndType(uri, mimeType);
if (task)
view.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2022-06-17 13:54:50 +00:00
2022-06-29 14:51:29 +00:00
if ("chooser".equals(open_with_pkg)) {
try {
2022-07-14 06:23:17 +00:00
if (open_with_tabs) {
EntityLog.log(context, "Launching direct uri=" + uri +
" intent=" + view +
" extras=" + TextUtils.join(", ", Log.getExtras(view.getExtras())));
context.startActivity(view);
} else {
EntityLog.log(context, "Launching chooser uri=" + uri +
" intent=" + view +
" extras=" + TextUtils.join(", ", Log.getExtras(view.getExtras())));
Intent chooser = Intent.createChooser(view, context.getString(R.string.title_select_app));
context.startActivity(chooser);
}
2022-06-29 14:51:29 +00:00
} catch (ActivityNotFoundException ex) {
Log.w(ex);
reportNoViewer(context, uri, ex);
}
} else if (browse || !open_with_tabs) {
2020-04-23 06:20:37 +00:00
try {
2022-06-17 13:54:50 +00:00
view.setPackage(open_with_pkg);
2022-07-03 08:23:04 +00:00
EntityLog.log(context, "Launching view uri=" + uri +
" intent=" + view +
" extras=" + TextUtils.join(", ", Log.getExtras(view.getExtras())));
2020-07-21 20:40:37 +00:00
context.startActivity(view);
2020-04-23 06:20:37 +00:00
} catch (Throwable ex) {
2022-01-16 07:43:56 +00:00
reportNoViewer(context, uri, ex);
2020-04-23 06:20:37 +00:00
}
2018-12-23 13:34:42 +00:00
} else {
2021-04-05 13:48:30 +00:00
boolean navbar_colorize = prefs.getBoolean("navbar_colorize", false);
int colorPrimary = resolveColor(context, R.attr.colorPrimary);
int colorPrimaryDark = resolveColor(context, R.attr.colorPrimaryDark);
CustomTabColorSchemeParams.Builder schemes = new CustomTabColorSchemeParams.Builder()
.setToolbarColor(colorPrimary)
.setSecondaryToolbarColor(colorPrimaryDark);
if (navbar_colorize)
schemes.setNavigationBarColor(colorPrimaryDark);
2018-12-23 13:34:42 +00:00
// https://developer.chrome.com/multidevice/android/customtabs
2021-04-05 13:48:30 +00:00
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder()
.setDefaultColorSchemeParams(schemes.build())
.setColorScheme(Helper.isDarkTheme(context)
? CustomTabsIntent.COLOR_SCHEME_DARK
: CustomTabsIntent.COLOR_SCHEME_LIGHT)
.setShareState(CustomTabsIntent.SHARE_STATE_ON)
.setUrlBarHidingEnabled(true)
.setStartAnimations(context, R.anim.activity_open_enter, R.anim.activity_open_exit)
.setExitAnimations(context, R.anim.activity_close_enter, R.anim.activity_close_exit);
2018-12-23 13:34:42 +00:00
2022-06-12 08:09:37 +00:00
Locale locale = Locale.getDefault();
Locale slocale = Resources.getSystem().getConfiguration().locale;
List<String> languages = new ArrayList<>();
languages.add(locale.toLanguageTag() + ";q=1.0");
if (!TextUtils.isEmpty(locale.getLanguage()))
languages.add(locale.getLanguage() + ";q=0.9");
if (!slocale.equals(locale)) {
languages.add(slocale.toLanguageTag() + ";q=0.8");
if (!TextUtils.isEmpty(slocale.getLanguage()))
languages.add(slocale.getLanguage() + ";q=0.7");
}
languages.add("*;q=0.5");
Bundle headers = new Bundle();
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language
headers.putString("Accept-Language", TextUtils.join(", ", languages));
2018-12-23 13:34:42 +00:00
CustomTabsIntent customTabsIntent = builder.build();
2022-06-12 08:09:37 +00:00
customTabsIntent.intent.putExtra(Browser.EXTRA_HEADERS, headers);
2022-06-17 13:54:50 +00:00
customTabsIntent.intent.setPackage(open_with_pkg);
2022-06-15 13:36:29 +00:00
2018-12-23 13:34:42 +00:00
try {
2022-07-03 08:23:04 +00:00
EntityLog.log(context, "Launching tab uri=" + uri +
" intent=" + customTabsIntent.intent +
" extras=" + TextUtils.join(", ", Log.getExtras(customTabsIntent.intent.getExtras())));
2018-12-23 13:34:42 +00:00
customTabsIntent.launchUrl(context, uri);
} catch (Throwable ex) {
2022-01-16 07:43:56 +00:00
reportNoViewer(context, uri, ex);
2018-12-23 13:34:42 +00:00
}
}
}
2022-06-03 08:47:12 +00:00
static boolean customTabsWarmup(Context context) {
2022-04-24 18:07:56 +00:00
if (context == null)
2022-06-03 08:47:12 +00:00
return false;
2022-04-24 18:07:56 +00:00
2020-02-26 10:19:19 +00:00
try {
2022-06-03 08:47:12 +00:00
return CustomTabsClient.connectAndInitialize(context, PACKAGE_CHROME);
2020-02-26 10:19:19 +00:00
} catch (Throwable ex) {
Log.w(ex);
2022-06-03 08:47:12 +00:00
return false;
2020-02-26 10:19:19 +00:00
}
}
2021-05-05 05:44:19 +00:00
static String getFAQLocale() {
switch (Locale.getDefault().getLanguage()) {
case "de":
return "de-rDE";
case "fr":
return "fr-rFR";
2021-05-08 07:30:19 +00:00
case "it":
return "it-rIT";
case "ro":
return "ro-rRO";
2021-05-05 05:44:19 +00:00
default:
return null;
}
}
2019-08-15 05:58:20 +00:00
static void viewFAQ(Context context, int question) {
2021-09-30 20:24:50 +00:00
viewFAQ(context, question, true /* Google translate */);
2021-05-17 20:12:22 +00:00
}
static void viewFAQ(Context context, int question, boolean english) {
2021-05-03 07:16:38 +00:00
// Redirection is done to prevent text editors from opening the link
// https://email.faircode.eu/faq -> https://github.com/M66B/FairEmail/blob/master/FAQ.md
// https://email.faircode.eu/docs -> https://github.com/M66B/FairEmail/tree/master/docs
// https://github.com/M66B/FairEmail/blob/master/FAQ.md#user-content-faq1
// https://github.com/M66B/FairEmail/blob/master/docs/FAQ-de-rDE.md#user-content-faq1
String base;
2021-05-17 20:12:22 +00:00
String locale = (english ? null : getFAQLocale());
2021-05-05 05:44:19 +00:00
if (locale == null)
base = "https://email.faircode.eu/faq";
else
base = "https://email.faircode.eu/docs/FAQ-" + locale + ".md";
2019-08-15 05:58:20 +00:00
if (question == 0)
2021-09-07 08:10:02 +00:00
view(context, Uri.parse(base + "#top"), "text/html", false, false);
2019-08-15 05:58:20 +00:00
else
2021-09-07 08:10:02 +00:00
view(context, Uri.parse(base + "#user-content-faq" + question), "text/html", false, false);
2019-01-14 10:29:47 +00:00
}
2021-07-22 14:06:53 +00:00
static Uri getPrivacyUri(Context context) {
// https://translate.google.com/translate?sl=auto&tl=<language>&u=<url>
return Uri.parse(PRIVACY_URI)
.buildUpon()
.appendQueryParameter("language", Locale.getDefault().getLanguage())
.appendQueryParameter("tag", Locale.getDefault().toLanguageTag())
.build();
}
2022-05-15 08:19:48 +00:00
static Uri getSupportUri(Context context, String reference) {
2021-08-23 13:20:07 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String language = prefs.getString("language", null);
Locale slocale = Resources.getSystem().getConfiguration().locale;
2021-04-06 06:59:35 +00:00
return Uri.parse(SUPPORT_URI)
.buildUpon()
2021-08-23 13:20:07 +00:00
.appendQueryParameter("product", "fairemailsupport")
2021-09-28 20:16:03 +00:00
.appendQueryParameter("version", BuildConfig.VERSION_NAME + BuildConfig.REVISION)
2021-08-23 13:20:07 +00:00
.appendQueryParameter("locale", slocale.toString())
.appendQueryParameter("language", language == null ? "" : language)
2021-04-06 06:59:35 +00:00
.appendQueryParameter("installed", Helper.hasValidFingerprint(context) ? "" : "Other")
2022-05-15 08:19:48 +00:00
.appendQueryParameter("reference", reference)
2021-04-06 06:59:35 +00:00
.build();
}
2022-05-15 08:19:48 +00:00
static Intent getIntentIssue(Context context, String reference) {
if (ActivityBilling.isPro(context)) {
2021-09-28 20:16:03 +00:00
String version = BuildConfig.VERSION_NAME + BuildConfig.REVISION + "/" +
2019-06-08 19:50:17 +00:00
(Helper.hasValidFingerprint(context) ? "1" : "3") +
2019-07-22 15:19:18 +00:00
(BuildConfig.PLAY_STORE_RELEASE ? "p" : "") +
(BuildConfig.DEBUG ? "d" : "") +
2019-08-13 08:27:17 +00:00
(ActivityBilling.isPro(context) ? "+" : "");
2019-06-08 19:50:17 +00:00
Intent intent = new Intent(Intent.ACTION_SEND);
2021-03-25 07:03:25 +00:00
//intent.setPackage(BuildConfig.APPLICATION_ID);
2019-06-08 19:50:17 +00:00
intent.setType("text/plain");
2019-06-08 19:50:17 +00:00
try {
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{Log.myAddress().getAddress()});
} catch (UnsupportedEncodingException ex) {
Log.w(ex);
}
2019-06-08 19:50:17 +00:00
intent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.title_issue_subject, version));
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String language = prefs.getString("language", null);
2021-10-02 14:35:10 +00:00
boolean reporting = prefs.getBoolean("crash_reports", false);
String uuid = prefs.getString("uuid", null);
Locale slocale = Resources.getSystem().getConfiguration().locale;
String html = "<br><br>";
html += "<p style=\"font-size:small;\">";
2021-10-02 18:36:36 +00:00
html += "Android: " + Build.VERSION.RELEASE + " (SDK " + Build.VERSION.SDK_INT + ")<br>";
2022-01-17 18:54:38 +00:00
html += "Device: " + Build.MANUFACTURER + " " + Build.MODEL + " " + Build.DEVICE + "<br>";
html += "Locale: " + Html.escapeHtml(slocale.toString()) + "<br>";
if (language != null)
html += "Language: " + Html.escapeHtml(language) + "<br>";
if ((reporting || BuildConfig.TEST_RELEASE) && uuid != null)
html += "UUID: " + Html.escapeHtml(uuid) + "<br>";
html += "</p>";
intent.putExtra(Intent.EXTRA_TEXT, HtmlHelper.getText(context, html));
intent.putExtra(Intent.EXTRA_HTML_TEXT, html);
2019-06-08 19:50:17 +00:00
return intent;
2021-02-12 14:58:59 +00:00
} else {
if (Helper.hasValidFingerprint(context))
2022-05-15 08:19:48 +00:00
return new Intent(Intent.ACTION_VIEW, getSupportUri(context, reference));
2021-02-12 14:58:59 +00:00
else
return new Intent(Intent.ACTION_VIEW, Uri.parse(XDA_URI));
}
2019-12-26 17:57:15 +00:00
}
static Intent getIntentRate(Context context) {
2020-06-14 16:34:13 +00:00
return new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + BuildConfig.APPLICATION_ID));
}
2020-03-26 07:40:26 +00:00
static long getInstallTime(Context context) {
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(BuildConfig.APPLICATION_ID, 0);
if (pi != null)
return pi.firstInstallTime;
} catch (Throwable ex) {
Log.e(ex);
}
return 0;
}
2022-06-10 14:53:14 +00:00
static int getTargetSdk(Context context) {
if (targetSdk == null)
try {
PackageManager pm = context.getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(BuildConfig.APPLICATION_ID, 0);
targetSdk = ai.targetSdkVersion;
} catch (Throwable ex) {
Log.e(ex);
targetSdk = Build.VERSION.SDK_INT;
}
return targetSdk;
}
2021-05-28 18:22:01 +00:00
static boolean isSupportedDevice() {
if ("Amazon".equals(Build.BRAND) && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
/*
java.lang.IllegalArgumentException: Comparison method violates its general contract!
java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeHi(TimSort.java:864)
at java.util.TimSort.mergeAt(TimSort.java:481)
at java.util.TimSort.mergeCollapse(TimSort.java:406)
at java.util.TimSort.sort(TimSort.java:210)
at java.util.TimSort.sort(TimSort.java:169)
at java.util.Arrays.sort(Arrays.java:2010)
at java.util.Collections.sort(Collections.java:1883)
at android.view.ViewGroup$ChildListForAccessibility.init(ViewGroup.java:7181)
at android.view.ViewGroup$ChildListForAccessibility.obtain(ViewGroup.java:7138)
at android.view.ViewGroup.dispatchPopulateAccessibilityEventInternal(ViewGroup.java:2734)
at android.view.View.dispatchPopulateAccessibilityEvent(View.java:5617)
at android.view.View.sendAccessibilityEventUncheckedInternal(View.java:5582)
at android.view.View.sendAccessibilityEventUnchecked(View.java:5566)
at android.view.View.sendAccessibilityEventInternal(View.java:5543)
at android.view.View.sendAccessibilityEvent(View.java:5512)
at android.view.View.onFocusChanged(View.java:5449)
at android.view.View.handleFocusGainInternal(View.java:5229)
at android.view.ViewGroup.handleFocusGainInternal(ViewGroup.java:651)
at android.view.View.requestFocusNoSearch(View.java:7950)
at android.view.View.requestFocus(View.java:7929)
at android.view.ViewGroup.requestFocus(ViewGroup.java:2612)
at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2657)
at android.view.ViewGroup.requestFocus(ViewGroup.java:2613)
at android.view.View.requestFocus(View.java:7896)
at android.view.View.requestFocus(View.java:7875)
at androidx.recyclerview.widget.RecyclerView.recoverFocusFromState(SourceFile:3788)
at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep3(SourceFile:4023)
at androidx.recyclerview.widget.RecyclerView.dispatchLayout(SourceFile:3652)
at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(SourceFile:1877)
at androidx.recyclerview.widget.RecyclerView$w.run(SourceFile:5044)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:781)
at android.view.Choreographer.doCallbacks(Choreographer.java:592)
at android.view.Choreographer.doFrame(Choreographer.java:559)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:767)
*/
return false;
}
return true;
}
static boolean isGoogle() {
return "Google".equalsIgnoreCase(Build.MANUFACTURER);
}
static boolean isSamsung() {
return "Samsung".equalsIgnoreCase(Build.MANUFACTURER);
}
2021-06-16 06:46:40 +00:00
static boolean isOnePlus() {
return "OnePlus".equalsIgnoreCase(Build.MANUFACTURER);
}
static boolean isHuawei() {
return "HUAWEI".equalsIgnoreCase(Build.MANUFACTURER);
}
2021-05-28 18:22:01 +00:00
static boolean isXiaomi() {
return "Xiaomi".equalsIgnoreCase(Build.MANUFACTURER);
}
2022-07-03 15:49:24 +00:00
static boolean isRedmiNote() {
// Manufacturer: Xiaomi
// Model: Redmi Note 8 Pro
// Model: Redmi Note 10S
return isXiaomi() &&
!TextUtils.isEmpty(Build.MODEL) &&
Build.MODEL.toLowerCase(Locale.ROOT).contains("redmi") &&
Build.MODEL.toLowerCase(Locale.ROOT).contains("note");
}
2021-06-16 06:46:40 +00:00
static boolean isMeizu() {
return "Meizu".equalsIgnoreCase(Build.MANUFACTURER);
}
static boolean isAsus() {
return "asus".equalsIgnoreCase(Build.MANUFACTURER);
}
static boolean isWiko() {
return "WIKO".equalsIgnoreCase(Build.MANUFACTURER);
}
static boolean isLenovo() {
return "LENOVO".equalsIgnoreCase(Build.MANUFACTURER);
}
static boolean isOppo() {
return "OPPO".equalsIgnoreCase(Build.MANUFACTURER);
}
static boolean isRealme() {
return "realme".equalsIgnoreCase(Build.MANUFACTURER);
}
static boolean isBlackview() {
return "Blackview".equalsIgnoreCase(Build.MANUFACTURER);
}
2021-09-12 16:15:00 +00:00
static boolean isSony() {
return "sony".equalsIgnoreCase(Build.MANUFACTURER);
}
static boolean isSurfaceDuo() {
return ("Microsoft".equalsIgnoreCase(Build.MANUFACTURER) && "Surface Duo".equals(Build.MODEL));
}
static boolean isArc() {
// https://github.com/google/talkback/blob/master/utils/src/main/java/com/google/android/accessibility/utils/FeatureSupport.java
return (Build.DEVICE != null) && Build.DEVICE.matches(".+_cheets|cheets_.+");
}
2021-09-12 16:15:00 +00:00
static boolean isStaminaEnabled(Context context) {
// https://dontkillmyapp.com/sony
if (!isSony())
return false;
try {
ContentResolver resolver = context.getContentResolver();
return (Settings.Secure.getInt(resolver, "somc.stamina_mode", 0) > 0);
} catch (Throwable ex) {
Log.e(ex);
return false;
}
}
2021-06-16 06:46:40 +00:00
static boolean isKilling() {
// https://dontkillmyapp.com/
return (isSamsung() ||
isOnePlus() ||
isHuawei() ||
isXiaomi() ||
isMeizu() ||
isAsus() ||
isWiko() ||
isLenovo() ||
isOppo() ||
// Vivo
isRealme() ||
isBlackview() ||
2022-03-20 08:47:12 +00:00
isSony());
2021-06-16 06:46:40 +00:00
}
2022-03-20 08:47:12 +00:00
static boolean isAndroid12() {
return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S);
2021-06-16 06:46:40 +00:00
}
2021-10-02 05:37:00 +00:00
static String getUiModeType(Context context) {
try {
2022-04-13 20:27:33 +00:00
UiModeManager uimm = Helper.getSystemService(context, UiModeManager.class);
2021-10-02 05:37:00 +00:00
int uiModeType = uimm.getCurrentModeType();
switch (uiModeType) {
case Configuration.UI_MODE_TYPE_UNDEFINED:
return "undefined";
case Configuration.UI_MODE_TYPE_NORMAL:
return "normal";
case Configuration.UI_MODE_TYPE_DESK:
return "desk";
case Configuration.UI_MODE_TYPE_CAR:
return "car";
case Configuration.UI_MODE_TYPE_TELEVISION:
return "television";
case Configuration.UI_MODE_TYPE_APPLIANCE:
return "applicance";
case Configuration.UI_MODE_TYPE_WATCH:
return "watch";
case Configuration.UI_MODE_TYPE_VR_HEADSET:
return "vr headset";
default:
return Integer.toString(uiModeType);
}
} catch (Throwable ex) {
Log.w(ex);
return null;
}
}
2022-01-16 07:43:56 +00:00
static void reportNoViewer(Context context, @NonNull Uri uri, @Nullable Throwable ex) {
reportNoViewer(context, new Intent().setData(uri), ex);
2021-01-30 10:13:29 +00:00
}
2022-01-16 07:43:56 +00:00
static void reportNoViewer(Context context, @NonNull Intent intent, @Nullable Throwable ex) {
if (ex != null) {
if (ex instanceof ActivityNotFoundException && BuildConfig.PLAY_STORE_RELEASE)
Log.w(ex);
else
Log.e(ex);
}
if (Helper.isTnef(intent.getType(), null)) {
Helper.viewFAQ(context, 155);
return;
}
2021-08-25 06:20:18 +00:00
View dview = LayoutInflater.from(context).inflate(R.layout.dialog_no_viewer, null);
TextView tvName = dview.findViewById(R.id.tvName);
TextView tvFullName = dview.findViewById(R.id.tvFullName);
TextView tvType = dview.findViewById(R.id.tvType);
2022-01-16 07:43:56 +00:00
TextView tvException = dview.findViewById(R.id.tvException);
2021-01-30 10:13:29 +00:00
String title = intent.getStringExtra(Intent.EXTRA_TITLE);
2021-08-25 06:20:18 +00:00
Uri data = intent.getData();
2021-01-30 10:13:29 +00:00
String type = intent.getType();
2021-08-25 06:20:18 +00:00
String fullName = (data == null ? intent.toString() : data.toString());
String extension = (data == null ? null : getExtension(data.getLastPathSegment()));
tvName.setText(title == null ? fullName : title);
tvFullName.setText(fullName);
tvFullName.setVisibility(title == null ? View.GONE : View.VISIBLE);
2021-08-25 20:03:10 +00:00
tvType.setText(type);
2021-08-25 06:20:18 +00:00
2022-01-16 07:43:56 +00:00
tvException.setText(ex == null ? null : ex.toString());
tvException.setVisibility(ex == null ? View.GONE : View.VISIBLE);
2021-08-25 06:20:18 +00:00
AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setView(dview)
2022-06-06 12:33:53 +00:00
.setNeutralButton(R.string.menu_faq, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Helper.getSupportUri(context, "Report:viewer");
view(context, uri, true);
}
})
2021-08-25 06:20:18 +00:00
.setNegativeButton(android.R.string.cancel, null);
if (hasPlayStore(context) && !TextUtils.isEmpty(extension)) {
2022-06-06 12:33:53 +00:00
builder.setPositiveButton(R.string.title_no_viewer_search, new DialogInterface.OnClickListener() {
2021-08-25 06:20:18 +00:00
@Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
Uri search = Uri.parse(PLAY_STORE_SEARCH)
.buildUpon()
.appendQueryParameter("q", extension)
.build();
Intent intent = new Intent(Intent.ACTION_VIEW, search);
context.startActivity(intent);
} catch (Throwable ex) {
Log.e(ex);
ToastEx.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
}
}
});
}
2021-01-30 10:13:29 +00:00
2021-08-25 06:20:18 +00:00
builder.show();
2021-01-30 10:13:29 +00:00
}
2021-02-02 16:43:46 +00:00
static void excludeFromRecents(Context context) {
2021-02-02 20:05:17 +00:00
try {
2022-05-24 07:46:47 +00:00
ActivityManager am = Helper.getSystemService(context, ActivityManager.class);
2021-02-02 20:05:17 +00:00
if (am == null)
return;
2021-02-02 16:43:46 +00:00
List<ActivityManager.AppTask> tasks = am.getAppTasks();
2021-02-02 20:05:17 +00:00
if (tasks == null || tasks.size() == 0)
return;
tasks.get(0).setExcludeFromRecents(true);
} catch (Throwable ex) {
Log.e(ex);
2021-02-02 16:43:46 +00:00
}
}
2021-04-04 12:53:25 +00:00
static int getOffset(TextView widget, Spannable buffer, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
return layout.getOffsetForHorizontal(line, x);
}
2021-12-26 19:39:58 +00:00
static String getRequestKey(Fragment fragment) {
String who;
try {
Class<?> cls = fragment.getClass();
while (!cls.isAssignableFrom(Fragment.class))
cls = cls.getSuperclass();
Field f = cls.getDeclaredField("mWho");
f.setAccessible(true);
who = (String) f.get(fragment);
} catch (Throwable ex) {
Log.w(ex);
String we = fragment.toString();
int pa = we.indexOf('(');
int sp = we.indexOf(' ', pa);
who = we.substring(pa + 1, sp);
}
return fragment.getClass().getName() + ":result:" + who;
}
2022-04-15 19:29:00 +00:00
static void clearViews(Object instance) {
try {
2022-04-18 07:54:52 +00:00
String cname = instance.getClass().getSimpleName();
2022-04-15 19:29:00 +00:00
for (Field field : instance.getClass().getDeclaredFields()) {
2022-04-18 07:54:52 +00:00
String fname = cname + ":" + field.getName();
2022-04-17 10:14:39 +00:00
Class<?> ftype = field.getType();
Class<?> type = (ftype.isArray() ? ftype.getComponentType() : ftype);
2022-04-18 07:54:52 +00:00
if (type == null) {
Log.e(fname + "=null");
continue;
}
2022-04-15 19:29:00 +00:00
if (View.class.isAssignableFrom(type) ||
Animator.class.isAssignableFrom(type) ||
Snackbar.class.isAssignableFrom(type) ||
SelectionTracker.class.isAssignableFrom(type) ||
SelectionTracker.SelectionPredicate.class.isAssignableFrom(type) ||
2022-04-17 10:14:39 +00:00
PagerAdapter.class.isAssignableFrom(type) ||
2022-05-24 07:46:57 +00:00
RecyclerView.Adapter.class.isAssignableFrom(type) ||
TwoStateOwner.class.isAssignableFrom(type))
2022-04-18 07:54:52 +00:00
try {
Log.i("Clearing " + fname);
field.setAccessible(true);
if (!ftype.isArray()) {
if (Animator.class.isAssignableFrom(type)) {
Animator animator = (Animator) field.get(instance);
if (animator != null) {
if (animator.isStarted())
animator.cancel();
animator.setTarget(null);
}
2022-04-18 07:49:13 +00:00
}
2022-04-17 10:14:39 +00:00
2022-04-18 07:54:52 +00:00
if (Snackbar.class.isAssignableFrom(type)) {
Snackbar snackbar = (Snackbar) field.get(instance);
if (snackbar != null)
snackbar.setAction(null, null);
}
2022-04-17 10:14:39 +00:00
}
2022-04-15 19:29:00 +00:00
2022-04-18 07:54:52 +00:00
field.set(instance, null);
} catch (Throwable ex) {
Log.e(new Throwable(fname, ex));
}
2022-04-15 19:29:00 +00:00
}
} catch (Throwable ex) {
2022-04-18 07:54:52 +00:00
Log.e(ex);
2022-04-15 19:29:00 +00:00
}
}
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);
}
static int pixels2dp(Context context, float pixels) {
float scale = context.getResources().getDisplayMetrics().density;
return Math.round(pixels / 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) {
2021-07-05 04:53:21 +00:00
return resolveColor(context, attr, 0xFF0000);
}
static int resolveColor(Context context, int attr, int def) {
2018-08-06 15:07:46 +00:00
int[] attrs = new int[]{attr};
TypedArray a = context.getTheme().obtainStyledAttributes(attrs);
2021-07-05 04:53:21 +00:00
int color = a.getColor(0, def);
2018-08-06 15:07:46 +00:00
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);
2020-11-23 14:23:39 +00:00
if ("ignore".equals(child.getTag()))
continue;
if (child instanceof Spinner ||
child instanceof EditText ||
child instanceof CheckBox ||
child instanceof ImageView /* =ImageButton */ ||
2019-09-19 13:29:00 +00:00
child instanceof RadioButton ||
2022-02-27 16:13:07 +00:00
(child instanceof Button && "disable".equals(child.getTag()))) {
if (child instanceof ImageView && ((ImageView) child).getImageTintList() != null)
child.setAlpha(enabled ? 1.0f : LOW_LIGHT);
child.setEnabled(enabled);
2022-02-27 16:13:07 +00:00
} else if (child instanceof BottomNavigationView) {
2018-08-13 13:53:46 +00:00
Menu menu = ((BottomNavigationView) child).getMenu();
menu.setGroupEnabled(0, enabled);
2019-12-02 06:37:09 +00:00
} else if (child instanceof RecyclerView)
; // do nothing
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, 1, 0, 0);
2019-05-16 06:13:18 +00:00
ViewGroup.LayoutParams lparam = view.getLayoutParams();
lparam.width = 0;
2020-10-08 12:14:19 +00:00
lparam.height = 1;
2019-05-16 06:13:18 +00:00
if (lparam instanceof ConstraintLayout.LayoutParams)
((ConstraintLayout.LayoutParams) lparam).setMargins(0, 0, 0, 0);
view.setLayoutParams(lparam);
}
2022-01-22 20:14:01 +00:00
static void setSnackbarLines(Snackbar snackbar, int lines) {
View sv = snackbar.getView();
if (sv == null)
return;
TextView tv = sv.findViewById(com.google.android.material.R.id.snackbar_text);
if (tv == null)
return;
tv.setMaxLines(lines);
}
2021-02-28 08:32:21 +00:00
static boolean isNight(Context context) {
// https://developer.android.com/guide/topics/ui/look-and-feel/darktheme#configuration_changes
int uiMode = context.getResources().getConfiguration().uiMode;
2021-06-05 06:47:26 +00:00
Log.i("UI mode=0x" + Integer.toHexString(uiMode));
2021-07-12 22:34:10 +00:00
return ((uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES);
2021-02-28 08:32:21 +00:00
}
2019-05-13 12:29:52 +00:00
static boolean isDarkTheme(Context context) {
2022-06-10 11:11:19 +00:00
// R.attr.isLightTheme
2019-05-13 12:29:52 +00:00
TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(R.attr.themeName, tv, true);
return (tv.string != null && !"light".contentEquals(tv.string));
}
2021-08-23 12:43:38 +00:00
static void showKeyboard(final View view) {
final Context context = view.getContext();
2022-06-12 09:38:16 +00:00
InputMethodManager imm = Helper.getSystemService(context, InputMethodManager.class);
2021-04-27 14:40:27 +00:00
if (imm == null)
return;
2021-10-26 08:05:00 +00:00
view.postDelayed(new Runnable() {
@Override
public void run() {
2022-03-16 18:20:52 +00:00
try {
Log.i("showKeyboard view=" + view);
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
} catch (Throwable ex) {
Log.e(ex);
}
2021-10-26 08:05:00 +00:00
}
}, 250);
2021-04-27 14:40:27 +00:00
}
2021-08-23 12:43:38 +00:00
static void hideKeyboard(final View view) {
final Context context = view.getContext();
2022-06-12 09:38:16 +00:00
InputMethodManager imm = Helper.getSystemService(context, InputMethodManager.class);
2021-08-23 12:43:38 +00:00
if (imm == null)
2021-08-07 18:23:25 +00:00
return;
2021-08-23 12:43:38 +00:00
2022-03-16 18:20:52 +00:00
try {
Log.i("hideKeyboard view=" + view);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
} catch (Throwable ex) {
Log.e(ex);
}
2021-08-07 18:23:25 +00:00
}
2022-06-12 11:19:38 +00:00
static boolean isKeyboardVisible(final View view) {
2022-06-12 15:13:16 +00:00
try {
if (view == null)
return false;
View root = view.getRootView();
if (root == null)
return false;
WindowInsetsCompat insets = ViewCompat.getRootWindowInsets(root);
if (insets == null)
return false;
boolean visible = insets.isVisible(WindowInsetsCompat.Type.ime());
Log.i("isKeyboardVisible=" + visible);
return visible;
} catch (Throwable ex) {
Log.e(ex);
2022-06-12 11:19:38 +00:00
return false;
2022-06-12 15:13:16 +00:00
}
2022-06-12 11:19:38 +00:00
}
2021-12-11 14:45:58 +00:00
static String getViewName(View view) {
StringBuilder sb = new StringBuilder(_getViewName(view));
ViewParent parent = view.getParent();
while (parent != null) {
if (parent instanceof View)
sb.insert(0, '/').insert(0, _getViewName((View) parent));
parent = parent.getParent();
}
return sb.toString();
}
private static String _getViewName(View view) {
if (view == null)
return "<null>";
int id = view.getId();
if (id == View.NO_ID)
return "";
try {
return view.getContext().getResources().getResourceEntryName(id);
} catch (Throwable ex) {
return ex.toString();
}
}
2021-12-11 15:37:56 +00:00
static int getBytesPerPixel(Bitmap.Config config) {
switch (config) {
case ALPHA_8:
return 1;
case RGB_565:
return 2;
case ARGB_4444:
return 4;
case ARGB_8888:
return 8;
case RGBA_F16:
return 8;
case HARDWARE:
return 0;
default:
return 8;
}
}
2019-05-12 17:14:34 +00:00
// Formatting
2019-10-10 13:09:40 +00:00
private static final DecimalFormat df = new DecimalFormat("@@");
2020-07-02 08:19:01 +00:00
static String humanReadableByteCount(long bytes) {
return humanReadableByteCount(bytes, true);
}
2021-09-08 10:34:36 +00:00
static String humanReadableByteCount(long bytes, boolean si) {
2021-08-30 05:24:31 +00:00
int sign = (int) Math.signum(bytes);
bytes = Math.abs(bytes);
int unit = (si ? 1000 : 1024);
if (bytes < unit)
return sign * bytes + " B";
2019-05-12 17:14:34 +00:00
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
2021-08-30 05:24:31 +00:00
return df.format(sign * bytes / Math.pow(unit, exp)) + " " + pre + "B";
2019-05-12 17:14:34 +00:00
}
2019-11-22 10:36:49 +00:00
static boolean isPrintableChar(char c) {
Character.UnicodeBlock block = Character.UnicodeBlock.of(c);
if (block == null || block == Character.UnicodeBlock.SPECIALS)
return false;
return !Character.isISOControl(c);
}
2019-07-15 19:28:25 +00:00
// https://issuetracker.google.com/issues/37054851
static DateFormat getTimeInstance(Context context) {
2021-04-27 12:12:04 +00:00
return getTimeInstance(context, SimpleDateFormat.MEDIUM);
2019-07-15 19:28:25 +00:00
}
2019-05-12 17:14:34 +00:00
static DateFormat getTimeInstance(Context context, int style) {
if (context != null &&
2021-04-27 12:12:04 +00:00
(style == SimpleDateFormat.SHORT || style == SimpleDateFormat.MEDIUM))
return new SimpleDateFormat(getTimePattern(context, style));
else
2019-05-12 17:14:34 +00:00
return SimpleDateFormat.getTimeInstance(style);
}
2021-04-27 12:12:04 +00:00
static DateFormat getDateInstance(Context context) {
return getDateInstance(context, SimpleDateFormat.MEDIUM);
2021-04-27 10:26:55 +00:00
}
2021-04-27 12:12:04 +00:00
private static DateFormat getDateInstance(Context context, int style) {
return SimpleDateFormat.getDateInstance(style);
2019-07-15 19:28:25 +00:00
}
2021-04-27 12:12:04 +00:00
static DateFormat getDateTimeInstance(Context context) {
return getDateTimeInstance(context, SimpleDateFormat.MEDIUM, SimpleDateFormat.MEDIUM);
2021-04-27 10:26:55 +00:00
}
2021-04-27 12:12:04 +00:00
static DateFormat getDateTimeInstance(Context context, int dateStyle, int timeStyle) {
if (context != null &&
(timeStyle == SimpleDateFormat.SHORT || timeStyle == SimpleDateFormat.MEDIUM)) {
DateFormat dateFormat = getDateInstance(context, dateStyle);
if (dateFormat instanceof SimpleDateFormat) {
String datePattern = ((SimpleDateFormat) dateFormat).toPattern();
String timePattern = getTimePattern(context, timeStyle);
return new SimpleDateFormat(datePattern + " " + timePattern);
}
}
2019-07-15 19:28:25 +00:00
return SimpleDateFormat.getDateTimeInstance(dateStyle, timeStyle);
}
2021-04-27 12:12:04 +00:00
private static String getTimePattern(Context context, int style) {
// https://issuetracker.google.com/issues/37054851
boolean is24Hour = android.text.format.DateFormat.is24HourFormat(context);
String skeleton = (is24Hour ? "Hm" : "hm");
if (style == SimpleDateFormat.MEDIUM)
skeleton += "s";
return android.text.format.DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
}
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);
}
2022-06-14 13:55:11 +00:00
static String formatDuration(long ms) {
int days = (int) (ms / (24 * 3600 * 1000L));
ms = ms % (24 * 3600 * 1000L);
long seconds = ms / 1000;
ms = ms % 1000;
return (days > 0 ? days + " " : "") + DateUtils.formatElapsedTime(seconds) + "." + ms;
}
2022-03-06 13:05:33 +00:00
static String formatNumber(Integer number, long max, NumberFormat nf) {
if (number == null)
return null;
return nf.format(Math.min(number, max)) + (number > max ? "+" : "");
}
2019-09-26 10:11:46 +00:00
static void linkPro(final TextView tv) {
if (ActivityBilling.isPro(tv.getContext()) && !BuildConfig.DEBUG)
hide(tv);
else {
tv.getPaint().setUnderlineText(true);
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tv.getContext().startActivity(new Intent(tv.getContext(), ActivityBilling.class));
}
});
}
}
static String getString(Context context, String language, int resid, Object... formatArgs) {
if (language == null)
return context.getString(resid, formatArgs);
return getString(context, new Locale(language), resid, formatArgs);
}
static String getString(Context context, Locale locale, int resid, Object... formatArgs) {
Configuration configuration = new Configuration(context.getResources().getConfiguration());
configuration.setLocale(locale);
Resources res = context.createConfigurationContext(configuration).getResources();
return res.getString(resid, formatArgs);
}
2019-12-01 11:24:03 +00:00
static String[] getStrings(Context context, int resid, Object... formatArgs) {
2020-03-26 13:44:53 +00:00
return getStrings(context, null, resid, formatArgs);
}
static String[] getStrings(Context context, String language, int resid, Object... formatArgs) {
List<Locale> locales = new ArrayList<>();
if (language != null)
locales.add(new Locale(language));
2019-12-01 11:24:03 +00:00
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
2020-03-26 13:44:53 +00:00
Locale l = Locale.getDefault();
2021-11-17 07:16:00 +00:00
locales.add(l);
2020-03-26 13:44:53 +00:00
if (!"en".equals(language) && !"en".equals(l.getLanguage()))
locales.add(new Locale("en"));
2019-12-01 11:24:03 +00:00
} else {
LocaleList ll = context.getResources().getConfiguration().getLocales();
for (int i = 0; i < ll.size(); i++) {
2020-03-26 13:44:53 +00:00
Locale l = ll.get(i);
2021-11-17 07:16:00 +00:00
locales.add(l);
2019-12-01 11:24:03 +00:00
}
}
2020-03-26 13:44:53 +00:00
List<String> result = new ArrayList<>();
Configuration configuration = new Configuration(context.getResources().getConfiguration());
for (Locale locale : locales) {
configuration.setLocale(locale);
Resources res = context.createConfigurationContext(configuration).getResources();
String text = res.getString(resid, formatArgs);
2021-11-17 07:16:00 +00:00
if (!result.contains(text))
result.add(text);
2020-03-26 13:44:53 +00:00
}
2019-12-01 11:24:03 +00:00
return result.toArray(new String[0]);
}
2020-07-20 12:50:10 +00:00
static String getLocalizedAsset(Context context, String name) throws IOException {
if (name == null || !name.contains("."))
throw new IllegalArgumentException(name);
String[] list = context.getResources().getAssets().list("");
if (list == null)
throw new IllegalArgumentException();
List<String> names = new ArrayList<>();
String[] c = name.split("\\.");
List<String> assets = Arrays.asList(list);
List<Locale> locales = new ArrayList<>();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
locales.add(Locale.getDefault());
else {
LocaleList ll = context.getResources().getConfiguration().getLocales();
for (int i = 0; i < ll.size(); i++)
locales.add(ll.get(i));
}
for (Locale locale : locales) {
String language = locale.getLanguage();
String country = locale.getCountry();
if ("en".equals(language) && "US".equals(country))
names.add(name);
else {
String localized = c[0] + "-" + language + "-r" + country + "." + c[1];
if (assets.contains(localized))
names.add(localized);
}
}
for (Locale locale : locales) {
String prefix = c[0] + "-" + locale.getLanguage();
for (String asset : assets)
if (asset.startsWith(prefix))
names.add(asset);
}
names.add(name);
String asset = names.get(0);
Log.i("Using " + asset +
" of " + TextUtils.join(",", names) +
" (" + TextUtils.join(",", locales) + ")");
return asset;
}
static boolean containsWhiteSpace(String text) {
return text.matches(".*\\s+.*");
}
static boolean containsControlChars(String text) {
2020-04-23 14:03:56 +00:00
int codePoint;
for (int offset = 0; offset < text.length(); ) {
2020-04-23 14:03:56 +00:00
codePoint = text.codePointAt(offset);
offset += Character.charCount(codePoint);
switch (Character.getType(codePoint)) {
case Character.CONTROL: // \p{Cc}
case Character.FORMAT: // \p{Cf}
case Character.PRIVATE_USE: // \p{Co}
case Character.SURROGATE: // \p{Cs}
case Character.UNASSIGNED: // \p{Cn}
return true;
}
}
return false;
}
2020-04-13 12:20:19 +00:00
static boolean isSingleScript(String s) {
// https://en.wikipedia.org/wiki/IDN_homograph_attack
2021-04-04 11:45:32 +00:00
if (TextUtils.isEmpty(s))
return true;
2020-04-13 12:20:19 +00:00
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
return true;
2020-04-23 14:03:56 +00:00
int codepoint;
Character.UnicodeScript us;
2020-04-13 12:20:19 +00:00
Character.UnicodeScript script = null;
for (int i = 0; i < s.length(); ) {
2020-04-23 14:03:56 +00:00
codepoint = s.codePointAt(i);
2020-04-13 12:20:19 +00:00
i += Character.charCount(codepoint);
2020-04-23 14:03:56 +00:00
us = Character.UnicodeScript.of(codepoint);
2020-04-13 12:20:19 +00:00
if (us.equals(Character.UnicodeScript.COMMON))
continue;
if (script == null)
script = us;
else if (!us.equals(script))
return false;
}
return true;
}
2020-08-06 17:00:11 +00:00
static Integer parseInt(String text) {
if (TextUtils.isEmpty(text))
return null;
if (!TextUtils.isDigitsOnly(text))
return null;
try {
return Integer.parseInt(text);
} catch (NumberFormatException ignored) {
return null;
}
}
2022-01-16 07:43:56 +00:00
static String toRoman(int value) {
2021-10-14 17:53:53 +00:00
if (value < 0 || value >= 4000)
return Integer.toString(value);
return ROMAN_1000[value / 1000] +
ROMAN_100[(value % 1000) / 100] +
ROMAN_10[(value % 100) / 10] +
ROMAN_1[value % 10];
}
2022-01-21 08:07:28 +00:00
static ActionMode.Callback getActionModeWrapper(TextView view) {
2022-01-16 07:01:59 +00:00
return new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
for (int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getItem(i);
Intent intent = item.getIntent();
2022-01-21 08:07:28 +00:00
if (intent != null &&
Intent.ACTION_PROCESS_TEXT.equals(intent.getAction())) {
2022-01-16 07:01:59 +00:00
item.setIntent(null);
item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
try {
2022-01-21 08:07:28 +00:00
int start = view.getSelectionStart();
int end = view.getSelectionEnd();
if (start > end) {
int tmp = start;
start = end;
end = tmp;
}
CharSequence selected = view.getText();
if (start >= 0 && end <= selected.length())
selected = selected.subSequence(start, end);
intent.putExtra(Intent.EXTRA_PROCESS_TEXT, selected);
view.getContext().startActivity(intent);
2022-01-16 07:01:59 +00:00
} catch (Throwable ex) {
2022-01-21 08:07:28 +00:00
reportNoViewer(view.getContext(), intent, ex);
2022-01-17 07:55:06 +00:00
/*
java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.PROCESS_TEXT typ=text/plain cmp=com.microsoft.launcher/com.microsoft.bing.ProcessTextSearch launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 } (has extras) } from ProcessRecord{befc028 15098:eu.faircode.email/u0a406} (pid=15098, uid=10406) not exported from uid 10021
at android.os.Parcel.readException(Parcel.java:1693)
at android.os.Parcel.readException(Parcel.java:1646)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3530)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1645)
at android.app.Activity.startActivityForResult(Activity.java:5033)
at android.view.View.startActivityForResult(View.java:6413)
at android.widget.Editor$ProcessTextIntentActionsHandler.fireIntent(Editor.java:7597)
at android.widget.Editor$ProcessTextIntentActionsHandler.performMenuItemAction(Editor.java:7542)
at android.widget.Editor$TextActionModeCallback.onActionItemClicked(Editor.java:4246)
at com.android.internal.policy.DecorView$ActionModeCallback2Wrapper.onActionItemClicked(DecorView.java:2971)
at com.android.internal.view.FloatingActionMode$3.onMenuItemSelected(FloatingActionMode.java:95)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:157)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
at com.android.internal.view.FloatingActionMode$4.onMenuItemClick(FloatingActionMode.java:124)
at com.android.internal.widget.FloatingToolbar$FloatingToolbarPopup$23.onItemClick(FloatingToolbar.java:1898)
at android.widget.AdapterView.performItemClick(AdapterView.java:339)
at android.widget.AbsListView.performItemClick(AbsListView.java:1705)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:4171)
at android.widget.AbsListView$13.run(AbsListView.java:6735)
*/
2022-01-16 07:01:59 +00:00
}
return true;
}
});
}
}
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
}
};
}
2022-04-27 05:54:19 +00:00
static boolean isDot(char c) {
return (c == '.' /* Latin */ || c == '。' /* Chinese */);
}
2019-05-12 17:14:34 +00:00
// Files
2018-12-24 10:47:21 +00:00
2022-06-24 11:46:15 +00:00
static {
System.loadLibrary("fairemail");
}
public static native void sync();
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-07-30 07:03:54 +00:00
2020-10-29 10:50:06 +00:00
return name
// Canonical files names cannot contain NUL
.replace("\0", "")
.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-11-20 11:40:56 +00:00
static String guessMimeType(String filename) {
String type = null;
String extension = Helper.getExtension(filename);
2020-07-14 13:07:09 +00:00
if (extension != null) {
extension = extension.toLowerCase(Locale.ROOT);
2022-05-06 18:40:44 +00:00
if (extension.endsWith(")")) {
int p = extension.lastIndexOf('(');
if (p > 0 && p < extension.length() - 1)
if (TextUtils.isDigitsOnly(extension.substring(p + 1, extension.length() - 1)))
extension = extension.substring(0, p).trim();
}
2021-02-05 12:00:57 +00:00
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
2020-07-14 13:07:09 +00:00
}
2019-11-20 11:40:56 +00:00
if (TextUtils.isEmpty(type))
2020-07-14 13:07:09 +00:00
if ("csv".equals(extension))
return "text/csv";
else if ("eml".equals(extension))
return "message/rfc822";
else if ("gpx".equals(extension))
return "application/gpx+xml";
else if ("log".equals(extension))
return "text/plain";
else if ("ovpn".equals(extension))
return "application/x-openvpn-profile";
2021-04-17 15:56:29 +00:00
else if ("mbox".equals(extension))
return "application/mbox"; // https://tools.ietf.org/html/rfc4155
2020-07-14 13:07:09 +00:00
else
return "application/octet-stream";
2019-11-20 11:40:56 +00:00
return type;
}
2020-07-14 13:07:09 +00:00
static String guessExtension(String mimeType) {
String extension = null;
if (mimeType != null) {
mimeType = mimeType.toLowerCase(Locale.ROOT);
extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
}
if (TextUtils.isEmpty(extension))
if ("text/csv".equals(mimeType))
return "csv";
else if ("message/rfc822".equals(mimeType))
return "eml";
else if ("application/gpx+xml".equals(mimeType))
return "gpx";
else if ("application/x-openvpn-profile".equals(mimeType))
return "ovpn";
return extension;
}
2019-01-21 16:45:05 +00:00
static void writeText(File file, String content) throws IOException {
try (FileOutputStream out = new FileOutputStream(file)) {
if (content != null)
out.write(content.getBytes());
2019-01-21 16:45:05 +00:00
}
}
2021-01-20 19:00:44 +00:00
static String readStream(InputStream is) throws IOException {
return readStream(is, StandardCharsets.UTF_8);
}
static String readStream(InputStream is, Charset charset) throws IOException {
2019-08-09 18:16:36 +00:00
ByteArrayOutputStream os = new ByteArrayOutputStream(Math.max(BUFFER_SIZE, is.available()));
byte[] buffer = new byte[BUFFER_SIZE];
2019-07-06 11:02:32 +00:00
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)) {
2021-01-20 19:00:44 +00:00
return readStream(in);
2019-01-21 16:45:05 +00:00
}
}
2020-09-16 18:30:40 +00:00
public static void readBuffer(InputStream is, byte[] buffer) throws IOException {
int left = buffer.length;
while (left > 0) {
int count = is.read(buffer, buffer.length - left, left);
if (count < 0)
throw new IOException("EOF");
left -= count;
}
}
2021-10-28 05:35:26 +00:00
static byte[] readBytes(InputStream is) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream(Math.max(BUFFER_SIZE, is.available()));
byte[] buffer = new byte[BUFFER_SIZE];
for (int len = is.read(buffer); len != -1; len = is.read(buffer))
os.write(buffer, 0, len);
return os.toByteArray();
}
2018-08-23 18:58:21 +00:00
static void copy(File src, File dst) throws IOException {
2021-10-12 13:54:23 +00:00
try (InputStream is = new FileInputStream(src)) {
2021-10-12 17:31:55 +00:00
try (OutputStream os = new FileOutputStream(dst)) {
2021-10-12 13:54:23 +00:00
copy(is, os);
2018-08-23 18:58:21 +00:00
}
}
}
2018-08-25 11:27:54 +00:00
2021-10-12 17:31:55 +00:00
static long copy(Context context, Uri uri, File file) throws IOException {
try (InputStream is = context.getContentResolver().openInputStream(uri)) {
2022-03-27 11:43:45 +00:00
if (is == null)
throw new FileNotFoundException(uri.toString());
2021-10-12 17:31:55 +00:00
try (OutputStream os = new FileOutputStream(file)) {
return copy(is, os);
}
}
}
2021-10-12 13:54:23 +00:00
static long copy(InputStream is, OutputStream os) throws IOException {
long size = 0;
byte[] buf = new byte[BUFFER_SIZE];
int len;
2021-10-12 13:54:23 +00:00
while ((len = is.read(buf)) > 0) {
size += len;
os.write(buf, 0, len);
}
return size;
}
2019-12-24 09:39:29 +00:00
static long getAvailableStorageSpace() {
2019-10-19 19:53:19 +00:00
StatFs stats = new StatFs(Environment.getDataDirectory().getAbsolutePath());
return stats.getAvailableBlocksLong() * stats.getBlockSizeLong();
}
2019-12-24 09:53:42 +00:00
static long getTotalStorageSpace() {
StatFs stats = new StatFs(Environment.getDataDirectory().getAbsolutePath());
return stats.getTotalBytes();
}
2022-04-30 20:05:28 +00:00
2022-04-30 20:35:22 +00:00
static long getCacheQuota(Context context) {
// https://developer.android.com/reference/android/content/Context#getCacheDir()
2022-04-30 20:05:28 +00:00
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
try {
StorageManager sm = Helper.getSystemService(context, StorageManager.class);
File cache = context.getCacheDir();
return sm.getCacheQuotaBytes(sm.getUuidForPath(cache));
} catch (IOException ex) {
Log.w(ex);
}
2022-05-01 05:52:49 +00:00
return 0;
2022-04-30 20:05:28 +00:00
}
2019-12-24 09:53:42 +00:00
2022-05-01 05:52:49 +00:00
static long getSizeUsed(File dir) {
2021-01-22 14:01:20 +00:00
long size = 0;
File[] listed = dir.listFiles();
if (listed != null)
for (File file : listed)
if (file.isDirectory())
2022-05-01 05:52:49 +00:00
size += getSizeUsed(file);
2021-01-22 14:01:20 +00:00
else
size += file.length();
return size;
}
2019-12-01 17:19:17 +00:00
static void openAdvanced(Intent intent) {
// https://issuetracker.google.com/issues/72053350
intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
intent.putExtra("android.content.extra.FANCY", true);
intent.putExtra("android.content.extra.SHOW_FILESIZE", true);
intent.putExtra("android.provider.extra.SHOW_ADVANCED", true);
//File initial = Environment.getExternalStorageDirectory();
//intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.fromFile(initial));
2019-12-01 17:19:17 +00:00
}
2021-08-29 19:18:09 +00:00
static HttpURLConnection openUrlRedirect(Context context, String source, int timeout) throws IOException {
int redirects = 0;
URL url = new URL(source);
while (true) {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(false);
urlConnection.setReadTimeout(timeout);
urlConnection.setConnectTimeout(timeout);
urlConnection.setInstanceFollowRedirects(true);
ConnectionHelper.setUserAgent(context, urlConnection);
2021-08-29 19:18:09 +00:00
urlConnection.connect();
try {
int status = urlConnection.getResponseCode();
if (status == HttpURLConnection.HTTP_MOVED_PERM ||
status == HttpURLConnection.HTTP_MOVED_TEMP ||
status == HttpURLConnection.HTTP_SEE_OTHER ||
status == 307 /* Temporary redirect */ ||
status == 308 /* Permanent redirect */) {
if (++redirects > MAX_REDIRECTS)
throw new IOException("Too many redirects");
String header = urlConnection.getHeaderField("Location");
if (header == null)
throw new IOException("Location header missing");
String location = URLDecoder.decode(header, StandardCharsets.UTF_8.name());
url = new URL(url, location);
Log.i("Redirect #" + redirects + " to " + url);
urlConnection.disconnect();
continue;
}
if (status != HttpURLConnection.HTTP_OK)
throw new IOException("Error " + status + ": " + urlConnection.getResponseMessage());
return urlConnection;
} catch (IOException ex) {
urlConnection.disconnect();
throw ex;
}
}
}
2022-04-30 19:30:22 +00:00
static class ByteArrayInOutStream extends ByteArrayOutputStream {
public ByteArrayInOutStream() {
super();
}
public ByteArrayInOutStream(int size) {
super(size);
}
public ByteArrayInputStream getInputStream() {
ByteArrayInputStream in = new ByteArrayInputStream(this.buf, 0, this.count);
this.buf = null;
return in;
}
}
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 sha1(byte[] data) throws NoSuchAlgorithmException {
return sha("SHA-1", data);
}
2018-08-25 11:27:54 +00:00
static String sha256(byte[] data) throws NoSuchAlgorithmException {
return sha("SHA-256", data);
}
2020-01-17 15:59:29 +00:00
static String md5(byte[] data) throws NoSuchAlgorithmException {
return sha("MD5", data);
}
static String sha(String digest, byte[] data) throws NoSuchAlgorithmException {
byte[] bytes = MessageDigest.getInstance(digest).digest(data);
return hex(bytes);
}
static String hex(byte[] bytes) {
2018-08-25 11:27:54 +00:00
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) {
2021-06-30 09:04:46 +00:00
return getFingerprint(context, "SHA1");
}
static String getFingerprint(Context context, String hash) {
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();
2021-06-30 09:04:46 +00:00
MessageDigest digest = MessageDigest.getInstance(hash);
2018-09-27 06:44:02 +00:00
byte[] bytes = digest.digest(cert);
StringBuilder sb = new StringBuilder();
for (byte b : bytes)
2021-07-17 12:09:45 +00:00
sb.append(String.format("%02X", b));
2018-09-27 06:44:02 +00:00
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) {
2021-05-02 07:48:08 +00:00
if (hasValidFingerprint == null) {
2021-06-30 10:00:15 +00:00
hasValidFingerprint = false;
2021-05-02 07:48:08 +00:00
String signed = getFingerprint(context);
2021-06-30 09:04:46 +00:00
String[] fingerprints = new String[]{
context.getString(R.string.fingerprint),
context.getString(R.string.fingerprint_amazon)
};
2021-06-30 10:00:15 +00:00
2021-06-30 09:04:46 +00:00
for (String fingerprint : fingerprints)
if (Objects.equals(signed, fingerprint)) {
hasValidFingerprint = true;
break;
}
2021-05-02 07:48:08 +00:00
}
return hasValidFingerprint;
2018-09-27 06:44:02 +00:00
}
2019-07-12 17:33:40 +00:00
static boolean canAuthenticate(Context context) {
2019-10-20 10:17:04 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String pin = prefs.getString("pin", null);
if (!TextUtils.isEmpty(pin))
return true;
2021-09-23 05:35:00 +00:00
try {
BiometricManager bm = BiometricManager.from(context);
return (bm.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_WEAK) == BiometricManager.BIOMETRIC_SUCCESS);
} catch (Throwable ex) {
/*
java.lang.SecurityException: eu.faircode.email from uid 10377 not allowed to perform USE_FINGERPRINT
at android.os.Parcel.createException(Parcel.java:1953)
at android.os.Parcel.readException(Parcel.java:1921)
at android.os.Parcel.readException(Parcel.java:1871)
at android.hardware.fingerprint.IFingerprintService$Stub$Proxy.isHardwareDetected(IFingerprintService.java:460)
at android.hardware.fingerprint.FingerprintManager.isHardwareDetected(FingerprintManager.java:792)
at androidx.core.hardware.fingerprint.FingerprintManagerCompat.isHardwareDetected(SourceFile:3)
at androidx.biometric.BiometricManager.canAuthenticateWithFingerprint(SourceFile:3)
at androidx.biometric.BiometricManager.canAuthenticateWithFingerprintOrUnknownBiometric(SourceFile:2)
at androidx.biometric.BiometricManager.canAuthenticateCompat(SourceFile:10)
at androidx.biometric.BiometricManager.canAuthenticate(SourceFile:5)
*/
Log.e(ex);
return false;
}
2019-07-12 17:33:40 +00:00
}
2021-10-30 09:10:24 +00:00
static boolean shouldAuthenticate(Context context, boolean pausing) {
2019-07-10 15:58:26 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean biometrics = prefs.getBoolean("biometrics", false);
2019-10-20 10:17:04 +00:00
String pin = prefs.getString("pin", null);
2019-07-10 15:58:26 +00:00
2019-10-20 10:17:04 +00:00
if (biometrics || !TextUtils.isEmpty(pin)) {
2019-07-10 17:58:02 +00:00
long now = new Date().getTime();
long last_authentication = prefs.getLong("last_authentication", 0);
long biometrics_timeout = prefs.getInt("biometrics_timeout", 2) * 60 * 1000L;
2021-10-30 09:10:24 +00:00
boolean autolock_nav = prefs.getBoolean("autolock_nav", false);
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
2021-10-30 09:10:24 +00:00
if (autolock_nav && pausing)
last_authentication = now - biometrics_timeout + AUTOLOCK_GRACE * 1000L;
else
last_authentication = now;
prefs.edit().putLong("last_authentication", last_authentication).apply();
2019-07-10 17:58:02 +00:00
}
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
}
2022-01-15 12:34:23 +00:00
static boolean shouldAutoLock(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean biometrics = prefs.getBoolean("biometrics", false);
String pin = prefs.getString("pin", null);
boolean autolock = prefs.getBoolean("autolock", true);
return (autolock && (biometrics || !TextUtils.isEmpty(pin)));
}
2020-05-30 13:59:51 +00:00
static void authenticate(final FragmentActivity activity, final LifecycleOwner owner,
2019-07-10 15:58:26 +00:00
Boolean enabled, final
Runnable authenticated, final Runnable cancelled) {
2021-08-19 16:45:49 +00:00
Log.i("Authenticate " + activity);
2019-10-20 10:17:04 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
String pin = prefs.getString("pin", null);
2019-10-20 10:17:04 +00:00
if (enabled != null || TextUtils.isEmpty(pin)) {
2021-08-19 16:45:49 +00:00
Log.i("Authenticate biometric enabled=" + enabled);
2019-10-20 10:17:04 +00:00
BiometricPrompt.PromptInfo.Builder info = new BiometricPrompt.PromptInfo.Builder()
.setTitle(activity.getString(enabled == null ? R.string.app_name : R.string.title_setup_biometrics));
2019-10-20 10:17:04 +00:00
KeyguardManager kgm = (KeyguardManager) activity.getSystemService(Context.KEYGUARD_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && kgm != null && kgm.isDeviceSecure())
info.setDeviceCredentialAllowed(true);
else
info.setNegativeButtonText(activity.getString(android.R.string.cancel));
2019-12-16 11:58:30 +00:00
info.setConfirmationRequired(false);
2019-10-20 10:17:04 +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));
2020-05-30 13:59:51 +00:00
final BiometricPrompt prompt = new BiometricPrompt(activity, executor,
2019-10-20 10:17:04 +00:00
new BiometricPrompt.AuthenticationCallback() {
2022-01-07 18:26:40 +00:00
private int fails = 0;
2019-10-20 10:17:04 +00:00
@Override
public void onAuthenticationError(final int errorCode, @NonNull final CharSequence errString) {
2022-04-25 06:12:43 +00:00
if (isCancelled(errorCode) || errorCode == BiometricPrompt.ERROR_UNABLE_TO_PROCESS)
2022-03-06 11:56:18 +00:00
Log.w("Authenticate biometric error " + errorCode + ": " + errString);
else
Log.e("Authenticate biometric error " + errorCode + ": " + errString);
if (isHardwareFailure(errorCode)) {
prefs.edit().remove("biometrics").apply();
ApplicationEx.getMainHandler().post(authenticated);
return;
}
2019-10-20 10:17:04 +00:00
2022-03-06 11:56:18 +00:00
if (!isCancelled(errorCode))
2022-05-01 11:46:06 +00:00
ApplicationEx.getMainHandler().post(new RunnableEx("auth:error") {
2019-10-21 07:13:40 +00:00
@Override
2022-05-01 11:46:06 +00:00
public void delegate() {
2019-10-21 07:13:40 +00:00
ToastEx.makeText(activity,
"Error " + errorCode + ": " + errString,
Toast.LENGTH_LONG).show();
}
});
2019-07-10 15:58:26 +00:00
2020-08-23 15:34:14 +00:00
ApplicationEx.getMainHandler().post(cancelled);
2019-10-20 10:17:04 +00:00
}
@Override
public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) {
2021-08-19 16:45:49 +00:00
Log.i("Authenticate biometric succeeded");
2019-10-20 10:17:04 +00:00
setAuthenticated(activity);
2020-08-23 15:34:14 +00:00
ApplicationEx.getMainHandler().post(authenticated);
2019-10-20 10:17:04 +00:00
}
@Override
public void onAuthenticationFailed() {
2021-08-19 16:45:49 +00:00
Log.w("Authenticate biometric failed");
2022-01-07 18:26:40 +00:00
if (++fails >= 3)
ApplicationEx.getMainHandler().post(cancelled);
2019-10-20 10:17:04 +00:00
}
2022-03-06 11:56:18 +00:00
private boolean isCancelled(int errorCode) {
return (errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON ||
errorCode == BiometricPrompt.ERROR_CANCELED ||
errorCode == BiometricPrompt.ERROR_USER_CANCELED);
}
private boolean isHardwareFailure(int errorCode) {
return (errorCode == BiometricPrompt.ERROR_HW_UNAVAILABLE ||
2022-05-26 07:06:50 +00:00
errorCode == BiometricPrompt.ERROR_NO_BIOMETRICS || // No fingerprints enrolled.
2022-03-06 11:56:18 +00:00
errorCode == BiometricPrompt.ERROR_HW_NOT_PRESENT ||
errorCode == BiometricPrompt.ERROR_NO_DEVICE_CREDENTIAL);
}
2019-10-20 10:17:04 +00:00
});
prompt.authenticate(info.build());
2020-05-30 13:59:51 +00:00
2022-05-01 11:46:06 +00:00
final Runnable cancelPrompt = new RunnableEx("auth:cancelprompt") {
2020-05-31 12:42:20 +00:00
@Override
2022-05-01 11:46:06 +00:00
public void delegate() {
2020-05-31 12:42:20 +00:00
try {
prompt.cancelAuthentication();
} catch (Throwable ex) {
Log.e(ex);
}
}
};
2020-08-23 15:34:14 +00:00
ApplicationEx.getMainHandler().postDelayed(cancelPrompt, 60 * 1000L);
2020-05-31 12:42:20 +00:00
2020-05-30 13:59:51 +00:00
owner.getLifecycle().addObserver(new LifecycleObserver() {
2020-05-30 14:21:25 +00:00
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
2021-08-19 16:45:49 +00:00
Log.i("Authenticate destroyed");
2022-05-01 11:46:06 +00:00
ApplicationEx.getMainHandler().removeCallbacks(cancelPrompt);
try {
prompt.cancelAuthentication();
} catch (Throwable ex) {
Log.e(ex);
}
2021-09-28 08:18:20 +00:00
owner.getLifecycle().removeObserver(this);
2020-05-30 13:59:51 +00:00
}
});
2019-10-20 10:17:04 +00:00
} else {
2021-08-19 16:45:49 +00:00
Log.i("Authenticate PIN");
2019-10-20 10:17:04 +00:00
final View dview = LayoutInflater.from(activity).inflate(R.layout.dialog_pin_ask, null);
final EditText etPin = dview.findViewById(R.id.etPin);
2021-12-20 14:22:41 +00:00
etPin.setEnabled(false);
2019-11-01 09:50:32 +00:00
final AlertDialog dialog = new AlertDialog.Builder(activity)
2019-10-20 10:17:04 +00:00
.setView(dview)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
String pin = prefs.getString("pin", "");
String entered = etPin.getText().toString();
2021-08-19 16:45:49 +00:00
Log.i("Authenticate PIN ok=" + pin.equals(entered));
2019-10-20 10:17:04 +00:00
if (pin.equals(entered)) {
prefs.edit()
.remove("pin_failure_at")
.remove("pin_failure_count")
.apply();
2019-10-20 10:17:04 +00:00
setAuthenticated(activity);
2020-08-23 15:34:14 +00:00
ApplicationEx.getMainHandler().post(authenticated);
2021-08-19 16:45:49 +00:00
} else {
int count = prefs.getInt("pin_failure_count", 0) + 1;
prefs.edit()
.putLong("pin_failure_at", new Date().getTime())
.putInt("pin_failure_count", count)
.apply();
2020-08-23 15:34:14 +00:00
ApplicationEx.getMainHandler().post(cancelled);
2021-08-19 16:45:49 +00:00
}
2019-10-20 10:17:04 +00:00
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
2021-08-19 16:45:49 +00:00
Log.i("Authenticate PIN cancelled");
2020-08-23 15:34:14 +00:00
ApplicationEx.getMainHandler().post(cancelled);
2019-10-20 10:17:04 +00:00
}
})
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
2021-08-19 16:45:49 +00:00
Log.i("Authenticate PIN dismissed");
2021-10-30 09:10:24 +00:00
if (shouldAuthenticate(activity, false)) // Some Android versions call dismiss on OK
2021-08-20 09:26:20 +00:00
ApplicationEx.getMainHandler().post(cancelled);
2019-10-20 10:17:04 +00:00
}
})
.create();
etPin.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
return true;
} else
return false;
}
});
2021-05-26 17:31:51 +00:00
try {
dialog.show();
2021-12-20 14:22:41 +00:00
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
long pin_failure_at = prefs.getLong("pin_failure_at", 0);
int pin_failure_count = prefs.getInt("pin_failure_count", 0);
long wait = (long) Math.pow(PIN_FAILURE_DELAY, pin_failure_count) * 1000L;
long delay = pin_failure_at + wait - new Date().getTime();
Log.i("PIN wait=" + wait + " delay=" + delay);
2022-03-16 18:20:52 +00:00
dview.postDelayed(new Runnable() {
2021-12-20 14:22:41 +00:00
@Override
public void run() {
2022-03-16 19:08:31 +00:00
try {
etPin.setCompoundDrawables(null, null, null, null);
etPin.setEnabled(true);
etPin.requestFocus();
showKeyboard(etPin);
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
} catch (Throwable ex) {
Log.e(ex);
}
2021-12-20 14:22:41 +00:00
}
}, delay < 0 ? 0 : delay);
2021-05-26 17:31:51 +00:00
} catch (Throwable ex) {
Log.e(ex);
/*
java.lang.RuntimeException: Unable to start activity ComponentInfo{eu.faircode.email/eu.faircode.email.ActivityMain}: java.lang.RuntimeException: InputChannel is not initialized.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3477)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3620)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2183)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:7604)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
Caused by: java.lang.RuntimeException: InputChannel is not initialized.
at android.view.InputEventReceiver.nativeInit(Native Method)
at android.view.InputEventReceiver.<init>(InputEventReceiver.java:71)
at android.view.ViewRootImpl$WindowInputEventReceiver.<init>(ViewRootImpl.java:7758)
at android.view.ViewRootImpl.setView(ViewRootImpl.java:1000)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:393)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
at android.app.Dialog.show(Dialog.java:342)
at eu.faircode.email.Helper.authenticate(SourceFile:15)
at eu.faircode.email.ActivityMain.onCreate(SourceFile:24)
at android.app.Activity.performCreate(Activity.java:7822)
*/
}
2019-10-20 10:17:04 +00:00
}
}
2019-11-06 09:40:50 +00:00
static void setAuthenticated(Context context) {
2021-08-19 16:45:49 +00:00
Date now = new Date();
Log.i("Authenticated now=" + now);
2019-10-20 10:17:04 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
2021-08-19 16:45:49 +00:00
prefs.edit().putLong("last_authentication", now.getTime()).apply();
2019-07-10 15:58:26 +00:00
}
2019-07-11 06:13:49 +00:00
static void clearAuthentication(Context context) {
2021-08-19 16:45:49 +00:00
Log.i("Authenticate clear");
2019-07-11 06:13:49 +00:00
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().remove("last_authentication").apply();
}
2020-01-29 19:02:45 +00:00
static void selectKeyAlias(final Activity activity, final LifecycleOwner owner, final String alias, final IKeyAlias intf) {
2019-12-05 14:18:53 +00:00
final Context context = activity.getApplicationContext();
new Thread(new Runnable() {
@Override
public void run() {
2020-01-29 19:02:45 +00:00
if (alias != null)
2019-12-05 14:18:53 +00:00
try {
2020-01-29 19:02:45 +00:00
if (KeyChain.getPrivateKey(context, alias) != null) {
Log.i("Private key available alias=" + alias);
2020-04-02 09:18:16 +00:00
deliver(alias);
2019-12-05 14:18:53 +00:00
return;
}
} catch (KeyChainException ex) {
Log.w(ex);
} catch (Throwable ex) {
Log.e(ex);
}
2020-08-23 15:34:14 +00:00
ApplicationEx.getMainHandler().post(new Runnable() {
2019-12-05 14:18:53 +00:00
@Override
public void run() {
KeyChain.choosePrivateKeyAlias(activity, new KeyChainAliasCallback() {
@Override
public void alias(@Nullable final String alias) {
Log.i("Selected key alias=" + alias);
2020-04-02 09:18:16 +00:00
deliver(alias);
2019-12-05 14:18:53 +00:00
}
},
2020-01-29 19:02:45 +00:00
null, null, null, -1, alias);
2019-12-05 14:18:53 +00:00
}
});
}
2020-04-02 09:18:16 +00:00
private void deliver(final String selected) {
2020-08-23 15:34:14 +00:00
ApplicationEx.getMainHandler().post(new Runnable() {
2020-04-02 09:18:16 +00:00
@Override
public void run() {
if (owner.getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.STARTED)) {
if (selected == null)
intf.onNothingSelected();
else
intf.onSelected(selected);
} else {
owner.getLifecycle().addObserver(new LifecycleObserver() {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
owner.getLifecycle().removeObserver(this);
if (selected == null)
intf.onNothingSelected();
else
intf.onSelected(selected);
}
2021-09-28 08:18:20 +00:00
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
owner.getLifecycle().removeObserver(this);
}
2020-04-02 09:18:16 +00:00
});
}
}
});
}
2019-12-05 14:18:53 +00:00
}).start();
}
interface IKeyAlias {
void onSelected(String alias);
void onNothingSelected();
}
2020-01-23 11:38:31 +00:00
public static String HMAC(String algo, int blocksize, byte[] key, byte[] text) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(algo);
if (key.length > blocksize)
key = md.digest(key);
byte[] ipad = new byte[blocksize];
byte[] opad = new byte[blocksize];
for (int i = 0; i < key.length; i++) {
ipad[i] = key[i];
opad[i] = key[i];
}
for (int i = 0; i < blocksize; i++) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
byte[] digest;
md.update(ipad);
md.update(text);
digest = md.digest();
md.update(opad);
md.update(digest);
digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest)
sb.append(String.format("%02x", b));
return sb.toString();
}
2019-05-12 17:14:34 +00:00
// Miscellaneous
2021-03-06 10:14:23 +00:00
static void gc() {
2021-03-10 19:25:56 +00:00
if (BuildConfig.DEBUG) {
Runtime.getRuntime().gc();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
2021-03-06 10:14:23 +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;
}
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) {
2020-06-25 07:14:05 +00:00
if (a1 == null && a2 == null)
return true;
if (a1 == null || a2 == null)
return false;
2018-11-25 12:34:08 +00:00
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();
}
2022-03-07 07:21:19 +00:00
static void clearAll(Context context) {
2022-05-24 07:46:47 +00:00
ActivityManager am = Helper.getSystemService(context, ActivityManager.class);
2022-03-07 07:21:19 +00:00
am.clearApplicationUserData();
}
2018-08-02 13:33:06 +00:00
}