From beaa70cd050f5a2d31d1736ae86d48f28176e73f Mon Sep 17 00:00:00 2001 From: M66B Date: Sun, 5 Dec 2021 18:59:23 +0100 Subject: [PATCH] Limit conversation action duration --- .../java/eu/faircode/email/TextHelper.java | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/eu/faircode/email/TextHelper.java b/app/src/main/java/eu/faircode/email/TextHelper.java index 3a7f026474..a8ee026888 100644 --- a/app/src/main/java/eu/faircode/email/TextHelper.java +++ b/app/src/main/java/eu/faircode/email/TextHelper.java @@ -24,12 +24,14 @@ import android.content.Context; import android.content.SharedPreferences; import android.icu.text.Transliterator; import android.os.Build; +import android.os.SystemClock; import android.text.TextUtils; import android.view.textclassifier.ConversationAction; import android.view.textclassifier.ConversationActions; import android.view.textclassifier.TextClassificationManager; import android.view.textclassifier.TextClassifier; +import androidx.annotation.RequiresApi; import androidx.preference.PreferenceManager; import java.time.ZoneId; @@ -42,12 +44,21 @@ import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; public class TextHelper { private static final int MAX_DETECT_SAMPLE_SIZE = 8192; private static final float MIN_DETECT_PROBABILITY = 0.80f; private static final String TRANSLITERATOR = "Any-Latin; Latin-ASCII"; private static final int MAX_CONVERSATION_SAMPLE_SIZE = 8192; + private static final long MAX_CONVERSATION_DURATION = 5000; // milliseconds + + private static final ExecutorService executor = + Helper.getBackgroundExecutor(0, "text"); static { System.loadLibrary("fairemail"); @@ -169,7 +180,31 @@ public class TextHelper { .setHints(hints) .build(); - return tcm.getTextClassifier().suggestConversationActions(request); + Future future = executor.submit(new Callable() { + @Override + @RequiresApi(api = Build.VERSION_CODES.Q) + public ConversationActions call() throws Exception { + long start = SystemClock.elapsedRealtime(); + try { + return tcm.getTextClassifier().suggestConversationActions(request); + } finally { + long elapse = SystemClock.elapsedRealtime() - start; + Log.i("Conversation actions=" + elapse + " ms"); + } + } + }); + + try { + return future.get(MAX_CONVERSATION_DURATION, TimeUnit.MILLISECONDS); + } catch (TimeoutException ex) { + Log.e(ex); + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + prefs.edit().putBoolean("conversation_actions", false); + return null; + } catch (Throwable ex) { + Log.e(ex); + return null; + } } private static class DetectResult {