From bdfdd3e0c531a7e00d4bfbd1da7336a52da17e40 Mon Sep 17 00:00:00 2001 From: Sajad <220944007+MyNameIsGlooboo@users.noreply.github.com> Date: Thu, 12 Nov 2026 06:57:40 +0000 Subject: [PATCH 1/5] Apply 29 verified review findings (triage: real medium and low impact) Backup/settings/lock, conversation list, thread, notifications/helpers and spam fixes; notification work moved off the main thread, group-chat block guard, select-all respects filter, lookalike-host warning, EXIF/XMP/IPTC stripping, audio focus resume, delete-conversation cleanup, MMS duplicate download guard, spam sent-address country matching. spam-2 (needs a schema change) is deferred. Co-Authored-By: Claude Sonnet 5.5 --- .../umessage/activities/SettingsActivity.kt | 9 +- .../umessage/activities/ThreadActivity.kt | 23 +- .../activities/VCardViewerActivity.kt | 7 +- .../umessage/dialogs/ImportMessagesDialog.kt | 7 +- .../glooboo/umessage/extensions/Context.kt | 42 +- .../umessage/helpers/AudioPlayerManager.kt | 47 +- .../glooboo/umessage/helpers/BackupCrypto.kt | 2 +- .../com/glooboo/umessage/helpers/Constants.kt | 1 + .../glooboo/umessage/helpers/ExifStripper.kt | 76 +- .../umessage/helpers/NotificationHelper.kt | 2 +- .../interfaces/MessageRemindersDao.kt | 3 + .../umessage/messaging/MessageReminders.kt | 8 + .../umessage/receivers/DirectReplyReceiver.kt | 35 +- .../umessage/receivers/MmsPushReceiver.kt | 281 +++--- .../glooboo/umessage/spam/SpamContracts.kt | 527 +++++------ .../spam/data/DefaultSpamRepository.kt | 860 +++++++++--------- .../spam/engine/AndroidSpamEnvironment.kt | 14 +- .../umessage/spam/engine/SpamEngine.kt | 594 ++++++------ .../ui/conversations/ArchivedRoute.kt | 397 ++++---- .../ui/conversations/ConversationsModels.kt | 2 + .../ConversationsSelectionBar.kt | 6 +- .../conversations/ConversationsViewModel.kt | 17 +- .../ui/forwarded/ForwardedViewModel.kt | 9 +- .../glooboo/umessage/ui/lock/LockViewModel.kt | 4 +- .../glooboo/umessage/ui/main/MainScreen.kt | 14 +- .../umessage/ui/main/MainSearchPage.kt | 310 ++++--- .../ui/newconversation/GroupRecipients.kt | 7 + .../newconversation/NewConversationScreen.kt | 10 +- .../glooboo/umessage/ui/spam/BlockedFilter.kt | 195 ++-- .../umessage/ui/spam/BlockedViewModel.kt | 15 +- .../glooboo/umessage/ui/thread/LinkSafety.kt | 21 +- .../umessage/ui/thread/ThreadAttachments.kt | 34 +- .../umessage/ui/thread/ThreadImages.kt | 4 +- .../umessage/ui/thread/ThreadItemsBuilder.kt | 8 +- .../res/values-fa/strings_triage_nov12.xml | 4 + app/src/main/res/values/strings.xml | 1 + .../umessage/helpers/ExifStripperTest.kt | 16 + .../ConversationsViewModelTest.kt | 21 + .../ui/newconversation/FilterContactsTest.kt | 8 + .../umessage/ui/thread/LinkSafetyTest.kt | 6 + 40 files changed, 1998 insertions(+), 1649 deletions(-) create mode 100644 app/src/main/res/values-fa/strings_triage_nov12.xml diff --git a/app/src/main/kotlin/com/glooboo/umessage/activities/SettingsActivity.kt b/app/src/main/kotlin/com/glooboo/umessage/activities/SettingsActivity.kt index 1a6bfb50..45411bee 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/SettingsActivity.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/SettingsActivity.kt @@ -153,7 +153,12 @@ class SettingsActivity : ComposeSimpleActivity() { private val saveDocument = registerForActivityResult(CreateExportDocument()) { uri -> if (uri != null) { - exportMessagesDialog?.exportMessages(uri) + val dialog = exportMessagesDialog + if (dialog != null) { + dialog.exportMessages(uri) + } else { + toast(org.fossify.commons.R.string.unknown_error_occurred) + } } } @@ -483,7 +488,7 @@ class SettingsActivity : ComposeSimpleActivity() { } private fun pickRestoreFile() = launchOwnPicker { - val types = arrayOf("application/json", "text/plain") + val types = arrayOf("application/json", "text/plain", "application/octet-stream") if (restoreViaDrive) openDriveSettingsBackup.launch(types) else openSettingsBackup.launch(types) restoreViaDrive = false } diff --git a/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt b/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt index 6f647719..b511e1b4 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt @@ -1067,7 +1067,13 @@ open class ThreadActivity : ComposeSimpleActivity() { } ensureBackgroundThread { - if (repository.loadingOlder) return@ensureBackgroundThread + if (repository.loadingOlder) { + // Another page load is running: try again when it is done instead of dropping the jump. + runOnUiThread { + window?.decorView?.postDelayed({ if (!isFinishing) jumpToMessage(target) }, JUMP_RETRY_MS) + } + return@ensureBackgroundThread + } repository.loadingOlder = true isJumpingToMessage = true @@ -1090,7 +1096,11 @@ open class ThreadActivity : ComposeSimpleActivity() { runOnUiThread { publishItems(latestThreadItems) repository.loadingOlder = false - vm.scrollToMessage(target, flash = true) + if (messages.any { it.key == target }) { + vm.scrollToMessage(target, flash = true) + } else { + toast(org.fossify.commons.R.string.unknown_error_occurred) + } isJumpingToMessage = false } } @@ -1199,6 +1209,8 @@ open class ThreadActivity : ComposeSimpleActivity() { } private fun reconcileProviderParticipants(): Boolean { + // A refresh must not overwrite recipients the user is still editing in the people panel. + if (vm.showPeople) return false val providerParticipants = getProviderThreadParticipants() ?: return false val participantsChanged = !recipients.sameAddressesAs(providerParticipants) recipients = providerParticipants @@ -1379,6 +1391,8 @@ open class ThreadActivity : ComposeSimpleActivity() { private fun sendMessage() { // Blank text, or a photo still being shrunk, cannot be sent (TU-04, TU-05). if (!vm.canSend) return + // Recipients edited in the panel are only final after "Done". + if (vm.showPeople) return SendSteps( needsSim = { sim.mustAsk() }, askSim = { onChosen -> @@ -1440,6 +1454,8 @@ open class ThreadActivity : ComposeSimpleActivity() { return } + // The composer clears only after the background save: a second tap meanwhile must not save a second copy. + if (!composerSend.tryStart()) return refreshedSinceSent = false val messageId = vm.scheduledMessageId ?: generateRandomId() val repeat = RepeatRule.fromName(vm.scheduledRepeat) @@ -1472,6 +1488,8 @@ open class ThreadActivity : ComposeSimpleActivity() { showErrorToast( e.localizedMessage ?: getString(org.fossify.commons.R.string.unknown_error_occurred) ) + } finally { + composerSend.finish() } } } @@ -1737,6 +1755,7 @@ open class ThreadActivity : ComposeSimpleActivity() { } companion object { + private const val JUMP_RETRY_MS = 300L /** Boolean extra: open the "Search in conversation" bar (TH-20), for example from Conversation details. */ const val EXTRA_OPEN_SEARCH = "com.glooboo.spamless.extra.OPEN_THREAD_SEARCH" } diff --git a/app/src/main/kotlin/com/glooboo/umessage/activities/VCardViewerActivity.kt b/app/src/main/kotlin/com/glooboo/umessage/activities/VCardViewerActivity.kt index 3ca44ccc..ed51d3ad 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/VCardViewerActivity.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/VCardViewerActivity.kt @@ -17,6 +17,7 @@ import ezvcard.property.Email import ezvcard.property.Telephone import org.fossify.commons.extensions.normalizePhoneNumber import org.fossify.commons.extensions.sendEmailIntent +import org.fossify.commons.extensions.toast /** Shows the contacts of a vCard attachment; the intent extra [EXTRA_VCARD_URI] is unchanged. */ class VCardViewerActivity : ComposeSimpleActivity() { @@ -53,7 +54,11 @@ class VCardViewerActivity : ComposeSimpleActivity() { setDataAndType(vCardUri, mimetype?.lowercase()) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } - startActivity(intent) + try { + startActivity(intent) + } catch (_: android.content.ActivityNotFoundException) { + toast(org.fossify.commons.R.string.system_service_disabled, android.widget.Toast.LENGTH_LONG) + } } private fun handleClick(property: VCardPropertyWrapper) { diff --git a/app/src/main/kotlin/com/glooboo/umessage/dialogs/ImportMessagesDialog.kt b/app/src/main/kotlin/com/glooboo/umessage/dialogs/ImportMessagesDialog.kt index d9cf00d4..6c1e88df 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/dialogs/ImportMessagesDialog.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/dialogs/ImportMessagesDialog.kt @@ -56,7 +56,12 @@ class ImportMessagesDialog( val scope = rememberCoroutineScope() val form = remember { ImportFormState(config.importSms, config.importMms) } LaunchedEffect(Unit) { - form.protectedFile = withContext(Dispatchers.IO) { ImportPasswordCheck.isProtected(activity, uri) } + form.checking = true + try { + form.protectedFile = withContext(Dispatchers.IO) { ImportPasswordCheck.isProtected(activity, uri) } + } finally { + form.checking = false + } } val job by BackupJob.state.collectAsState() val done = (job as? BackupJob.State.ImportDone)?.takeIf { form.started } diff --git a/app/src/main/kotlin/com/glooboo/umessage/extensions/Context.kt b/app/src/main/kotlin/com/glooboo/umessage/extensions/Context.kt index fdb73de8..0fb13941 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/extensions/Context.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/extensions/Context.kt @@ -80,6 +80,7 @@ import com.glooboo.umessage.messaging.ScheduledSendClaims import com.glooboo.umessage.messaging.SmsSender import com.glooboo.umessage.messaging.scheduledActionFor import com.glooboo.umessage.messaging.cancelRemindersForMessage +import com.glooboo.umessage.messaging.cancelRemindersForThread import com.glooboo.umessage.messaging.scheduleMessage import com.glooboo.umessage.models.Attachment import com.glooboo.umessage.models.Conversation @@ -645,6 +646,8 @@ fun Context.getMmsAttachments( filename = "" ) ) + // The SMIL names list every media part in order, pictures and videos included, so these count too. + attachmentCounts[id] = (attachmentCounts[id] ?: 0) + 1 } else if (mimetype != "application/smil") { val count = attachmentCounts[id] ?: 0 val attachmentName = attachmentNames[id]?.getOrNull(count) ?: "" @@ -1009,6 +1012,8 @@ fun Context.deleteConversation(threadId: Long) { contentResolver.delete(uri, selection, selectionArgs) } catch (e: Exception) { showErrorToast(e) + // The messages are still in the provider: wiping the local copy would only bring them back later. + return } uri = Mms.CONTENT_URI @@ -1016,6 +1021,7 @@ fun Context.deleteConversation(threadId: Long) { contentResolver.delete(uri, selection, selectionArgs) } catch (e: Exception) { e.printStackTrace() + return } conversationsDB.deleteThreadId(threadId) @@ -1023,6 +1029,11 @@ fun Context.deleteConversation(threadId: Long) { kotlinx.coroutines.runBlocking { messageNotes.onThreadDeleted(threadId) } messagesDB.deleteThreadMessages(threadId) MessagingCache.participantsCache.remove(threadId) + // Per-conversation leftovers: reminders (and their alarms), the draft, the mute and the hidden mark. + cancelRemindersForThread(threadId) + runCatching { draftsDB.delete(threadId) } + runCatching { com.glooboo.umessage.helpers.MutePrefs.get(this).unmute(threadId) } + runCatching { com.glooboo.umessage.helpers.HiddenChats.get(this).unhide(threadId) } if (config.customNotifications.contains(threadId.toString())) { config.removeCustomNotificationsByThreadId(threadId) @@ -1291,25 +1302,24 @@ fun Context.showReceivedMessageNotification( // The chat may have been opened and marked read between the delivery and this post; a notification posted // now would outlive the cancel that came first and keep the chat looking unread. The database is read off the // main thread, where Room refuses queries. + // The whole post (smart replies, avatar, shortcut, notify) runs on this background thread; none of it needs main. ensureBackgroundThread { val alreadyRead = isMessageSavedAsRead(messageId, isMms) - Handler(Looper.getMainLooper()).post { - if (alreadyRead) { - notificationManager.cancel(threadId.hashCode()) - return@post - } - notificationHelper.showMessageNotification( - messageId = messageId, - isMms = isMms, - address = address, - body = body, - threadId = threadId, - bitmap = bitmap, - sender = senderName, - subscriptionId = subscriptionId, - notify = notify, - ) + if (alreadyRead) { + notificationManager.cancel(threadId.hashCode()) + return@ensureBackgroundThread } + notificationHelper.showMessageNotification( + messageId = messageId, + isMms = isMms, + address = address, + body = body, + threadId = threadId, + bitmap = bitmap, + sender = senderName, + subscriptionId = subscriptionId, + notify = notify, + ) } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/helpers/AudioPlayerManager.kt b/app/src/main/kotlin/com/glooboo/umessage/helpers/AudioPlayerManager.kt index 2f90ac03..566ac5cc 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/helpers/AudioPlayerManager.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/helpers/AudioPlayerManager.kt @@ -16,6 +16,7 @@ import android.os.Looper import androidx.core.content.ContextCompat import org.fossify.commons.helpers.ensureBackgroundThread +@Suppress("TooManyFunctions") object AudioPlayerManager { private const val PROGRESS_INTERVAL_MS = 200L @@ -34,6 +35,8 @@ object AudioPlayerManager { private var noisyReceiverContext: Application? = null private var isPreparing = false private var pendingSeekPositionMs = 0 + /** Set when a short focus loss (a call, a notification sound) paused playback; the focus gain resumes it. */ + private var resumeOnGain = false private val handler = Handler(Looper.getMainLooper()) private val audioAttributes = AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_MEDIA) @@ -43,9 +46,13 @@ object AudioPlayerManager { .setWillPauseWhenDucked(true) .setOnAudioFocusChangeListener({ focusChange -> when (focusChange) { - AudioManager.AUDIOFOCUS_LOSS, + AudioManager.AUDIOFOCUS_LOSS -> { + resumeOnGain = false + pause() + } AudioManager.AUDIOFOCUS_LOSS_TRANSIENT, - AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> pause() + AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> pauseForTransientLoss() + AudioManager.AUDIOFOCUS_GAIN -> resumeAfterTransientLoss() } }, handler) .build() @@ -130,6 +137,7 @@ object AudioPlayerManager { mediaPlayer = null currentUri = null isPreparing = false + resumeOnGain = false pendingSeekPositionMs = 0 player?.release() noisyReceiverContext?.unregisterReceiver(noisyReceiver) @@ -193,6 +201,7 @@ object AudioPlayerManager { } private fun startPlayback(context: Context) { + resumeOnGain = false if (audioManager?.requestAudioFocus(focusRequest) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { playbackFailed() return @@ -215,7 +224,41 @@ object AudioPlayerManager { } } + /** Pauses for a short focus loss but keeps the focus request, so the gain callback can resume. */ + private fun pauseForTransientLoss() { + val player = mediaPlayer ?: return + if (isPreparing) { + release() + return + } + try { + if (!player.isPlaying) return + player.pause() + resumeOnGain = true + handler.removeCallbacks(progressRunnable) + currentListeners.forEach { it.onPlaybackStateChanged(false) } + } catch (_: IllegalStateException) { + playbackFailed() + } + } + + private fun resumeAfterTransientLoss() { + if (!resumeOnGain) return + resumeOnGain = false + val player = mediaPlayer ?: return + if (isPreparing) return + try { + player.start() + currentListeners.forEach { it.onPlaybackStateChanged(true) } + handler.removeCallbacks(progressRunnable) + if (currentListeners.isNotEmpty()) handler.post(progressRunnable) + } catch (_: IllegalStateException) { + playbackFailed() + } + } + private fun pause() { + resumeOnGain = false if (isPreparing) { release() return diff --git a/app/src/main/kotlin/com/glooboo/umessage/helpers/BackupCrypto.kt b/app/src/main/kotlin/com/glooboo/umessage/helpers/BackupCrypto.kt index 4e8906a3..cbb5781f 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/helpers/BackupCrypto.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/helpers/BackupCrypto.kt @@ -31,7 +31,7 @@ object BackupCrypto { /** The file is not a protected export, or it is cut short or changed. */ class DamagedFileException(message: String) : IOException(message) - const val ITERATIONS = 200_000 + const val ITERATIONS = 600_000 const val CHUNK_SIZE = 64 * 1024 /** `UMSGENC1`: key from the plain password. `UMSGENC2` (written now): key from the folded password (I8). */ diff --git a/app/src/main/kotlin/com/glooboo/umessage/helpers/Constants.kt b/app/src/main/kotlin/com/glooboo/umessage/helpers/Constants.kt index 910fe158..8a2b48d6 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/helpers/Constants.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/helpers/Constants.kt @@ -25,6 +25,7 @@ const val DEFAULT_SIM_ID = "default_sim_id" const val DEFAULT_SIM_PHONE = -2 const val DEFAULT_SIM_ASK = -3 const val NOTIFICATION_CHANNEL_ID = "fossify_messages" +const val FAILED_SEND_CHANNEL_ID = "umessage_failed_send" const val SHOW_CHARACTER_COUNTER = "show_character_counter" const val USE_SIMPLE_CHARACTERS = "use_simple_characters" const val SEND_ON_ENTER = "send_on_enter" diff --git a/app/src/main/kotlin/com/glooboo/umessage/helpers/ExifStripper.kt b/app/src/main/kotlin/com/glooboo/umessage/helpers/ExifStripper.kt index 4b8ead0a..a4c6825b 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/helpers/ExifStripper.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/helpers/ExifStripper.kt @@ -61,13 +61,31 @@ object ExifStripper { false } - /** Clears the tags of the JPEG [file] in place. False when it is no JPEG or could not be saved (left as it was). */ + /** + * Clears the tags of the JPEG [file] in place. The Exif block (with its embedded thumbnail), XMP, IPTC and + * comments are dropped; only the orientation is written back. False when it is no JPEG or could not be saved + * (left as it was). + */ fun strip(file: File): Boolean { if (!isJpeg(file)) return false return try { - val exif = ExifInterface(file.absolutePath) - CLEARED_TAGS.forEach { exif.setAttribute(it, null) } - exif.saveAttributes() + val orientation = ExifInterface(file.absolutePath) + .getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED) + val rewritten = dropMetadataSegments(file) + if (rewritten) { + if (orientation != ExifInterface.ORIENTATION_UNDEFINED && + orientation != ExifInterface.ORIENTATION_NORMAL + ) { + val exif = ExifInterface(file.absolutePath) + exif.setAttribute(ExifInterface.TAG_ORIENTATION, orientation.toString()) + exif.saveAttributes() + } + } else { + // Unusual layout: clear the listed tags in place instead. + val exif = ExifInterface(file.absolutePath) + CLEARED_TAGS.forEach { exif.setAttribute(it, null) } + exif.saveAttributes() + } true } catch (_: IOException) { false @@ -75,4 +93,54 @@ object ExifStripper { false } } + + private const val MIN_JPEG_SIZE = 4 + private const val SOI_LENGTH = 2 + private const val SEGMENT_HEADER = 4 + private const val LENGTH_FIELD = 2 + private const val BYTE_MASK = 0xFF + private const val LENGTH_HIGH = 2 + private const val LENGTH_LOW = 3 + private const val MARKER_PREFIX = 0xFF + private const val MARKER_SOS = 0xDA + private const val MARKER_APP1 = 0xE1 + private const val MARKER_APP13 = 0xED + private const val MARKER_COMMENT = 0xFE + + /** + * Copies [file] without its Exif/XMP (APP1), IPTC (APP13) and comment segments. False, with [file] untouched, + * when the markers do not parse. + */ + internal fun dropMetadataSegments(file: File): Boolean { + val result = withoutMetadata(file.readBytes()) ?: return false + file.writeBytes(result) + return true + } + + private fun withoutMetadata(bytes: ByteArray): ByteArray? { + if (bytes.size < MIN_JPEG_SIZE) return null + val out = java.io.ByteArrayOutputStream(bytes.size) + out.write(bytes, 0, SOI_LENGTH) // SOI + var i = SOI_LENGTH + while (i + SEGMENT_HEADER <= bytes.size) { + if (bytes[i] != MARKER_PREFIX.toByte()) return null + val marker = bytes[i + 1].toInt() and BYTE_MASK + if (marker == MARKER_PREFIX) { i++; continue } // fill byte + if (marker == MARKER_SOS) { // start of scan: the rest is picture data + out.write(bytes, i, bytes.size - i) + return out.toByteArray() + } + val length = segmentLength(bytes, i) + val end = i + LENGTH_FIELD + length + if (length < LENGTH_FIELD || end > bytes.size) return null + val drop = marker == MARKER_APP1 || marker == MARKER_APP13 || marker == MARKER_COMMENT + if (!drop) out.write(bytes, i, end - i) + i = end + } + return null + } + + private fun segmentLength(bytes: ByteArray, at: Int): Int = + ((bytes[at + LENGTH_HIGH].toInt() and BYTE_MASK) shl Byte.SIZE_BITS) or + (bytes[at + LENGTH_LOW].toInt() and BYTE_MASK) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/helpers/NotificationHelper.kt b/app/src/main/kotlin/com/glooboo/umessage/helpers/NotificationHelper.kt index 9191ddb2..d89d159d 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/helpers/NotificationHelper.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/helpers/NotificationHelper.kt @@ -376,7 +376,7 @@ class NotificationHelper(private val context: Context) { val hasCustomNotifications = context.config.customNotifications.contains(threadId.toString()) val notificationChannelId = - if (hasCustomNotifications) threadId.toString() else NOTIFICATION_CHANNEL_ID + if (hasCustomNotifications) threadId.toString() else FAILED_SEND_CHANNEL_ID if (!hasCustomNotifications) { createChannel(notificationChannelId, context.getString(R.string.message_not_sent_short)) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/interfaces/MessageRemindersDao.kt b/app/src/main/kotlin/com/glooboo/umessage/interfaces/MessageRemindersDao.kt index 8931b1fb..95034d4a 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/interfaces/MessageRemindersDao.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/interfaces/MessageRemindersDao.kt @@ -24,6 +24,9 @@ interface MessageRemindersDao { @Query("SELECT * FROM message_reminders WHERE message_id = :messageId AND is_mms = :isMMS") suspend fun getForMessage(messageId: Long, isMMS: Boolean): List + @Query("SELECT * FROM message_reminders WHERE thread_id = :threadId") + suspend fun getForThread(threadId: Long): List + @Query("DELETE FROM message_reminders WHERE id = :id") suspend fun delete(id: Long): Int diff --git a/app/src/main/kotlin/com/glooboo/umessage/messaging/MessageReminders.kt b/app/src/main/kotlin/com/glooboo/umessage/messaging/MessageReminders.kt index 5d0fe09a..0524a3c2 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/messaging/MessageReminders.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/messaging/MessageReminders.kt @@ -105,6 +105,14 @@ fun Context.cancelRemindersForMessage(key: MessageKey) { } } +/** A deleted conversation takes the reminders of its messages with it, alarms included. */ +fun Context.cancelRemindersForThread(threadId: Long) { + runCatching { + val dao = getMessagesDB().MessageRemindersDao() + runBlocking { dao.getForThread(threadId) }.forEach { cancelReminder(it.id) } + } +} + /** * Sets the alarm of every saved reminder again: after boot, a package update, a time change, a change of the * "Alarms & reminders" access and on app start. A reminder whose time passed meanwhile fires at once; it is deleted diff --git a/app/src/main/kotlin/com/glooboo/umessage/receivers/DirectReplyReceiver.kt b/app/src/main/kotlin/com/glooboo/umessage/receivers/DirectReplyReceiver.kt index fb64a01b..dd7821ae 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/receivers/DirectReplyReceiver.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/receivers/DirectReplyReceiver.kt @@ -5,8 +5,6 @@ import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.pm.PackageManager -import android.os.Handler -import android.os.Looper import android.telephony.SmsManager import androidx.core.app.RemoteInput import androidx.core.content.ContextCompat @@ -80,23 +78,26 @@ class DirectReplyReceiver : BroadcastReceiver() { runCatching { context.notifySendFailedInBackground(recipients, threadId) } } + // A failed reply keeps the failure notification only: re-posting the typed text as a received message + // would hide it, and the chat was not read. + if (failed) return + val photoUri = SimpleContactsHelper(context).getPhotoUriFromPhoneNumber(address) val bitmap = context.getNotificationBitmap(photoUri) - Handler(Looper.getMainLooper()).post { - context.notificationHelper.showMessageNotification( - messageId = messageId, - isMms = false, - address = address, - body = body, - threadId = threadId, - bitmap = bitmap, - sender = null, - alertOnlyOnce = true, - // A group keeps its group look after a reply (I19). - notify = NotifyContext(isGroup = recipients.size > 1), - offerSmartReplies = false - ) - } + // Already on a background thread (runInBackground); the notification work does not need the main thread. + context.notificationHelper.showMessageNotification( + messageId = messageId, + isMms = false, + address = address, + body = body, + threadId = threadId, + bitmap = bitmap, + sender = null, + alertOnlyOnce = true, + // A group keeps its group look after a reply (I19). + notify = NotifyContext(isGroup = recipients.size > 1), + offerSmartReplies = false + ) context.markThreadMessagesRead(threadId) context.conversationsDB.markRead(threadId) diff --git a/app/src/main/kotlin/com/glooboo/umessage/receivers/MmsPushReceiver.kt b/app/src/main/kotlin/com/glooboo/umessage/receivers/MmsPushReceiver.kt index d00bb2df..facdee2a 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/receivers/MmsPushReceiver.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/receivers/MmsPushReceiver.kt @@ -1,139 +1,142 @@ -package com.glooboo.umessage.receivers - -import android.content.BroadcastReceiver -import android.content.Context -import android.content.Intent -import android.util.Log -import com.android.mms.transaction.PushReceiver -import org.fossify.commons.helpers.ensureBackgroundThread -import com.glooboo.umessage.spam.MmsMedia -import com.glooboo.umessage.spam.mms.BlockedMmsDownloader -import com.glooboo.umessage.spam.mms.MmsPushAction -import com.glooboo.umessage.spam.mms.MmsPushGate -import com.glooboo.umessage.spam.engine.SpamEngine -import java.lang.reflect.Modifier -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.ExecutorService -import java.util.concurrent.TimeUnit - -/** - * Replaces mmslib's PushReceiver in the manifest. Looks at the WAP push (notification-ind) before anything is - * downloaded: if the sender is blocked, nothing reaches the system inbox. A placeholder lands in the Blocked folder - * and the MMS is downloaded into uMessage's private storage only ([BlockedMmsDownloader]), so it can be rescued. - * Everything else is handed unchanged to the library's own PushReceiver, so allowed MMS behave exactly as before. - */ -class MmsPushReceiver : BroadcastReceiver() { - - override fun onReceive(context: Context, intent: Intent) { - val pending = goAsync() - val appContext = context.applicationContext - try { - ensureBackgroundThread { - try { - process(appContext, intent) - } finally { - runCatching { pending.finish() } - } - } - } catch (t: Throwable) { - // Could not even start the worker: fall back to the stock behaviour right now. - delegate(appContext, intent) - runCatching { pending.finish() } - } - } - - internal fun process(context: Context, intent: Intent) { - val action = try { - val subscriptionId = intent.receivingSubscriptionId() - MmsPushGate.decide( - pushData = intent.getByteArrayExtra(EXTRA_DATA), - subscriptionId = subscriptionId, - now = System.currentTimeMillis(), - ) { probe -> - // MmsReceiver's content filter runs after download without the SIM; remember it per sender. - MmsSubscriptions.remember(probe.address, subscriptionId) - SpamEngine.evaluate(context, probe, source = "MMS_PUSH") - } - } catch (t: Throwable) { - MmsPushAction.Deliver("gate error") - } - - if (action is MmsPushAction.Block) { - if (alreadyHandled(action.transactionId) || storeAndDownload(context, action)) return - } - delegate(context, intent) - awaitLibraryPushTask() - } - - /** - * Stores the placeholder in Blocked and starts downloading the MMS into uMessage's private storage, so "Not spam" - * can restore it with its pictures later (SE-29). False when even the placeholder could not be stored; the - * caller then delivers the MMS normally (never lose a message). - */ - private fun storeAndDownload(context: Context, action: MmsPushAction.Block): Boolean { - val downloadable = action.contentLocation.isNotEmpty() - val id = SpamEngine.storeBlockedId( - context, action.placeholder, action.decision, - media = if (downloadable) MmsMedia.DOWNLOADING else MmsMedia.MISSING, - ) ?: return false - if (downloadable) { - try { - BlockedMmsDownloader.start(context, id, action.contentLocation, action.placeholder.subscriptionId) - } catch (t: Throwable) { - Log.w(MmsReceiver.TAG, "Blocked MMS download did not start", t) - SpamEngine.attachDownloadedMedia(context, id, null, null) - } - } - return true - } - - private fun delegate(context: Context, intent: Intent) { - try { - PushReceiver().onReceive(context, intent) - } catch (_: Throwable) { - } - } - - /** - * mmslib's PushReceiver only queues its ReceivePushTask (persist the notification-ind, start the download) on - * its own single-thread executor and returns, without a PendingResult. Finishing our broadcast right away would - * let the process be killed before the notification-ind is written, losing the MMS. A no-op queued behind the - * task on the same executor finishes only after the task has run, so wait for it (bounded, well inside the - * broadcast timeout) before the caller finishes the broadcast. If the executor can't be found (library change, - * R8), this returns at once, which is the old behaviour. - */ - private fun awaitLibraryPushTask() { - try { - val executor = libraryExecutor ?: return - executor.submit {}.get(LIBRARY_TASK_TIMEOUT_MS, TimeUnit.MILLISECONDS) - } catch (_: Throwable) { - } - } - - /** The carrier re-sends the same notification-ind; store only the first one within a short time. */ - private fun alreadyHandled(transactionId: String): Boolean { - if (transactionId.isEmpty()) return false - val now = System.currentTimeMillis() - seen.entries.removeAll { now - it.value > SEEN_TTL_MS } - return seen.putIfAbsent(transactionId, now) != null - } - - private companion object { - const val EXTRA_DATA = "data" - const val SEEN_TTL_MS = 10 * 60 * 1000L - const val LIBRARY_TASK_TIMEOUT_MS = 20_000L - val seen = ConcurrentHashMap() - - /** PushReceiver's private static PUSH_RECEIVER_EXECUTOR, found by type so field renaming doesn't matter. */ - val libraryExecutor: ExecutorService? by lazy { - runCatching { - PushReceiver::class.java.declaredFields - .firstOrNull { - Modifier.isStatic(it.modifiers) && ExecutorService::class.java.isAssignableFrom(it.type) - } - ?.apply { isAccessible = true } - ?.get(null) as? ExecutorService - }.getOrNull() - } - } -} +package com.glooboo.umessage.receivers + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.util.Log +import com.android.mms.transaction.PushReceiver +import org.fossify.commons.helpers.ensureBackgroundThread +import com.glooboo.umessage.spam.MmsMedia +import com.glooboo.umessage.spam.mms.BlockedMmsDownloader +import com.glooboo.umessage.spam.mms.MmsPushAction +import com.glooboo.umessage.spam.mms.MmsPushGate +import com.glooboo.umessage.spam.engine.SpamEngine +import java.lang.reflect.Modifier +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.ExecutorService +import java.util.concurrent.TimeUnit + +/** + * Replaces mmslib's PushReceiver in the manifest. Looks at the WAP push (notification-ind) before anything is + * downloaded: if the sender is blocked, nothing reaches the system inbox. A placeholder lands in the Blocked folder + * and the MMS is downloaded into uMessage's private storage only ([BlockedMmsDownloader]), so it can be rescued. + * Everything else is handed unchanged to the library's own PushReceiver, so allowed MMS behave exactly as before. + */ +class MmsPushReceiver : BroadcastReceiver() { + + override fun onReceive(context: Context, intent: Intent) { + val pending = goAsync() + val appContext = context.applicationContext + try { + ensureBackgroundThread { + try { + process(appContext, intent) + } finally { + runCatching { pending.finish() } + } + } + } catch (t: Throwable) { + // Could not even start the worker: fall back to the stock behaviour right now. + delegate(appContext, intent) + runCatching { pending.finish() } + } + } + + internal fun process(context: Context, intent: Intent) { + val action = try { + val subscriptionId = intent.receivingSubscriptionId() + MmsPushGate.decide( + pushData = intent.getByteArrayExtra(EXTRA_DATA), + subscriptionId = subscriptionId, + now = System.currentTimeMillis(), + ) { probe -> + // MmsReceiver's content filter runs after download without the SIM; remember it per sender. + MmsSubscriptions.remember(probe.address, subscriptionId) + SpamEngine.evaluate(context, probe, source = "MMS_PUSH") + } + } catch (t: Throwable) { + MmsPushAction.Deliver("gate error") + } + + if (action is MmsPushAction.Block) { + if (alreadyHandled(action.transactionId) || storeAndDownload(context, action)) return + } + delegate(context, intent) + awaitLibraryPushTask() + } + + /** + * Stores the placeholder in Blocked and starts downloading the MMS into uMessage's private storage, so "Not spam" + * can restore it with its pictures later (SE-29). False when even the placeholder could not be stored; the + * caller then delivers the MMS normally (never lose a message). + */ + private fun storeAndDownload(context: Context, action: MmsPushAction.Block): Boolean { + val downloadable = action.contentLocation.isNotEmpty() + var duplicate = false + val id = SpamEngine.storeBlockedId( + context, action.placeholder, action.decision, + media = if (downloadable) MmsMedia.DOWNLOADING else MmsMedia.MISSING, + onDuplicate = { duplicate = true }, + ) ?: return false + // A second push for the same MMS reuses the first row; a second download would overwrite the first one's media. + if (downloadable && !duplicate) { + try { + BlockedMmsDownloader.start(context, id, action.contentLocation, action.placeholder.subscriptionId) + } catch (t: Throwable) { + Log.w(MmsReceiver.TAG, "Blocked MMS download did not start", t) + SpamEngine.attachDownloadedMedia(context, id, null, null) + } + } + return true + } + + private fun delegate(context: Context, intent: Intent) { + try { + PushReceiver().onReceive(context, intent) + } catch (_: Throwable) { + } + } + + /** + * mmslib's PushReceiver only queues its ReceivePushTask (persist the notification-ind, start the download) on + * its own single-thread executor and returns, without a PendingResult. Finishing our broadcast right away would + * let the process be killed before the notification-ind is written, losing the MMS. A no-op queued behind the + * task on the same executor finishes only after the task has run, so wait for it (bounded, well inside the + * broadcast timeout) before the caller finishes the broadcast. If the executor can't be found (library change, + * R8), this returns at once, which is the old behaviour. + */ + private fun awaitLibraryPushTask() { + try { + val executor = libraryExecutor ?: return + executor.submit {}.get(LIBRARY_TASK_TIMEOUT_MS, TimeUnit.MILLISECONDS) + } catch (_: Throwable) { + } + } + + /** The carrier re-sends the same notification-ind; store only the first one within a short time. */ + private fun alreadyHandled(transactionId: String): Boolean { + if (transactionId.isEmpty()) return false + val now = System.currentTimeMillis() + seen.entries.removeAll { now - it.value > SEEN_TTL_MS } + return seen.putIfAbsent(transactionId, now) != null + } + + private companion object { + const val EXTRA_DATA = "data" + const val SEEN_TTL_MS = 10 * 60 * 1000L + const val LIBRARY_TASK_TIMEOUT_MS = 20_000L + val seen = ConcurrentHashMap() + + /** PushReceiver's private static PUSH_RECEIVER_EXECUTOR, found by type so field renaming doesn't matter. */ + val libraryExecutor: ExecutorService? by lazy { + runCatching { + PushReceiver::class.java.declaredFields + .firstOrNull { + Modifier.isStatic(it.modifiers) && ExecutorService::class.java.isAssignableFrom(it.type) + } + ?.apply { isAccessible = true } + ?.get(null) as? ExecutorService + }.getOrNull() + } + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/SpamContracts.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/SpamContracts.kt index e6b798c7..50746b59 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/SpamContracts.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/SpamContracts.kt @@ -1,262 +1,265 @@ -package com.glooboo.umessage.spam - -import kotlinx.coroutines.flow.Flow - -/** - * Public contract of the uMessage spam engine. - * Frozen interface: implementations live in `spam/engine` and `spam/data`, - * UI code under the ui package depends only on this file. - */ - -enum class UnknownSenderMode { STRICT, SMART, OFF } - -/** I03: how a message from an unknown sender that reached the inbox is announced. Codes are never affected. */ -enum class UnknownInboxNotify { NOTIFY, SILENT, NONE } - -enum class ListKind { ALLOW, BLOCK } - -enum class RuleType { - /** Exact number, compared after normalization. */ - NUMBER, - - /** Normalized number starts with pattern. */ - PREFIX, - - /** Alphanumeric sender id, e.g. "VM-HDFCBK", case-insensitive exact match. */ - SENDER_ID, - - /** Case-insensitive substring of the message body. */ - KEYWORD, - - /** Java regex matched against the message body. */ - REGEX, -} - -/** SIM scope of a rule. [subscriptionId] == null means both SIMs. */ -data class SpamRule( - val id: Long = 0, - val kind: ListKind, - val type: RuleType, - val pattern: String, - val subscriptionId: Int? = null, - val note: String = "", - val createdAt: Long = System.currentTimeMillis(), -) - -data class IncomingMessage( - val address: String, - val body: String, - val subscriptionId: Int, - val isMms: Boolean = false, - val receivedAt: Long = System.currentTimeMillis(), -) - -enum class DecisionReason { - ALLOW_RULE, BLOCK_RULE, CONTACT, OTP_EXEMPTION, UNKNOWN_SENDER, MODE_OFF, NO_MATCH, - - /** - * Allowed because contacts cannot be read (READ_CONTACTS missing, a provider error, or the sent-message history - * could not be read), so the filter cannot tell a known number from an unknown one. Unknown-sender blocking is - * skipped for phone numbers instead of blocking everyone. - */ - CONTACTS_UNAVAILABLE, - - /** Allowed because the user has sent a message to this number before, so it is known like a contact. */ - KNOWN_CONVERSATION, - - /** I24: held because the sender's number is from outside the home country chosen in the settings. */ - FOREIGN_NUMBER, -} - -sealed interface FilterDecision { - val reason: DecisionReason - /** [ruleId] names the allow rule that let it through (SE-39); null for every other reason. */ - data class Allow(override val reason: DecisionReason, val ruleId: Long? = null) : FilterDecision - data class Block(override val reason: DecisionReason, val ruleId: Long? = null) : FilterDecision -} - -/** Body stored for an MMS that was blocked before its text could be read (it was never downloaded). */ -const val MMS_PLACEHOLDER_BODY = "MMS blocked" - -/** - * What uMessage holds of a blocked MMS's content (pictures, audio, text parts). Always [NONE] for an SMS. - * Kept content is the whole downloaded MMS (its PDU) in app-private storage, so "Not spam" can put it in the inbox. - */ -enum class MmsMedia { - /** An SMS. */ - NONE, - - /** uMessage started downloading the MMS when it blocked it; the result has not arrived yet. */ - DOWNLOADING, - - /** The downloaded MMS is kept; "Not spam" restores it with its pictures. */ - STORED, - - /** The MMS content is not kept: the download failed, the carrier expired it, or an older build blocked it. */ - MISSING, -} - -/** What a "Not spam" restore of one blocked message did. */ -enum class RestoreOutcome { - /** Everything is in the inbox: an SMS, or an MMS with its pictures. */ - RESTORED, - - /** An MMS whose text is in the inbox (as an SMS), but whose pictures could not be recovered. */ - TEXT_ONLY, - - /** An MMS without text whose content could not be recovered. Nothing was put in the inbox. */ - NOTHING, - - /** The kept MMS could not be put in the inbox. It is still in Blocked; nothing was lost. */ - FAILED, - - /** No such blocked message (already restored or deleted). */ - NOT_FOUND, -} - -/** - * What [SpamRepository.restore] did with one blocked message, kept so [SpamRepository.undoRestore] can take it back. - * [message] is the blocked row as it was (null when there was none). The other fields are the data layer's own - * references, 0 when unknown: [inboxId] the system SMS or MMS row it became, [pendingId] the pending_sms row still - * waiting to be delivered (the inbox insert failed and will be replayed), [eventId] the "restored" statistics event. - */ -data class RestoreReceipt( - val message: BlockedMessage?, - val outcome: RestoreOutcome, - val inboxId: Long = 0, - val pendingId: Long = 0, - val eventId: Long = 0, -) - -/** A message held back by the filter. Never written to the system SMS provider until restored. */ -data class BlockedMessage( - val id: Long = 0, - val address: String, - val body: String, - val subscriptionId: Int, - val isMms: Boolean, - val receivedAt: Long, - val reason: DecisionReason, - val ruleId: Long? = null, - val media: MmsMedia = if (isMms) MmsMedia.MISSING else MmsMedia.NONE, - /** Name of the kept MMS in app-private storage, set when [media] is [MmsMedia.STORED]. */ - val mediaFile: String? = null, - /** Not opened yet: the sender's row on the Blocked tab shows it bold, as an unread chat. Added in version 6. */ - val unread: Boolean = false, -) { - /** The message has readable text (an MMS blocked before it was downloaded only has the placeholder). */ - val hasText: Boolean - get() = body.isNotBlank() && body != MMS_PLACEHOLDER_BODY - - /** The whole MMS, pictures included, is kept and can be restored. */ - val hasStoredMedia: Boolean - get() = isMms && media == MmsMedia.STORED && !mediaFile.isNullOrBlank() - - /** - * False for an MMS of which nothing was kept: "Not spam" then puts nothing in the inbox. An MMS whose - * pictures are lost but whose text is known restores that text (as an SMS). - */ - val canRestoreContent: Boolean - get() = !isMms || hasStoredMedia || hasText - - /** What "Not spam" is expected to do with this message (it can still turn out [RestoreOutcome.FAILED]). */ - val expectedRestore: RestoreOutcome - get() = when { - !isMms || hasStoredMedia -> RestoreOutcome.RESTORED - hasText -> RestoreOutcome.TEXT_ONLY - else -> RestoreOutcome.NOTHING - } - - /** [media] as the UI should show it: a download that has not answered in [DOWNLOAD_TIMEOUT_MS] has failed. */ - fun mediaAt(now: Long): MmsMedia = - if (media == MmsMedia.DOWNLOADING && now - receivedAt > DOWNLOAD_TIMEOUT_MS) MmsMedia.MISSING else media - - companion object { - const val DOWNLOAD_TIMEOUT_MS = 15 * 60 * 1000L - } -} - -data class SpamStats(val blockedTotal: Int, val blockedLast7Days: Int, val restoredTotal: Int) - -data class SpamSettings( - val mode: UnknownSenderMode = UnknownSenderMode.SMART, - /** Blocked messages older than this are purged. 0 = keep forever. */ - val purgeAfterDays: Int = 30, - val notifyOnBlock: Boolean = false, - val unknownInboxNotify: UnknownInboxNotify = UnknownInboxNotify.NOTIFY, - /** I67: an "Open link" button on notifications from known senders. */ - val openLinkAction: Boolean = false, - /** I24: ISO region (e.g. "GB") of the home country; numbers from other countries are held. Blank = off. */ - val blockOutsideRegion: String = "", -) - -/** Pure decision logic. No Android I/O except contact lookup supplied by the implementation. */ -interface SpamFilter { - /** Blocking call; run off the main thread. */ - fun evaluate(message: IncomingMessage): FilterDecision -} - -interface SpamRepository { - val blocked: Flow> - val rules: Flow> - val settings: Flow - val stats: Flow - - /** Throws IllegalArgumentException for a REGEX rule that [RegexGuard.validate] rejects. */ - suspend fun addRule(rule: SpamRule): Long - - /** - * Changes the stored rule [SpamRule.id] in place: its id (which blocked messages refer to) and creation time are - * kept. Returns [SpamRule.id], or the id of another rule that already holds the new value, in which case nothing - * is changed. Throws IllegalArgumentException for a REGEX rule that [RegexGuard.validate] rejects and - * NoSuchElementException when the rule no longer exists. - */ - suspend fun updateRule(rule: SpamRule): Long - suspend fun removeRule(id: Long) - - /** Removes several rules at once. */ - suspend fun removeRules(ids: List) = ids.forEach { removeRule(it) } - - /** - * Undo of a delete: puts [rules] back with their old ids where possible, so the reason chips of blocked messages - * point at them again. A rule whose value was added again in the meantime is skipped. - */ - suspend fun restoreRules(rules: List) = rules.forEach { runCatching { addRule(it.copy(id = 0)) } } - suspend fun updateSettings(transform: (SpamSettings) -> SpamSettings) - - /** Stores a blocked message (called by receivers). */ - suspend fun storeBlocked(message: BlockedMessage): Long - - /** - * Inserts the message into the system inbox and shows it. Rules are not changed: the sender is not - * whitelisted (that is a separate "Always allow" choice). Idempotent: a second call for the same id does - * nothing ([RestoreOutcome.NOT_FOUND]). A kept MMS goes back with its pictures. Of an MMS whose content was not - * kept only its text (if any) is restored; the outcome says so, so the UI never claims a picture came back. - */ - suspend fun markNotSpam(blockedId: Long): RestoreOutcome - - /** - * [markNotSpam] that can still be undone: the message is in the inbox when this returns, but a kept MMS's files - * stay until [finishRestore], so [undoRestore] can put it back in Blocked whole. Call [finishRestore] once undo is - * no longer offered; when the process dies first, the files are swept with the other unreferenced ones. - */ - suspend fun restore(blockedId: Long): RestoreReceipt = RestoreReceipt(null, markNotSpam(blockedId)) - - /** - * Undo of [restore]: takes the message out of the system inbox and puts it back in Blocked as it was (same id, - * text, sender, time, SIM, reason and kept files), and takes back the "restored" count. Returns false when it - * could not be undone; the message then stays in the inbox, so nothing is lost. - */ - suspend fun undoRestore(receipt: RestoreReceipt): Boolean = false - - /** Ends the undo window of [restore]: the kept MMS files the inbox copy no longer needs are deleted. */ - suspend fun finishRestore(receipt: RestoreReceipt) = Unit - - /** Adds a BLOCK rule for the sender and removes their allow rules. Their blocked messages are kept. */ - suspend fun blockSender(blockedId: Long) - - /** Marks held messages read (the sender's thread was opened), so their row on the Blocked tab is no longer bold. */ - suspend fun markBlockedRead(ids: List) = Unit - suspend fun deleteBlocked(ids: List) - suspend fun purgeExpired() -} +package com.glooboo.umessage.spam + +import kotlinx.coroutines.flow.Flow + +/** + * Public contract of the uMessage spam engine. + * Frozen interface: implementations live in `spam/engine` and `spam/data`, + * UI code under the ui package depends only on this file. + */ + +enum class UnknownSenderMode { STRICT, SMART, OFF } + +/** I03: how a message from an unknown sender that reached the inbox is announced. Codes are never affected. */ +enum class UnknownInboxNotify { NOTIFY, SILENT, NONE } + +enum class ListKind { ALLOW, BLOCK } + +enum class RuleType { + /** Exact number, compared after normalization. */ + NUMBER, + + /** Normalized number starts with pattern. */ + PREFIX, + + /** Alphanumeric sender id, e.g. "VM-HDFCBK", case-insensitive exact match. */ + SENDER_ID, + + /** Case-insensitive substring of the message body. */ + KEYWORD, + + /** Java regex matched against the message body. */ + REGEX, +} + +/** SIM scope of a rule. [subscriptionId] == null means both SIMs. */ +data class SpamRule( + val id: Long = 0, + val kind: ListKind, + val type: RuleType, + val pattern: String, + val subscriptionId: Int? = null, + val note: String = "", + val createdAt: Long = System.currentTimeMillis(), +) + +data class IncomingMessage( + val address: String, + val body: String, + val subscriptionId: Int, + val isMms: Boolean = false, + val receivedAt: Long = System.currentTimeMillis(), +) + +enum class DecisionReason { + ALLOW_RULE, BLOCK_RULE, CONTACT, OTP_EXEMPTION, UNKNOWN_SENDER, MODE_OFF, NO_MATCH, + + /** + * Allowed because contacts cannot be read (READ_CONTACTS missing, a provider error, or the sent-message history + * could not be read), so the filter cannot tell a known number from an unknown one. Unknown-sender blocking is + * skipped for phone numbers instead of blocking everyone. + */ + CONTACTS_UNAVAILABLE, + + /** Allowed because the user has sent a message to this number before, so it is known like a contact. */ + KNOWN_CONVERSATION, + + /** I24: held because the sender's number is from outside the home country chosen in the settings. */ + FOREIGN_NUMBER, +} + +sealed interface FilterDecision { + val reason: DecisionReason + /** [ruleId] names the allow rule that let it through (SE-39); null for every other reason. */ + data class Allow(override val reason: DecisionReason, val ruleId: Long? = null) : FilterDecision + data class Block(override val reason: DecisionReason, val ruleId: Long? = null) : FilterDecision +} + +/** Body stored for an MMS that was blocked before its text could be read (it was never downloaded). */ +const val MMS_PLACEHOLDER_BODY = "MMS blocked" + +/** + * What uMessage holds of a blocked MMS's content (pictures, audio, text parts). Always [NONE] for an SMS. + * Kept content is the whole downloaded MMS (its PDU) in app-private storage, so "Not spam" can put it in the inbox. + */ +enum class MmsMedia { + /** An SMS. */ + NONE, + + /** uMessage started downloading the MMS when it blocked it; the result has not arrived yet. */ + DOWNLOADING, + + /** The downloaded MMS is kept; "Not spam" restores it with its pictures. */ + STORED, + + /** The MMS content is not kept: the download failed, the carrier expired it, or an older build blocked it. */ + MISSING, +} + +/** What a "Not spam" restore of one blocked message did. */ +enum class RestoreOutcome { + /** Everything is in the inbox: an SMS, or an MMS with its pictures. */ + RESTORED, + + /** An MMS whose text is in the inbox (as an SMS), but whose pictures could not be recovered. */ + TEXT_ONLY, + + /** An MMS without text whose content could not be recovered. Nothing was put in the inbox. */ + NOTHING, + + /** The kept MMS could not be put in the inbox. It is still in Blocked; nothing was lost. */ + FAILED, + + /** No such blocked message (already restored or deleted). */ + NOT_FOUND, +} + +/** + * What [SpamRepository.restore] did with one blocked message, kept so [SpamRepository.undoRestore] can take it back. + * [message] is the blocked row as it was (null when there was none). The other fields are the data layer's own + * references, 0 when unknown: [inboxId] the system SMS or MMS row it became, [pendingId] the pending_sms row still + * waiting to be delivered (the inbox insert failed and will be replayed), [eventId] the "restored" statistics event. + */ +data class RestoreReceipt( + val message: BlockedMessage?, + val outcome: RestoreOutcome, + val inboxId: Long = 0, + val pendingId: Long = 0, + val eventId: Long = 0, +) + +/** A message held back by the filter. Never written to the system SMS provider until restored. */ +data class BlockedMessage( + val id: Long = 0, + val address: String, + val body: String, + val subscriptionId: Int, + val isMms: Boolean, + val receivedAt: Long, + val reason: DecisionReason, + val ruleId: Long? = null, + val media: MmsMedia = if (isMms) MmsMedia.MISSING else MmsMedia.NONE, + /** Name of the kept MMS in app-private storage, set when [media] is [MmsMedia.STORED]. */ + val mediaFile: String? = null, + /** Not opened yet: the sender's row on the Blocked tab shows it bold, as an unread chat. Added in version 6. */ + val unread: Boolean = false, +) { + /** The message has readable text (an MMS blocked before it was downloaded only has the placeholder). */ + val hasText: Boolean + get() = body.isNotBlank() && body != MMS_PLACEHOLDER_BODY + + /** The whole MMS, pictures included, is kept and can be restored. */ + val hasStoredMedia: Boolean + get() = isMms && media == MmsMedia.STORED && !mediaFile.isNullOrBlank() + + /** + * False for an MMS of which nothing was kept: "Not spam" then puts nothing in the inbox. An MMS whose + * pictures are lost but whose text is known restores that text (as an SMS). + */ + val canRestoreContent: Boolean + get() = !isMms || hasStoredMedia || hasText + + /** What "Not spam" is expected to do with this message (it can still turn out [RestoreOutcome.FAILED]). */ + val expectedRestore: RestoreOutcome + get() = when { + !isMms || hasStoredMedia -> RestoreOutcome.RESTORED + hasText -> RestoreOutcome.TEXT_ONLY + else -> RestoreOutcome.NOTHING + } + + /** [media] as the UI should show it: a download that has not answered in [DOWNLOAD_TIMEOUT_MS] has failed. */ + fun mediaAt(now: Long): MmsMedia = + if (media == MmsMedia.DOWNLOADING && now - receivedAt > DOWNLOAD_TIMEOUT_MS) MmsMedia.MISSING else media + + companion object { + const val DOWNLOAD_TIMEOUT_MS = 15 * 60 * 1000L + } +} + +data class SpamStats(val blockedTotal: Int, val blockedLast7Days: Int, val restoredTotal: Int) + +data class SpamSettings( + val mode: UnknownSenderMode = UnknownSenderMode.SMART, + /** Blocked messages older than this are purged. 0 = keep forever. */ + val purgeAfterDays: Int = 30, + val notifyOnBlock: Boolean = false, + val unknownInboxNotify: UnknownInboxNotify = UnknownInboxNotify.NOTIFY, + /** I67: an "Open link" button on notifications from known senders. */ + val openLinkAction: Boolean = false, + /** I24: ISO region (e.g. "GB") of the home country; numbers from other countries are held. Blank = off. */ + val blockOutsideRegion: String = "", +) + +/** Pure decision logic. No Android I/O except contact lookup supplied by the implementation. */ +interface SpamFilter { + /** Blocking call; run off the main thread. */ + fun evaluate(message: IncomingMessage): FilterDecision +} + +interface SpamRepository { + val blocked: Flow> + val rules: Flow> + val settings: Flow + val stats: Flow + + /** Throws IllegalArgumentException for a REGEX rule that [RegexGuard.validate] rejects. */ + suspend fun addRule(rule: SpamRule): Long + + /** + * Changes the stored rule [SpamRule.id] in place: its id (which blocked messages refer to) and creation time are + * kept. Returns [SpamRule.id], or the id of another rule that already holds the new value, in which case nothing + * is changed. Throws IllegalArgumentException for a REGEX rule that [RegexGuard.validate] rejects and + * NoSuchElementException when the rule no longer exists. + */ + suspend fun updateRule(rule: SpamRule): Long + suspend fun removeRule(id: Long) + + /** Removes several rules at once. */ + suspend fun removeRules(ids: List) = ids.forEach { removeRule(it) } + + /** + * Undo of a delete: puts [rules] back with their old ids where possible, so the reason chips of blocked messages + * point at them again. A rule whose value was added again in the meantime is skipped. + */ + suspend fun restoreRules(rules: List) = rules.forEach { runCatching { addRule(it.copy(id = 0)) } } + suspend fun updateSettings(transform: (SpamSettings) -> SpamSettings) + + /** Stores a blocked message (called by receivers). */ + suspend fun storeBlocked(message: BlockedMessage): Long + + /** [storeBlocked] that also says whether the message was already held (the row id returned is the first copy's). */ + suspend fun storeBlockedChecked(message: BlockedMessage): Pair = storeBlocked(message) to false + + /** + * Inserts the message into the system inbox and shows it. Rules are not changed: the sender is not + * whitelisted (that is a separate "Always allow" choice). Idempotent: a second call for the same id does + * nothing ([RestoreOutcome.NOT_FOUND]). A kept MMS goes back with its pictures. Of an MMS whose content was not + * kept only its text (if any) is restored; the outcome says so, so the UI never claims a picture came back. + */ + suspend fun markNotSpam(blockedId: Long): RestoreOutcome + + /** + * [markNotSpam] that can still be undone: the message is in the inbox when this returns, but a kept MMS's files + * stay until [finishRestore], so [undoRestore] can put it back in Blocked whole. Call [finishRestore] once undo is + * no longer offered; when the process dies first, the files are swept with the other unreferenced ones. + */ + suspend fun restore(blockedId: Long): RestoreReceipt = RestoreReceipt(null, markNotSpam(blockedId)) + + /** + * Undo of [restore]: takes the message out of the system inbox and puts it back in Blocked as it was (same id, + * text, sender, time, SIM, reason and kept files), and takes back the "restored" count. Returns false when it + * could not be undone; the message then stays in the inbox, so nothing is lost. + */ + suspend fun undoRestore(receipt: RestoreReceipt): Boolean = false + + /** Ends the undo window of [restore]: the kept MMS files the inbox copy no longer needs are deleted. */ + suspend fun finishRestore(receipt: RestoreReceipt) = Unit + + /** Adds a BLOCK rule for the sender and removes their allow rules. Their blocked messages are kept. */ + suspend fun blockSender(blockedId: Long) + + /** Marks held messages read (the sender's thread was opened), so their row on the Blocked tab is no longer bold. */ + suspend fun markBlockedRead(ids: List) = Unit + suspend fun deleteBlocked(ids: List) + suspend fun purgeExpired() +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepository.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepository.kt index edfb6568..13c4d562 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepository.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepository.kt @@ -1,428 +1,432 @@ -package com.glooboo.umessage.spam.data - -import android.provider.Telephony -import java.util.concurrent.ConcurrentHashMap -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.flatMapLatest -import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import kotlinx.coroutines.withContext -import com.glooboo.umessage.spam.BlockedMessage -import com.glooboo.umessage.spam.ListKind -import com.glooboo.umessage.spam.MMS_PLACEHOLDER_BODY -import com.glooboo.umessage.spam.MmsMedia -import com.glooboo.umessage.spam.RegexGuard -import com.glooboo.umessage.spam.RestoreOutcome -import com.glooboo.umessage.spam.RestoreReceipt -import com.glooboo.umessage.spam.RuleType -import com.glooboo.umessage.spam.SpamRepository -import com.glooboo.umessage.spam.SpamRule -import com.glooboo.umessage.spam.SpamSettings -import com.glooboo.umessage.spam.SpamStats -import com.glooboo.umessage.spam.engine.NumberNormalizer - -class DefaultSpamRepository( - private val platform: SpamPlatform, - private val db: SpamDatabase, - private val settingsStore: SpamSettingsStore, - private val normalizer: NumberNormalizer, - /** Country of a SIM, used to normalize numbers of rules scoped to that SIM. Null = default region. */ - private val regionForSubscription: (Int) -> String? = { null }, - /** The note on a rule added by "Block sender" on the Blocked screen, in the user's language. */ - private val blockedFromMessageNote: () -> String = { "" }, - /** The note on a rule added when a keyword or regex rule blocks a message and so blocks its sender too. */ - private val blockedFromKeywordNote: () -> String = { "" }, - /** The note on a rule added when a keyword or regex ALLOW rule allows a message and so allows its sender too. */ - private val allowedFromKeywordNote: () -> String = { "" }, -) : SpamRepository { - - private val dao get() = db.spamDao() - - /** Serializes restores so a double tap cannot deliver the same message twice. */ - private val restoreLock = Mutex() - - /** - * Kept MMS files of restores that can still be undone ([restore] until [finishRestore]). No row names them any - * more, so the sweep must be told to keep them. Memory only: after a process death they are swept like any - * other leftover, and the restore stays done. - */ - private val heldMedia: MutableSet = ConcurrentHashMap.newKeySet() - - override val blocked: Flow> = - dao.observeBlocked().map { list -> list.map { it.toModel() } } - - override val rules: Flow> = - dao.observeRules().map { list -> list.map { it.toRule() } } - - override val settings: Flow = settingsStore.observe() - - @OptIn(ExperimentalCoroutinesApi::class) - override val stats: Flow = combine( - dao.observeEventCount(SpamEventType.BLOCKED), - weekWindowStart().flatMapLatest { since -> dao.observeEventCountSince(SpamEventType.BLOCKED, since) }, - dao.observeEventCount(SpamEventType.RESTORED), - ) { total, week, restored -> SpamStats(total, week, restored) } - - /** Start of the "last 7 days" window, moved forward regularly so a long-lived screen does not go stale. */ - private fun weekWindowStart(): Flow = flow { - while (true) { - emit(System.currentTimeMillis() - WEEK_MS) - delay(STATS_WINDOW_REFRESH_MS) - } - } - - fun currentRules(): List = dao.getRules().map { it.toRule() } - - fun currentSettings(): SpamSettings = settingsStore.get() - - override suspend fun addRule(rule: SpamRule): Long = withContext(Dispatchers.IO) { - if (rule.type == RuleType.REGEX) { - RegexGuard.validate(rule.pattern)?.let { throw IllegalArgumentException("Rejected pattern: $it") } - } - db.runInTransaction { insertRule(rule) } - } - - override suspend fun updateRule(rule: SpamRule): Long = withContext(Dispatchers.IO) { - if (rule.type == RuleType.REGEX) { - RegexGuard.validate(rule.pattern)?.let { throw IllegalArgumentException("Rejected pattern: $it") } - } - db.runInTransaction { - val current = dao.getRule(rule.id) ?: throw NoSuchElementException("No rule ${rule.id}") - val pattern = cleanPattern(rule) - val other = dao.findRule(rule.kind, rule.type, pattern, rule.subscriptionId) - if (other != null && other.id != rule.id) return@runInTransaction other.id - dao.updateRule(SpamRuleEntity.from(rule.copy(pattern = pattern, createdAt = current.createdAt))) - rule.id - } - } - - override suspend fun removeRule(id: Long) = withContext(Dispatchers.IO) { dao.deleteRule(id) } - - override suspend fun removeRules(ids: List) = withContext(Dispatchers.IO) { - if (ids.isEmpty()) return@withContext - db.runInTransaction { ids.chunked(SQL_CHUNK).forEach(dao::deleteRules) } - } - - override suspend fun restoreRules(rules: List) = withContext(Dispatchers.IO) { - db.runInTransaction { - rules.forEach { rule -> - if (rule.type == RuleType.REGEX && RegexGuard.validate(rule.pattern) != null) return@forEach - val pattern = cleanPattern(rule) - if (dao.findRule(rule.kind, rule.type, pattern, rule.subscriptionId) != null) return@forEach - // Room ids are AUTOINCREMENT, so a deleted rule's id is never handed to another rule. - val id = if (rule.id > 0 && dao.getRule(rule.id) == null) rule.id else 0 - dao.insertRule(SpamRuleEntity.from(rule.copy(id = id, pattern = pattern))) - } - } - } - - override suspend fun updateSettings(transform: (SpamSettings) -> SpamSettings) = - withContext(Dispatchers.IO) { settingsStore.update(transform) } - - override suspend fun storeBlocked(message: BlockedMessage): Long = withContext(Dispatchers.IO) { - val capped = message.copy( - id = 0, - address = BlockedLimits.limitAddress(message.address), - body = BlockedLimits.limitBody(if (message.isMms && message.body.isBlank()) MMS_PLACEHOLDER_BODY else message.body), - // A newly held message has not been looked at. - unread = true, - ) - var duplicate = false - val id = db.runInTransaction { - val existing = dao.findDuplicateBlocked( - capped.address, capped.body, capped.isMms, - capped.receivedAt - BlockedLimits.DUPLICATE_WINDOW_MS, - capped.receivedAt + BlockedLimits.DUPLICATE_WINDOW_MS, - ) - if (existing != null) { - duplicate = true - existing - } else { - val rowId = dao.insertBlocked(BlockedMessageEntity.from(capped)) - dao.insertEvent(SpamEventEntity(type = SpamEventType.BLOCKED, timestamp = System.currentTimeMillis())) - rowId - } - } - if (duplicate) { - // The carrier sent the same MMS twice; the first copy keeps its own content. - capped.mediaFile?.let { platform.deleteMedia(listOf(it)) } - } else if (settingsStore.get().notifyOnBlock) { - runCatching { platform.notifyBlocked(capped.copy(id = id)) } - } - id - } - - /** - * Records the result of the download uMessage started for a blocked MMS: [mediaFile] is the kept content (null - * when the download failed) and [text] its text. Returns false when the row is gone (restored or deleted while - * downloading); the caller then deletes [mediaFile]. Blocking; called from a receiver's worker thread. - */ - fun attachDownloadedMedia(blockedId: Long, mediaFile: String?, text: String?): Boolean = - db.runInTransaction { - val row = dao.getBlocked(blockedId) ?: return@runInTransaction false - val body = text?.takeIf { it.isNotBlank() }?.let(BlockedLimits::limitBody) ?: row.body - val media = if (mediaFile != null) MmsMedia.STORED else MmsMedia.MISSING - dao.updateMedia(blockedId, media, mediaFile, body) > 0 - } - - /** - * Claims the blocked row and hands its content to the pending_sms write-ahead queue in one transaction, then - * delivers it. A second call finds no row and does nothing; a crash after the claim is recovered by the - * pending replay, so the message is neither lost nor inserted twice. - * - * Rules are not touched (T12): restoring one message must not whitelist the sender, because an allow rule beats - * every block rule and a spoofed sender id would then get through anything. "Always allow" is a separate choice - * the Blocked screen offers afterwards. - */ - override suspend fun markNotSpam(blockedId: Long): RestoreOutcome = - restore(blockedId).also { finishRestore(it) }.outcome - - /** [markNotSpam] without deleting kept MMS files yet, so [undoRestore] can still put the message back whole. */ - override suspend fun restore(blockedId: Long): RestoreReceipt = withContext(Dispatchers.IO) { - restoreLock.withLock { - val stored = dao.getBlocked(blockedId)?.toModel() - ?: return@withLock RestoreReceipt(null, RestoreOutcome.NOT_FOUND) - val receipt = if (stored.hasStoredMedia) restoreKeptMms(stored) else restoreText(blockedId) - if (receipt.outcome != RestoreOutcome.FAILED) { - receipt.message?.mediaFile?.let { heldMedia += it } - runCatching { platform.cancelBlockedNotifications(listOf(blockedId)) } - } - receipt - } - } - - /** - * Inbox first, then Blocked: the message is taken out of the inbox and only then put back, so a failure leaves it - * in the inbox (where the restore put it) and never nowhere. The blocked row gets its old id and kept files back. - */ - override suspend fun undoRestore(receipt: RestoreReceipt): Boolean = withContext(Dispatchers.IO) { - val message = receipt.message - val undoable = receipt.outcome != RestoreOutcome.FAILED && receipt.outcome != RestoreOutcome.NOT_FOUND - if (message == null || !undoable) return@withContext false - restoreLock.withLock { - if (!takeOutOfInbox(receipt, message)) return@withLock false - db.runInTransaction { - if (dao.getBlocked(message.id) == null) dao.insertBlocked(BlockedMessageEntity.from(message)) - if (receipt.eventId > 0) dao.deleteEvent(receipt.eventId) - } - message.mediaFile?.let { heldMedia -= it } - true - } - } - - /** - * Where the restore put the message: nowhere for an MMS of which nothing was kept, the pending queue when the - * inbox insert failed (and the replay has not delivered it yet), else the system row it became. - */ - private fun takeOutOfInbox(receipt: RestoreReceipt, message: BlockedMessage): Boolean = when { - receipt.outcome == RestoreOutcome.NOTHING -> true - receipt.pendingId > 0 && dao.deletePending(receipt.pendingId) > 0 -> true - receipt.inboxId > 0 -> runCatching { platform.removeRestored(receipt.inboxId, message.hasStoredMedia) } - .getOrDefault(false) - else -> false - } - - /** - * The undo window is over: the kept MMS files the inbox copy no longer needs go. A file a blocked row names again - * (the restore was undone) is left alone. - */ - override suspend fun finishRestore(receipt: RestoreReceipt) = withContext(Dispatchers.IO) { - val file = receipt.message?.mediaFile - if (receipt.outcome == RestoreOutcome.FAILED || file == null) return@withContext - restoreLock.withLock { - heldMedia -= file - if (file !in dao.allMediaFiles()) platform.deleteMedia(listOf(file)) - } - } - - /** - * A kept MMS goes into the inbox first and leaves Blocked only after that worked, so a failure loses nothing - * (the row and its files stay, and the user is told). The lock keeps a double tap from inserting it twice. The - * files stay until [finishRestore]. - */ - private fun restoreKeptMms(message: BlockedMessage): RestoreReceipt { - val inboxId = runCatching { platform.deliverRestoredMms(message) }.getOrNull() - ?: return RestoreReceipt(message, RestoreOutcome.FAILED) - var eventId = 0L - db.runInTransaction { - if (dao.getBlocked(message.id) != null) { - dao.deleteBlocked(listOf(message.id)) - val event = SpamEventEntity(type = SpamEventType.RESTORED, timestamp = System.currentTimeMillis()) - eventId = dao.insertEvent(event) - } - } - return RestoreReceipt(message, RestoreOutcome.RESTORED, inboxId = inboxId, eventId = eventId) - } - - /** - * An SMS, or an MMS whose content was not kept: its text (if any) is restored as an SMS. When the inbox insert - * fails the receipt names the pending row instead, which the replay delivers later. - */ - private fun restoreText(blockedId: Long): RestoreReceipt { - val now = System.currentTimeMillis() - var pending: PendingSmsEntity? = null - var message: BlockedMessage? = null - var eventId = 0L - db.runInTransaction { - val row = dao.getBlocked(blockedId)?.toModel() ?: return@runInTransaction - dao.deleteBlocked(listOf(blockedId)) - eventId = dao.insertEvent(SpamEventEntity(type = SpamEventType.RESTORED, timestamp = now)) - message = row - - // An MMS of which nothing was kept has nothing to restore; one with text gets that text as an SMS. - if (row.canRestoreContent) { - val entity = PendingSmsEntity( - address = row.address, - subject = "", - body = row.body, - date = row.receivedAt, - subscriptionId = row.subscriptionId, - status = Telephony.Sms.STATUS_NONE, - createdAt = now, - ) - pending = entity.copy(id = dao.insertPending(entity)) - } - } - val restored = message ?: return RestoreReceipt(null, RestoreOutcome.NOT_FOUND) - val receipt = RestoreReceipt(restored, restored.expectedRestore, eventId = eventId) - val queued = pending ?: return receipt - PendingSmsQueue.lease(queued.id, now) - val inboxId = runCatching { platform.deliverRestored(queued) }.getOrNull() - return if (inboxId != null) receipt.copy(inboxId = inboxId) else receipt.copy(pendingId = queued.id) - } - - /** - * Adds a block rule for the sender and removes their allow rules. Their messages already in Blocked stay there - * (SU-18): the user may still want to read or restore them, and deleting is its own action. - */ - override suspend fun blockSender(blockedId: Long) = withContext(Dispatchers.IO) { - val message = dao.getBlocked(blockedId) ?: return@withContext - val type = ruleTypeFor(message.address) - val pattern = normalizer.normalize(message.address) - - db.runInTransaction { - dao.getRules().filter { - it.kind == ListKind.ALLOW && it.type == type && it.pattern == pattern - }.forEach { dao.deleteRule(it.id) } - insertRule(SpamRule(kind = ListKind.BLOCK, type = type, pattern = pattern, note = blockedFromMessageNote())) - } - } - - /** - * After a keyword or regex BLOCK rule [ruleId] blocked the stored message [blockedId], also blocks its sender: - * adds a block rule for the number or sender id and removes their allow rules. Does nothing when the rule is not a - * block rule of those two types, when [mayBlock] says no for the address (a contact, a number the user wrote to, - * or a lookup that failed), or when the sender already has a block rule. Never throws. True when a rule was added. - */ - suspend fun blockSenderOfKeywordMatch(blockedId: Long, ruleId: Long?, mayBlock: (String) -> Boolean): Boolean = - withContext(Dispatchers.IO) { - runCatching { - val matched = ruleId?.let { id -> dao.getRules().firstOrNull { it.id == id } } - val message = dao.getBlocked(blockedId) - val eligible = message != null && matched != null && isKeywordRule(matched, ListKind.BLOCK) - if (message == null || !eligible || !mayBlock(message.address)) return@runCatching false - val type = ruleTypeFor(message.address) - val pattern = normalizer.normalize(message.address) - db.runInTransaction { - val rules = dao.getRules().filter { it.type == type && it.pattern == pattern } - if (rules.any { it.kind == ListKind.BLOCK }) return@runInTransaction false - rules.filter { it.kind == ListKind.ALLOW }.forEach { dao.deleteRule(it.id) } - val note = blockedFromKeywordNote() - insertRule(SpamRule(kind = ListKind.BLOCK, type = type, pattern = pattern, note = note)) - true - } - }.getOrDefault(false) - } - - /** - * After a keyword or regex ALLOW rule [ruleId] allowed a delivered message from [address], also allows its sender: - * adds an allow rule for the number or sender id. The mirror of [blockSenderOfKeywordMatch], but it never removes - * a rule: a sender that already has any rule (an explicit block wins and stays; an explicit allow is enough) is - * left alone. Does nothing when the rule is not an allow rule of those two types, when the address is blank, or - * when [mayAllow] says no (a contact, a number the user wrote to, or a lookup that failed). Never throws. True - * when a rule was added. - */ - suspend fun allowSenderOfKeywordMatch(address: String, ruleId: Long?, mayAllow: (String) -> Boolean): Boolean = - withContext(Dispatchers.IO) { - runCatching { - val matched = ruleId?.let { id -> dao.getRules().firstOrNull { it.id == id } } - val pattern = normalizer.normalize(address) - val eligible = matched != null && isKeywordRule(matched, ListKind.ALLOW) && pattern.isNotEmpty() - if (!eligible || !mayAllow(address)) return@runCatching false - val type = ruleTypeFor(address) - db.runInTransaction { - if (dao.getRules().any { it.type == type && it.pattern == pattern }) return@runInTransaction false - val note = allowedFromKeywordNote() - insertRule(SpamRule(kind = ListKind.ALLOW, type = type, pattern = pattern, note = note)) - true - } - }.getOrDefault(false) - } - - private fun isKeywordRule(rule: SpamRuleEntity, kind: ListKind): Boolean = - rule.kind == kind && (rule.type == RuleType.KEYWORD || rule.type == RuleType.REGEX) - - override suspend fun markBlockedRead(ids: List) { - if (ids.isEmpty()) return - withContext(Dispatchers.IO) { ids.chunked(SQL_CHUNK).forEach { dao.markBlockedRead(it) } } - } - - override suspend fun deleteBlocked(ids: List): Unit = withContext(Dispatchers.IO) { - if (ids.isEmpty()) return@withContext - val files = db.runInTransaction> { - ids.chunked(SQL_CHUNK).flatMap { chunk -> dao.mediaFilesOf(chunk).also { dao.deleteBlocked(chunk) } } - } - if (files.isNotEmpty()) platform.deleteMedia(files) - runCatching { platform.cancelBlockedNotifications(ids) } - } - - /** Deletes expired blocked messages together with their kept MMS content, and content no row refers to. */ - override suspend fun purgeExpired() = withContext(Dispatchers.IO) { - val days = settingsStore.get().purgeAfterDays - if (days > 0) { - val before = System.currentTimeMillis() - days * DAY_MS - val files = db.runInTransaction> { - dao.mediaFilesBefore(before).also { dao.deleteBlockedBefore(before) } - } - if (files.isNotEmpty()) platform.deleteMedia(files) - } - platform.sweepMedia(dao.allMediaFiles().toSet() + heldMedia) - } - - private fun ruleTypeFor(address: String) = if (normalizer.isSenderId(address)) RuleType.SENDER_ID else RuleType.NUMBER - - private fun cleanPattern(rule: SpamRule): String = when (rule.type) { - RuleType.NUMBER -> ruleNormalizer(rule.subscriptionId).normalize(rule.pattern) - RuleType.SENDER_ID -> normalizer.normalize(rule.pattern) - RuleType.PREFIX -> normalizer.cleanPrefix(rule.pattern) - else -> rule.pattern.trim() - } - - private fun insertRule(rule: SpamRule): Long { - val pattern = cleanPattern(rule) - val existing = dao.findRule(rule.kind, rule.type, pattern, rule.subscriptionId) - if (existing != null) return existing.id - return dao.insertRule(SpamRuleEntity.from(rule.copy(id = 0, pattern = pattern))) - } - - /** A rule scoped to one SIM reads national numbers in that SIM's country. */ - private fun ruleNormalizer(subscriptionId: Int?): NumberNormalizer { - val region = subscriptionId?.let { runCatching { regionForSubscription(it) }.getOrNull() } - return if (region.isNullOrBlank()) normalizer else normalizer.withRegion(region) - } - - private companion object { - const val DAY_MS = 24L * 60 * 60 * 1000 - const val WEEK_MS = 7 * DAY_MS - const val STATS_WINDOW_REFRESH_MS = 15L * 60 * 1000 - - /** Stays below SQLite's limit of bound variables per statement. */ - const val SQL_CHUNK = 500 - } -} +package com.glooboo.umessage.spam.data + +import android.provider.Telephony +import java.util.concurrent.ConcurrentHashMap +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import com.glooboo.umessage.spam.BlockedMessage +import com.glooboo.umessage.spam.ListKind +import com.glooboo.umessage.spam.MMS_PLACEHOLDER_BODY +import com.glooboo.umessage.spam.MmsMedia +import com.glooboo.umessage.spam.RegexGuard +import com.glooboo.umessage.spam.RestoreOutcome +import com.glooboo.umessage.spam.RestoreReceipt +import com.glooboo.umessage.spam.RuleType +import com.glooboo.umessage.spam.SpamRepository +import com.glooboo.umessage.spam.SpamRule +import com.glooboo.umessage.spam.SpamSettings +import com.glooboo.umessage.spam.SpamStats +import com.glooboo.umessage.spam.engine.NumberNormalizer + +class DefaultSpamRepository( + private val platform: SpamPlatform, + private val db: SpamDatabase, + private val settingsStore: SpamSettingsStore, + private val normalizer: NumberNormalizer, + /** Country of a SIM, used to normalize numbers of rules scoped to that SIM. Null = default region. */ + private val regionForSubscription: (Int) -> String? = { null }, + /** The note on a rule added by "Block sender" on the Blocked screen, in the user's language. */ + private val blockedFromMessageNote: () -> String = { "" }, + /** The note on a rule added when a keyword or regex rule blocks a message and so blocks its sender too. */ + private val blockedFromKeywordNote: () -> String = { "" }, + /** The note on a rule added when a keyword or regex ALLOW rule allows a message and so allows its sender too. */ + private val allowedFromKeywordNote: () -> String = { "" }, +) : SpamRepository { + + private val dao get() = db.spamDao() + + /** Serializes restores so a double tap cannot deliver the same message twice. */ + private val restoreLock = Mutex() + + /** + * Kept MMS files of restores that can still be undone ([restore] until [finishRestore]). No row names them any + * more, so the sweep must be told to keep them. Memory only: after a process death they are swept like any + * other leftover, and the restore stays done. + */ + private val heldMedia: MutableSet = ConcurrentHashMap.newKeySet() + + override val blocked: Flow> = + dao.observeBlocked().map { list -> list.map { it.toModel() } } + + override val rules: Flow> = + dao.observeRules().map { list -> list.map { it.toRule() } } + + override val settings: Flow = settingsStore.observe() + + @OptIn(ExperimentalCoroutinesApi::class) + override val stats: Flow = combine( + dao.observeEventCount(SpamEventType.BLOCKED), + weekWindowStart().flatMapLatest { since -> dao.observeEventCountSince(SpamEventType.BLOCKED, since) }, + dao.observeEventCount(SpamEventType.RESTORED), + ) { total, week, restored -> SpamStats(total, week, restored) } + + /** Start of the "last 7 days" window, moved forward regularly so a long-lived screen does not go stale. */ + private fun weekWindowStart(): Flow = flow { + while (true) { + emit(System.currentTimeMillis() - WEEK_MS) + delay(STATS_WINDOW_REFRESH_MS) + } + } + + fun currentRules(): List = dao.getRules().map { it.toRule() } + + fun currentSettings(): SpamSettings = settingsStore.get() + + override suspend fun addRule(rule: SpamRule): Long = withContext(Dispatchers.IO) { + if (rule.type == RuleType.REGEX) { + RegexGuard.validate(rule.pattern)?.let { throw IllegalArgumentException("Rejected pattern: $it") } + } + db.runInTransaction { insertRule(rule) } + } + + override suspend fun updateRule(rule: SpamRule): Long = withContext(Dispatchers.IO) { + if (rule.type == RuleType.REGEX) { + RegexGuard.validate(rule.pattern)?.let { throw IllegalArgumentException("Rejected pattern: $it") } + } + db.runInTransaction { + val current = dao.getRule(rule.id) ?: throw NoSuchElementException("No rule ${rule.id}") + val pattern = cleanPattern(rule) + val other = dao.findRule(rule.kind, rule.type, pattern, rule.subscriptionId) + if (other != null && other.id != rule.id) return@runInTransaction other.id + dao.updateRule(SpamRuleEntity.from(rule.copy(pattern = pattern, createdAt = current.createdAt))) + rule.id + } + } + + override suspend fun removeRule(id: Long) = withContext(Dispatchers.IO) { dao.deleteRule(id) } + + override suspend fun removeRules(ids: List) = withContext(Dispatchers.IO) { + if (ids.isEmpty()) return@withContext + db.runInTransaction { ids.chunked(SQL_CHUNK).forEach(dao::deleteRules) } + } + + override suspend fun restoreRules(rules: List) = withContext(Dispatchers.IO) { + db.runInTransaction { + rules.forEach { rule -> + if (rule.type == RuleType.REGEX && RegexGuard.validate(rule.pattern) != null) return@forEach + val pattern = cleanPattern(rule) + if (dao.findRule(rule.kind, rule.type, pattern, rule.subscriptionId) != null) return@forEach + // Room ids are AUTOINCREMENT, so a deleted rule's id is never handed to another rule. + val id = if (rule.id > 0 && dao.getRule(rule.id) == null) rule.id else 0 + dao.insertRule(SpamRuleEntity.from(rule.copy(id = id, pattern = pattern))) + } + } + } + + override suspend fun updateSettings(transform: (SpamSettings) -> SpamSettings) = + withContext(Dispatchers.IO) { settingsStore.update(transform) } + + override suspend fun storeBlocked(message: BlockedMessage): Long = storeBlockedChecked(message).first + + override suspend fun storeBlockedChecked( + message: BlockedMessage, + ): Pair = withContext(Dispatchers.IO) { + val capped = message.copy( + id = 0, + address = BlockedLimits.limitAddress(message.address), + body = BlockedLimits.limitBody(if (message.isMms && message.body.isBlank()) MMS_PLACEHOLDER_BODY else message.body), + // A newly held message has not been looked at. + unread = true, + ) + var duplicate = false + val id = db.runInTransaction { + val existing = dao.findDuplicateBlocked( + capped.address, capped.body, capped.isMms, + capped.receivedAt - BlockedLimits.DUPLICATE_WINDOW_MS, + capped.receivedAt + BlockedLimits.DUPLICATE_WINDOW_MS, + ) + if (existing != null) { + duplicate = true + existing + } else { + val rowId = dao.insertBlocked(BlockedMessageEntity.from(capped)) + dao.insertEvent(SpamEventEntity(type = SpamEventType.BLOCKED, timestamp = System.currentTimeMillis())) + rowId + } + } + if (duplicate) { + // The carrier sent the same MMS twice; the first copy keeps its own content. + capped.mediaFile?.let { platform.deleteMedia(listOf(it)) } + } else if (settingsStore.get().notifyOnBlock) { + runCatching { platform.notifyBlocked(capped.copy(id = id)) } + } + id to duplicate + } + + /** + * Records the result of the download uMessage started for a blocked MMS: [mediaFile] is the kept content (null + * when the download failed) and [text] its text. Returns false when the row is gone (restored or deleted while + * downloading); the caller then deletes [mediaFile]. Blocking; called from a receiver's worker thread. + */ + fun attachDownloadedMedia(blockedId: Long, mediaFile: String?, text: String?): Boolean = + db.runInTransaction { + val row = dao.getBlocked(blockedId) ?: return@runInTransaction false + val body = text?.takeIf { it.isNotBlank() }?.let(BlockedLimits::limitBody) ?: row.body + val media = if (mediaFile != null) MmsMedia.STORED else MmsMedia.MISSING + dao.updateMedia(blockedId, media, mediaFile, body) > 0 + } + + /** + * Claims the blocked row and hands its content to the pending_sms write-ahead queue in one transaction, then + * delivers it. A second call finds no row and does nothing; a crash after the claim is recovered by the + * pending replay, so the message is neither lost nor inserted twice. + * + * Rules are not touched (T12): restoring one message must not whitelist the sender, because an allow rule beats + * every block rule and a spoofed sender id would then get through anything. "Always allow" is a separate choice + * the Blocked screen offers afterwards. + */ + override suspend fun markNotSpam(blockedId: Long): RestoreOutcome = + restore(blockedId).also { finishRestore(it) }.outcome + + /** [markNotSpam] without deleting kept MMS files yet, so [undoRestore] can still put the message back whole. */ + override suspend fun restore(blockedId: Long): RestoreReceipt = withContext(Dispatchers.IO) { + restoreLock.withLock { + val stored = dao.getBlocked(blockedId)?.toModel() + ?: return@withLock RestoreReceipt(null, RestoreOutcome.NOT_FOUND) + val receipt = if (stored.hasStoredMedia) restoreKeptMms(stored) else restoreText(blockedId) + if (receipt.outcome != RestoreOutcome.FAILED) { + receipt.message?.mediaFile?.let { heldMedia += it } + runCatching { platform.cancelBlockedNotifications(listOf(blockedId)) } + } + receipt + } + } + + /** + * Inbox first, then Blocked: the message is taken out of the inbox and only then put back, so a failure leaves it + * in the inbox (where the restore put it) and never nowhere. The blocked row gets its old id and kept files back. + */ + override suspend fun undoRestore(receipt: RestoreReceipt): Boolean = withContext(Dispatchers.IO) { + val message = receipt.message + val undoable = receipt.outcome != RestoreOutcome.FAILED && receipt.outcome != RestoreOutcome.NOT_FOUND + if (message == null || !undoable) return@withContext false + restoreLock.withLock { + if (!takeOutOfInbox(receipt, message)) return@withLock false + db.runInTransaction { + if (dao.getBlocked(message.id) == null) dao.insertBlocked(BlockedMessageEntity.from(message)) + if (receipt.eventId > 0) dao.deleteEvent(receipt.eventId) + } + message.mediaFile?.let { heldMedia -= it } + true + } + } + + /** + * Where the restore put the message: nowhere for an MMS of which nothing was kept, the pending queue when the + * inbox insert failed (and the replay has not delivered it yet), else the system row it became. + */ + private fun takeOutOfInbox(receipt: RestoreReceipt, message: BlockedMessage): Boolean = when { + receipt.outcome == RestoreOutcome.NOTHING -> true + receipt.pendingId > 0 && dao.deletePending(receipt.pendingId) > 0 -> true + receipt.inboxId > 0 -> runCatching { platform.removeRestored(receipt.inboxId, message.hasStoredMedia) } + .getOrDefault(false) + else -> false + } + + /** + * The undo window is over: the kept MMS files the inbox copy no longer needs go. A file a blocked row names again + * (the restore was undone) is left alone. + */ + override suspend fun finishRestore(receipt: RestoreReceipt) = withContext(Dispatchers.IO) { + val file = receipt.message?.mediaFile + if (receipt.outcome == RestoreOutcome.FAILED || file == null) return@withContext + restoreLock.withLock { + heldMedia -= file + if (file !in dao.allMediaFiles()) platform.deleteMedia(listOf(file)) + } + } + + /** + * A kept MMS goes into the inbox first and leaves Blocked only after that worked, so a failure loses nothing + * (the row and its files stay, and the user is told). The lock keeps a double tap from inserting it twice. The + * files stay until [finishRestore]. + */ + private fun restoreKeptMms(message: BlockedMessage): RestoreReceipt { + val inboxId = runCatching { platform.deliverRestoredMms(message) }.getOrNull() + ?: return RestoreReceipt(message, RestoreOutcome.FAILED) + var eventId = 0L + db.runInTransaction { + if (dao.getBlocked(message.id) != null) { + dao.deleteBlocked(listOf(message.id)) + val event = SpamEventEntity(type = SpamEventType.RESTORED, timestamp = System.currentTimeMillis()) + eventId = dao.insertEvent(event) + } + } + return RestoreReceipt(message, RestoreOutcome.RESTORED, inboxId = inboxId, eventId = eventId) + } + + /** + * An SMS, or an MMS whose content was not kept: its text (if any) is restored as an SMS. When the inbox insert + * fails the receipt names the pending row instead, which the replay delivers later. + */ + private fun restoreText(blockedId: Long): RestoreReceipt { + val now = System.currentTimeMillis() + var pending: PendingSmsEntity? = null + var message: BlockedMessage? = null + var eventId = 0L + db.runInTransaction { + val row = dao.getBlocked(blockedId)?.toModel() ?: return@runInTransaction + dao.deleteBlocked(listOf(blockedId)) + eventId = dao.insertEvent(SpamEventEntity(type = SpamEventType.RESTORED, timestamp = now)) + message = row + + // An MMS of which nothing was kept has nothing to restore; one with text gets that text as an SMS. + if (row.canRestoreContent) { + val entity = PendingSmsEntity( + address = row.address, + subject = "", + body = row.body, + date = row.receivedAt, + subscriptionId = row.subscriptionId, + status = Telephony.Sms.STATUS_NONE, + createdAt = now, + ) + pending = entity.copy(id = dao.insertPending(entity)) + } + } + val restored = message ?: return RestoreReceipt(null, RestoreOutcome.NOT_FOUND) + val receipt = RestoreReceipt(restored, restored.expectedRestore, eventId = eventId) + val queued = pending ?: return receipt + PendingSmsQueue.lease(queued.id, now) + val inboxId = runCatching { platform.deliverRestored(queued) }.getOrNull() + return if (inboxId != null) receipt.copy(inboxId = inboxId) else receipt.copy(pendingId = queued.id) + } + + /** + * Adds a block rule for the sender and removes their allow rules. Their messages already in Blocked stay there + * (SU-18): the user may still want to read or restore them, and deleting is its own action. + */ + override suspend fun blockSender(blockedId: Long) = withContext(Dispatchers.IO) { + val message = dao.getBlocked(blockedId) ?: return@withContext + val type = ruleTypeFor(message.address) + val pattern = normalizer.normalize(message.address) + + db.runInTransaction { + dao.getRules().filter { + it.kind == ListKind.ALLOW && it.type == type && it.pattern == pattern + }.forEach { dao.deleteRule(it.id) } + insertRule(SpamRule(kind = ListKind.BLOCK, type = type, pattern = pattern, note = blockedFromMessageNote())) + } + } + + /** + * After a keyword or regex BLOCK rule [ruleId] blocked the stored message [blockedId], also blocks its sender: + * adds a block rule for the number or sender id and removes their allow rules. Does nothing when the rule is not a + * block rule of those two types, when [mayBlock] says no for the address (a contact, a number the user wrote to, + * or a lookup that failed), or when the sender already has a block rule. Never throws. True when a rule was added. + */ + suspend fun blockSenderOfKeywordMatch(blockedId: Long, ruleId: Long?, mayBlock: (String) -> Boolean): Boolean = + withContext(Dispatchers.IO) { + runCatching { + val matched = ruleId?.let { id -> dao.getRules().firstOrNull { it.id == id } } + val message = dao.getBlocked(blockedId) + val eligible = message != null && matched != null && isKeywordRule(matched, ListKind.BLOCK) + if (message == null || !eligible || !mayBlock(message.address)) return@runCatching false + val type = ruleTypeFor(message.address) + val pattern = normalizer.normalize(message.address) + db.runInTransaction { + val rules = dao.getRules().filter { it.type == type && it.pattern == pattern } + if (rules.any { it.kind == ListKind.BLOCK }) return@runInTransaction false + rules.filter { it.kind == ListKind.ALLOW }.forEach { dao.deleteRule(it.id) } + val note = blockedFromKeywordNote() + insertRule(SpamRule(kind = ListKind.BLOCK, type = type, pattern = pattern, note = note)) + true + } + }.getOrDefault(false) + } + + /** + * After a keyword or regex ALLOW rule [ruleId] allowed a delivered message from [address], also allows its sender: + * adds an allow rule for the number or sender id. The mirror of [blockSenderOfKeywordMatch], but it never removes + * a rule: a sender that already has any rule (an explicit block wins and stays; an explicit allow is enough) is + * left alone. Does nothing when the rule is not an allow rule of those two types, when the address is blank, or + * when [mayAllow] says no (a contact, a number the user wrote to, or a lookup that failed). Never throws. True + * when a rule was added. + */ + suspend fun allowSenderOfKeywordMatch(address: String, ruleId: Long?, mayAllow: (String) -> Boolean): Boolean = + withContext(Dispatchers.IO) { + runCatching { + val matched = ruleId?.let { id -> dao.getRules().firstOrNull { it.id == id } } + val pattern = normalizer.normalize(address) + val eligible = matched != null && isKeywordRule(matched, ListKind.ALLOW) && pattern.isNotEmpty() + if (!eligible || !mayAllow(address)) return@runCatching false + val type = ruleTypeFor(address) + db.runInTransaction { + if (dao.getRules().any { it.type == type && it.pattern == pattern }) return@runInTransaction false + val note = allowedFromKeywordNote() + insertRule(SpamRule(kind = ListKind.ALLOW, type = type, pattern = pattern, note = note)) + true + } + }.getOrDefault(false) + } + + private fun isKeywordRule(rule: SpamRuleEntity, kind: ListKind): Boolean = + rule.kind == kind && (rule.type == RuleType.KEYWORD || rule.type == RuleType.REGEX) + + override suspend fun markBlockedRead(ids: List) { + if (ids.isEmpty()) return + withContext(Dispatchers.IO) { ids.chunked(SQL_CHUNK).forEach { dao.markBlockedRead(it) } } + } + + override suspend fun deleteBlocked(ids: List): Unit = withContext(Dispatchers.IO) { + if (ids.isEmpty()) return@withContext + val files = db.runInTransaction> { + ids.chunked(SQL_CHUNK).flatMap { chunk -> dao.mediaFilesOf(chunk).also { dao.deleteBlocked(chunk) } } + } + if (files.isNotEmpty()) platform.deleteMedia(files) + runCatching { platform.cancelBlockedNotifications(ids) } + } + + /** Deletes expired blocked messages together with their kept MMS content, and content no row refers to. */ + override suspend fun purgeExpired() = withContext(Dispatchers.IO) { + val days = settingsStore.get().purgeAfterDays + if (days > 0) { + val before = System.currentTimeMillis() - days * DAY_MS + val files = db.runInTransaction> { + dao.mediaFilesBefore(before).also { dao.deleteBlockedBefore(before) } + } + if (files.isNotEmpty()) platform.deleteMedia(files) + } + platform.sweepMedia(dao.allMediaFiles().toSet() + heldMedia) + } + + private fun ruleTypeFor(address: String) = if (normalizer.isSenderId(address)) RuleType.SENDER_ID else RuleType.NUMBER + + private fun cleanPattern(rule: SpamRule): String = when (rule.type) { + RuleType.NUMBER -> ruleNormalizer(rule.subscriptionId).normalize(rule.pattern) + RuleType.SENDER_ID -> normalizer.normalize(rule.pattern) + RuleType.PREFIX -> normalizer.cleanPrefix(rule.pattern) + else -> rule.pattern.trim() + } + + private fun insertRule(rule: SpamRule): Long { + val pattern = cleanPattern(rule) + val existing = dao.findRule(rule.kind, rule.type, pattern, rule.subscriptionId) + if (existing != null) return existing.id + return dao.insertRule(SpamRuleEntity.from(rule.copy(id = 0, pattern = pattern))) + } + + /** A rule scoped to one SIM reads national numbers in that SIM's country. */ + private fun ruleNormalizer(subscriptionId: Int?): NumberNormalizer { + val region = subscriptionId?.let { runCatching { regionForSubscription(it) }.getOrNull() } + return if (region.isNullOrBlank()) normalizer else normalizer.withRegion(region) + } + + private companion object { + const val DAY_MS = 24L * 60 * 60 * 1000 + const val WEEK_MS = 7 * DAY_MS + const val STATS_WINDOW_REFRESH_MS = 15L * 60 * 1000 + + /** Stays below SQLite's limit of bound variables per statement. */ + const val SQL_CHUNK = 500 + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/AndroidSpamEnvironment.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/AndroidSpamEnvironment.kt index f332878a..7e53b2b8 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/AndroidSpamEnvironment.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/AndroidSpamEnvironment.kt @@ -9,7 +9,6 @@ import android.net.Uri import android.os.Looper import android.provider.ContactsContract import android.provider.Telephony -import android.telephony.PhoneNumberUtils import android.telephony.SubscriptionManager import android.telephony.TelephonyManager import androidx.core.content.ContextCompat @@ -61,7 +60,7 @@ class SystemContactChecker( /** Normalized and raw addresses the user has sent a message to. Null until loaded or after a change. */ @Volatile private var sentCache: SentAddresses? = null - private class SentAddresses(val normalized: MutableSet, val raw: MutableSet) + private class SentAddresses(val normalized: MutableSet, val index: ContactNumberIndex) /** * Messages that changed since [sentCache] was built. Every received text changes the message store, so instead of @@ -125,9 +124,8 @@ class SystemContactChecker( val sent = sentAddresses() ?: return ContactLookup.UNKNOWN if (normalizer.normalize(address) in sent.normalized) return ContactLookup.FOUND // The normalized forms can differ when a number was typed without its country code in another region; the - // platform comparison (same trailing digits, compatible prefixes) catches those. - val loose = sent.raw.any { PhoneNumberUtils.compare(it, address) } - return if (loose) ContactLookup.FOUND else ContactLookup.NOT_FOUND + // index catches those, but never across two known countries (PhoneNumberUtils.compare matched trailing digits). + return if (sent.index.contains(address)) ContactLookup.FOUND else ContactLookup.NOT_FOUND } private fun sentAddresses(): SentAddresses? = synchronized(sentLock) { @@ -136,7 +134,9 @@ class SystemContactChecker( changedMessages.clear() val raw = loadSentSmsAddresses() ?: return null raw += loadSentMmsAddresses() - return SentAddresses(raw.mapTo(HashSet()) { normalizer.normalize(it) }, raw).also { sentCache = it } + val index = ContactNumberIndex(normalizer, plausibleRegions(appContext)) + raw.forEach { index.add(it, Unit) } + return SentAddresses(raw.mapTo(HashSet()) { normalizer.normalize(it) }, index).also { sentCache = it } } /** @@ -154,7 +154,7 @@ class SystemContactChecker( changedSmsRecipient(id) } ?: return false recipients.forEach { address -> - sent.raw += address + sent.index.add(address, Unit) sent.normalized += normalizer.normalize(address) } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/SpamEngine.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/SpamEngine.kt index 45e98c2a..fe174351 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/SpamEngine.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/SpamEngine.kt @@ -1,296 +1,298 @@ -package com.glooboo.umessage.spam.engine - -import android.annotation.SuppressLint -import android.content.Context -import android.telephony.SubscriptionManager -import kotlinx.coroutines.runBlocking -import com.glooboo.umessage.helpers.W3aPrefs -import com.glooboo.umessage.spam.ForwardRepository -import com.glooboo.umessage.spam.data.DefaultForwardRepository -import com.glooboo.umessage.spam.BlockedMessage -import com.glooboo.umessage.spam.DecisionReason -import com.glooboo.umessage.spam.DecisionRuleText -import com.glooboo.umessage.spam.FilterDecision -import com.glooboo.umessage.spam.IncomingMessage -import com.glooboo.umessage.spam.MmsMedia -import com.glooboo.umessage.spam.SpamLogEntry -import com.glooboo.umessage.spam.UMessage -import com.glooboo.umessage.spam.data.AndroidSpamPlatform -import com.glooboo.umessage.spam.data.BlockedNotifier -import com.glooboo.umessage.spam.data.DefaultSpamRepository -import com.glooboo.umessage.spam.data.SpamDatabase -import com.glooboo.umessage.spam.data.SpamSettingsStore - -/** - * Wiring and the fail-open entry points used by the receivers. The singletons below hold no Context directly: - * Android access goes through the application context captured by [AndroidSpamPlatform] and the environment - * classes, behind interfaces. - */ -object SpamEngine { - @Volatile private var repository: DefaultSpamRepository? = null - @Volatile private var filter: DefaultSpamFilter? = null - @Volatile private var settingsStore: SpamSettingsStore? = null - @Volatile private var forwardPlanner: ForwardPlanner? = null - @Volatile private var checker: SystemContactChecker? = null - - fun install() { - UMessage.filterFactory = { filter(it) } - UMessage.repositoryFactory = { repository(it) } - } - - fun repository(context: Context): DefaultSpamRepository = repository ?: synchronized(this) { - repository ?: run { - val app = context.applicationContext - DefaultSpamRepository( - platform = AndroidSpamPlatform(app), - db = SpamDatabase.getInstance(app), - settingsStore = settingsStore(app), - normalizer = normalizer(app), - regionForSubscription = { subscriptionRegion(app, it) }, - blockedFromMessageNote = { com.glooboo.umessage.ui.spam.RuleNotes.BLOCKED_FROM_MESSAGE }, - blockedFromKeywordNote = { com.glooboo.umessage.ui.spam.RuleNotes.BLOCKED_FROM_KEYWORD }, - allowedFromKeywordNote = { com.glooboo.umessage.ui.spam.RuleNotes.ALLOWED_FROM_KEYWORD }, - ).also { repository = it } - } - } - - fun filter(context: Context): DefaultSpamFilter = filter ?: synchronized(this) { - filter ?: run { - val app = context.applicationContext - val repo = repository(app) - val normalizer = normalizer(app) - DefaultSpamFilter( - rules = repo::currentRules, - settings = repo::currentSettings, - contacts = contactChecker(app), - normalizer = normalizer, - legacy = FossifyLegacyBlocklist(app), - regionForSubscription = { subscriptionRegion(app, it) }, - ).also { filter = it } - } - } - - /** - * The one contact checker of the process: it registers content observers and keeps the address book and the sent - * history in memory, so the filter and the helpers below share it instead of each making (and leaking) their own. - */ - fun contactChecker(context: Context): SystemContactChecker = checker ?: synchronized(this) { - checker ?: run { - val app = context.applicationContext - SystemContactChecker(app, normalizer(app)).also { checker = it } - } - } - - /** Stops the shared checker's observers and forgets it (and the filter that holds it); a test starts clean. */ - internal fun resetContactChecker() = synchronized(this) { - checker?.close() - checker = null - filter = null - } - - /** A thin wrapper over the database's DAO, made on each call so it always uses the current database instance. */ - fun forwardRepository(context: Context): ForwardRepository = - DefaultForwardRepository(SpamDatabase.getInstance(context.applicationContext).forwardDao()) - - /** The forward rules' matcher: the same number, sender id, keyword and pattern reading as the spam filter. */ - fun forwardPlanner(context: Context): ForwardPlanner = forwardPlanner ?: synchronized(this) { - forwardPlanner ?: run { - val app = context.applicationContext - ForwardPlanner( - matcher = RuleMatcher(normalizer(app), regionForSubscription = { subscriptionRegion(app, it) }), - simInSlot = { slot -> subscriptionInSlot(app, slot) }, - codeMask = { W3aPrefs.get(app).forwardCodeMasker() }, - ).also { forwardPlanner = it } - } - } - - /** The active SIM in 1-based [slot], or null (empty slot, no permission). */ - @SuppressLint("MissingPermission") - private fun subscriptionInSlot(context: Context, slot: Int): Int? = runCatching { - context.getSystemService(SubscriptionManager::class.java) - ?.getActiveSubscriptionInfoForSimSlotIndex(slot - 1)?.subscriptionId - }.getOrNull() - - private fun settingsStore(context: Context): SpamSettingsStore = settingsStore ?: synchronized(this) { - settingsStore ?: SpamSettingsStore(context).also { settingsStore = it } - } - - private fun normalizer(context: Context): NumberNormalizer { - val app = context.applicationContext - return NumberNormalizer { defaultRegion(app) } - } - - /** Whether the user has written to [address] before: such a number is known, like a contact. Never throws. */ - fun hasWrittenTo(context: Context, address: String): Boolean = runCatching { - contactChecker(context).sentTo(address) == ContactLookup.FOUND - }.getOrDefault(false) - - /** Returns the Block decision, or null when allowed or when the filter itself fails (never drop on error). */ - fun block(context: Context, message: IncomingMessage, source: String? = null): FilterDecision.Block? = - evaluate(context, message, source) as? FilterDecision.Block - - /** - * Full decision, logged to [SpamLog]. Null when the filter itself failed, including with an Error such as - * ExceptionInInitializerError or OutOfMemoryError (callers must then deliver). - */ - fun evaluate(context: Context, message: IncomingMessage, source: String? = null): FilterDecision? { - val where = source ?: if (message.isMms) "MMS" else "SMS" - val decision = try { - UMessage.filter(context).evaluate(message) - } catch (t: Throwable) { - record(context, message, "ERROR", t.javaClass.simpleName, where) - return null - } - // DecisionReason.CONTACTS_UNAVAILABLE lands here too, so a missing contacts permission is visible in the log. - val ruleId = when (decision) { - is FilterDecision.Block -> decision.ruleId - is FilterDecision.Allow -> decision.ruleId - } - record( - context, message, if (decision is FilterDecision.Block) "BLOCK" else "ALLOW", decision.reason.name, where, - ruleId, ruleId?.let { ruleLabelOf(context, it) }.orEmpty(), - ) - return decision - } - - /** The short label (the value) of rule [id] for the decision log; empty when the rule can't be read. */ - private fun ruleLabelOf(context: Context, id: Long): String = try { - repository(context).currentRules().firstOrNull { it.id == id }?.let { DecisionRuleText.label(it) }.orEmpty() - } catch (_: Throwable) { - "" - } - - private fun record( - context: Context, - message: IncomingMessage, - decision: String, - reason: String, - source: String, - ruleId: Long? = null, - ruleLabel: String = "", - ) { - try { - UMessage.log(context).record( - SpamLogEntry( - System.currentTimeMillis(), message.address, message.subscriptionId, decision, reason, source, - ruleId, ruleLabel, - ) - ) - } catch (_: Throwable) { - } - } - - /** - * Write-ahead store of a blocked message. Returns false when storing failed for any reason (Errors included), - * so the caller delivers it instead. An MMS with a blank body is stored with the placeholder text. - */ - fun storeBlocked(context: Context, message: IncomingMessage, decision: FilterDecision.Block): Boolean = - storeBlockedId(context, message, decision) != null - - /** - * [storeBlocked] returning the row id (null when storing failed). For an MMS, [media] / [mediaFile] say what - * of its content is kept (default: nothing). - */ - fun storeBlockedId( - context: Context, - message: IncomingMessage, - decision: FilterDecision.Block, - media: MmsMedia = if (message.isMms) MmsMedia.MISSING else MmsMedia.NONE, - mediaFile: String? = null, - ): Long? { - return try { - val id = runBlocking { - val repo = UMessage.repository(context) - repo.storeBlocked( - BlockedMessage( - address = message.address, - body = message.body, - subscriptionId = message.subscriptionId, - isMms = message.isMms, - receivedAt = message.receivedAt, - reason = decision.reason, - ruleId = decision.ruleId, - media = media, - mediaFile = mediaFile, - ) - ) - } - blockSenderOfKeyword(context, id, decision) - purgeExpired(context) - id - } catch (t: Throwable) { - record(context, message, "ERROR", "STORE_FAILED_" + t.javaClass.simpleName, "STORE") - null - } - } - - /** - * A keyword or regex block rule blocks the sender too, once the message is really stored (so probes that only - * evaluate never add rules). A contact, a number the user wrote to, or a failed lookup keeps the sender unblocked. - * Never throws. - */ - private fun blockSenderOfKeyword(context: Context, blockedId: Long, decision: FilterDecision.Block) { - if (decision.reason != DecisionReason.BLOCK_RULE || decision.ruleId == null) return - runCatching { - val app = context.applicationContext - val repo = UMessage.repository(app) as? DefaultSpamRepository ?: return - val contacts = contactChecker(app) - runBlocking { - repo.blockSenderOfKeywordMatch(blockedId, decision.ruleId) { address -> - contacts.canReadContacts() && - contacts.lookup(address) == ContactLookup.NOT_FOUND && - contacts.sentTo(address) == ContactLookup.NOT_FOUND - } - } - } - } - - /** - * A keyword or regex allow rule allows the sender too, once the message is really delivered (so probes that only - * evaluate never add rules). Does nothing for any other decision, including an allow by a sender rule or a - * contact. A contact, a number the user wrote to, a sender that already has a rule, or a failed lookup leaves the - * rules alone. Never throws. - */ - fun allowSenderOfKeyword(context: Context, message: IncomingMessage, decision: FilterDecision?) { - val allow = decision as? FilterDecision.Allow ?: return - if (allow.reason != DecisionReason.ALLOW_RULE || allow.ruleId == null) return - runCatching { - val app = context.applicationContext - val repo = UMessage.repository(app) as? DefaultSpamRepository ?: return - val contacts = contactChecker(app) - runBlocking { - repo.allowSenderOfKeywordMatch(message.address, allow.ruleId) { address -> - contacts.canReadContacts() && - contacts.lookup(address) == ContactLookup.NOT_FOUND && - contacts.sentTo(address) == ContactLookup.NOT_FOUND - } - } - } - } - - /** - * Records what the download of a blocked MMS produced (see [DefaultSpamRepository.attachDownloadedMedia]). - * False when the row is gone or recording failed; the caller then deletes [mediaFile]. - */ - fun attachDownloadedMedia(context: Context, blockedId: Long, mediaFile: String?, text: String?): Boolean = try { - (UMessage.repository(context) as? DefaultSpamRepository)?.attachDownloadedMedia(blockedId, mediaFile, text) == true - } catch (_: Throwable) { - false - } - - /** - * Deletes expired blocked messages, at most once per [com.glooboo.umessage.spam.data.PurgePolicy.INTERVAL_MS]. - * Called from the receivers and app start; the UI calls the repository directly for an immediate purge. - */ - fun purgeExpired(context: Context, now: Long = System.currentTimeMillis()) { - try { - val app = context.applicationContext - if (!settingsStore(app).claimPurge(now)) return - // The decision log has its own, shorter retention; it goes first so a failing repository purge - // can't keep old sender numbers around. - runCatching { UMessage.log(app).purgeExpired() } - runBlocking { repository(app).purgeExpired() } - } catch (_: Throwable) { - } - } -} +package com.glooboo.umessage.spam.engine + +import android.annotation.SuppressLint +import android.content.Context +import android.telephony.SubscriptionManager +import kotlinx.coroutines.runBlocking +import com.glooboo.umessage.helpers.W3aPrefs +import com.glooboo.umessage.spam.ForwardRepository +import com.glooboo.umessage.spam.data.DefaultForwardRepository +import com.glooboo.umessage.spam.BlockedMessage +import com.glooboo.umessage.spam.DecisionReason +import com.glooboo.umessage.spam.DecisionRuleText +import com.glooboo.umessage.spam.FilterDecision +import com.glooboo.umessage.spam.IncomingMessage +import com.glooboo.umessage.spam.MmsMedia +import com.glooboo.umessage.spam.SpamLogEntry +import com.glooboo.umessage.spam.UMessage +import com.glooboo.umessage.spam.data.AndroidSpamPlatform +import com.glooboo.umessage.spam.data.BlockedNotifier +import com.glooboo.umessage.spam.data.DefaultSpamRepository +import com.glooboo.umessage.spam.data.SpamDatabase +import com.glooboo.umessage.spam.data.SpamSettingsStore + +/** + * Wiring and the fail-open entry points used by the receivers. The singletons below hold no Context directly: + * Android access goes through the application context captured by [AndroidSpamPlatform] and the environment + * classes, behind interfaces. + */ +object SpamEngine { + @Volatile private var repository: DefaultSpamRepository? = null + @Volatile private var filter: DefaultSpamFilter? = null + @Volatile private var settingsStore: SpamSettingsStore? = null + @Volatile private var forwardPlanner: ForwardPlanner? = null + @Volatile private var checker: SystemContactChecker? = null + + fun install() { + UMessage.filterFactory = { filter(it) } + UMessage.repositoryFactory = { repository(it) } + } + + fun repository(context: Context): DefaultSpamRepository = repository ?: synchronized(this) { + repository ?: run { + val app = context.applicationContext + DefaultSpamRepository( + platform = AndroidSpamPlatform(app), + db = SpamDatabase.getInstance(app), + settingsStore = settingsStore(app), + normalizer = normalizer(app), + regionForSubscription = { subscriptionRegion(app, it) }, + blockedFromMessageNote = { com.glooboo.umessage.ui.spam.RuleNotes.BLOCKED_FROM_MESSAGE }, + blockedFromKeywordNote = { com.glooboo.umessage.ui.spam.RuleNotes.BLOCKED_FROM_KEYWORD }, + allowedFromKeywordNote = { com.glooboo.umessage.ui.spam.RuleNotes.ALLOWED_FROM_KEYWORD }, + ).also { repository = it } + } + } + + fun filter(context: Context): DefaultSpamFilter = filter ?: synchronized(this) { + filter ?: run { + val app = context.applicationContext + val repo = repository(app) + val normalizer = normalizer(app) + DefaultSpamFilter( + rules = repo::currentRules, + settings = repo::currentSettings, + contacts = contactChecker(app), + normalizer = normalizer, + legacy = FossifyLegacyBlocklist(app), + regionForSubscription = { subscriptionRegion(app, it) }, + ).also { filter = it } + } + } + + /** + * The one contact checker of the process: it registers content observers and keeps the address book and the sent + * history in memory, so the filter and the helpers below share it instead of each making (and leaking) their own. + */ + fun contactChecker(context: Context): SystemContactChecker = checker ?: synchronized(this) { + checker ?: run { + val app = context.applicationContext + SystemContactChecker(app, normalizer(app)).also { checker = it } + } + } + + /** Stops the shared checker's observers and forgets it (and the filter that holds it); a test starts clean. */ + internal fun resetContactChecker() = synchronized(this) { + checker?.close() + checker = null + filter = null + } + + /** A thin wrapper over the database's DAO, made on each call so it always uses the current database instance. */ + fun forwardRepository(context: Context): ForwardRepository = + DefaultForwardRepository(SpamDatabase.getInstance(context.applicationContext).forwardDao()) + + /** The forward rules' matcher: the same number, sender id, keyword and pattern reading as the spam filter. */ + fun forwardPlanner(context: Context): ForwardPlanner = forwardPlanner ?: synchronized(this) { + forwardPlanner ?: run { + val app = context.applicationContext + ForwardPlanner( + matcher = RuleMatcher(normalizer(app), regionForSubscription = { subscriptionRegion(app, it) }), + simInSlot = { slot -> subscriptionInSlot(app, slot) }, + codeMask = { W3aPrefs.get(app).forwardCodeMasker() }, + ).also { forwardPlanner = it } + } + } + + /** The active SIM in 1-based [slot], or null (empty slot, no permission). */ + @SuppressLint("MissingPermission") + private fun subscriptionInSlot(context: Context, slot: Int): Int? = runCatching { + context.getSystemService(SubscriptionManager::class.java) + ?.getActiveSubscriptionInfoForSimSlotIndex(slot - 1)?.subscriptionId + }.getOrNull() + + private fun settingsStore(context: Context): SpamSettingsStore = settingsStore ?: synchronized(this) { + settingsStore ?: SpamSettingsStore(context).also { settingsStore = it } + } + + private fun normalizer(context: Context): NumberNormalizer { + val app = context.applicationContext + return NumberNormalizer { defaultRegion(app) } + } + + /** Whether the user has written to [address] before: such a number is known, like a contact. Never throws. */ + fun hasWrittenTo(context: Context, address: String): Boolean = runCatching { + contactChecker(context).sentTo(address) == ContactLookup.FOUND + }.getOrDefault(false) + + /** Returns the Block decision, or null when allowed or when the filter itself fails (never drop on error). */ + fun block(context: Context, message: IncomingMessage, source: String? = null): FilterDecision.Block? = + evaluate(context, message, source) as? FilterDecision.Block + + /** + * Full decision, logged to [SpamLog]. Null when the filter itself failed, including with an Error such as + * ExceptionInInitializerError or OutOfMemoryError (callers must then deliver). + */ + fun evaluate(context: Context, message: IncomingMessage, source: String? = null): FilterDecision? { + val where = source ?: if (message.isMms) "MMS" else "SMS" + val decision = try { + UMessage.filter(context).evaluate(message) + } catch (t: Throwable) { + record(context, message, "ERROR", t.javaClass.simpleName, where) + return null + } + // DecisionReason.CONTACTS_UNAVAILABLE lands here too, so a missing contacts permission is visible in the log. + val ruleId = when (decision) { + is FilterDecision.Block -> decision.ruleId + is FilterDecision.Allow -> decision.ruleId + } + record( + context, message, if (decision is FilterDecision.Block) "BLOCK" else "ALLOW", decision.reason.name, where, + ruleId, ruleId?.let { ruleLabelOf(context, it) }.orEmpty(), + ) + return decision + } + + /** The short label (the value) of rule [id] for the decision log; empty when the rule can't be read. */ + private fun ruleLabelOf(context: Context, id: Long): String = try { + repository(context).currentRules().firstOrNull { it.id == id }?.let { DecisionRuleText.label(it) }.orEmpty() + } catch (_: Throwable) { + "" + } + + private fun record( + context: Context, + message: IncomingMessage, + decision: String, + reason: String, + source: String, + ruleId: Long? = null, + ruleLabel: String = "", + ) { + try { + UMessage.log(context).record( + SpamLogEntry( + System.currentTimeMillis(), message.address, message.subscriptionId, decision, reason, source, + ruleId, ruleLabel, + ) + ) + } catch (_: Throwable) { + } + } + + /** + * Write-ahead store of a blocked message. Returns false when storing failed for any reason (Errors included), + * so the caller delivers it instead. An MMS with a blank body is stored with the placeholder text. + */ + fun storeBlocked(context: Context, message: IncomingMessage, decision: FilterDecision.Block): Boolean = + storeBlockedId(context, message, decision) != null + + /** + * [storeBlocked] returning the row id (null when storing failed). For an MMS, [media] / [mediaFile] say what + * of its content is kept (default: nothing). + */ + fun storeBlockedId( + context: Context, + message: IncomingMessage, + decision: FilterDecision.Block, + media: MmsMedia = if (message.isMms) MmsMedia.MISSING else MmsMedia.NONE, + mediaFile: String? = null, + onDuplicate: (() -> Unit)? = null, + ): Long? { + return try { + val (id, duplicate) = runBlocking { + val repo = UMessage.repository(context) + repo.storeBlockedChecked( + BlockedMessage( + address = message.address, + body = message.body, + subscriptionId = message.subscriptionId, + isMms = message.isMms, + receivedAt = message.receivedAt, + reason = decision.reason, + ruleId = decision.ruleId, + media = media, + mediaFile = mediaFile, + ) + ) + } + if (duplicate) onDuplicate?.invoke() + blockSenderOfKeyword(context, id, decision) + purgeExpired(context) + id + } catch (t: Throwable) { + record(context, message, "ERROR", "STORE_FAILED_" + t.javaClass.simpleName, "STORE") + null + } + } + + /** + * A keyword or regex block rule blocks the sender too, once the message is really stored (so probes that only + * evaluate never add rules). A contact, a number the user wrote to, or a failed lookup keeps the sender unblocked. + * Never throws. + */ + private fun blockSenderOfKeyword(context: Context, blockedId: Long, decision: FilterDecision.Block) { + if (decision.reason != DecisionReason.BLOCK_RULE || decision.ruleId == null) return + runCatching { + val app = context.applicationContext + val repo = UMessage.repository(app) as? DefaultSpamRepository ?: return + val contacts = contactChecker(app) + runBlocking { + repo.blockSenderOfKeywordMatch(blockedId, decision.ruleId) { address -> + contacts.canReadContacts() && + contacts.lookup(address) == ContactLookup.NOT_FOUND && + contacts.sentTo(address) == ContactLookup.NOT_FOUND + } + } + } + } + + /** + * A keyword or regex allow rule allows the sender too, once the message is really delivered (so probes that only + * evaluate never add rules). Does nothing for any other decision, including an allow by a sender rule or a + * contact. A contact, a number the user wrote to, a sender that already has a rule, or a failed lookup leaves the + * rules alone. Never throws. + */ + fun allowSenderOfKeyword(context: Context, message: IncomingMessage, decision: FilterDecision?) { + val allow = decision as? FilterDecision.Allow ?: return + if (allow.reason != DecisionReason.ALLOW_RULE || allow.ruleId == null) return + runCatching { + val app = context.applicationContext + val repo = UMessage.repository(app) as? DefaultSpamRepository ?: return + val contacts = contactChecker(app) + runBlocking { + repo.allowSenderOfKeywordMatch(message.address, allow.ruleId) { address -> + contacts.canReadContacts() && + contacts.lookup(address) == ContactLookup.NOT_FOUND && + contacts.sentTo(address) == ContactLookup.NOT_FOUND + } + } + } + } + + /** + * Records what the download of a blocked MMS produced (see [DefaultSpamRepository.attachDownloadedMedia]). + * False when the row is gone or recording failed; the caller then deletes [mediaFile]. + */ + fun attachDownloadedMedia(context: Context, blockedId: Long, mediaFile: String?, text: String?): Boolean = try { + (UMessage.repository(context) as? DefaultSpamRepository)?.attachDownloadedMedia(blockedId, mediaFile, text) == true + } catch (_: Throwable) { + false + } + + /** + * Deletes expired blocked messages, at most once per [com.glooboo.umessage.spam.data.PurgePolicy.INTERVAL_MS]. + * Called from the receivers and app start; the UI calls the repository directly for an immediate purge. + */ + fun purgeExpired(context: Context, now: Long = System.currentTimeMillis()) { + try { + val app = context.applicationContext + if (!settingsStore(app).claimPurge(now)) return + // The decision log has its own, shorter retention; it goes first so a failing repository purge + // can't keep old sender numbers around. + runCatching { UMessage.log(app).purgeExpired() } + runBlocking { repository(app).purgeExpired() } + } catch (_: Throwable) { + } + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ArchivedRoute.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ArchivedRoute.kt index 344ad1cb..cd9e5a6a 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ArchivedRoute.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ArchivedRoute.kt @@ -1,196 +1,201 @@ -package com.glooboo.umessage.ui.conversations - -import android.app.Application -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalResources -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import com.glooboo.umessage.R -import com.glooboo.umessage.helpers.HiddenChats -import com.glooboo.umessage.helpers.NavPrefs -import com.glooboo.umessage.ui.components.showUndo -import com.glooboo.umessage.ui.icons.Symbols -import kotlinx.coroutines.launch -import androidx.lifecycle.AndroidViewModel -import androidx.lifecycle.compose.LifecycleResumeEffect -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.lifecycle.viewmodel.compose.viewModel -import com.glooboo.umessage.extensions.config -import com.glooboo.umessage.extensions.conversationsDB -import com.glooboo.umessage.extensions.deleteConversation -import com.glooboo.umessage.extensions.getAllDrafts -import com.glooboo.umessage.extensions.markThreadMessagesRead -import com.glooboo.umessage.extensions.removeAllArchivedConversations -import com.glooboo.umessage.extensions.updateConversationArchivedStatus -import com.glooboo.umessage.helpers.refreshConversations -import com.glooboo.umessage.models.Conversation -import com.glooboo.umessage.models.Events -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import org.fossify.commons.extensions.notificationManager -import org.fossify.commons.helpers.ensureBackgroundThread -import org.greenrobot.eventbus.EventBus -import org.greenrobot.eventbus.Subscribe -import org.greenrobot.eventbus.ThreadMode - -data class ArchivedUiState(val rows: List = emptyList(), val loading: Boolean = true) - -/** Archived conversations for the Archived tab; unarchiving or deleting keeps the proven data calls. */ -class ArchivedViewModel(application: Application) : AndroidViewModel(application) { - private val app: Application get() = getApplication() - private val _state = MutableStateFlow(ArchivedUiState()) - val state: StateFlow = _state.asStateFlow() - - init { - EventBus.getDefault().takeUnless { it.isRegistered(this) }?.register(this) - } - - override fun onCleared() { - EventBus.getDefault().unregister(this) - } - - fun load() { - ensureBackgroundThread { - val conversations = try { - app.conversationsDB.getAllArchived() - } catch (_: Exception) { - emptyList() - } - val drafts = runCatching { app.getAllDrafts() }.getOrDefault(HashMap()) - val pinned = app.config.pinnedConversations - // B06: hidden chats stay out of the archive too, until they are unlocked. - val rows = HiddenChats.get(app).withoutHidden(conversations) { it.threadId } - .sortedWith( - compareByDescending { pinned.contains(it.threadId.toString()) } - .thenByDescending { it.date }, - ) - .map { it.toFolderRow(app, drafts, pinned) } - _state.value = ArchivedUiState(rows = rows, loading = false) - } - } - - fun unarchive(ids: Set) { - ensureBackgroundThread { - ids.forEach { app.updateConversationArchivedStatus(it, false) } - refreshConversations() - } - } - - /** Undo of [unarchive]. */ - fun archiveAgain(ids: Set) { - ensureBackgroundThread { - ids.forEach { app.updateConversationArchivedStatus(it, true) } - refreshConversations() - } - } - - /** CL-32: archived promotions pile up unread; this marks every archived chat read. */ - fun markAllRead() { - ensureBackgroundThread { - _state.value.rows.filter { it.unread }.forEach { runCatching { app.markThreadMessagesRead(it.threadId) } } - refreshConversations() - } - } - - fun delete(ids: Set) { - ensureBackgroundThread { - ids.forEach { - app.deleteConversation(it) - app.notificationManager.cancel(it.hashCode()) - } - refreshConversations() - } - } - - fun deleteAll() { - app.removeAllArchivedConversations { load() } - } - - @Subscribe(threadMode = ThreadMode.MAIN) - fun refreshConversations(@Suppress("unused") event: Events.RefreshConversations) { - load() - } -} - -/** - * Archived tab: the shared folder screen without a back arrow; reloads whenever it comes back on screen. Unarchiving - * says where the chats went and offers Undo; a one-line intro explains what the archive does until it is dismissed. - */ -@Composable -fun ArchivedRoute(onOpen: (ConversationRow) -> Unit, onBackToMessages: (() -> Unit)? = null) { - val viewModel: ArchivedViewModel = viewModel() - val state by viewModel.state.collectAsStateWithLifecycle() - val context = LocalContext.current - val resources = LocalResources.current - val scope = rememberCoroutineScope() - val snackbar = remember { SnackbarHostState() } - val prefs = remember(context) { NavPrefs.get(context) } - val introDismissed by prefs.archivedIntroDismissedFlow.collectAsStateWithLifecycle(initialValue = true) - LifecycleResumeEffect(viewModel) { - viewModel.load() - onPauseOrDispose { } - } - ConversationFolderScreen( - folder = ConversationFolder.Archive, - rows = state.rows, - loading = state.loading, - onBack = null, - onOpen = onOpen, - onRestore = { ids -> - viewModel.unarchive(ids) - scope.launch { - snackbar.showUndo( - message = resources.getQuantityString(R.plurals.nav_archived_moved, ids.size, ids.size), - undoLabel = resources.getString(R.string.convlist_undo), - onUndo = { viewModel.archiveAgain(ids) }, - ) - } - }, - onDelete = viewModel::delete, - onEmpty = viewModel::deleteAll, - snackbarHostState = snackbar, - onBackToMessages = onBackToMessages, - onMarkAllRead = viewModel::markAllRead, - intro = if (introDismissed) null else { - { ArchivedIntro(onDismiss = { prefs.archivedIntroDismissed = true }) } - }, - ) -} - -@Composable -private fun ArchivedIntro(onDismiss: () -> Unit) { - Surface( - shape = RoundedCornerShape(12.dp), - color = MaterialTheme.colorScheme.surfaceContainerHigh, - modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), - ) { - Row(Modifier.padding(start = 16.dp), verticalAlignment = Alignment.CenterVertically) { - Text( - stringResource(R.string.nav_archived_intro), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.weight(1f).padding(vertical = 8.dp), - ) - IconButton(onClick = onDismiss) { - Icon(Symbols.Close, contentDescription = stringResource(R.string.nav_archived_intro_dismiss)) - } - } - } -} +package com.glooboo.umessage.ui.conversations + +import android.app.Application +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalResources +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.glooboo.umessage.R +import com.glooboo.umessage.helpers.HiddenChats +import com.glooboo.umessage.helpers.NavPrefs +import com.glooboo.umessage.ui.components.showUndo +import com.glooboo.umessage.ui.icons.Symbols +import kotlinx.coroutines.launch +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import com.glooboo.umessage.extensions.config +import com.glooboo.umessage.extensions.conversationsDB +import com.glooboo.umessage.extensions.deleteConversation +import com.glooboo.umessage.extensions.getAllDrafts +import com.glooboo.umessage.extensions.markThreadMessagesRead +import com.glooboo.umessage.extensions.removeAllArchivedConversations +import com.glooboo.umessage.extensions.updateConversationArchivedStatus +import com.glooboo.umessage.helpers.refreshConversations +import com.glooboo.umessage.models.Conversation +import com.glooboo.umessage.models.Events +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import org.fossify.commons.extensions.notificationManager +import org.fossify.commons.helpers.ensureBackgroundThread +import org.greenrobot.eventbus.EventBus +import org.greenrobot.eventbus.Subscribe +import org.greenrobot.eventbus.ThreadMode + +data class ArchivedUiState(val rows: List = emptyList(), val loading: Boolean = true) + +/** Archived conversations for the Archived tab; unarchiving or deleting keeps the proven data calls. */ +class ArchivedViewModel(application: Application) : AndroidViewModel(application) { + private val app: Application get() = getApplication() + private val _state = MutableStateFlow(ArchivedUiState()) + val state: StateFlow = _state.asStateFlow() + + init { + EventBus.getDefault().takeUnless { it.isRegistered(this) }?.register(this) + } + + /** Loads run one after another, so a slow older read can never overwrite the state a newer one published. */ + private val loader = java.util.concurrent.Executors.newSingleThreadExecutor() + + override fun onCleared() { + EventBus.getDefault().unregister(this) + loader.shutdown() + } + + fun load() { + if (loader.isShutdown) return + loader.execute { + val conversations = try { + app.conversationsDB.getAllArchived() + } catch (_: Exception) { + emptyList() + } + val drafts = runCatching { app.getAllDrafts() }.getOrDefault(HashMap()) + val pinned = app.config.pinnedConversations + // B06: hidden chats stay out of the archive too, until they are unlocked. + val rows = HiddenChats.get(app).withoutHidden(conversations) { it.threadId } + .sortedWith( + compareByDescending { pinned.contains(it.threadId.toString()) } + .thenByDescending { it.date }, + ) + .map { it.toFolderRow(app, drafts, pinned) } + _state.value = ArchivedUiState(rows = rows, loading = false) + } + } + + fun unarchive(ids: Set) { + ensureBackgroundThread { + ids.forEach { app.updateConversationArchivedStatus(it, false) } + refreshConversations() + } + } + + /** Undo of [unarchive]. */ + fun archiveAgain(ids: Set) { + ensureBackgroundThread { + ids.forEach { app.updateConversationArchivedStatus(it, true) } + refreshConversations() + } + } + + /** CL-32: archived promotions pile up unread; this marks every archived chat read. */ + fun markAllRead() { + ensureBackgroundThread { + _state.value.rows.filter { it.unread }.forEach { runCatching { app.markThreadMessagesRead(it.threadId) } } + refreshConversations() + } + } + + fun delete(ids: Set) { + ensureBackgroundThread { + ids.forEach { + app.deleteConversation(it) + app.notificationManager.cancel(it.hashCode()) + } + refreshConversations() + } + } + + fun deleteAll() { + app.removeAllArchivedConversations { load() } + } + + @Subscribe(threadMode = ThreadMode.MAIN) + fun refreshConversations(@Suppress("unused") event: Events.RefreshConversations) { + load() + } +} + +/** + * Archived tab: the shared folder screen without a back arrow; reloads whenever it comes back on screen. Unarchiving + * says where the chats went and offers Undo; a one-line intro explains what the archive does until it is dismissed. + */ +@Composable +fun ArchivedRoute(onOpen: (ConversationRow) -> Unit, onBackToMessages: (() -> Unit)? = null) { + val viewModel: ArchivedViewModel = viewModel() + val state by viewModel.state.collectAsStateWithLifecycle() + val context = LocalContext.current + val resources = LocalResources.current + val scope = rememberCoroutineScope() + val snackbar = remember { SnackbarHostState() } + val prefs = remember(context) { NavPrefs.get(context) } + val introDismissed by prefs.archivedIntroDismissedFlow.collectAsStateWithLifecycle(initialValue = true) + LifecycleResumeEffect(viewModel) { + viewModel.load() + onPauseOrDispose { } + } + ConversationFolderScreen( + folder = ConversationFolder.Archive, + rows = state.rows, + loading = state.loading, + onBack = null, + onOpen = onOpen, + onRestore = { ids -> + viewModel.unarchive(ids) + scope.launch { + snackbar.showUndo( + message = resources.getQuantityString(R.plurals.nav_archived_moved, ids.size, ids.size), + undoLabel = resources.getString(R.string.convlist_undo), + onUndo = { viewModel.archiveAgain(ids) }, + ) + } + }, + onDelete = viewModel::delete, + onEmpty = viewModel::deleteAll, + snackbarHostState = snackbar, + onBackToMessages = onBackToMessages, + onMarkAllRead = viewModel::markAllRead, + intro = if (introDismissed) null else { + { ArchivedIntro(onDismiss = { prefs.archivedIntroDismissed = true }) } + }, + ) +} + +@Composable +private fun ArchivedIntro(onDismiss: () -> Unit) { + Surface( + shape = RoundedCornerShape(12.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), + ) { + Row(Modifier.padding(start = 16.dp), verticalAlignment = Alignment.CenterVertically) { + Text( + stringResource(R.string.nav_archived_intro), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f).padding(vertical = 8.dp), + ) + IconButton(onClick = onDismiss) { + Icon(Symbols.Close, contentDescription = stringResource(R.string.nav_archived_intro_dismiss)) + } + } + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsModels.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsModels.kt index 547f3589..f2438335 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsModels.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsModels.kt @@ -46,6 +46,8 @@ data class SelectionActions( val canArchive: Boolean = false, /** "Report spam" blocks one sender per chat, so it is offered only when no group chat is selected. */ val canReportSpam: Boolean = false, + /** "Block number" skips group chats, so it is offered only when at least one single-sender chat is selected. */ + val canBlock: Boolean = false, val canAddContact: Boolean = false, val canCopyNumber: Boolean = false, val canDial: Boolean = false, diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsSelectionBar.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsSelectionBar.kt index 8dbcdd91..8f79bf59 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsSelectionBar.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsSelectionBar.kt @@ -50,6 +50,8 @@ fun ConversationsSelectionBar( modifier: Modifier = Modifier, /** I29: opens the label picker for the selected rows; no Labels entry while null. */ onLabels: (() -> Unit)? = null, + /** Select all of the rows on screen (a filter may hide some); the whole list by default. */ + onSelectAll: () -> Unit = callbacks.onSelectAll, ) { var menuOpen by remember { mutableStateOf(false) } var blockDialog by rememberSaveable { mutableStateOf(false) } @@ -58,7 +60,7 @@ fun ConversationsSelectionBar( SelectionTopBar(count = selection.count, onClose = callbacks.onClearSelection, modifier = modifier) { // CL-22: Select all is on the bar itself, not buried in the menu (Pin moved there to make room). if (!selection.allSelected) { - IconButton(onClick = callbacks.onSelectAll) { + IconButton(onClick = onSelectAll) { Icon(Symbols.SelectAll, contentDescription = stringResource(R.string.convlist_select_all)) } } @@ -183,7 +185,7 @@ private fun selectionMenuGroups( } }, buildList { - add(MenuEntry(R.string.ux8a_selection_block, Symbols.Block, onBlock)) + if (selection.canBlock) add(MenuEntry(R.string.ux8a_selection_block, Symbols.Block, onBlock)) if (selection.canReportSpam) { add( MenuEntry( diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModel.kt index bbb6a94b..f496812b 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModel.kt @@ -281,8 +281,9 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic } } - fun selectAll() { - selected = _state.value.rows.mapTo(HashSet()) { it.threadId } + /** Selects every row, or only [visibleThreadIds] when a filter hides some rows (select all must not reach them). */ + fun selectAll(visibleThreadIds: Collection? = null) { + selected = visibleThreadIds?.toHashSet() ?: _state.value.rows.mapTo(HashSet()) { it.threadId } requestRebuild() } @@ -467,7 +468,8 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic * snackbar offers Undo, which removes the rules again (through [undoReportSpam], with nothing to unarchive). */ fun blockSelected() { - val conversations = selectedConversations() + // A group chat has no single sender, so it is left out, as blockOne and reportSpamSelected do. + val conversations = selectedConversations().filterNot { it.isGroupConversation } if (conversations.isEmpty()) return selected = emptySet() requestRebuild() @@ -647,7 +649,6 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic private fun build(s: Snapshot): ConversationsUiState { val config = app.config - val withNotes = noteThreads val pinned = config.pinnedConversations val customNotifications = config.customNotifications // One binder call per rebuild instead of one per chat with its own notification channel. @@ -674,7 +675,6 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic .thenByDescending { unreadFirst && !it.read } .thenByDescending { it.date }, ) - val minute = now / MINUTE_MS val rows = sorted.map { c -> val draft = s.drafts[c.threadId] val simSlot = if (showSim && !c.isGroupConversation) { @@ -692,8 +692,8 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic muted = mutePrefs.isMuted(c.threadId) || (customNotifications.contains(c.threadId.toString()) && c.threadId.toString() in mutedChannels), otpFresh = !c.read && now - c.date * 1000L in 0..OTP_CHIP_MS, - hasNotes = c.threadId in withNotes, - minute = minute, locale = locale, + hasNotes = c.threadId in noteThreads, + minute = now / MINUTE_MS, locale = locale, ) rowCache.get(c.threadId, input) { val unread = !c.read @@ -751,13 +751,14 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic canMarkUnread = chosen.any { it.read }, canArchive = s.status.archiveAvailable, canReportSpam = chosen.none { it.isGroupConversation }, + canBlock = chosen.any { !it.isGroupConversation }, canAddContact = single != null && !single.isGroupConversation, canCopyNumber = single != null && !single.isGroupConversation, canDial = single != null && !single.isGroupConversation && !isShortCodeWithLetters(single.phoneNumber), canRename = single != null && single.isGroupConversation, canShowDetails = single != null, allSelected = chosen.size == rows.size, - numbers = chosen.map { it.phoneNumber }.distinct(), + numbers = chosen.filterNot { it.isGroupConversation }.map { it.phoneNumber }.distinct(), renameInitial = single?.title.orEmpty(), ) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedViewModel.kt index 7a34eb15..84813bb4 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedViewModel.kt @@ -119,10 +119,15 @@ class ForwardedViewModel(application: Application) : AndroidViewModel(applicatio if (ids.isEmpty() || ui.value.busy) return ui.update { it.copy(busy = true) } viewModelScope.launch(Dispatchers.IO) { - val results = ids.map { ForwardResend.retry(app, it) } + val results = try { + ids.map { id -> + runCatching { ForwardResend.retry(app, id) }.getOrDefault(ForwardResend.RetryResult.FAILED) + } + } finally { + ui.update { it.copy(busy = false) } + } runCatching { refreshMessages() } runCatching { refreshConversations() } - ui.update { it.copy(busy = false) } _events.emit(retriedEvent(results)) } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/lock/LockViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/lock/LockViewModel.kt index 356a10c7..bd32c08d 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/lock/LockViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/lock/LockViewModel.kt @@ -102,7 +102,9 @@ class LockViewModel(app: Application) : AndroidViewModel(app) { } fun submitPattern(cells: List) { - if (!inputEnabled || cells.isEmpty()) return + // A touch of 1-3 dots is not an attempt: a pattern is never shorter than the minimum, + // so it must not count as a failure. + if (!inputEnabled || cells.size < com.glooboo.umessage.dialogs.AppLockLogic.MIN_PATTERN_DOTS) return verify { session.submitPattern(cells) } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainScreen.kt index 9717cfe9..773c3a41 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainScreen.kt @@ -238,12 +238,9 @@ private fun ActiveFilterBar( } } -/** Selecting rows closes the search, and "select all" must not leave a filter on that hides some selected rows. */ +/** Selecting rows closes the search. "Select all" selects the filtered rows only, so the filter stays on. */ @Composable -private fun SelectionSearchEffects(selecting: Boolean, allSelected: Boolean, search: MainSearchState) { - LaunchedEffect(selecting, allSelected) { - if (selecting && allSelected) search.filter = InboxFilter.All - } +private fun SelectionSearchEffects(selecting: Boolean, search: MainSearchState) { LaunchedEffect(selecting) { if (selecting && search.active) search.close() } @@ -295,7 +292,7 @@ private fun MessagesTab( val shortcut = rememberSimThreads(search) ?: labels.shortcut val simName = simTiles.firstOrNull { it.subscriptionId == search.simId }?.label .takeIf { filter == InboxFilter.Sim } - SelectionSearchEffects(selecting, state.selection.allSelected, search) + SelectionSearchEffects(selecting, search) // Leaving search parks focus on a hidden spot instead of clearing it: cleared focus is handed back to the first // focusable item, which took 3-4 Back presses to leave. val keyboard = LocalSoftwareKeyboardController.current @@ -340,6 +337,11 @@ private fun MessagesTab( selection = state.selection, callbacks = callbacks, onLabels = labels.openPicker, + onSelectAll = { + viewModel.selectAll( + InboxFilterPolicy.filterRows(state.rows, filter, shortcut.threads).map { it.threadId }, + ) + }, ) } else { MainTopBar( diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchPage.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchPage.kt index 37b3451d..75680698 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchPage.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchPage.kt @@ -1,151 +1,159 @@ -package com.glooboo.umessage.ui.main - -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.statusBarsPadding -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.foundation.text.KeyboardActions -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextField -import androidx.compose.material3.TextFieldDefaults -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.Alignment -import androidx.compose.ui.focus.FocusRequester -import androidx.compose.ui.focus.focusRequester -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalSoftwareKeyboardController -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import com.glooboo.umessage.R -import com.glooboo.umessage.helpers.SearchHistoryPrefs -import com.glooboo.umessage.models.SearchResult -import com.glooboo.umessage.ui.conversations.ConversationRow -import com.glooboo.umessage.ui.icons.Symbols -import com.glooboo.umessage.ui.labels.activeLabelName - -/** The most the filter chip in the field may take, so a long label name leaves room for the typed text. */ -private val FieldChipMaxWidth = 168.dp - -/** - * N11: the full-screen search page. A text field with a back arrow on top; below it the tiles (with the labels and the - * last searches) until a tile is picked or text is typed, then the matching conversations, one row each. Picking a tile - * lists its conversations at once, hides the keyboard and shows the tile as a removable chip in the field (U21), in - * place of the tile grid. [rows] are the inbox's conversations, which the tiles filter; - * [shortcut] is what the Unknown, Starred, Images, Links, label and SIM tiles found. Back from the results returns to - * the tiles; [onLeave] closes the page, and the caller also hides the keyboard and parks focus there, so the inbox - * below does not hand it to its first button. - */ -@Composable -internal fun MainSearchPage( - search: MainSearchState, - rows: List, - shortcut: ShortcutHits, - onQueryChange: (String) -> Unit, - onOpenResult: (SearchResult) -> Unit, - onLeave: () -> Unit, - modifier: Modifier = Modifier, - simTiles: List = emptyList(), - onOpenStars: () -> Unit = {}, -) { - val keyboard = LocalSoftwareKeyboardController.current - val fieldFocus = remember { FocusRequester() } - val context = LocalContext.current - // CL-14: the last few searches, kept on the phone, come back as chips on the empty search page. - val history = remember(context) { SearchHistoryPrefs.get(context) } - var recent by remember { mutableStateOf(history.recentSearches) } - val saveRecent = { query: String -> if (isSearchable(query)) recent = history.remember(query.trim()) } - val resultsListState = rememberLazyListState() - val goBack = { if (search.hasTileOn()) search.backToTiles(onQueryChange) else onLeave() } - LaunchedEffect(Unit) { fieldFocus.requestFocus() } - - Surface(modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { - Column(Modifier.fillMaxSize().statusBarsPadding()) { - TextField( - value = search.query, - onValueChange = onQueryChange, - modifier = Modifier.fillMaxWidth().focusRequester(fieldFocus), - singleLine = true, - placeholder = { - Text(stringResource(R.string.main_search_hint), maxLines = 1, overflow = TextOverflow.Ellipsis) - }, - leadingIcon = { - Row(verticalAlignment = Alignment.CenterVertically) { - IconButton(onClick = goBack) { - Icon(Symbols.ArrowBack, contentDescription = stringResource(R.string.main_search_back)) - } - if (search.filter != InboxFilter.All) { - ActiveFilterChip( - search.filter, - onClear = { search.filter = InboxFilter.All }, - modifier = Modifier.widthIn(max = FieldChipMaxWidth), - labelName = activeLabelName(search) - ?: simTiles.firstOrNull { it.subscriptionId == search.simId }?.label - .takeIf { search.filter == InboxFilter.Sim }, - ) - } - } - }, - trailingIcon = { - if (search.query.isNotEmpty()) { - IconButton(onClick = { onQueryChange("") }) { - Icon(Symbols.Close, contentDescription = stringResource(R.string.main_search_clear)) - } - } - }, - keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), - keyboardActions = KeyboardActions(onSearch = { - saveRecent(search.query) - keyboard?.hide() - }), - colors = TextFieldDefaults.colors( - focusedContainerColor = Color.Transparent, - unfocusedContainerColor = Color.Transparent, - focusedIndicatorColor = Color.Transparent, - unfocusedIndicatorColor = Color.Transparent, - ), - ) - val actions = SearchPanelActions( - onPickRecent = onQueryChange, - onClearRecent = { - history.recentSearches = emptyList() - recent = emptyList() - }, - onFilter = { - // Starred is its own screen: one row per starred message, not the chats that hold them. - if (it == InboxFilter.Starred) { - onOpenStars() - } else { - search.filter = it - if (it != InboxFilter.All) keyboard?.hide() - } - }, - onSim = { - search.toggleSim(it) - if (search.filter == InboxFilter.Sim) keyboard?.hide() - }, - onOpen = { result -> - saveRecent(search.query) - onOpenResult(result) - }, - ) - SearchResultsPanel(search, rows, shortcut, resultsListState, recent, simTiles, actions) - } - } -} +package com.glooboo.umessage.ui.main + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextField +import androidx.compose.material3.TextFieldDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.Alignment +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.glooboo.umessage.R +import com.glooboo.umessage.helpers.HiddenChats +import com.glooboo.umessage.helpers.HiddenChatsSession +import com.glooboo.umessage.helpers.SearchHistoryPrefs +import com.glooboo.umessage.models.SearchResult +import com.glooboo.umessage.ui.conversations.ConversationRow +import com.glooboo.umessage.ui.icons.Symbols +import com.glooboo.umessage.ui.labels.activeLabelName + +/** The most the filter chip in the field may take, so a long label name leaves room for the typed text. */ +private val FieldChipMaxWidth = 168.dp + +/** + * N11: the full-screen search page. A text field with a back arrow on top; below it the tiles (with the labels and the + * last searches) until a tile is picked or text is typed, then the matching conversations, one row each. Picking a tile + * lists its conversations at once, hides the keyboard and shows the tile as a removable chip in the field (U21), in + * place of the tile grid. [rows] are the inbox's conversations, which the tiles filter; + * [shortcut] is what the Unknown, Starred, Images, Links, label and SIM tiles found. Back from the results returns to + * the tiles; [onLeave] closes the page, and the caller also hides the keyboard and parks focus there, so the inbox + * below does not hand it to its first button. + */ +@Composable +internal fun MainSearchPage( + search: MainSearchState, + rows: List, + shortcut: ShortcutHits, + onQueryChange: (String) -> Unit, + onOpenResult: (SearchResult) -> Unit, + onLeave: () -> Unit, + modifier: Modifier = Modifier, + simTiles: List = emptyList(), + onOpenStars: () -> Unit = {}, +) { + val keyboard = LocalSoftwareKeyboardController.current + val fieldFocus = remember { FocusRequester() } + val context = LocalContext.current + // CL-14: the last few searches, kept on the phone, come back as chips on the empty search page. + val history = remember(context) { SearchHistoryPrefs.get(context) } + var recent by remember { mutableStateOf(history.recentSearches) } + // A search typed while hidden chats are unlocked may be about them; the chips outlive the unlock, so skip it then. + val hiddenChats = remember(context) { HiddenChats.get(context) } + val saveRecent = { query: String -> + val hiddenOpen = hiddenChats.isLockOn() && HiddenChatsSession.isUnlocked() && + hiddenChats.chosenIds().isNotEmpty() + if (isSearchable(query) && !hiddenOpen) recent = history.remember(query.trim()) + } + val resultsListState = rememberLazyListState() + val goBack = { if (search.hasTileOn()) search.backToTiles(onQueryChange) else onLeave() } + LaunchedEffect(Unit) { fieldFocus.requestFocus() } + + Surface(modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Column(Modifier.fillMaxSize().statusBarsPadding()) { + TextField( + value = search.query, + onValueChange = onQueryChange, + modifier = Modifier.fillMaxWidth().focusRequester(fieldFocus), + singleLine = true, + placeholder = { + Text(stringResource(R.string.main_search_hint), maxLines = 1, overflow = TextOverflow.Ellipsis) + }, + leadingIcon = { + Row(verticalAlignment = Alignment.CenterVertically) { + IconButton(onClick = goBack) { + Icon(Symbols.ArrowBack, contentDescription = stringResource(R.string.main_search_back)) + } + if (search.filter != InboxFilter.All) { + ActiveFilterChip( + search.filter, + onClear = { search.filter = InboxFilter.All }, + modifier = Modifier.widthIn(max = FieldChipMaxWidth), + labelName = activeLabelName(search) + ?: simTiles.firstOrNull { it.subscriptionId == search.simId }?.label + .takeIf { search.filter == InboxFilter.Sim }, + ) + } + } + }, + trailingIcon = { + if (search.query.isNotEmpty()) { + IconButton(onClick = { onQueryChange("") }) { + Icon(Symbols.Close, contentDescription = stringResource(R.string.main_search_clear)) + } + } + }, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { + saveRecent(search.query) + keyboard?.hide() + }), + colors = TextFieldDefaults.colors( + focusedContainerColor = Color.Transparent, + unfocusedContainerColor = Color.Transparent, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + ), + ) + val actions = SearchPanelActions( + onPickRecent = onQueryChange, + onClearRecent = { + history.recentSearches = emptyList() + recent = emptyList() + }, + onFilter = { + // Starred is its own screen: one row per starred message, not the chats that hold them. + if (it == InboxFilter.Starred) { + onOpenStars() + } else { + search.filter = it + if (it != InboxFilter.All) keyboard?.hide() + } + }, + onSim = { + search.toggleSim(it) + if (search.filter == InboxFilter.Sim) keyboard?.hide() + }, + onOpen = { result -> + saveRecent(search.query) + onOpenResult(result) + }, + ) + SearchResultsPanel(search, rows, shortcut, resultsListState, recent, simTiles, actions) + } + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/newconversation/GroupRecipients.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/newconversation/GroupRecipients.kt index 3efc6a3f..470c26de 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/newconversation/GroupRecipients.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/newconversation/GroupRecipients.kt @@ -8,6 +8,13 @@ data class GroupRecipient(val name: String, val number: String) /** The same number however it was written ("+1 555-..." and "+1555..."): digits and a leading +. */ internal fun recipientKey(number: String): String = typedPhoneNumber(number) ?: number.trim() +/** The address a typed group recipient texts: a phone number, or an email address; null for any other text. */ +internal fun typedGroupRecipient(typed: String): String? { + val text = typed.trim() + typedPhoneNumber(text)?.let { return it } + return text.takeIf { Regex("[^@\\s]+@[^@\\s]+\\.[^@\\s]+").matches(it) } +} + /** Adds [recipient], or removes them when their number is already picked (a second tap on a contact). */ internal fun toggleRecipient(picked: List, recipient: GroupRecipient): List { val key = recipientKey(recipient.number) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/newconversation/NewConversationScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/newconversation/NewConversationScreen.kt index 11522e6c..578f2b9d 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/newconversation/NewConversationScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/newconversation/NewConversationScreen.kt @@ -188,9 +188,13 @@ fun NewConversationScreen( val submit: () -> Unit = { val typed = query.trim() if (groupMode) { - val number = typedPhoneNumber(typed) ?: typed - picked = addRecipient(picked, GroupRecipient(number, number)) - query = "" + val number = typedGroupRecipient(typed) + if (number == null) { + Toast.makeText(context, R.string.group_recipient_invalid, Toast.LENGTH_SHORT).show() + } else { + picked = addRecipient(picked, GroupRecipient(number, number)) + query = "" + } } else { onSubmitAddress(typed) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedFilter.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedFilter.kt index e32ca1c0..f306a1c0 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedFilter.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedFilter.kt @@ -1,91 +1,104 @@ -package com.glooboo.umessage.ui.spam - -import com.glooboo.umessage.spam.BlockedMessage -import com.glooboo.umessage.spam.DecisionReason - -/** - * The chip row under the Blocked banner (ID-14): narrows the held messages by why or where they were held. Uses only - * what each blocked row already carries (reason, text, SIM); nothing is stored per message. - */ -sealed interface BlockedFilter { - data object All : BlockedFilter - - /** Held because the sender is not a contact or a known number. */ - data object UnknownSender : BlockedFilter - - /** Held by one of the user's own block rules (or an old block list). */ - data object MyRules : BlockedFilter - - /** The text contains a web address. */ - data object HasLink : BlockedFilter - - data class Sim(val subscriptionId: Int) : BlockedFilter -} - -object BlockedFilters { - - fun matches(filter: BlockedFilter, message: BlockedMessage): Boolean = when (filter) { - BlockedFilter.All -> true - BlockedFilter.UnknownSender -> - message.reason == DecisionReason.UNKNOWN_SENDER || message.reason == DecisionReason.FOREIGN_NUMBER - BlockedFilter.MyRules -> message.reason == DecisionReason.BLOCK_RULE - BlockedFilter.HasLink -> BlockedHints.hasLink(message.body) - is BlockedFilter.Sim -> message.subscriptionId == filter.subscriptionId - } - - fun apply(filter: BlockedFilter, messages: List): List = - if (filter == BlockedFilter.All) messages else messages.filter { matches(filter, it) } - - /** - * How many senders each chip would list, for the count badges. The list shows one row per sender, so counting - * messages made "All 4" sit over 3 rows when one sender had two messages (emulator check, round 4). A sender - * counts for a chip when any of their messages matches it, as [apply] then [groupBySender] would list them. - */ - fun counts( - messages: List, - subscriptionIds: Collection, - keyOf: (String) -> String = { it }, - ): Map { - fun senders(filter: BlockedFilter) = apply(filter, messages).mapTo(HashSet()) { keyOf(it.address) }.size - return buildMap { - put(BlockedFilter.All, senders(BlockedFilter.All)) - put(BlockedFilter.UnknownSender, senders(BlockedFilter.UnknownSender)) - put(BlockedFilter.MyRules, senders(BlockedFilter.MyRules)) - put(BlockedFilter.HasLink, senders(BlockedFilter.HasLink)) - subscriptionIds.forEach { id -> put(BlockedFilter.Sim(id), senders(BlockedFilter.Sim(id))) } - } - } - - /** - * Whether a chip is worth showing (U31): All and the chosen chip always; any other only when it narrows the list, - * so "Unknown sender 4" next to "All 4" is left out. - */ - fun chipShown(option: BlockedFilter, selected: BlockedFilter, counts: Map): Boolean { - if (option == BlockedFilter.All || option == selected) return true - val count = counts[option] ?: 0 - return count > 0 && count < (counts[BlockedFilter.All] ?: 0) - } - - /** The chip row appears only when some chip other than All can be shown, or one is still chosen. */ - fun rowShown(selected: BlockedFilter, counts: Map): Boolean = - selected != BlockedFilter.All || counts.keys.any { it != BlockedFilter.All && chipShown(it, selected, counts) } - - /** Stored form of the selection, so it survives leaving the screen. */ - fun encode(filter: BlockedFilter): String = when (filter) { - BlockedFilter.All -> "all" - BlockedFilter.UnknownSender -> "unknown" - BlockedFilter.MyRules -> "rules" - BlockedFilter.HasLink -> "link" - is BlockedFilter.Sim -> "sim:${filter.subscriptionId}" - } - - /** Anything unreadable means [BlockedFilter.All]. */ - fun decode(value: String?): BlockedFilter = when { - value == "unknown" -> BlockedFilter.UnknownSender - value == "rules" -> BlockedFilter.MyRules - value == "link" -> BlockedFilter.HasLink - value != null && value.startsWith("sim:") -> - value.removePrefix("sim:").toIntOrNull()?.let { BlockedFilter.Sim(it) } ?: BlockedFilter.All - else -> BlockedFilter.All - } -} +package com.glooboo.umessage.ui.spam + +import com.glooboo.umessage.spam.BlockedMessage +import com.glooboo.umessage.spam.DecisionReason + +/** + * The chip row under the Blocked banner (ID-14): narrows the held messages by why or where they were held. Uses only + * what each blocked row already carries (reason, text, SIM); nothing is stored per message. + */ +sealed interface BlockedFilter { + data object All : BlockedFilter + + /** Held because the sender is not a contact or a known number. */ + data object UnknownSender : BlockedFilter + + /** Held by one of the user's own block rules (or an old block list). */ + data object MyRules : BlockedFilter + + /** The text contains a web address. */ + data object HasLink : BlockedFilter + + data class Sim(val subscriptionId: Int) : BlockedFilter +} + +object BlockedFilters { + + fun matches(filter: BlockedFilter, message: BlockedMessage): Boolean = when (filter) { + BlockedFilter.All -> true + BlockedFilter.UnknownSender -> + message.reason == DecisionReason.UNKNOWN_SENDER || message.reason == DecisionReason.FOREIGN_NUMBER + BlockedFilter.MyRules -> message.reason == DecisionReason.BLOCK_RULE + BlockedFilter.HasLink -> BlockedHints.hasLink(message.body) + is BlockedFilter.Sim -> message.subscriptionId == filter.subscriptionId + } + + fun apply(filter: BlockedFilter, messages: List): List = + if (filter == BlockedFilter.All) messages else messages.filter { matches(filter, it) } + + /** + * How many senders each chip would list, for the count badges. The list shows one row per sender, so counting + * messages made "All 4" sit over 3 rows when one sender had two messages (emulator check, round 4). A sender + * counts for a chip when any of their messages matches it, as [apply] then [groupBySender] would list them. + */ + fun counts( + messages: List, + subscriptionIds: Collection, + keyOf: (String) -> String = { it }, + ): Map { + // One pass: the link check (two regexes) runs once per message, not once per chip. + val all = HashSet() + val unknown = HashSet() + val rules = HashSet() + val links = HashSet() + val bySim = subscriptionIds.associateWith { HashSet() } + for (message in messages) { + val key = keyOf(message.address) + all += key + if (matches(BlockedFilter.UnknownSender, message)) unknown += key + if (matches(BlockedFilter.MyRules, message)) rules += key + if (BlockedHints.hasLink(message.body)) links += key + bySim[message.subscriptionId]?.add(key) + } + return buildMap { + put(BlockedFilter.All, all.size) + put(BlockedFilter.UnknownSender, unknown.size) + put(BlockedFilter.MyRules, rules.size) + put(BlockedFilter.HasLink, links.size) + bySim.forEach { (id, keys) -> put(BlockedFilter.Sim(id), keys.size) } + } + } + + /** + * Whether a chip is worth showing (U31): All and the chosen chip always; any other only when it narrows the list, + * so "Unknown sender 4" next to "All 4" is left out. + */ + fun chipShown(option: BlockedFilter, selected: BlockedFilter, counts: Map): Boolean { + if (option == BlockedFilter.All || option == selected) return true + val count = counts[option] ?: 0 + return count > 0 && count < (counts[BlockedFilter.All] ?: 0) + } + + /** The chip row appears only when some chip other than All can be shown, or one is still chosen. */ + fun rowShown(selected: BlockedFilter, counts: Map): Boolean = + selected != BlockedFilter.All || counts.keys.any { it != BlockedFilter.All && chipShown(it, selected, counts) } + + /** Stored form of the selection, so it survives leaving the screen. */ + fun encode(filter: BlockedFilter): String = when (filter) { + BlockedFilter.All -> "all" + BlockedFilter.UnknownSender -> "unknown" + BlockedFilter.MyRules -> "rules" + BlockedFilter.HasLink -> "link" + is BlockedFilter.Sim -> "sim:${filter.subscriptionId}" + } + + /** Anything unreadable means [BlockedFilter.All]. */ + fun decode(value: String?): BlockedFilter = when { + value == "unknown" -> BlockedFilter.UnknownSender + value == "rules" -> BlockedFilter.MyRules + value == "link" -> BlockedFilter.HasLink + value != null && value.startsWith("sim:") -> + value.removePrefix("sim:").toIntOrNull()?.let { BlockedFilter.Sim(it) } ?: BlockedFilter.All + else -> BlockedFilter.All + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModel.kt index fce74f77..033e4f37 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModel.kt @@ -16,6 +16,7 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update @@ -275,7 +276,8 @@ class BlockedViewModel( restored = aux.restored, hasPendingUndo = pending.any, ) - }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), BlockedUiState()) + }.flowOn(Dispatchers.Default) // grouping, filtering and the link checks stay off the main thread + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), BlockedUiState()) init { viewModelScope.launch { @@ -561,6 +563,12 @@ class BlockedViewModel( if (clearsRestoredLog) clearLogTokens += token pendingDeletes.update { it + (token to ids) } events.trySend(BlockedEvent.Deleted(token, ids.size)) + // The screen's snackbar normally commits; this makes the delete final even when the screen is left + // with the model still alive (commitDelete ignores a token that is gone or already being committed). + viewModelScope.launch { + delay(UNDO_WINDOW_MS) + commitDelete(token) + } } fun undoDelete(token: Long) { @@ -570,14 +578,19 @@ class BlockedViewModel( fun commitDelete(token: Long) { val ids = pendingDeletes.value[token] ?: return + if (!deleting.add(token)) return viewModelScope.launch { runCatching { repository.deleteBlocked(ids) } .onSuccess { if (clearLogTokens.remove(token)) restoredLog.clear() } .onFailure { events.trySend(BlockedEvent.Failed) } pendingDeletes.update { it - token } + deleting -= token } } + /** Delete tokens whose commit is running, so the timer and the snackbar never delete twice. */ + private val deleting = HashSet() + /** * Shows the Undo snackbar again for every action still waiting on one. Call when the screen starts collecting * [eventFlow]: after a rotation the old snackbar was cancelled without an answer, which left the rows hidden with diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/LinkSafety.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/LinkSafety.kt index ff22e124..dcd8f569 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/LinkSafety.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/LinkSafety.kt @@ -37,6 +37,7 @@ data class LinkReport(val flags: List, val lookalikeOf: String? = null * I07: offline checks of a link's address. Advice only: every flag is a reason to look twice, never a verdict, and * nothing here leaves the phone. */ +@Suppress("TooManyFunctions") object LinkSafety { private const val MIN_DISTANCE_BRAND = 6 @@ -48,7 +49,14 @@ object LinkSafety { private val dottedIp = Regex("^\\d{1,3}(\\.\\d{1,3}){3}$") private val hexIp = Regex("^0x[0-9a-f]+(\\.0x[0-9a-f]+)*$") private val secondLevel = setOf("co", "com", "org", "net", "gov", "edu", "ac", "sch") - private val confusables = mapOf('0' to 'o', '1' to 'l', '3' to 'e', '4' to 'a', '5' to 's', '$' to 's') + private val confusables = mapOf('0' to 'o', '1' to 'l', '3' to 'e', '4' to 'a', '5' to 's', '$' to 's', + // Cyrillic and Greek letters that look like Latin ones. + 'а' to 'a', 'е' to 'e', 'о' to 'o', 'р' to 'p', 'с' to 'c', 'у' to 'y', 'х' to 'x', 'і' to 'i', 'ј' to 'j', + 'ѕ' to 's', 'һ' to 'h', 'ԁ' to 'd', 'ɡ' to 'g', 'ο' to 'o', 'α' to 'a', 'ν' to 'v', 'ρ' to 'p', 'τ' to 't', + 'ι' to 'i', 'κ' to 'k', 'ε' to 'e', + ) + private const val MAX_ASCII = 127 + private val arabicScripts = setOf(Character.UnicodeScript.ARABIC, Character.UnicodeScript.COMMON) private val ignorable = setOf('-', '_', '\u200c', '\u200d') /** Flags of [uri], in a fixed order. A mail address or an empty value gets none. */ @@ -84,7 +92,8 @@ object LinkSafety { val labels = host.split('.') if (labels.any { it.startsWith("xn--") }) flags += LinkFlag.PUNYCODE if (domain(host) in linkShorteners || linkShorteners.any { host.endsWith(".$it") }) flags += LinkFlag.SHORTENER - if (labels.any { mixesScripts(decode(it)) }) flags += LinkFlag.MIXED_SCRIPT + val decoded = labels.map(::decode) + if (decoded.any { mixesScripts(it) || isForeignScript(it) }) flags += LinkFlag.MIXED_SCRIPT return flags } @@ -98,6 +107,14 @@ object LinkSafety { private fun mixesScripts(label: String): Boolean = label.filter { it.isLetter() }.map { Character.UnicodeScript.of(it.code) }.toSet().size > 1 + /** + * A whole label in another alphabet can still imitate a Latin name (all-Cyrillic "аpple"-style hosts). Persian and + * Arabic names are common here and are not flagged; any other non-ASCII letter is. + */ + private fun isForeignScript(label: String): Boolean = label.any { + it.isLetter() && it.code > MAX_ASCII && Character.UnicodeScript.of(it.code) !in arabicScripts + } + /** The registrable domain: "pay.example.co.uk" -> "example.co.uk", "a.b.example.com" -> "example.com". */ private fun domain(host: String): String { val labels = host.split('.') diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadAttachments.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadAttachments.kt index b8a4baff..f6824991 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadAttachments.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadAttachments.kt @@ -93,7 +93,7 @@ private fun iconForMimeType(mimeType: String) = when { else -> Symbols.Description } -/** Image or video preview inside a message bubble. Hidden when the file cannot be decoded, like the old list. */ +/** Image or video preview inside a message bubble. A file that cannot be decoded shows a card that still opens it. */ @OptIn(ExperimentalFoundationApi::class) @Composable fun MessageMedia( @@ -107,9 +107,37 @@ fun MessageMedia( val context = LocalContext.current val density = context.resources.displayMetrics.density val widthPx = (width.value * density).toInt().coerceAtLeast(1) - val load by rememberGlideBitmap(uri, widthPx, (widthPx * MAX_MEDIA_HEIGHT_RATIO).toInt()) + // A failed decode keeps a tappable card (open in the system viewer) and a tap also tries the load again. + var attempt by remember(uri) { mutableIntStateOf(0) } + val load by rememberGlideBitmap(uri, widthPx, (widthPx * MAX_MEDIA_HEIGHT_RATIO).toInt(), attempt) val result = load - if (result == ImageLoad.Failed) return + if (result == ImageLoad.Failed) { + val failedDescription = stringResource( + if (isVideo) R.string.thread_video_attachment else R.string.thread_image_attachment, + ) + Box( + modifier = modifier + .width(width) + .aspectRatio(1f) + .background(MaterialTheme.colorScheme.surfaceVariant) + .semantics { contentDescription = failedDescription } + .combinedClickable( + onClick = { + if (gestures.selecting) { + gestures.onToggleSelect() + } else { + attempt++ + onOpen() + } + }, + onLongClick = gestures.onLongClick, + ), + contentAlignment = Alignment.Center, + ) { + Icon(Symbols.Description, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant) + } + return + } val bitmap = (result as? ImageLoad.Loaded)?.bitmap val key = uri.toString() diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadImages.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadImages.kt index d7d709aa..2355dcc4 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadImages.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadImages.kt @@ -25,10 +25,10 @@ sealed interface ImageLoad { * Glide stays the image loader so MMS part Uris, video frames and the disk cache behave as they did in the old list. */ @Composable -fun rememberGlideBitmap(model: Any?, maxWidth: Int, maxHeight: Int): State { +fun rememberGlideBitmap(model: Any?, maxWidth: Int, maxHeight: Int, attempt: Int = 0): State { val context = LocalContext.current.applicationContext if (model == null) return remember { mutableStateOf(ImageLoad.Failed) } - return produceState(initialValue = null, model, maxWidth, maxHeight) { + return produceState(initialValue = null, model, maxWidth, maxHeight, attempt) { val target = Glide.with(context) .asBitmap() .load(model) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadItemsBuilder.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadItemsBuilder.kt index 2545836c..09efe23b 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadItemsBuilder.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadItemsBuilder.kt @@ -51,6 +51,8 @@ fun buildThreadItems( val newlyRead = ArrayList() var prevDateTime = 0 var prevSIMId = -2 + // Scheduled messages sort last by their future date; the "Sent" row belongs to the last one that is not. + val lastRealIndex = sorted.indexOfLast { !it.isScheduled } sorted.forEachIndexed { i, message -> if (message.getStableId() in tapbacks.hidden) { // A hidden reaction is marked read like any message; the unread line moves to the next one shown. @@ -76,12 +78,14 @@ fun buildThreadItems( if (message.type == Telephony.Sms.MESSAGE_TYPE_FAILED) { items.add(ThreadError(message.id, message.body, message.isMMS)) } - if (message.type == Telephony.Sms.MESSAGE_TYPE_OUTBOX) { + if (message.type == Telephony.Sms.MESSAGE_TYPE_OUTBOX || + (message.type == Telephony.Sms.MESSAGE_TYPE_QUEUED && !message.isScheduled) + ) { items.add(ThreadSending(message.id)) } if (!message.read && seen) newlyRead.add(message) - if (i == sorted.lastIndex && message.type == Telephony.Sms.MESSAGE_TYPE_SENT) { + if (i == lastRealIndex && message.type == Telephony.Sms.MESSAGE_TYPE_SENT) { // "Delivered" only while delivery reports are on: a network can report delivery the app never asked for. // An MMS has no delivery report: its status column is empty and reads as 0, which is not "delivered". val delivered = deliveryReportsOn && !message.isMMS && message.status == Telephony.Sms.STATUS_COMPLETE diff --git a/app/src/main/res/values-fa/strings_triage_nov12.xml b/app/src/main/res/values-fa/strings_triage_nov12.xml new file mode 100644 index 00000000..7060215f --- /dev/null +++ b/app/src/main/res/values-fa/strings_triage_nov12.xml @@ -0,0 +1,4 @@ + + + یک شماره تلفن یا ایمیل وارد کنید + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f1dc9121..929b1f23 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -177,4 +177,5 @@ Haven't found some strings? There's more at the translation files --> + Enter a phone number or an email address diff --git a/app/src/test/kotlin/com/glooboo/umessage/helpers/ExifStripperTest.kt b/app/src/test/kotlin/com/glooboo/umessage/helpers/ExifStripperTest.kt index 90fcf3df..15335ce6 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/helpers/ExifStripperTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/helpers/ExifStripperTest.kt @@ -62,6 +62,22 @@ class ExifStripperTest { assertThat(BitmapFactory.decodeFile(file.absolutePath).sameAs(before)).isTrue() } + @Test + fun stripDropsXmpAndComments() { + val file = geotaggedJpeg() + val xmp = "http://ns.adobe.com/xap/1.0/\u0000SecretPlace".toByteArray() + val len = xmp.size + 2 + val segment = byteArrayOf(0xFF.toByte(), 0xE1.toByte(), (len shr 8).toByte(), len.toByte()) + xmp + val bytes = file.readBytes() + file.writeBytes(bytes.copyOfRange(0, 2) + segment + bytes.copyOfRange(2, bytes.size)) + assertThat(String(file.readBytes(), Charsets.ISO_8859_1)).contains("SecretPlace") + + assertThat(ExifStripper.strip(file)).isTrue() + + assertThat(String(file.readBytes(), Charsets.ISO_8859_1)).doesNotContain("SecretPlace") + assertThat(BitmapFactory.decodeFile(file.absolutePath)).isNotNull() + } + @Test fun theOriginalIsLeftAloneWhenACopyIsStripped() { val original = geotaggedJpeg() diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModelTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModelTest.kt index 337a9dd9..d0ebfd79 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModelTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModelTest.kt @@ -201,6 +201,27 @@ class ConversationsViewModelTest { assertThat(vm.state.value.selection.canReportSpam).isFalse() } + @Test + fun blockIsOfferedAndAppliedToSingleSendersOnly() { + val group = dad.copy(threadId = 3, isGroupConversation = true) + vm.submit(listOf(group, mom), cached = false, firstRun = false) + awaitUntil { rowIds().size == 2 } + vm.startSelect(group.threadId) + awaitUntil { vm.state.value.selection.count == 1 } + assertThat(vm.state.value.selection.canBlock).isFalse() + vm.startSelect(mom.threadId) + awaitUntil { vm.state.value.selection.count == 2 } + assertThat(vm.state.value.selection.canBlock).isTrue() + + vm.blockSelected() + awaitUntil { events.any { it is ConversationsEvent.Blocked } } + val event = events.single { it is ConversationsEvent.Blocked } as ConversationsEvent.Blocked + assertThat(event.count).isEqualTo(1) + val repository = SpamRepositoryProvider.get(app) + vm.undoReportSpam(event.token) + awaitUntil { !SenderBlocking.isBlocked(rules(repository), mom.phoneNumber) } + } + private fun rules(repository: SpamRepository) = runBlocking { repository.rules.first() } @Test diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/newconversation/FilterContactsTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/newconversation/FilterContactsTest.kt index 5b4332a5..29148ce7 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/newconversation/FilterContactsTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/newconversation/FilterContactsTest.kt @@ -84,6 +84,14 @@ class FilterContactsTest { assertThat(typedPhoneNumber("someone@example.com")).isNull() } + @Test + fun groupRecipientMustBeANumberOrAnEmail() { + assertThat(typedGroupRecipient("(021) 8888-1234")).isEqualTo("02188881234") + assertThat(typedGroupRecipient(" someone@example.com ")).isEqualTo("someone@example.com") + assertThat(typedGroupRecipient("Sara")).isNull() + assertThat(typedGroupRecipient("not an@email")).isNull() + } + // MC-12 @Test fun contactItemKeysAreUniqueEvenWhenIdsRepeat() { diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/thread/LinkSafetyTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/LinkSafetyTest.kt index 98bc16a2..22e942d0 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/thread/LinkSafetyTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/LinkSafetyTest.kt @@ -21,6 +21,12 @@ class LinkSafetyTest { ).forEach { assertThat(flags(it)).isEmpty() } } + @Test + fun aWholeCyrillicOrGreekHostIsFlagged() { + assertThat(flags("https://аррӏе.test/x")).contains(LinkFlag.MIXED_SCRIPT) + assertThat(flags("https://αβγ.test/x")).contains(LinkFlag.MIXED_SCRIPT) + } + @Test fun shortenersAreFlagged() { assertThat(flags("https://bit.ly/abc")).containsExactly(LinkFlag.SHORTENER) From 7067b68079551475fdc6e97d8b32e774fe3925bf Mon Sep 17 00:00:00 2001 From: Sajad <220944007+MyNameIsGlooboo@users.noreply.github.com> Date: Thu, 12 Nov 2026 07:27:55 +0000 Subject: [PATCH 2/5] Apply decided review items and spam-2 Schema 8 (pending_sms.approved, spam_rules hitCount/lastHit), contacts skip keyword/pattern/prefix/domain block rules, DOMAIN rule type with Rules UI, rule hit counter, newest-first Rules sort, auto-block warning, keywords in settings backup, MMS import from XML backup, alphanumeric codes next to a keyword, Mark all read with Undo, blocked messages in main search, Blocked screen search, Always allow in Why-blocked dialog, chat opens without READ_PHONE_STATE, failure reason on failed messages. Co-Authored-By: Claude Sonnet 5.5 --- .../8.json | 489 ++++++++++++++++ .../glooboo/umessage/activities/MainRoutes.kt | 2 + .../umessage/activities/ThreadActivity.kt | 39 +- .../glooboo/umessage/backup/SettingsBackup.kt | 21 +- .../umessage/backup/SettingsBackupFormat.kt | 24 + .../umessage/helpers/MessagesImporter.kt | 149 ++++- .../com/glooboo/umessage/helpers/OtpCodes.kt | 13 +- .../umessage/messaging/SendingErrors.kt | 20 +- .../umessage/messaging/SmsFailureReason.kt | 77 +++ .../glooboo/umessage/models/ThreadItems.kt | 12 +- .../receivers/SmsStatusSentReceiver.kt | 8 + .../glooboo/umessage/spam/SpamContracts.kt | 10 + .../spam/data/DefaultSpamRepository.kt | 19 +- .../glooboo/umessage/spam/data/PendingSms.kt | 530 +++++++++--------- .../com/glooboo/umessage/spam/data/SpamDao.kt | 4 + .../umessage/spam/data/SpamDatabase.kt | 24 +- .../umessage/spam/data/SpamEntities.kt | 9 +- .../umessage/spam/engine/DefaultSpamFilter.kt | 31 +- .../umessage/spam/engine/DomainMatch.kt | 54 ++ .../umessage/spam/engine/OtpDetector.kt | 64 ++- .../umessage/spam/engine/RuleMatcher.kt | 4 + .../glooboo/umessage/ui/components/Dialogs.kt | 3 + .../ui/conversations/ConversationsModels.kt | 6 + .../ui/conversations/ConversationsScreen.kt | 8 + .../conversations/ConversationsViewModel.kt | 46 ++ .../glooboo/umessage/ui/main/BlockedHit.kt | 147 +++++ .../com/glooboo/umessage/ui/main/InboxMenu.kt | 2 + .../umessage/ui/main/InboxMenuPolicy.kt | 6 +- .../glooboo/umessage/ui/main/MainScreen.kt | 8 +- .../glooboo/umessage/ui/main/MainSearch.kt | 4 + .../umessage/ui/main/MainSearchPage.kt | 6 + .../umessage/ui/main/MainSearchPanel.kt | 12 +- .../umessage/ui/main/MainSearchViewModel.kt | 46 ++ .../com/glooboo/umessage/ui/main/NoteHit.kt | 8 +- .../umessage/ui/main/SearchPanelActions.kt | 2 + .../umessage/ui/settings/RestoreSummary.kt | 3 + .../umessage/ui/spam/AlwaysAllowPolicy.kt | 21 + .../umessage/ui/spam/BlockedActions.kt | 2 + .../umessage/ui/spam/BlockedDetails.kt | 1 + .../glooboo/umessage/ui/spam/BlockedFilter.kt | 29 + .../glooboo/umessage/ui/spam/BlockedScreen.kt | 54 ++ .../glooboo/umessage/ui/spam/BlockedThread.kt | 8 +- .../umessage/ui/spam/BlockedViewModel.kt | 50 +- .../umessage/ui/spam/BlockedWhyDialog.kt | 24 +- .../umessage/ui/spam/ForwardRulesScreen.kt | 1 + .../umessage/ui/spam/KeywordHelpDialog.kt | 14 + .../com/glooboo/umessage/ui/spam/RuleHits.kt | 51 ++ .../com/glooboo/umessage/ui/spam/RuleLogic.kt | 31 +- .../umessage/ui/spam/RuleMatchPicker.kt | 4 +- .../com/glooboo/umessage/ui/spam/RuleNotes.kt | 2 +- .../glooboo/umessage/ui/spam/RulesOrder.kt | 48 ++ .../glooboo/umessage/ui/spam/RulesScreen.kt | 60 +- .../umessage/ui/spam/RulesViewModel.kt | 16 +- .../umessage/ui/thread/ThreadBubbles.kt | 14 +- .../umessage/ui/thread/ThreadItemsBuilder.kt | 260 +++++---- .../glooboo/umessage/ui/thread/ThreadRows.kt | 10 +- .../umessage/ui/thread/ThreadSimController.kt | 4 +- .../values-fa/strings_decisions_backup.xml | 4 + .../strings_decisions_blocked_domain.xml | 4 + .../res/values-fa/strings_decisions_main.xml | 14 + .../res/values-fa/strings_decisions_rules.xml | 47 ++ .../values-fa/strings_decisions_thread.xml | 4 + .../res/values/strings_decisions_backup.xml | 4 + .../strings_decisions_blocked_domain.xml | 4 + .../res/values/strings_decisions_main.xml | 21 + .../res/values/strings_decisions_rules.xml | 47 ++ .../res/values/strings_decisions_thread.xml | 7 + .../backup/SettingsBackupFormatTest.kt | 31 + .../umessage/helpers/MessagesBackupTest.kt | 82 ++- .../glooboo/umessage/helpers/OtpCodesTest.kt | 24 + .../umessage/helpers/SmsXmlWriterTest.kt | 7 +- .../spam/data/PendingSmsReplayTest.kt | 39 ++ .../spam/data/SpamDatabaseMigrationTest.kt | 2 +- .../spam/data/SpamRuleStatsMigrationTest.kt | 106 ++++ .../umessage/spam/data/SpamRuleStatsTest.kt | 139 +++++ .../spam/engine/DefaultSpamFilterTest.kt | 74 +++ .../umessage/spam/engine/DomainMatchTest.kt | 82 +++ .../umessage/spam/engine/OtpDetectorTest.kt | 41 ++ .../ui/conversations/MarkAllReadTest.kt | 35 ++ .../umessage/ui/main/BlockedHitTest.kt | 54 ++ .../umessage/ui/main/InboxMenuPolicyTest.kt | 13 +- .../ui/main/MainSearchViewModelTest.kt | 17 + .../umessage/ui/spam/AlwaysAllowPolicyTest.kt | 31 + .../umessage/ui/spam/BlockedSearchTest.kt | 56 ++ .../ui/spam/BlockedViewModelActionsTest.kt | 27 + .../ui/spam/BlockedViewModelReview2Test.kt | 2 +- .../umessage/ui/spam/RulesDecisionsTest.kt | 252 +++++++++ .../umessage/ui/thread/FailureReasonTest.kt | 61 ++ 88 files changed, 3476 insertions(+), 469 deletions(-) create mode 100644 app/schemas/com.glooboo.umessage.spam.data.SpamDatabase/8.json create mode 100644 app/src/main/kotlin/com/glooboo/umessage/messaging/SmsFailureReason.kt create mode 100644 app/src/main/kotlin/com/glooboo/umessage/spam/engine/DomainMatch.kt create mode 100644 app/src/main/kotlin/com/glooboo/umessage/ui/main/BlockedHit.kt create mode 100644 app/src/main/kotlin/com/glooboo/umessage/ui/spam/AlwaysAllowPolicy.kt create mode 100644 app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleHits.kt create mode 100644 app/src/main/kotlin/com/glooboo/umessage/ui/spam/RulesOrder.kt create mode 100644 app/src/main/res/values-fa/strings_decisions_backup.xml create mode 100644 app/src/main/res/values-fa/strings_decisions_blocked_domain.xml create mode 100644 app/src/main/res/values-fa/strings_decisions_main.xml create mode 100644 app/src/main/res/values-fa/strings_decisions_rules.xml create mode 100644 app/src/main/res/values-fa/strings_decisions_thread.xml create mode 100644 app/src/main/res/values/strings_decisions_backup.xml create mode 100644 app/src/main/res/values/strings_decisions_blocked_domain.xml create mode 100644 app/src/main/res/values/strings_decisions_main.xml create mode 100644 app/src/main/res/values/strings_decisions_rules.xml create mode 100644 app/src/main/res/values/strings_decisions_thread.xml create mode 100644 app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamRuleStatsMigrationTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamRuleStatsTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/spam/engine/DomainMatchTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/ui/conversations/MarkAllReadTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/ui/main/BlockedHitTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/ui/spam/AlwaysAllowPolicyTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedSearchTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/ui/spam/RulesDecisionsTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/ui/thread/FailureReasonTest.kt diff --git a/app/schemas/com.glooboo.umessage.spam.data.SpamDatabase/8.json b/app/schemas/com.glooboo.umessage.spam.data.SpamDatabase/8.json new file mode 100644 index 00000000..2345d8a6 --- /dev/null +++ b/app/schemas/com.glooboo.umessage.spam.data.SpamDatabase/8.json @@ -0,0 +1,489 @@ +{ + "formatVersion": 1, + "database": { + "version": 8, + "identityHash": "2502717225e1e99e4383384e43d05508", + "entities": [ + { + "tableName": "spam_rules", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `kind` TEXT NOT NULL, `type` TEXT NOT NULL, `pattern` TEXT NOT NULL, `subscriptionId` INTEGER, `note` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `hitCount` INTEGER NOT NULL DEFAULT 0, `lastHit` INTEGER NOT NULL DEFAULT 0)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "pattern", + "columnName": "pattern", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subscriptionId", + "columnName": "subscriptionId", + "affinity": "INTEGER" + }, + { + "fieldPath": "note", + "columnName": "note", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hitCount", + "columnName": "hitCount", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "lastHit", + "columnName": "lastHit", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_spam_rules_kind_type_pattern_subscriptionId", + "unique": true, + "columnNames": [ + "kind", + "type", + "pattern", + "subscriptionId" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_spam_rules_kind_type_pattern_subscriptionId` ON `${TABLE_NAME}` (`kind`, `type`, `pattern`, `subscriptionId`)" + } + ] + }, + { + "tableName": "blocked_messages", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `address` TEXT NOT NULL, `body` TEXT NOT NULL, `subscriptionId` INTEGER NOT NULL, `isMms` INTEGER NOT NULL, `receivedAt` INTEGER NOT NULL, `reason` TEXT NOT NULL, `ruleId` INTEGER, `media` TEXT NOT NULL DEFAULT 'NONE', `mediaFile` TEXT, `unread` INTEGER NOT NULL DEFAULT 0)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "address", + "columnName": "address", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "body", + "columnName": "body", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subscriptionId", + "columnName": "subscriptionId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isMms", + "columnName": "isMms", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "receivedAt", + "columnName": "receivedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "reason", + "columnName": "reason", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "ruleId", + "columnName": "ruleId", + "affinity": "INTEGER" + }, + { + "fieldPath": "media", + "columnName": "media", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'NONE'" + }, + { + "fieldPath": "mediaFile", + "columnName": "mediaFile", + "affinity": "TEXT" + }, + { + "fieldPath": "unread", + "columnName": "unread", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_blocked_messages_receivedAt", + "unique": false, + "columnNames": [ + "receivedAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_blocked_messages_receivedAt` ON `${TABLE_NAME}` (`receivedAt`)" + } + ] + }, + { + "tableName": "spam_events", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `type` TEXT NOT NULL, `timestamp` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_spam_events_type_timestamp", + "unique": false, + "columnNames": [ + "type", + "timestamp" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_spam_events_type_timestamp` ON `${TABLE_NAME}` (`type`, `timestamp`)" + } + ] + }, + { + "tableName": "pending_sms", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `address` TEXT NOT NULL, `subject` TEXT NOT NULL, `body` TEXT NOT NULL, `date` INTEGER NOT NULL, `subscriptionId` INTEGER NOT NULL, `status` INTEGER NOT NULL, `createdAt` INTEGER NOT NULL, `dateSent` INTEGER NOT NULL DEFAULT 0, `approved` INTEGER NOT NULL DEFAULT 0)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "address", + "columnName": "address", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subject", + "columnName": "subject", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "body", + "columnName": "body", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "date", + "columnName": "date", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "subscriptionId", + "columnName": "subscriptionId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dateSent", + "columnName": "dateSent", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "approved", + "columnName": "approved", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "forward_rules", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `senderType` TEXT, `senderPattern` TEXT NOT NULL DEFAULT '', `bodyType` TEXT, `bodyPattern` TEXT NOT NULL DEFAULT '', `windowStart` INTEGER, `windowEnd` INTEGER, `subscriptionId` INTEGER, `targets` TEXT NOT NULL, `sendFrom` TEXT NOT NULL DEFAULT 'SAME', `includeCodes` INTEGER NOT NULL DEFAULT 0, `enabled` INTEGER NOT NULL DEFAULT 1, `note` TEXT NOT NULL DEFAULT '', `createdAt` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "senderType", + "columnName": "senderType", + "affinity": "TEXT" + }, + { + "fieldPath": "senderPattern", + "columnName": "senderPattern", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "bodyType", + "columnName": "bodyType", + "affinity": "TEXT" + }, + { + "fieldPath": "bodyPattern", + "columnName": "bodyPattern", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "windowStart", + "columnName": "windowStart", + "affinity": "INTEGER" + }, + { + "fieldPath": "windowEnd", + "columnName": "windowEnd", + "affinity": "INTEGER" + }, + { + "fieldPath": "subscriptionId", + "columnName": "subscriptionId", + "affinity": "INTEGER" + }, + { + "fieldPath": "targets", + "columnName": "targets", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sendFrom", + "columnName": "sendFrom", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'SAME'" + }, + { + "fieldPath": "includeCodes", + "columnName": "includeCodes", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "enabled", + "columnName": "enabled", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "note", + "columnName": "note", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + } + }, + { + "tableName": "forward_log", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `at` INTEGER NOT NULL, `updatedAt` INTEGER NOT NULL, `ruleId` INTEGER NOT NULL, `sourceAddress` TEXT NOT NULL, `sourceDate` INTEGER NOT NULL, `sourceIsMms` INTEGER NOT NULL, `target` TEXT NOT NULL, `subscriptionId` INTEGER, `status` TEXT NOT NULL, `errorCode` TEXT, `attempts` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "at", + "columnName": "at", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ruleId", + "columnName": "ruleId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sourceAddress", + "columnName": "sourceAddress", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sourceDate", + "columnName": "sourceDate", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sourceIsMms", + "columnName": "sourceIsMms", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "target", + "columnName": "target", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "subscriptionId", + "columnName": "subscriptionId", + "affinity": "INTEGER" + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "errorCode", + "columnName": "errorCode", + "affinity": "TEXT" + }, + { + "fieldPath": "attempts", + "columnName": "attempts", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_forward_log_at", + "unique": false, + "columnNames": [ + "at" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_forward_log_at` ON `${TABLE_NAME}` (`at`)" + } + ] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2502717225e1e99e4383384e43d05508')" + ] + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/com/glooboo/umessage/activities/MainRoutes.kt b/app/src/main/kotlin/com/glooboo/umessage/activities/MainRoutes.kt index 997c0281..836fb756 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/MainRoutes.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/MainRoutes.kt @@ -59,6 +59,8 @@ class MainRoutes(private val activity: BaseSimpleActivity) { onSelectAll = viewModel::selectAll, onPin = viewModel::pinSelected, onMarkRead = viewModel::markSelectedRead, + onMarkAllRead = viewModel::markAllRead, + onUndoMarkAllRead = viewModel::undoMarkAllRead, onArchiveSelected = viewModel::archiveSelected, onDeleteSelected = viewModel::deleteSelected, onArchiveOne = viewModel::archiveOne, diff --git a/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt b/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt index b511e1b4..77a56d2f 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt @@ -95,6 +95,7 @@ import com.glooboo.umessage.messaging.ScheduledSendClaims import com.glooboo.umessage.messaging.MmsRetryResult import com.glooboo.umessage.messaging.SendOutcome import com.glooboo.umessage.messaging.downloadMms +import com.glooboo.umessage.messaging.SmsFailureReason import com.glooboo.umessage.messaging.undownloadedMms import com.glooboo.umessage.messaging.isLongMmsMessage import com.glooboo.umessage.messaging.scheduledAttachmentTracker @@ -1123,18 +1124,15 @@ open class ThreadActivity : ComposeSimpleActivity() { } private fun loadConversation(isFreshLaunch: Boolean) { - handlePermission(PERMISSION_READ_PHONE_STATE) { granted -> - if (granted) { - setupComposer(isFreshLaunch) - setupConversation() - setupCachedMessages { - setupThread { - takeSearchedMessage()?.let { jumpToMessage(it) } - if (isFreshLaunch) applyLaunchHints() - } + handlePermission(PERMISSION_READ_PHONE_STATE) { _ -> + // Thread-17: a denied permission only costs the SIM features (names, the SIM picker); the chat opens. + setupComposer(isFreshLaunch) + setupConversation() + setupCachedMessages { + setupThread { + takeSearchedMessage()?.let { jumpToMessage(it) } + if (isFreshLaunch) applyLaunchHints() } - } else { - finish() } } } @@ -1291,13 +1289,29 @@ open class ThreadActivity : ComposeSimpleActivity() { } @SuppressLint("MissingPermission") + /** + * Thread-27: the stored reasons of the failed texts. Read off the main thread; the main thread reuses the + * last read. + */ + private fun failureCodes(): Map { + if (messages.none { it.type == Telephony.Sms.MESSAGE_TYPE_FAILED && !it.isMMS }) return emptyMap() + if (Looper.myLooper() != Looper.getMainLooper()) lastFailureCodes = SmsFailureReason.failedCodes(this, threadId) + return lastFailureCodes + } + + @Volatile + private var lastFailureCodes: Map = emptyMap() + + // READ_PHONE_STATE may be denied: the SIM read is guarded by runCatching (thread-17). + @android.annotation.SuppressLint("MissingPermission") private fun getThreadItems(): List { if (isFinishing) { return emptyList() } val simLabels = lookups.sims { - simHeaderLabels(subscriptionManagerCompat().activeSubscriptionInfoList, composerPrefs) + val activeSims = runCatching { subscriptionManagerCompat().activeSubscriptionInfoList }.getOrNull() + simHeaderLabels(activeSims, composerPrefs) } // TU-11: only mark messages read while the user can see them. // I26: decided once, from the provider's messages and before they are marked read. @@ -1309,6 +1323,7 @@ open class ThreadActivity : ComposeSimpleActivity() { messages, simLabels, seen = isSeenByUser(), deliveryReportsOn = config.enableDeliveryReports, firstUnreadId = vm.firstUnreadId, showTapbacks = w3cPrefs.showTapbacks, undownloadedMms = undownloadedMms(messages), + failureCodes = failureCodes(), ) latestReactions = result.reactions if (!isCodeSender()) { diff --git a/app/src/main/kotlin/com/glooboo/umessage/backup/SettingsBackup.kt b/app/src/main/kotlin/com/glooboo/umessage/backup/SettingsBackup.kt index 23c341af..d85308c8 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/backup/SettingsBackup.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/backup/SettingsBackup.kt @@ -5,6 +5,7 @@ import android.database.SQLException import android.net.Uri import com.glooboo.umessage.BuildConfig import com.glooboo.umessage.extensions.config +import com.glooboo.umessage.helpers.BlockedKeywordsFormat import com.glooboo.umessage.helpers.DateStyle import com.glooboo.umessage.helpers.NavPrefs import com.glooboo.umessage.helpers.TextSize @@ -44,6 +45,7 @@ import kotlinx.coroutines.withContext * the file replace the phone's. Forward rules come in switched off with checked targets (H1), and "Pause all * forwarding" is only ever turned on. The caller (Settings) asks for the app-lock check before [read]. */ +@Suppress("TooManyFunctions") object SettingsBackup { /** Why an import did nothing. */ @@ -67,6 +69,8 @@ object SettingsBackup { val newRules: List = content.rules, /** Rules of the file already on the phone (or repeated in the file). */ val rulesPresent: Int = 0, + /** The blocked words of the file that are not on the phone yet. */ + val newKeywords: List = emptyList(), ) { val allowRules: Int get() = newRules.count { it.kind == ListKind.ALLOW } val blockRules: Int get() = newRules.size - allowRules @@ -82,6 +86,7 @@ object SettingsBackup { val forwardRulesAdded: Int = 0, val forwardRulesSkipped: Int = 0, val settingsApplied: Boolean = false, + val keywordsAdded: Int = 0, val failure: Failure? = null, ) { val ok: Boolean get() = failure == null @@ -109,6 +114,7 @@ object SettingsBackup { }, settings = collectSettings(app, repo.settings.first()), appVersion = BuildConfig.VERSION_NAME, + blockedKeywords = BlockedKeywordsFormat.sorted(app.config.blockedKeywords), ) val text = SettingsBackupFormat.encode(content, System.currentTimeMillis()) SafeOutput.write(app, uri) { it.write(text.toByteArray(Charsets.UTF_8)) } @@ -135,7 +141,8 @@ object SettingsBackup { val current = collectSettings(app, repo.settings.first()) val changed = SettingsBackupFormat.changedSettings(current, content.settings) val (fresh, present) = SettingsBackupFormat.newRules(content.rules, repo.rules.first()) - Preview(content, forwards, changed, fresh, present) to null + val keywords = SettingsBackupFormat.newKeywords(content.blockedKeywords, app.config.blockedKeywords) + Preview(content, forwards, changed, fresh, present, keywords) to null } catch (_: IOException) { null to Failure.UNREADABLE } catch (_: SQLException) { @@ -162,6 +169,7 @@ object SettingsBackup { } val applied = applySettings(app, preview.content.settings) + val keywordsAdded = addKeywords(app, preview.content.blockedKeywords) Result( rulesAdded = rulesAdded, rulesSkipped = (preview.content.rules.size - rulesAdded).coerceAtLeast(0), @@ -172,6 +180,7 @@ object SettingsBackup { 0 }, settingsApplied = applied, + keywordsAdded = keywordsAdded, ) } catch (_: IOException) { Result(failure = Failure.UNREADABLE) @@ -182,6 +191,16 @@ object SettingsBackup { } } + /** Adds the words of the file to the phone's blocked words; never removes one. Returns how many were new. */ + private fun addKeywords(context: Context, incoming: List): Int { + if (incoming.isEmpty()) return 0 + val before = context.config.blockedKeywords + val after = incoming.fold(before) { set, word -> BlockedKeywordsFormat.add(set, word) } + if (after.size == before.size) return 0 + context.config.blockedKeywords = after + return after.size - before.size + } + private fun collectSettings(context: Context, spam: SpamSettings): BackupSettings { val nav = NavPrefs.get(context) val w3a = W3aPrefs.get(context) diff --git a/app/src/main/kotlin/com/glooboo/umessage/backup/SettingsBackupFormat.kt b/app/src/main/kotlin/com/glooboo/umessage/backup/SettingsBackupFormat.kt index 8692de46..ea81293a 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/backup/SettingsBackupFormat.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/backup/SettingsBackupFormat.kt @@ -1,5 +1,6 @@ package com.glooboo.umessage.backup +import com.glooboo.umessage.helpers.BlockedKeywordsFormat import com.glooboo.umessage.spam.ForwardRule import com.glooboo.umessage.spam.RuleType import com.glooboo.umessage.spam.SpamRule @@ -9,6 +10,7 @@ import com.glooboo.umessage.ui.spam.ForwardTargets import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put @@ -199,6 +201,11 @@ data class BackupContent( /** Rules and forward rules of the file left out because it held more than the import limits. Set by decode. */ val droppedRules: Int = 0, val droppedForwardRules: Int = 0, + /** + * The blocked words of Rules > Blocked words (the app's keyword list). Files from before this field lack it and + * give an empty list: a restore only ever adds words, so such a file takes none away. + */ + val blockedKeywords: List = emptyList(), ) /** @@ -227,6 +234,7 @@ object SettingsBackupFormat { const val MAX_NOTE = 200 const val MAX_TARGET = 40 const val MAX_VERSION = 40 + const val MAX_KEYWORDS = 2000 private val json = Json { prettyPrint = true } @@ -239,6 +247,9 @@ object SettingsBackupFormat { content.appVersion?.let { put("appVersion", it) } put("rules", buildJsonArray { content.rules.forEach { add(BackupJson.rule(it)) } }) put("forwardRules", buildJsonArray { content.forwardRules.forEach { add(BackupJson.forward(it)) } }) + if (content.blockedKeywords.isNotEmpty()) { + put("blockedKeywords", buildJsonArray { content.blockedKeywords.forEach { add(JsonPrimitive(it)) } }) + } put("settings", BackupJson.settings(content.settings)) } return json.encodeToString(JsonElement.serializer(), root) @@ -264,9 +275,22 @@ object SettingsBackupFormat { appVersion = root.str("appVersion")?.take(MAX_VERSION), droppedRules = (rules.size - MAX_RULES).coerceAtLeast(0), droppedForwardRules = (forwards.size - MAX_FORWARD_RULES).coerceAtLeast(0), + blockedKeywords = readKeywords(root), ) } + /** The words of the file that are valid (see [BlockedKeywordsFormat.clean]), each once, at most [MAX_KEYWORDS]. */ + private fun readKeywords(root: JsonObject): List = root.array("blockedKeywords").orEmpty() + .mapNotNull { (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content } + .mapNotNull(BlockedKeywordsFormat::clean) + .filter { it.length <= MAX_PATTERN } + .distinctBy { it.lowercase() } + .take(MAX_KEYWORDS) + + /** The words of [incoming] not in [existing] yet (any case), the ones a restore adds. */ + fun newKeywords(incoming: List, existing: Collection): List = + incoming.filter { !BlockedKeywordsFormat.contains(existing, it) } + /** * Splits the [incoming] rules into the ones not on the phone yet and the count already present, with the same * idea as the repository's duplicate check (kind, type, pattern; numbers by their last digits, sender names and diff --git a/app/src/main/kotlin/com/glooboo/umessage/helpers/MessagesImporter.kt b/app/src/main/kotlin/com/glooboo/umessage/helpers/MessagesImporter.kt index b957df8d..2d41c17a 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/helpers/MessagesImporter.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/helpers/MessagesImporter.kt @@ -1,6 +1,7 @@ package com.glooboo.umessage.helpers import android.content.Context +import android.provider.Telephony import android.util.Xml import com.glooboo.umessage.backup.AppDataBackupSupport import com.glooboo.umessage.backup.BlockedBackupSupport @@ -8,7 +9,9 @@ import com.glooboo.umessage.models.AppDataBackup import com.glooboo.umessage.models.BlockedBackup import com.glooboo.umessage.models.ImportSummary import com.glooboo.umessage.models.MessagesBackup +import com.glooboo.umessage.models.MmsAddress import com.glooboo.umessage.models.MmsBackup +import com.glooboo.umessage.models.MmsPart import com.glooboo.umessage.models.NotesBackup import com.glooboo.umessage.models.SmsBackup import com.glooboo.umessage.models.WriteOutcome @@ -19,6 +22,7 @@ import kotlinx.serialization.json.DecodeSequenceMode import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.decodeToSequence +import com.google.android.mms.pdu_alt.PduHeaders import org.fossify.commons.helpers.isUpsideDownCakePlus import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserException @@ -31,7 +35,7 @@ import java.io.InputStream * size can be restored. Two formats are understood, told apart by their first character: * * - this app's JSON (an array of SMS and MMS entries, also written by Fossify Messages); - * - the XML of "SMS Backup & Restore" (its SMS only; its picture messages are counted and reported, not restored). + * - the XML of "SMS Backup & Restore" (its SMS and its picture messages, attachments up to a size limit). * * Every entry ends up in one bucket of the returned [ImportSummary]. A damaged entry is skipped and counted, and the * restore goes on; a file that stops making sense part way keeps everything before that point and says so. Nothing @@ -39,6 +43,7 @@ import java.io.InputStream * * Restoring is idempotent (see [MessagesWriter]), so running the same file again only adds what is missing. */ +@Suppress("TooManyFunctions") class MessagesImporter( private val context: Context, private val writer: MessagesWriter = MessagesWriter(context), @@ -237,7 +242,21 @@ class MessagesImporter( "mms" -> { summary.entriesRead++ - if (options.mms) summary.unsupportedMms++ else summary.skippedByChoice++ + if (options.mms) { + val mms = try { + parser.readMms() + } catch (e: XmlPullParserException) { + throw e + } catch (e: java.io.IOException) { + throw e + } catch (_: Exception) { + summary.damaged++ + null + } + if (mms != null) restore(mms, options, summary) + } else { + summary.skippedByChoice++ + } parser.skipToEnd() } @@ -275,6 +294,121 @@ class MessagesImporter( ) } + /** + * A picture message of the XML: the attributes of `` and its `` and `` children, read through to + * the end tag of the element. Parts and addresses beyond the limits, and an attachment larger than + * [MAX_PART_BASE64], are left out (the writer then reports the message as restored without that attachment). + * Throws when the date or the box is missing. + */ + private fun XmlPullParser.readMms(): MmsBackup { + val attrs = HashMap() + for (i in 0 until attributeCount) { + val value = getAttributeValue(i) + if (value != "null") attrs[getAttributeName(i)] = value + } + val date = requireNotNull(attrs["date"]?.toLongOrNull()) { "no date" } + val box = requireNotNull(attrs["msg_box"]?.toIntOrNull()) { "no box" } + val parts = mutableListOf() + val addresses = mutableListOf() + readMmsChildren(parts, addresses) + // Files without only give address="a~b": the first number sent a received message. + if (addresses.isEmpty()) addresses += addressesFromAttribute(attrs["address"], box) + return mmsFrom(attrs, date, box, parts, addresses) + } + + /** Reads the `` and `` children up to the end tag of the `` element. */ + private fun XmlPullParser.readMmsChildren(parts: MutableList, addresses: MutableList) { + var depth = 1 + while (depth != 0) { + when (next()) { + XmlPullParser.START_TAG -> { + depth++ + readMmsChild(parts, addresses) + } + XmlPullParser.END_TAG -> depth-- + XmlPullParser.END_DOCUMENT -> throw XmlPullParserException("file ends inside an element") + } + } + } + + private fun XmlPullParser.readMmsChild(parts: MutableList, addresses: MutableList) { + when (name) { + "part" -> readPart(parts.size)?.takeIf { parts.size < MAX_PARTS }?.let { parts += it } + "addr" -> readAddress()?.takeIf { addresses.size < MAX_ADDRESSES }?.let { addresses += it } + } + } + + private fun addressesFromAttribute(attribute: String?, box: Int): List { + val numbers = attribute.orEmpty().split('~').map { it.trim() } + .filter { it.isNotEmpty() && it.length <= MAX_ADDRESS }.take(MAX_ADDRESSES) + return numbers.mapIndexed { i, number -> + val received = box == Telephony.Mms.MESSAGE_BOX_INBOX + val addressType = if (received && i == 0) PduHeaders.FROM else PduHeaders.TO + MmsAddress(number, addressType, UTF8_CHARSET) + } + } + + /** The provider keeps MMS times in seconds; SMS Backup & Restore writes them in milliseconds. */ + private fun seconds(time: Long) = if (time >= MILLIS_FROM) time / MILLIS_PER_SECOND else time + + private fun mmsFrom( + attrs: Map, date: Long, box: Int, parts: List, addresses: List, + ): MmsBackup { + val received = box == Telephony.Mms.MESSAGE_BOX_INBOX + fun int(name: String, default: Int) = attrs[name]?.toIntOrNull() ?: default + return MmsBackup( + creator = null, + contentType = attrs["ct_t"] ?: "application/vnd.wap.multipart.related", + deliveryReport = int("d_rpt", 0), + date = seconds(date), + dateSent = seconds(attrs["date_sent"]?.toLongOrNull() ?: 0), + locked = int("locked", 0), + messageType = int( + "m_type", if (received) PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF else PduHeaders.MESSAGE_TYPE_SEND_REQ, + ), + messageBox = box, + read = int("read", 1), + readReport = int("rr", 0), + seen = int("seen", 1), + textOnly = int("text_only", if (parts.none { it.isNonText() }) 1 else 0), + status = attrs["st"], + subject = attrs["sub"], + subjectCharSet = attrs["sub_cs"], + // Another phone's SIM ids mean nothing here. + subscriptionId = -1, + transactionId = attrs["tr_id"], + addresses = addresses, + parts = parts, + ) + } + + private fun XmlPullParser.readPart(index: Int): MmsPart? { + fun attr(name: String): String? = getAttributeValue(null, name)?.takeUnless { it == "null" } + val type = attr("ct")?.takeIf { it.isNotBlank() } ?: return null + return MmsPart( + contentDisposition = attr("cd"), + charset = attr("chset"), + contentId = attr("cid"), + contentLocation = attr("cl"), + contentType = type, + ctStart = attr("ctt_s"), + ctType = attr("ctt_t"), + filename = attr("fn"), + name = attr("name"), + sequenceOrder = attr("seq")?.toIntOrNull() ?: index, + text = attr("text"), + // An attachment over the size limit is left out, so the message is restored without it. + data = attr("data")?.takeIf { it.length <= MAX_PART_BASE64 }, + ) + } + + private fun XmlPullParser.readAddress(): MmsAddress? { + fun attr(name: String): String? = getAttributeValue(null, name)?.takeUnless { it == "null" } + val address = attr("address")?.trim()?.takeIf { it.isNotEmpty() && it.length <= MAX_ADDRESS } ?: return null + val type = attr("type")?.toIntOrNull() ?: return null + return MmsAddress(address, type, attr("charset")?.toIntOrNull() ?: UTF8_CHARSET) + } + /** Moves past the end of the element the parser is on, whatever it contains. */ private fun XmlPullParser.skipToEnd() { if (eventType != XmlPullParser.START_TAG) return @@ -303,6 +437,17 @@ class MessagesImporter( const val BUFFER = 64 * 1024 const val PEEK_LIMIT = 64 const val PROGRESS_EVERY = 25 + + /** Limits of one XML picture message, so a hostile file cannot fill the phone or the memory. */ + const val MAX_PARTS = 100 + const val MAX_ADDRESSES = 100 + const val MAX_ADDRESS = 100 + const val UTF8_CHARSET = 106 + const val MILLIS_FROM = 100_000_000_000L + const val MILLIS_PER_SECOND = 1000L + + /** Longest base64 text of one attachment read: about 14 MB of attachment. */ + const val MAX_PART_BASE64 = 19_000_000 } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/helpers/OtpCodes.kt b/app/src/main/kotlin/com/glooboo/umessage/helpers/OtpCodes.kt index fe33ce93..b6ac73d6 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/helpers/OtpCodes.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/helpers/OtpCodes.kt @@ -17,7 +17,8 @@ data class CodeToken(val kind: CodeKind, val value: String) * A message holds a code when either * - a 4-8 digit number sits next to an OTP keyword ([OtpDetector.nearKeyword]; the shape of the number, the keyword * lists and the vetoes for advertisements, prices, years and phone numbers are the detector's, and - * [OtpCodeExtractor.locate] picks the number), or + * [OtpCodeExtractor.locate] picks the number) or a letters-and-digits code has a keyword in its sentence + * ([OtpDetector.alphanumericCodes], "Your code is ab12cd"), or * - a labelled value says what it is ("password: x7Kq2", "code: 482913"). A user name is a value to copy, but no code. * * Everything is read through [TextNormalizer.fold], so every value comes back with Latin digits (Persian "۴۸۲۹۱۳" @@ -90,10 +91,12 @@ object OtpCodes { /** Digit codes with a keyword next to them: position and value; the closest to a keyword when none is adjacent. */ private fun keywordCodes(text: String): List> { if (!OtpDetector.nearKeyword(text)) return emptyList() - val adjacent = OtpCodeExtractor.keywordBound(text) - .filter { OtpDetector.keywordNextTo(text, it.groups[1]!!.range) } - .map { it.groups[1]!!.range.first to OtpCodeExtractor.digitsOf(it.groupValues[1]) } - .toList() + val adjacent = ( + OtpCodeExtractor.keywordBound(text) + .filter { OtpDetector.keywordNextTo(text, it.groups[1]!!.range) } + .map { it.groups[1]!!.range.first to OtpCodeExtractor.digitsOf(it.groupValues[1]) } + .toList() + OtpDetector.alphanumericCodes(text) + ).sortedBy { it.first } if (adjacent.isNotEmpty()) return adjacent return listOfNotNull(locate(text)) .map { it.groups[1]!!.range.first to OtpCodeExtractor.digitsOf(it.groupValues[1]) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/messaging/SendingErrors.kt b/app/src/main/kotlin/com/glooboo/umessage/messaging/SendingErrors.kt index 31585715..ed25b72a 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/messaging/SendingErrors.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/messaging/SendingErrors.kt @@ -6,7 +6,6 @@ import android.telephony.SmsManager import com.glooboo.umessage.R import com.glooboo.umessage.receivers.SendStatusReceiver -@Suppress("CyclomaticComplexMethod") fun Context.getSmsSendingError( resultCode: Int, errorCode: Int = SendStatusReceiver.NO_ERROR_CODE, @@ -16,7 +15,18 @@ fun Context.getSmsSendingError( return null } - val messageId = if (noDefault) { + val message = getString(smsSendingErrorRes(resultCode, noDefault)) + return if (errorCode == SendStatusReceiver.NO_ERROR_CODE) { + getString(R.string.sms_sending_error_details, message, resultCode) + } else { + getString(R.string.sms_sending_error_radio_details, message, resultCode, errorCode) + } +} + +/** The text that names why an SMS send report with [resultCode] failed; "Message not sent" when it names nothing. */ +@Suppress("CyclomaticComplexMethod") +internal fun smsSendingErrorRes(resultCode: Int, noDefault: Boolean = false): Int { + return if (noDefault) { R.string.sms_error_no_sim_selected } else { when (resultCode) { @@ -102,12 +112,6 @@ fun Context.getSmsSendingError( else -> R.string.message_not_sent_short } } - val message = getString(messageId) - return if (errorCode == SendStatusReceiver.NO_ERROR_CODE) { - getString(R.string.sms_sending_error_details, message, resultCode) - } else { - getString(R.string.sms_sending_error_radio_details, message, resultCode, errorCode) - } } @Suppress("CyclomaticComplexMethod") diff --git a/app/src/main/kotlin/com/glooboo/umessage/messaging/SmsFailureReason.kt b/app/src/main/kotlin/com/glooboo/umessage/messaging/SmsFailureReason.kt new file mode 100644 index 00000000..408becca --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/messaging/SmsFailureReason.kt @@ -0,0 +1,77 @@ +package com.glooboo.umessage.messaging + +import android.content.ContentValues +import android.content.Context +import android.net.Uri +import android.provider.Telephony.Sms +import android.telephony.SmsManager +import com.glooboo.umessage.R + +/** + * Thread-27: why a text failed, shown under the "Not sent" row. + * + * The phone's send report ([SmsManager] result code) is kept in the provider's own `error_code` column of the failed + * row, so no table of this app changes. 0 means "no reason stored" (every real failure code is 1 or more). + */ +object SmsFailureReason { + + /** The provider's column for a message's error code (the same string as `Telephony.Sms.ERROR_CODE`). */ + internal const val COLUMN = "error_code" + + /** No reason stored: the message did not fail, or failed before the reason was kept. */ + const val NONE = 0 + + /** Writes [resultCode] (a failed send report) on the provider row [uri]. Never throws: the reason is a nicety. */ + fun record(context: Context, uri: Uri?, resultCode: Int) { + if (uri == null || resultCode <= NONE) return + runCatching { + context.contentResolver.update(uri, ContentValues().apply { put(COLUMN, resultCode) }, null, null) + } + } + + /** Forgets the reason of [uri]: the message went out after all. */ + fun clear(context: Context, uri: Uri?) { + if (uri == null) return + runCatching { + context.contentResolver.update(uri, ContentValues().apply { put(COLUMN, NONE) }, null, null) + } + } + + /** + * The stored reason of each failed text of [threadId], by message id; rows without a reason are left out. One + * provider query: call it off the main thread. + */ + fun failedCodes(context: Context, threadId: Long): Map { + if (threadId <= 0L) return emptyMap() + return runCatching { + val codes = HashMap() + context.contentResolver.query( + Sms.CONTENT_URI, + arrayOf(Sms._ID, COLUMN), + "${Sms.THREAD_ID} = ? AND ${Sms.TYPE} = ?", + arrayOf(threadId.toString(), Sms.MESSAGE_TYPE_FAILED.toString()), + null, + )?.use { cursor -> + while (cursor.moveToNext()) { + val code = cursor.getInt(1) + if (code > NONE) codes[cursor.getLong(0)] = code + } + } + codes + }.getOrDefault(emptyMap()) + } + + /** + * The words for a stored [code], or null when none is stored. A general failure, and a code that names nothing + * more specific, read as [R.string.thread_failed_reason_generic]. + */ + fun text(context: Context, code: Int): String? { + if (code <= NONE) return null + val res = smsSendingErrorRes(code) + return if (code == SmsManager.RESULT_ERROR_GENERIC_FAILURE || res == R.string.message_not_sent_short) { + context.getString(R.string.thread_failed_reason_generic, code) + } else { + context.getString(res) + } + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/models/ThreadItems.kt b/app/src/main/kotlin/com/glooboo/umessage/models/ThreadItems.kt index 8e40f4c5..6dfa2f24 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/models/ThreadItems.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/models/ThreadItems.kt @@ -5,8 +5,16 @@ package com.glooboo.umessage.models */ sealed class ThreadItem { data class ThreadDateTime(val date: Int, val simID: String) : ThreadItem() - /** The failed message is [messageId] of type [isMMS] (see [MessageKey]); Retry acts on that pair. */ - data class ThreadError(val messageId: Long, val messageText: String, val isMMS: Boolean = false) : ThreadItem() { + /** + * The failed message is [messageId] of type [isMMS] (see [MessageKey]); Retry acts on that pair. [reasonCode] is + * the phone's send-report code kept for it (0: none), see SmsFailureReason. + */ + data class ThreadError( + val messageId: Long, + val messageText: String, + val isMMS: Boolean = false, + val reasonCode: Int = 0, + ) : ThreadItem() { val key: MessageKey get() = MessageKey(messageId, isMMS) } /** diff --git a/app/src/main/kotlin/com/glooboo/umessage/receivers/SmsStatusSentReceiver.kt b/app/src/main/kotlin/com/glooboo/umessage/receivers/SmsStatusSentReceiver.kt index 31efe23f..0015b6ee 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/receivers/SmsStatusSentReceiver.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/receivers/SmsStatusSentReceiver.kt @@ -23,6 +23,7 @@ import com.glooboo.umessage.helpers.hasFailedSendNotification import com.glooboo.umessage.helpers.refreshConversations import com.glooboo.umessage.helpers.refreshMessages import com.glooboo.umessage.messaging.SentParts +import com.glooboo.umessage.messaging.SmsFailureReason import com.glooboo.umessage.spam.data.ForwardDelivery /** Handles updating databases and states when a SMS message is sent. */ @@ -77,6 +78,13 @@ class SmsStatusSentReceiver : SendStatusReceiver() { context.messagesDB.updateType(messageId, isMMS = false, type = type) val groupUri = groupRowUri(intent) + // Thread-27: the thread names why it failed, from the phone's own report; a later success forgets it. + if (outcome == SentParts.Outcome.FAILED_FIRST) { + SmsFailureReason.record(context, intent.data, receiverResultCode) + SmsFailureReason.record(context, groupUri, receiverResultCode) + } else if (outcome == SentParts.Outcome.SENT) { + SmsFailureReason.clear(context, intent.data) + } if (outcome.isFailure()) { groupUri?.let { messageIdOf(it) }?.let { context.messagesDB.updateType(it, isMMS = false, type = type) } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/SpamContracts.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/SpamContracts.kt index 50746b59..649220d1 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/SpamContracts.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/SpamContracts.kt @@ -30,6 +30,12 @@ enum class RuleType { /** Java regex matched against the message body. */ REGEX, + + /** + * A web domain such as "example.com": matches a link in the message body whose host is that domain or one of its + * subdomains ("www.example.com", "a.b.example.com", but not "notexample.com" or "example.com.evil.net"). + */ + DOMAIN, } /** SIM scope of a rule. [subscriptionId] == null means both SIMs. */ @@ -41,6 +47,10 @@ data class SpamRule( val subscriptionId: Int? = null, val note: String = "", val createdAt: Long = System.currentTimeMillis(), + /** How many messages this rule has blocked (counted by the engine, not editable). */ + val hitCount: Int = 0, + /** When this rule last blocked a message in milliseconds, 0 = never. */ + val lastHit: Long = 0L, ) data class IncomingMessage( diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepository.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepository.kt index 13c4d562..1ac5eb2c 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepository.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepository.kt @@ -14,6 +14,7 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import com.glooboo.umessage.spam.BlockedMessage +import com.glooboo.umessage.spam.DecisionReason import com.glooboo.umessage.spam.ListKind import com.glooboo.umessage.spam.MMS_PLACEHOLDER_BODY import com.glooboo.umessage.spam.MmsMedia @@ -25,6 +26,7 @@ import com.glooboo.umessage.spam.SpamRepository import com.glooboo.umessage.spam.SpamRule import com.glooboo.umessage.spam.SpamSettings import com.glooboo.umessage.spam.SpamStats +import com.glooboo.umessage.spam.engine.DomainMatch import com.glooboo.umessage.spam.engine.NumberNormalizer class DefaultSpamRepository( @@ -97,7 +99,15 @@ class DefaultSpamRepository( val pattern = cleanPattern(rule) val other = dao.findRule(rule.kind, rule.type, pattern, rule.subscriptionId) if (other != null && other.id != rule.id) return@runInTransaction other.id - dao.updateRule(SpamRuleEntity.from(rule.copy(pattern = pattern, createdAt = current.createdAt))) + // The counters belong to the engine: an edit from a screen that read the rule earlier must not reset them. + dao.updateRule( + SpamRuleEntity.from( + rule.copy( + pattern = pattern, createdAt = current.createdAt, + hitCount = current.hitCount, lastHit = current.lastHit, + ) + ) + ) rule.id } } @@ -150,6 +160,11 @@ class DefaultSpamRepository( } else { val rowId = dao.insertBlocked(BlockedMessageEntity.from(capped)) dao.insertEvent(SpamEventEntity(type = SpamEventType.BLOCKED, timestamp = System.currentTimeMillis())) + // spam-23: a rule that blocked a new message counts it (one cheap UPDATE in this transaction, which + // already runs off the main thread). A duplicate copy is not a new hit; a deleted rule matches no row. + if (capped.reason == DecisionReason.BLOCK_RULE && capped.ruleId != null) { + dao.recordRuleHit(capped.ruleId, System.currentTimeMillis()) + } rowId } } @@ -289,6 +304,7 @@ class DefaultSpamRepository( subscriptionId = row.subscriptionId, status = Telephony.Sms.STATUS_NONE, createdAt = now, + approved = true, ) pending = entity.copy(id = dao.insertPending(entity)) } @@ -405,6 +421,7 @@ class DefaultSpamRepository( RuleType.NUMBER -> ruleNormalizer(rule.subscriptionId).normalize(rule.pattern) RuleType.SENDER_ID -> normalizer.normalize(rule.pattern) RuleType.PREFIX -> normalizer.cleanPrefix(rule.pattern) + RuleType.DOMAIN -> DomainMatch.clean(rule.pattern) else -> rule.pattern.trim() } diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/data/PendingSms.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/data/PendingSms.kt index 65cc5ec8..a8392c41 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/data/PendingSms.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/data/PendingSms.kt @@ -1,261 +1,269 @@ -package com.glooboo.umessage.spam.data - -import android.content.Context -import android.provider.Telephony -import androidx.room.ColumnInfo -import androidx.room.Entity -import androidx.room.PrimaryKey -import com.glooboo.umessage.extensions.getThreadId -import com.glooboo.umessage.helpers.NotifyContext -import com.glooboo.umessage.helpers.OtpCodeExtractor -import com.glooboo.umessage.spam.DecisionReason -import com.glooboo.umessage.spam.FilterDecision -import com.glooboo.umessage.spam.engine.UnknownNotifyPolicy -import com.glooboo.umessage.spam.IncomingMessage -import com.glooboo.umessage.spam.SpamLogEntry -import com.glooboo.umessage.spam.SpamSettings -import com.glooboo.umessage.spam.UMessage -import com.glooboo.umessage.spam.engine.ForwardCandidate -import com.glooboo.umessage.spam.engine.SpamEngine -import java.util.concurrent.ConcurrentHashMap - -/** An SMS that reached the receiver but has not been filtered and saved yet. Written first, deleted last. */ -@Entity(tableName = "pending_sms") -data class PendingSmsEntity( - @PrimaryKey(autoGenerate = true) val id: Long = 0, - val address: String, - val subject: String, - val body: String, - val date: Long, - val subscriptionId: Int, - val status: Int, - val createdAt: Long, - /** The carrier's send time from the PDU in milliseconds, 0 when unknown. [date] stays the arrival time. */ - @ColumnInfo(defaultValue = "0") val dateSent: Long = 0L, -) - -object PendingSmsPolicy { - /** A receiver normally finishes within seconds; older rows belong to a process that died. */ - const val GRACE_MS = 30_000L - - /** - * After this long rows stop going through the filter (it may be what keeps failing) and are delivered - * straight to the inbox instead. They are never dropped without being delivered. - */ - const val MAX_AGE_MS = 7L * 24 * 60 * 60 * 1000 - - /** A row being processed in this process is left alone by replay for this long. */ - const val LEASE_MS = 5L * 60 * 1000 - - fun isDue(createdAt: Long, now: Long): Boolean = now - createdAt >= GRACE_MS - - fun isExpired(createdAt: Long, now: Long): Boolean = now - createdAt > MAX_AGE_MS - - /** [leasedAt] is when this process started working on the row, null when nobody is. */ - fun isLeased(leasedAt: Long?, now: Long): Boolean = leasedAt != null && now >= leasedAt && now - leasedAt < LEASE_MS -} - -/** The single path every incoming SMS takes: filter, then store as blocked or deliver to the inbox. */ -object IncomingSmsProcessor { - - /** - * Filters and stores [message]. Throws when it could not be saved anywhere, so the caller keeps the pending - * row (it is then replayed later). A filter failure never throws: the message is delivered instead. - */ - fun process(context: Context, message: PendingSmsEntity) { - val incoming = IncomingMessage( - address = message.address, - body = message.body, - subscriptionId = message.subscriptionId, - isMms = false, - receivedAt = message.date, - ) - val decision = SpamEngine.evaluate(context, incoming) - val block = decision as? FilterDecision.Block - if (block != null && SpamEngine.storeBlocked(context, incoming, block)) return - deliver(context, message, notifyContextFor(context, message, decision)) - SpamEngine.allowSenderOfKeyword(context, incoming, decision) - // Only now, with the SMS safely in the inbox: blocked spam never reaches this line. Never throws, so a - // forwarding problem cannot make the caller keep (and later replay) a message that is already delivered. - ForwardDelivery.onInboxMessage( - context, - ForwardCandidate( - address = message.address, - body = message.body, - subscriptionId = message.subscriptionId, - isMms = false, - receivedAt = message.date, - ), - ) - } - - /** - * I03: how loud the notification of an inbox message is. In Off mode a number the user has written to counts as - * known, as it does in the other modes. A failed filter ([decision] null) notifies as usual. - */ - internal fun notifyContextFor( - context: Context, - message: PendingSmsEntity, - decision: FilterDecision?, - ): NotifyContext { - var reason = (decision as? FilterDecision.Allow)?.reason - if (reason == DecisionReason.MODE_OFF && SpamEngine.hasWrittenTo(context, message.address)) { - reason = DecisionReason.KNOWN_CONVERSATION - } - val setting = runCatching { SpamEngine.repository(context).currentSettings().unknownInboxNotify } - .getOrDefault(SpamSettings().unknownInboxNotify) - val hasCode = OtpCodeExtractor.extract(message.body) != null - return NotifyContext(UnknownNotifyPolicy.modeFor(reason, setting, hasCode), reason) - } - - /** - * Puts [message] in the inbox. [deliverIncomingSms] throws only when the provider insert itself did not happen, - * so one plain retry here cannot create a duplicate (and is skipped when the row is somehow already there). - * Throws [SmsInsertException] when the message is still not stored. - */ - fun deliver(context: Context, message: PendingSmsEntity, notify: NotifyContext = NotifyContext()): Long { - return try { - context.deliverIncomingSms( - address = message.address, - subject = message.subject, - body = message.body, - date = message.date, - subscriptionId = message.subscriptionId, - status = message.status, - notify = notify, - dateSent = message.dateSent, - ) - } catch (first: Throwable) { - insertRaw(context, message, first) - } - } - - /** Last resort: a bare provider insert without the cache, conversation or notification steps. */ - internal fun insertRaw(context: Context, message: PendingSmsEntity, cause: Throwable? = null): Long { - if (PendingSmsQueue.alreadyInInbox(context, message)) return -1L - val threadId = runCatching { context.getThreadId(message.address) }.getOrDefault(0L) - return try { - context.insertSmsOrThrow( - address = message.address, - subject = message.subject, - body = message.body, - date = message.date, - read = 0, - threadId = threadId, - type = Telephony.Sms.MESSAGE_TYPE_INBOX, - subscriptionId = message.subscriptionId, - dateSent = message.dateSent, - ) - } catch (t: Throwable) { - throw SmsInsertException("SMS could not be stored", cause ?: t) - } - } -} - -object PendingSmsQueue { - - /** Rows this process is working on right now (row id -> start time), so replay does not process them twice. */ - private val leases = ConcurrentHashMap() - - /** Returns the row id, or 0 when the write failed (the caller then just processes the message directly). */ - fun add(context: Context, message: PendingSmsEntity): Long = try { - SpamDatabase.getInstance(context).spamDao().insertPending(message).also { lease(it) } - } catch (t: Throwable) { - 0L - } - - /** Marks [id] as being processed by the caller until [done] (or until the lease runs out). */ - fun lease(id: Long, now: Long = System.currentTimeMillis()) { - if (id > 0L) leases[id] = now - } - - /** - * The caller gave up on [id] for now (its save failed). The row stays in the table; dropping the lease lets the - * next replay retry it at once instead of waiting [PendingSmsPolicy.LEASE_MS]. - */ - fun release(id: Long) { - leases.remove(id) - } - - fun done(context: Context, id: Long) { - if (id == 0L) return - runCatching { SpamDatabase.getInstance(context).spamDao().deletePending(id) } - leases.remove(id) - } - - /** - * Re-runs messages left behind by a killed process or a failed save. Blocking call, run off the main thread. - * A row is removed only after it was stored (blocked or in the inbox). Rows older than - * [PendingSmsPolicy.MAX_AGE_MS] skip the filter and are delivered straight to the inbox. - * - * Returns how many rows are still waiting afterwards (failed now, not due yet or leased by another caller), or - * -1 when the queue could not be read at all. Either way a value other than 0 means "try again later". - */ - @Synchronized - fun replay(context: Context, now: Long = System.currentTimeMillis()): Int { - val dao = try { - SpamDatabase.getInstance(context).spamDao() - } catch (t: Throwable) { - return -1 - } - val rows = try { - dao.getPending() - } catch (t: Throwable) { - return -1 - } - var waiting = 0 - for (row in rows) { - if (!PendingSmsPolicy.isDue(row.createdAt, now) || PendingSmsPolicy.isLeased(leases[row.id], now)) { - waiting++ - continue - } - lease(row.id, now) - val expired = PendingSmsPolicy.isExpired(row.createdAt, now) - val result = runCatching { - when { - alreadyInInbox(context, row) -> Unit - expired -> if (!alreadyBlocked(dao, row)) IncomingSmsProcessor.deliver(context, row) - else -> IncomingSmsProcessor.process(context, row) - } - } - result.exceptionOrNull()?.let { error -> - val reason = (if (expired) "EXPIRED_" else "") + error.javaClass.simpleName - runCatching { - UMessage.log(context).record( - SpamLogEntry(now, row.address, row.subscriptionId, "ERROR", reason, "PENDING_REPLAY") - ) - } - } - if (result.isSuccess) { - done(context, row.id) - } else { - // Let the next replay retry right away instead of waiting out the lease. - leases.remove(row.id) - waiting++ - } - } - return waiting - } - - /** The row was stored as blocked already (the process died before the pending row was deleted). */ - private fun alreadyBlocked(dao: SpamDao, row: PendingSmsEntity): Boolean = runCatching { - dao.findDuplicateBlocked( - BlockedLimits.limitAddress(row.address), - BlockedLimits.limitBody(row.body), - false, - row.date - BlockedLimits.DUPLICATE_WINDOW_MS, - row.date + BlockedLimits.DUPLICATE_WINDOW_MS, - ) != null - }.getOrDefault(false) - - /** The process may have died after the inbox insert and before the row was deleted. */ - internal fun alreadyInInbox(context: Context, row: PendingSmsEntity): Boolean = runCatching { - context.contentResolver.query( - Telephony.Sms.Inbox.CONTENT_URI, - arrayOf(Telephony.Sms._ID), - "${Telephony.Sms.ADDRESS} = ? AND ${Telephony.Sms.BODY} = ? AND ${Telephony.Sms.DATE} = ?", - arrayOf(row.address, row.body, row.date.toString()), - null, - )?.use { it.count > 0 } ?: false - }.getOrDefault(false) -} +package com.glooboo.umessage.spam.data + +import android.content.Context +import android.provider.Telephony +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.PrimaryKey +import com.glooboo.umessage.extensions.getThreadId +import com.glooboo.umessage.helpers.NotifyContext +import com.glooboo.umessage.helpers.OtpCodeExtractor +import com.glooboo.umessage.spam.DecisionReason +import com.glooboo.umessage.spam.FilterDecision +import com.glooboo.umessage.spam.engine.UnknownNotifyPolicy +import com.glooboo.umessage.spam.IncomingMessage +import com.glooboo.umessage.spam.SpamLogEntry +import com.glooboo.umessage.spam.SpamSettings +import com.glooboo.umessage.spam.UMessage +import com.glooboo.umessage.spam.engine.ForwardCandidate +import com.glooboo.umessage.spam.engine.SpamEngine +import java.util.concurrent.ConcurrentHashMap + +/** An SMS that reached the receiver but has not been filtered and saved yet. Written first, deleted last. */ +@Entity(tableName = "pending_sms") +data class PendingSmsEntity( + @PrimaryKey(autoGenerate = true) val id: Long = 0, + val address: String, + val subject: String, + val body: String, + val date: Long, + val subscriptionId: Int, + val status: Int, + val createdAt: Long, + /** The carrier's send time from the PDU in milliseconds, 0 when unknown. [date] stays the arrival time. */ + @ColumnInfo(defaultValue = "0") val dateSent: Long = 0L, + /** + * Added in version 8. True for a message the user restored from Blocked (spam-2): it already passed the filter by + * the user's decision, so a replay delivers it to the inbox without filtering it again. + */ + @ColumnInfo(defaultValue = "0") val approved: Boolean = false, +) + +object PendingSmsPolicy { + /** A receiver normally finishes within seconds; older rows belong to a process that died. */ + const val GRACE_MS = 30_000L + + /** + * After this long rows stop going through the filter (it may be what keeps failing) and are delivered + * straight to the inbox instead. They are never dropped without being delivered. + */ + const val MAX_AGE_MS = 7L * 24 * 60 * 60 * 1000 + + /** A row being processed in this process is left alone by replay for this long. */ + const val LEASE_MS = 5L * 60 * 1000 + + fun isDue(createdAt: Long, now: Long): Boolean = now - createdAt >= GRACE_MS + + fun isExpired(createdAt: Long, now: Long): Boolean = now - createdAt > MAX_AGE_MS + + /** [leasedAt] is when this process started working on the row, null when nobody is. */ + fun isLeased(leasedAt: Long?, now: Long): Boolean = leasedAt != null && now >= leasedAt && now - leasedAt < LEASE_MS +} + +/** The single path every incoming SMS takes: filter, then store as blocked or deliver to the inbox. */ +object IncomingSmsProcessor { + + /** + * Filters and stores [message]. Throws when it could not be saved anywhere, so the caller keeps the pending + * row (it is then replayed later). A filter failure never throws: the message is delivered instead. + */ + fun process(context: Context, message: PendingSmsEntity) { + val incoming = IncomingMessage( + address = message.address, + body = message.body, + subscriptionId = message.subscriptionId, + isMms = false, + receivedAt = message.date, + ) + val decision = SpamEngine.evaluate(context, incoming) + val block = decision as? FilterDecision.Block + if (block != null && SpamEngine.storeBlocked(context, incoming, block)) return + deliver(context, message, notifyContextFor(context, message, decision)) + SpamEngine.allowSenderOfKeyword(context, incoming, decision) + // Only now, with the SMS safely in the inbox: blocked spam never reaches this line. Never throws, so a + // forwarding problem cannot make the caller keep (and later replay) a message that is already delivered. + ForwardDelivery.onInboxMessage( + context, + ForwardCandidate( + address = message.address, + body = message.body, + subscriptionId = message.subscriptionId, + isMms = false, + receivedAt = message.date, + ), + ) + } + + /** + * I03: how loud the notification of an inbox message is. In Off mode a number the user has written to counts as + * known, as it does in the other modes. A failed filter ([decision] null) notifies as usual. + */ + internal fun notifyContextFor( + context: Context, + message: PendingSmsEntity, + decision: FilterDecision?, + ): NotifyContext { + var reason = (decision as? FilterDecision.Allow)?.reason + if (reason == DecisionReason.MODE_OFF && SpamEngine.hasWrittenTo(context, message.address)) { + reason = DecisionReason.KNOWN_CONVERSATION + } + val setting = runCatching { SpamEngine.repository(context).currentSettings().unknownInboxNotify } + .getOrDefault(SpamSettings().unknownInboxNotify) + val hasCode = OtpCodeExtractor.extract(message.body) != null + return NotifyContext(UnknownNotifyPolicy.modeFor(reason, setting, hasCode), reason) + } + + /** + * Puts [message] in the inbox. [deliverIncomingSms] throws only when the provider insert itself did not happen, + * so one plain retry here cannot create a duplicate (and is skipped when the row is somehow already there). + * Throws [SmsInsertException] when the message is still not stored. + */ + fun deliver(context: Context, message: PendingSmsEntity, notify: NotifyContext = NotifyContext()): Long { + return try { + context.deliverIncomingSms( + address = message.address, + subject = message.subject, + body = message.body, + date = message.date, + subscriptionId = message.subscriptionId, + status = message.status, + notify = notify, + dateSent = message.dateSent, + ) + } catch (first: Throwable) { + insertRaw(context, message, first) + } + } + + /** Last resort: a bare provider insert without the cache, conversation or notification steps. */ + internal fun insertRaw(context: Context, message: PendingSmsEntity, cause: Throwable? = null): Long { + if (PendingSmsQueue.alreadyInInbox(context, message)) return -1L + val threadId = runCatching { context.getThreadId(message.address) }.getOrDefault(0L) + return try { + context.insertSmsOrThrow( + address = message.address, + subject = message.subject, + body = message.body, + date = message.date, + read = 0, + threadId = threadId, + type = Telephony.Sms.MESSAGE_TYPE_INBOX, + subscriptionId = message.subscriptionId, + dateSent = message.dateSent, + ) + } catch (t: Throwable) { + throw SmsInsertException("SMS could not be stored", cause ?: t) + } + } +} + +object PendingSmsQueue { + + /** Rows this process is working on right now (row id -> start time), so replay does not process them twice. */ + private val leases = ConcurrentHashMap() + + /** Returns the row id, or 0 when the write failed (the caller then just processes the message directly). */ + fun add(context: Context, message: PendingSmsEntity): Long = try { + SpamDatabase.getInstance(context).spamDao().insertPending(message).also { lease(it) } + } catch (t: Throwable) { + 0L + } + + /** Marks [id] as being processed by the caller until [done] (or until the lease runs out). */ + fun lease(id: Long, now: Long = System.currentTimeMillis()) { + if (id > 0L) leases[id] = now + } + + /** + * The caller gave up on [id] for now (its save failed). The row stays in the table; dropping the lease lets the + * next replay retry it at once instead of waiting [PendingSmsPolicy.LEASE_MS]. + */ + fun release(id: Long) { + leases.remove(id) + } + + fun done(context: Context, id: Long) { + if (id == 0L) return + runCatching { SpamDatabase.getInstance(context).spamDao().deletePending(id) } + leases.remove(id) + } + + /** + * Re-runs messages left behind by a killed process or a failed save. Blocking call, run off the main thread. + * A row is removed only after it was stored (blocked or in the inbox). Rows older than + * [PendingSmsPolicy.MAX_AGE_MS] skip the filter and are delivered straight to the inbox. + * + * Returns how many rows are still waiting afterwards (failed now, not due yet or leased by another caller), or + * -1 when the queue could not be read at all. Either way a value other than 0 means "try again later". + */ + @Synchronized + fun replay(context: Context, now: Long = System.currentTimeMillis()): Int { + val dao = try { + SpamDatabase.getInstance(context).spamDao() + } catch (t: Throwable) { + return -1 + } + val rows = try { + dao.getPending() + } catch (t: Throwable) { + return -1 + } + return rows.count { replayRow(context, dao, it, now) } + } + + /** Re-runs one row. Returns true when it is still waiting afterwards. */ + private fun replayRow(context: Context, dao: SpamDao, row: PendingSmsEntity, now: Long): Boolean { + if (!PendingSmsPolicy.isDue(row.createdAt, now) || PendingSmsPolicy.isLeased(leases[row.id], now)) { + return true + } + lease(row.id, now) + val expired = PendingSmsPolicy.isExpired(row.createdAt, now) + val result = runCatching { + when { + alreadyInInbox(context, row) -> Unit + // A restored message is the user's decision: no second filter pass, and no "already blocked" test + // (an identical spam text blocked meanwhile must not stop it from reaching the inbox). + row.approved -> IncomingSmsProcessor.deliver(context, row, NotifyContext.NONE) + expired -> if (!alreadyBlocked(dao, row)) IncomingSmsProcessor.deliver(context, row) + else -> IncomingSmsProcessor.process(context, row) + } + } + result.exceptionOrNull()?.let { error -> + val reason = (if (expired) "EXPIRED_" else "") + error.javaClass.simpleName + runCatching { + UMessage.log(context).record( + SpamLogEntry(now, row.address, row.subscriptionId, "ERROR", reason, "PENDING_REPLAY") + ) + } + } + if (result.isSuccess) { + done(context, row.id) + return false + } + // Let the next replay retry right away instead of waiting out the lease. + leases.remove(row.id) + return true + } + + /** The row was stored as blocked already (the process died before the pending row was deleted). */ + private fun alreadyBlocked(dao: SpamDao, row: PendingSmsEntity): Boolean = runCatching { + dao.findDuplicateBlocked( + BlockedLimits.limitAddress(row.address), + BlockedLimits.limitBody(row.body), + false, + row.date - BlockedLimits.DUPLICATE_WINDOW_MS, + row.date + BlockedLimits.DUPLICATE_WINDOW_MS, + ) != null + }.getOrDefault(false) + + /** The process may have died after the inbox insert and before the row was deleted. */ + internal fun alreadyInInbox(context: Context, row: PendingSmsEntity): Boolean = runCatching { + context.contentResolver.query( + Telephony.Sms.Inbox.CONTENT_URI, + arrayOf(Telephony.Sms._ID), + "${Telephony.Sms.ADDRESS} = ? AND ${Telephony.Sms.BODY} = ? AND ${Telephony.Sms.DATE} = ?", + arrayOf(row.address, row.body, row.date.toString()), + null, + )?.use { it.count > 0 } ?: false + }.getOrDefault(false) +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamDao.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamDao.kt index 4c942bb7..b144ced0 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamDao.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamDao.kt @@ -46,6 +46,10 @@ interface SpamDao { @Update fun updateRule(rule: SpamRuleEntity): Int + /** Counts one more message blocked by rule [id] (no row changes when the rule was deleted meanwhile). */ + @Query("UPDATE spam_rules SET hitCount = hitCount + 1, lastHit = :at WHERE id = :id") + fun recordRuleHit(id: Long, at: Long): Int + @Query("SELECT * FROM blocked_messages ORDER BY receivedAt DESC, id DESC") fun observeBlocked(): Flow> diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamDatabase.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamDatabase.kt index 84f8fcb7..f34ac028 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamDatabase.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamDatabase.kt @@ -107,14 +107,34 @@ abstract class SpamDatabase : RoomDatabase() { /** Schema version that added the carrier send time to the pending queue. */ private const val VERSION_DATE_SENT = 7 + /** + * Schema 8 (owner decisions on the triage): a restored message in the pending queue skips the filter on + * replay (`approved`), and block rules count their hits (`hitCount`, `lastHit`). Existing rows keep behavior: + * nothing is approved, no rule has a hit. The new DOMAIN rule type needs no column (the type is stored by + * name). + */ + private val MIGRATION_7_8 = object : Migration(VERSION_DATE_SENT, VERSION_RULE_STATS) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE `pending_sms` ADD COLUMN `approved` INTEGER NOT NULL DEFAULT 0") + db.execSQL("ALTER TABLE `spam_rules` ADD COLUMN `hitCount` INTEGER NOT NULL DEFAULT 0") + db.execSQL("ALTER TABLE `spam_rules` ADD COLUMN `lastHit` INTEGER NOT NULL DEFAULT 0") + } + } + + /** Schema version that added the approved flag and the rule hit counters. */ + private const val VERSION_RULE_STATS = 8 + internal const val DATABASE_NAME = "spamless.db" /** Must equal the `version` in [Database] above. */ - internal const val VERSION = VERSION_DATE_SENT + internal const val VERSION = VERSION_RULE_STATS /** Every migration, oldest first. */ internal val ALL_MIGRATIONS: Array = - arrayOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7) + arrayOf( + MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, + MIGRATION_7_8, + ) fun getInstance(context: Context): SpamDatabase = instance ?: synchronized(this) { instance ?: build(context.applicationContext, DATABASE_NAME).also { instance = it } diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamEntities.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamEntities.kt index 165a19c0..6dca937c 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamEntities.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamEntities.kt @@ -20,12 +20,17 @@ data class SpamRuleEntity( val subscriptionId: Int?, val note: String, val createdAt: Long, + /** Added in version 8: how many messages this rule blocked. Rules from before it start at 0. */ + @ColumnInfo(defaultValue = "0") val hitCount: Int = 0, + /** Added in version 8: when this rule last blocked a message in milliseconds, 0 = never. */ + @ColumnInfo(defaultValue = "0") val lastHit: Long = 0L, ) { - fun toRule() = SpamRule(id, kind, type, pattern, subscriptionId, note, createdAt) + fun toRule() = SpamRule(id, kind, type, pattern, subscriptionId, note, createdAt, hitCount, lastHit) companion object { fun from(rule: SpamRule) = SpamRuleEntity( - rule.id, rule.kind, rule.type, rule.pattern, rule.subscriptionId, rule.note, rule.createdAt + rule.id, rule.kind, rule.type, rule.pattern, rule.subscriptionId, rule.note, rule.createdAt, + rule.hitCount, rule.lastHit, ) } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/DefaultSpamFilter.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/DefaultSpamFilter.kt index 7f61a8ff..e7b8318f 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/DefaultSpamFilter.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/DefaultSpamFilter.kt @@ -4,6 +4,7 @@ import com.glooboo.umessage.spam.DecisionReason import com.glooboo.umessage.spam.FilterDecision import com.glooboo.umessage.spam.IncomingMessage import com.glooboo.umessage.spam.ListKind +import com.glooboo.umessage.spam.RuleType import com.glooboo.umessage.spam.SpamFilter import com.glooboo.umessage.spam.SpamRule import com.glooboo.umessage.spam.SpamSettings @@ -31,13 +32,20 @@ class DefaultSpamFilter( return FilterDecision.Allow(DecisionReason.ALLOW_RULE, it.id) } - scoped.firstOrNull { it.kind == ListKind.BLOCK && matches(it, message, numbers) }?.let { + val isPhoneNumber = !normalizer.isSenderId(message.address) + // Looked up at most once, and only when it decides something (a pattern rule matched, or below). + val lookup by lazy { if (isPhoneNumber) contactLookup(message.address) else ContactLookup.NOT_FOUND } + // spam-6: a saved contact is never held by a keyword, pattern, prefix or domain block rule. Blocking the exact + // number (or sender id) still works: that is a deliberate choice about this very sender. + val fromContact = { lookup == ContactLookup.FOUND } + + scoped.firstOrNull { + it.kind == ListKind.BLOCK && matches(it, message, numbers) && !(skipsContacts(it) && fromContact()) + }?.let { return FilterDecision.Block(DecisionReason.BLOCK_RULE, it.id) } - if (matchesLegacy(message)) return FilterDecision.Block(DecisionReason.BLOCK_RULE) + if (matchesLegacy(message, fromContact)) return FilterDecision.Block(DecisionReason.BLOCK_RULE) - val isPhoneNumber = !normalizer.isSenderId(message.address) - val lookup = if (isPhoneNumber) contactLookup(message.address) else ContactLookup.NOT_FOUND if (lookup == ContactLookup.FOUND) return FilterDecision.Allow(DecisionReason.CONTACT) // Q2: the foreign-number hold belongs to Smart and Strict only; with the filter Off nothing is held. val mode = effectiveMode() @@ -134,13 +142,22 @@ class DefaultSpamFilter( * The old Fossify keyword and number lists. A failure in either (a provider error, a malformed entry) skips only * that list: the rest of the filter still runs, so one bad entry cannot switch filtering off for every message. */ - private fun matchesLegacy(message: IncomingMessage): Boolean { + private fun matchesLegacy(message: IncomingMessage, fromContact: () -> Boolean): Boolean { val keywords = runCatching { legacy.blockedKeywords() }.getOrDefault(emptyList()) - // Older installs could store whitespace-only keywords; one of those would match every message. - if (keywords.any { it.isNotBlank() && TextNormalizer.containsObfuscated(message.body, it) }) return true + // Older installs could store whitespace-only keywords; one of those would match every message. A legacy + // keyword is a keyword rule: it does not hold a contact either. + if (keywords.any { it.isNotBlank() && TextNormalizer.containsObfuscated(message.body, it) } && !fromContact()) { + return true + } return message.address.isNotBlank() && runCatching { legacy.isNumberBlocked(message.address) }.getOrDefault(false) } + /** Block rules that read the text or a part of the sender, not the exact sender: a contact is not held by them. */ + private fun skipsContacts(rule: SpamRule): Boolean = when (rule.type) { + RuleType.KEYWORD, RuleType.REGEX, RuleType.PREFIX, RuleType.DOMAIN -> true + RuleType.NUMBER, RuleType.SENDER_ID -> false + } + private fun matches(rule: SpamRule, message: IncomingMessage, numbers: List): Boolean = matcher.matches(rule, message, numbers) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/DomainMatch.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/DomainMatch.kt new file mode 100644 index 00000000..f1d4b5e7 --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/DomainMatch.kt @@ -0,0 +1,54 @@ +package com.glooboo.umessage.spam.engine + +import com.glooboo.umessage.spam.TextNormalizer + +/** + * The DOMAIN rule type: whether a message body links to a domain. A link's host matches a rule domain when it is that + * domain or one of its subdomains ("www.example.com" and "a.b.example.com" match "example.com"; "notexample.com" and + * "example.com.evil.net" do not). + */ +object DomainMatch { + + /** A dot, also written to dodge link detection: "[.]", "(.)", "{.}", "[dot]", "(dot)". Every bracket is escaped. */ + private const val DISGUISED_DOT = "(?:\\.|\\[\\.\\]|\\(\\.\\)|\\{\\.\\}|\\[dot\\]|\\(dot\\))" + private const val LABEL = "[a-z0-9](?:[a-z0-9\\-]*[a-z0-9])?" + + private fun hostRegex(dot: String) = Regex( + "(? { + val text = TextNormalizer.fold(body) + val regex = if (disguised) anyHost else plainHost + return regex.findAll(text).map { it.value.lowercase().replace(disguisedDot, ".") }.toList() + } + + /** Whether [body] links to [pattern] or a subdomain of it. A rule domain without a dot never matches. */ + fun matches(body: String, pattern: String, disguised: Boolean = true): Boolean { + val domain = clean(pattern) + if (!domain.contains('.')) return false + return hosts(body, disguised).any { it == domain || it.endsWith(".$domain") } + } + + /** + * A rule's domain as stored: lower case, without scheme, "www." is kept (it is a subdomain like any other), path, + * port, a leading "*." or ".", or a trailing dot. "https://Example.com/a?b" becomes "example.com". + */ + fun clean(pattern: String): String { + var text = TextNormalizer.fold(pattern).trim().lowercase() + text = text.replace(disguisedDot, ".") + text = text.substringAfter("://") + text = text.substringBefore('/').substringBefore('?').substringBefore('#') + text = text.substringAfterLast('@').substringBefore(':') + return text.trimStart('*', '.').trimEnd('.') + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/OtpDetector.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/OtpDetector.kt index 04acbd09..3c7a72a8 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/OtpDetector.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/OtpDetector.kt @@ -7,7 +7,8 @@ import com.glooboo.umessage.spam.TextNormalizer * Heuristic one-time-password detector for SMART mode. Pure JVM. * * A body looks like an OTP when a 4-8 digit code sits next to an OTP keyword: at most a few plain words - * between them, in either order ("Your OTP is 4821", "123456 is your login code", "رمز پویا: ۱۲۳۴۵"). + * between them, in either order ("Your OTP is 4821", "123456 is your login code", "رمز پویا: ۱۲۳۴۵"). A letters-and-digits + * code ("Your code is ab12cd") counts too, but only next to a keyword in its own sentence ([alphanumericCodes]). * The text is read through [TextNormalizer.fold] first, so Persian and Arabic digits, Arabic letter forms (ي, ك), * kashida and zero-width characters do not hide a code. Word edges are explicit lookarounds over letters and * digits of any script, because `\b` behaves differently in the JVM and Android (ICU) regex engines. @@ -100,6 +101,26 @@ object OtpDetector { RegexOption.IGNORE_CASE, ) + /** + * A letters-and-digits code that no digit rule sees ("ab12cd", "x7kq2m", "12ab34"): 4-8 letters and digits in one + * run, at least two of each, letters and digits alternating at least twice. Deliberately narrow, as it only counts + * next to a keyword in the same sentence ([alphanumericCodes]): a promo code ("SAVE20": letters, then digits), + * a time or unit ("10am", "500mb"), an ordinal ("3rd"), a word with one digit ("mp3s") and a run holding four + * digits in a row (the digit rule's business: "G-482915" is copied as 482915) are no match. Not glued to a + * letter, a digit or the characters of an address, a path or a price. + */ + private val alphanumericCode = Regex( + "(?= 0) after = after.substring(0, end) + } if (strongBefore.containsMatchIn(before) || strongAfter.containsMatchIn(after)) return true if (cjkBefore.containsMatchIn(before) || cjkAfter.containsMatchIn(after)) return true if (marketingSoft.containsMatchIn(text)) return false @@ -184,20 +210,36 @@ object OtpDetector { return !year && (weakBefore.containsMatchIn(before) || weakAfter.containsMatchIn(after)) } + /** + * The letters-and-digits codes of [text] (already folded) with a keyword in the same sentence, a few plain words + * before or after them: position and value, as written ("Your code is ab12cd" gives ab12cd). Never bare: a token + * of this shape without a keyword, in an advertisement, or next to the generic word in a text of offers is no code. + */ + internal fun alphanumericCodes(text: String): List> { + if (marketingHard.containsMatchIn(text)) return emptyList() + return alphanumericCode.findAll(text) + .filter { keywordNextTo(text, it.range, sameSentence = true) } + .map { it.range.first to it.value } + .toList() + } + /** Whether [text] is an advertisement ("promo", "discount", "50%"): such a text is never a code. */ internal fun isMarketing(text: String): Boolean = marketingHard.containsMatchIn(TextNormalizer.fold(text)) /** - * The keyword rule behind [looksLikeOtp]: a 4-8 digit code next to an OTP keyword (a few plain words apart, either - * order), in a text that is not an advertisement. Labelled values are [OtpCodes]' business. + * The keyword rule behind [looksLikeOtp]: a 4-8 digit code, or a letters-and-digits one ([alphanumericCodes]), next + * to an OTP keyword (a few plain words apart, either order), in a text that is not an advertisement. Labelled values are [OtpCodes]' business. */ internal fun nearKeyword(body: String): Boolean { val text = TextNormalizer.fold(body) - if (marketingHard.containsMatchIn(text)) return false - if (strongOtp.containsMatchIn(text) || cjkOtp.containsMatchIn(text)) return true - if (marketingSoft.containsMatchIn(text)) return false - // Only the generic word "code": a year-like number is no code when the text speaks of a year or a date. - return (if (yearContext.containsMatchIn(text)) weakOtp else weakOtpAnyNumber).containsMatchIn(text) + return when { + marketingHard.containsMatchIn(text) -> false + strongOtp.containsMatchIn(text) || cjkOtp.containsMatchIn(text) -> true + alphanumericCodes(text).isNotEmpty() -> true + marketingSoft.containsMatchIn(text) -> false + // Only the generic word "code": a year-like number is no code when the text speaks of a year or a date. + else -> (if (yearContext.containsMatchIn(text)) weakOtp else weakOtpAnyNumber).containsMatchIn(text) + } } /** diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/RuleMatcher.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/RuleMatcher.kt index 19534533..1cfc60ed 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/RuleMatcher.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/RuleMatcher.kt @@ -54,6 +54,10 @@ class RuleMatcher( // A keyword in double quotes only matches as a whole word ([KeywordMatch]). RuleType.KEYWORD -> KeywordMatch.matches(message.body, pattern, obfuscated = rule.kind == ListKind.BLOCK) + // A link host in the body equals the domain or is a subdomain of it. An ALLOW rule ignores disguised dots + // ("example[.]com"), so a spammer cannot dress a link up as an allowed domain. + RuleType.DOMAIN -> DomainMatch.matches(message.body, pattern, disguised = rule.kind == ListKind.BLOCK) + RuleType.REGEX -> regex(pattern)?.let { matchesRegex(pattern, it, TextNormalizer.fold(message.body)) } == true } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/components/Dialogs.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/components/Dialogs.kt index f5000ed6..eca450ee 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/components/Dialogs.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/components/Dialogs.kt @@ -117,6 +117,8 @@ fun InfoDialog( modifier: Modifier = Modifier, title: String? = null, confirmLabel: String = stringResource(R.string.screens_ok), + /** An extra button beside OK, or null for none. */ + dismissButton: (@Composable () -> Unit)? = null, content: @Composable () -> Unit, ) { AlertDialog( @@ -125,6 +127,7 @@ fun InfoDialog( title = title?.let { { Text(it) } }, text = { Column(Modifier.verticalScroll(rememberScrollState())) { content() } }, confirmButton = { TextButton(onClick = onDismiss) { Text(confirmLabel) } }, + dismissButton = dismissButton, ) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsModels.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsModels.kt index f2438335..fe93e7cf 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsModels.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsModels.kt @@ -86,6 +86,9 @@ data class ConversationsUiState( sealed interface ConversationsEvent { data class Deleted(val token: Long, val count: Int) : ConversationsEvent data class Archived(val token: Long, val count: Int) : ConversationsEvent + + /** "Mark all read" read [count] chats; Undo makes exactly those chats unread again ([token]). */ + data class MarkedAllRead(val token: Long, val count: Int) : ConversationsEvent /** Block rules were added for [count] conversations' senders. Offers Undo ([token] as for [ReportedSpam]). */ data class Blocked(val token: Long, val count: Int) : ConversationsEvent @@ -110,6 +113,9 @@ class ConversationsCallbacks( val onSelectAll: () -> Unit = {}, val onPin: (Boolean) -> Unit = {}, val onMarkRead: (Boolean) -> Unit = {}, + /** The inbox menu's "Mark all read" (main-21), and the snackbar's Undo for it. */ + val onMarkAllRead: () -> Unit = {}, + val onUndoMarkAllRead: (Long) -> Unit = {}, val onArchiveSelected: () -> Unit = {}, val onDeleteSelected: () -> Unit = {}, val onConfirmDelete: () -> Unit = {}, diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsScreen.kt index 4a92fc9a..4d3ce1b4 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsScreen.kt @@ -178,6 +178,14 @@ private suspend fun showEvent( ) if (result == SnackbarResult.ActionPerformed) callbacks.onUndoArchive(event.token) } + is ConversationsEvent.MarkedAllRead -> { + val result = snackbar.showSnackbar( + message = resources.getQuantityString(R.plurals.decm_marked_all_read, event.count, event.count), + actionLabel = undoLabel, + duration = SnackbarDuration.Long, + ) + if (result == SnackbarResult.ActionPerformed) callbacks.onUndoMarkAllRead(event.token) + } is ConversationsEvent.Blocked -> { val result = snackbar.showSnackbar( message = resources.getQuantityString(R.plurals.convlist_blocked_done, event.count, event.count), diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModel.kt index f496812b..de921032 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModel.kt @@ -322,6 +322,48 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic } } + /** main-21: the threads each "Mark all read" changed, by token, so Undo restores exactly those. */ + private val markedAllRead = HashMap>() + + /** + * Marks every unread chat in the list read (chats concealed behind the app lock and chats pending delete or + * archive are not in the list, so they are left alone). Offers Undo, which makes only these chats unread again. + */ + fun markAllRead() { + val concealed = HiddenChats.get(app).hiddenIds() + val targets = unreadThreadsToMarkRead(source, hidden + concealed) + if (targets.isEmpty()) return + val ids = targets.toHashSet() + val token = nextToken++ + markedAllRead[token] = targets + source = source.map { c -> if (c.threadId in ids) c.copy(read = true, unreadCount = 0) else c } + requestRebuild() + viewModelScope.launch(Dispatchers.IO) { + val failed = runCatching { targets.forEach { app.markThreadMessagesRead(it) } }.isFailure + withContext(Dispatchers.Main) { + if (failed) { + markedAllRead.remove(token) + _events.trySend(ConversationsEvent.Failed) + } else { + _events.trySend(ConversationsEvent.MarkedAllRead(token, targets.size)) + } + } + refreshConversations() + } + } + + /** Undo of [markAllRead]: only the chats it changed become unread again. */ + fun undoMarkAllRead(token: Long) { + val ids = markedAllRead.remove(token) ?: return + val set = ids.toHashSet() + source = source.map { c -> if (c.threadId in set) c.copy(read = false) else c } + requestRebuild() + viewModelScope.launch(Dispatchers.IO) { + ids.forEach { runCatching { app.markThreadMessagesUnread(it) } } + refreshConversations() + } + } + fun archiveSelected() = archive(selected.toList()) fun archiveOne(threadId: Long) = archive(listOf(threadId)) @@ -803,6 +845,10 @@ internal fun conversationPreview(snippet: String?, draft: String?, noTextLabel: } /** CL-32: of the threads being archived, the ones that are unread now and get marked read by the archive. */ +/** main-21: the unread chats "Mark all read" changes: every unread one except those in [excluded]. */ +internal fun unreadThreadsToMarkRead(conversations: List, excluded: Set): List = + conversations.filter { !it.read && it.threadId !in excluded }.map { it.threadId } + internal fun threadsToMarkRead(conversations: List, archiving: List): List { val ids = archiving.toHashSet() return conversations.filter { it.threadId in ids && !it.read }.map { it.threadId } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/BlockedHit.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/BlockedHit.kt new file mode 100644 index 00000000..83cf3371 --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/BlockedHit.kt @@ -0,0 +1,147 @@ +package com.glooboo.umessage.ui.main + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.glooboo.umessage.R +import com.glooboo.umessage.spam.BlockedMessage +import com.glooboo.umessage.ui.components.rememberCodeHidden +import com.glooboo.umessage.ui.icons.Symbols +import com.glooboo.umessage.ui.spam.BlockedFilters +import com.glooboo.umessage.ui.theme.contentDirection + +/** main-22: a sender of blocked (spam) messages with at least one message that holds the typed text. */ +internal data class BlockedHit( + /** The sender as the newest matching message wrote it; opens that sender's blocked thread. */ + val address: String, + /** The sender as shown (a number in the phone's grouping). */ + val title: String, + /** The newest matching message, cut around the match. */ + val snippet: String, + val date: String, + /** How many of the sender's blocked messages match. */ + val count: Int, +) + +/** + * One hit per sender from the held [messages] that answer [query] (text or sender), newest first. Messages of a sender + * whose key is in [hiddenSenderKeys] are left out: a sender who has a chat hidden behind the app lock is not revealed + * through the spam section either. [keyOf] says which addresses are one sender (see SenderKeys). + */ +internal fun buildBlockedHits( + messages: List, + query: String, + keyOf: (String) -> String, + hiddenSenderKeys: Set, + title: (String) -> String, + formatDate: (Long) -> String, +): List = messages + .filter { BlockedFilters.matchesQuery(it, query) } + .groupBy { keyOf(it.address) } + .filterKeys { it !in hiddenSenderKeys } + .values + .map { list -> list.sortedByDescending { it.receivedAt } } + .sortedByDescending { it.first().receivedAt } + .map { list -> + val newest = list.first() + BlockedHit( + address = newest.address, + title = title(newest.address), + snippet = if (newest.hasText) searchExcerpt(newest.body, query) else "", + date = formatDate(newest.receivedAt), + count = list.size, + ) + } + +/** The blocked hits the page lists: only while text is typed and no tile filter is on, like the notes. */ +internal fun MainSearchState.shownBlockedHits(typed: Boolean): List = + if (typed && filter == InboxFilter.All) blockedHits else emptyList() + +/** The "Blocked messages" section: heading, then one card with a row per sender. */ +internal fun LazyListScope.blockedSection( + page: ResultPage, + query: String, + onSeeAll: () -> Unit, + onOpen: (String) -> Unit, + heading: String, +) { + if (page.items.isEmpty()) return + item(key = "h-blocked") { SectionHeading(heading, page.hidden > 0, onSeeAll) } + items(page.items.size, key = { "b-" + page.items[it].address }) { index -> + BlockedResultRow(page.items[index], query, onOpen, Modifier.sectionCardRow(index, page.items.size)) + } +} + +/** A blocked sender: a shield, the sender with the match marked, the date, the matching text and how many matched. */ +@Composable +internal fun BlockedResultRow( + hit: BlockedHit, + query: String, + onOpen: (String) -> Unit, + modifier: Modifier = Modifier, +) { + val colors = MaterialTheme.colorScheme + val highlight = SpanStyle(color = colors.primary, fontWeight = FontWeight.Bold) + Row( + modifier = modifier + .fillMaxWidth() + .clickable { onOpen(hit.address) } + .heightIn(min = 72.dp) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(16.dp), + ) { + Icon(Symbols.Warning, contentDescription = null, tint = colors.error, modifier = Modifier.size(24.dp)) + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + highlightedText(hit.title, query, highlight), + style = MaterialTheme.typography.titleMedium, + color = colors.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + Text( + hit.date, + style = MaterialTheme.typography.labelMedium, + color = colors.onSurfaceVariant, + maxLines = 1, + ) + } + if (hit.snippet.isNotEmpty()) { + Text( + highlightedText(rememberCodeHidden(hit.snippet), query, highlight), + style = MaterialTheme.typography.bodyMedium.contentDirection(), + color = colors.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + if (hit.count > 1) { + Text( + pluralStringResource(R.plurals.w2b1_search_matches, hit.count, hit.count), + style = MaterialTheme.typography.labelMedium, + color = colors.primary, + ) + } + } + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/InboxMenu.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/InboxMenu.kt index 890caec1..bb5bc668 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/InboxMenu.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/InboxMenu.kt @@ -56,6 +56,7 @@ internal fun InboxOverflowMenu( } private fun menuIcon(item: InboxMenuItem): ImageVector = when (item) { + InboxMenuItem.MarkAllRead -> Symbols.DoneAll InboxMenuItem.Archived -> Symbols.Archive InboxMenuItem.RecycleBin -> Symbols.RestoreFromTrash InboxMenuItem.Scheduled -> Symbols.ScheduleSend @@ -64,6 +65,7 @@ private fun menuIcon(item: InboxMenuItem): ImageVector = when (item) { } private fun menuLabel(item: InboxMenuItem): Int = when (item) { + InboxMenuItem.MarkAllRead -> R.string.nav_folder_mark_all_read InboxMenuItem.Archived -> R.string.main_tab_archived InboxMenuItem.RecycleBin -> R.string.ux8a_menu_recycle_bin InboxMenuItem.Scheduled -> R.string.scheduled_list_title diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/InboxMenuPolicy.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/InboxMenuPolicy.kt index d2d0bcaf..f7e1ba5c 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/InboxMenuPolicy.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/InboxMenuPolicy.kt @@ -1,7 +1,7 @@ package com.glooboo.umessage.ui.main /** The entries of the inbox's overflow menu, in the order shown; Settings is always last. */ -internal enum class InboxMenuItem { RecycleBin, Archived, Scheduled, Starred, Settings } +internal enum class InboxMenuItem { MarkAllRead, RecycleBin, Archived, Scheduled, Starred, Settings } /** What the menu needs to know to decide which entries have something behind them. */ internal data class InboxMenuInputs( @@ -11,6 +11,8 @@ internal data class InboxMenuInputs( val scheduledCount: Int, /** The Archived tab is in the bottom bar, so the menu must not list it a second time. */ val archivedTabShown: Boolean = false, + /** Unread chats in the list; "Mark all read" is offered only while there are some. */ + val unreadCount: Int = 0, ) /** @@ -23,6 +25,8 @@ internal data class InboxMenuInputs( internal object InboxMenuPolicy { fun entries(inputs: InboxMenuInputs): List = buildList { + // Mark all read is first: it acts on the list the user is looking at. + if (inputs.unreadCount > 0) add(InboxMenuItem.MarkAllRead) // The bin comes first so it is easy to find; it is listed whenever it is switched on, empty or not. if (inputs.recycleBinOn) add(InboxMenuItem.RecycleBin) if (!inputs.archivedTabShown && inputs.archiveAvailable) { diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainScreen.kt index 773c3a41..3fb1e924 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainScreen.kt @@ -250,8 +250,10 @@ private fun openInboxMenuItem( item: InboxMenuItem, navigation: MainNavigation, onOpenArchivedTab: () -> Unit, + onMarkAllRead: () -> Unit = {}, ) { when (item) { + InboxMenuItem.MarkAllRead -> onMarkAllRead() InboxMenuItem.Archived -> onOpenArchivedTab() InboxMenuItem.RecycleBin -> navigation.onRecycleBin() InboxMenuItem.Scheduled -> navigation.onScheduled() @@ -346,9 +348,11 @@ private fun MessagesTab( } else { MainTopBar( onSearch = { search.active = true }, - menu = InboxMenuPolicy.entries(menuInputs), + menu = InboxMenuPolicy.entries(menuInputs.copy(unreadCount = state.rows.count { it.unread })), recycleBinCount = rememberRecycleBinCount(menuInputs.recycleBinOn, state.rows.size), - onMenu = { item -> openInboxMenuItem(item, navigation, onOpenArchivedTab) }, + onMenu = { item -> + openInboxMenuItem(item, navigation, onOpenArchivedTab, callbacks.onMarkAllRead) + }, ) // A warning to act on stays in view. NotificationsOffBanner() diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearch.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearch.kt index 2f8b4640..f46b8d7a 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearch.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearch.kt @@ -229,6 +229,9 @@ class MainSearchState { /** The private notes that hold [query]; the page lists them under "Notes". */ internal var noteHits by mutableStateOf>(emptyList()) + /** main-22: the senders of blocked (spam) messages that hold [query]; the page lists them under "Blocked". */ + internal var blockedHits by mutableStateOf>(emptyList()) + /** N11: the filter picked with a tile. It outlives the search: the inbox keeps showing it. */ var filter by mutableStateOf(InboxFilter.All) @@ -243,5 +246,6 @@ class MainSearchState { query = "" results = emptyList() noteHits = emptyList() + blockedHits = emptyList() } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchPage.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchPage.kt index 75680698..76562171 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchPage.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchPage.kt @@ -41,6 +41,7 @@ import com.glooboo.umessage.models.SearchResult import com.glooboo.umessage.ui.conversations.ConversationRow import com.glooboo.umessage.ui.icons.Symbols import com.glooboo.umessage.ui.labels.activeLabelName +import com.glooboo.umessage.ui.spam.BlockedThreadActivity /** The most the filter chip in the field may take, so a long label name leaves room for the typed text. */ private val FieldChipMaxWidth = 168.dp @@ -152,6 +153,11 @@ internal fun MainSearchPage( saveRecent(search.query) onOpenResult(result) }, + onOpenBlocked = { address -> + saveRecent(search.query) + // The thread asks for the app lock itself when it covers the Blocked screens. + context.startActivity(BlockedThreadActivity.intent(context, address)) + }, ) SearchResultsPanel(search, rows, shortcut, resultsListState, recent, simTiles, actions) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchPanel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchPanel.kt index e1780321..ed503335 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchPanel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchPanel.kt @@ -122,6 +122,8 @@ private fun SearchPanelBody( val contacts = rememberContactHits(query, filter, typed) // Notes are searched in all messages, so a tile that narrows the list leaves them out, like the contacts. val notes = search.shownNoteHits(typed) + // main-22: blocked messages are searched in all messages too; they are left out under a tile, like the notes. + val blocked = search.shownBlockedHits(typed) Column(Modifier.fillMaxSize()) { when { filter == InboxFilter.All && !typed -> SearchTilesPage(search, simTiles, recent, bottomPadding, actions) @@ -132,17 +134,19 @@ private fun SearchPanelBody( listed.isEmpty() && tileOnly -> if (filter != InboxFilter.Sim || shortcut.loaded) { SearchFilterEmpty(filter) } - noHits(listed, contacts, notes) -> SearchHint(stringResource(R.string.main_search_no_results)) + noHits(listed, contacts, notes, blocked) -> SearchHint(stringResource(R.string.main_search_no_results)) else -> ConversationResults( all = listed, contacts = contacts, notes = notes, + blocked = blocked, query = query, labels = labels, listState = listState, bottomPadding = bottomPadding, resetKey = listOf(filter, search.labelId, search.simId, query), onOpen = actions.onOpen, + onOpenBlockedHit = actions.onOpenBlocked, ) } } @@ -197,19 +201,23 @@ private fun ConversationResults( all: List, contacts: List, notes: List, + blocked: List, query: String, labels: Map>, listState: LazyListState, bottomPadding: PaddingValues, resetKey: Any, onOpen: (SearchResult) -> Unit, + onOpenBlockedHit: (String) -> Unit, ) { var conversationsShown by remember(resetKey) { mutableIntStateOf(SECTION_PREVIEW) } var contactsShown by remember(resetKey) { mutableIntStateOf(SECTION_PREVIEW) } var notesShown by remember(resetKey) { mutableIntStateOf(SECTION_PREVIEW) } + var blockedShown by remember(resetKey) { mutableIntStateOf(SECTION_PREVIEW) } val conversationPage = remember(all, conversationsShown) { resultPage(all, conversationsShown) } val contactPage = remember(contacts, contactsShown) { resultPage(contacts, contactsShown) } val notePage = remember(notes, notesShown) { resultPage(notes, notesShown) } + val blockedPage = remember(blocked, blockedShown) { resultPage(blocked, blockedShown) } val context = LocalContext.current val scope = rememberCoroutineScope() val openContact = { hit: ContactHit -> @@ -233,12 +241,14 @@ private fun ConversationResults( val conversationsTitle = stringResource(R.string.search_section_conversations) val contactsTitle = stringResource(R.string.search_section_contacts) val notesTitle = stringResource(R.string.notes_section) + val blockedTitle = stringResource(R.string.decm_search_section_blocked) LazyColumn(state = listState, modifier = Modifier.fillMaxSize(), contentPadding = bottomPadding) { conversationSection( conversationPage, query, labels, { conversationsShown = Int.MAX_VALUE }, onOpen, conversationsTitle, ) contactSection(contactPage, query, { contactsShown = Int.MAX_VALUE }, openContact, contactsTitle) noteSection(notePage, query, { notesShown = Int.MAX_VALUE }, onOpen, notesTitle) + blockedSection(blockedPage, query, { blockedShown = Int.MAX_VALUE }, onOpenBlockedHit, blockedTitle) } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchViewModel.kt index 32662d82..accd3217 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchViewModel.kt @@ -11,7 +11,15 @@ import com.glooboo.umessage.extensions.messagesDB import com.glooboo.umessage.helpers.HiddenChats import com.glooboo.umessage.helpers.messageNotes import com.glooboo.umessage.models.SearchResult +import com.glooboo.umessage.ui.components.displayNumber import com.glooboo.umessage.ui.components.displayTitle +import com.glooboo.umessage.ui.lock.LockScope +import com.glooboo.umessage.ui.spam.BlockedFilters +import com.glooboo.umessage.ui.spam.SenderKeys +import com.glooboo.umessage.ui.spam.SpamRepositoryProvider +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.first +import org.fossify.commons.extensions.appLockManager import com.glooboo.umessage.ui.components.formatListTimeStyled import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -35,6 +43,9 @@ class MainSearchViewModel(application: Application, handle: SavedStateHandle) : /** Finds the private notes that hold the text, off the main thread. Tests replace it. */ internal var runNoteSearch: suspend (String) -> List = ::searchNotes + /** Finds the blocked (spam) messages that hold the text, off the main thread. Tests replace it. */ + internal var runBlockedSearch: suspend (String) -> List = ::searchBlocked + private var searchJob: Job? = null init { @@ -61,12 +72,14 @@ class MainSearchViewModel(application: Application, handle: SavedStateHandle) : if (!isSearchable(text)) { state.results = emptyList() state.noteHits = emptyList() + state.blockedHits = emptyList() return } searchJob = viewModelScope.launch { delay(SEARCH_DEBOUNCE_MS) // cancelled by the next key press (MC-17) state.results = runSearch(text.trim()) state.noteHits = runNoteSearch(text.trim()) + state.blockedHits = runBlockedSearch(text.trim()) } } @@ -141,6 +154,39 @@ class MainSearchViewModel(application: Application, handle: SavedStateHandle) : } } + /** + * The blocked messages that hold [text], one hit per sender (main-22). Nothing is found while the app lock covers + * only chosen parts and is locked (the Blocked tab is behind it), and a sender who has a chat hidden behind the + * lock (B06) is not found until it is unlocked. A failing spam store gives no hits, never an error on the page. + */ + internal suspend fun searchBlocked(text: String): List = withContext(Dispatchers.IO) { + val app = getApplication() + try { + if (LockScope.blockedLocked(app) && app.appLockManager.isLocked()) return@withContext emptyList() + val matching = SpamRepositoryProvider.get(app).blocked.first() + .filter { BlockedFilters.matchesQuery(it, text) } + if (matching.isEmpty()) return@withContext emptyList() + val keys = SenderKeys.forDevice(app) + val hiddenKeys = HiddenChats.get(app).hiddenIds() + .mapNotNull { app.conversationsDB.getConversationWithThreadId(it) } + .flatMap { it.phoneNumber.split(',') } + .map { it.trim() }.filter { it.isNotEmpty() } + .mapTo(HashSet()) { keys.keyOf(it) } + buildBlockedHits( + messages = matching, + query = text, + keyOf = keys::keyOf, + hiddenSenderKeys = hiddenKeys, + title = { displayNumber(app, it) }, + formatDate = { millis -> formatListTimeStyled(app, millis) }, + ) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + emptyList() + } + } + internal companion object { const val KEY_SAVED = "main_search" const val KEY_ACTIVE = "active" diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/NoteHit.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/NoteHit.kt index 2f96801a..2d47f4e4 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/NoteHit.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/NoteHit.kt @@ -74,8 +74,12 @@ internal fun MainSearchState.shownNoteHits(typed: Boolean): List = if (typed && filter == InboxFilter.All) noteHits else emptyList() /** True when no conversation, contact or note matched. */ -internal fun noHits(listed: List, contacts: List, notes: List) = - listed.isEmpty() && contacts.isEmpty() && notes.isEmpty() +internal fun noHits( + listed: List, + contacts: List, + notes: List, + blocked: List = emptyList(), +) = listed.isEmpty() && contacts.isEmpty() && notes.isEmpty() && blocked.isEmpty() /** The "Notes" section: heading, then one card with a row per matching note. */ internal fun LazyListScope.noteSection( diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/SearchPanelActions.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/SearchPanelActions.kt index 9ba03258..9143f500 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/SearchPanelActions.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/SearchPanelActions.kt @@ -9,4 +9,6 @@ internal class SearchPanelActions( val onFilter: (InboxFilter) -> Unit, val onSim: (Int) -> Unit, val onOpen: (SearchResult) -> Unit, + /** Opens the blocked thread of a sender found in the spam section (main-22). */ + val onOpenBlocked: (String) -> Unit = {}, ) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/settings/RestoreSummary.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/settings/RestoreSummary.kt index d42a9b48..281b8844 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/settings/RestoreSummary.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/settings/RestoreSummary.kt @@ -70,6 +70,9 @@ object RestoreSummary { if (preview.rulesPresent > 0) { parts += context.getString(R.string.settings_f_restore_rules_present, preview.rulesPresent) } + if (preview.newKeywords.isNotEmpty()) { + parts += context.getString(R.string.decisions_backup_keywords, preview.newKeywords.size) + } val tooMany = preview.content.droppedRules + preview.content.droppedForwardRules if (tooMany > 0) parts += context.getString(R.string.settings_f_restore_too_many, tooMany) val forwards = preview.forwards diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/AlwaysAllowPolicy.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/AlwaysAllowPolicy.kt new file mode 100644 index 00000000..290ca5d1 --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/AlwaysAllowPolicy.kt @@ -0,0 +1,21 @@ +package com.glooboo.umessage.ui.spam + +import com.glooboo.umessage.spam.ListKind +import com.glooboo.umessage.spam.SpamRule +import com.glooboo.umessage.ui.thread.isSameSender +import com.glooboo.umessage.ui.thread.planSpamReport + +/** spamui-21: when the "Always allow" button of the Why-blocked dialog is offered for a sender. */ +internal object AlwaysAllowPolicy { + + /** + * True when no allow rule names [address] yet and the sender is not a name anyone can fake (see + * [SenderBlocking.isSpoofable]; "Not spam" adds no rule for those either). Uses phone-number matching, so call it + * off the main thread. + */ + fun canOffer(rules: Collection, address: String): Boolean { + if (address.isBlank() || SenderBlocking.isSpoofable(address)) return false + val type = planSpamReport(emptyList(), address).type + return rules.none { it.kind == ListKind.ALLOW && it.type == type && isSameSender(it.pattern, address, type) } + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedActions.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedActions.kt index f51dd954..a2841b3f 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedActions.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedActions.kt @@ -19,6 +19,8 @@ class BlockedActions( val onDeleteAll: () -> Unit = {}, /** A chip under the banner (ID-14). */ val onSetFilter: (BlockedFilter) -> Unit = {}, + /** The search box of the tab (spamui-20). */ + val onSetQuery: (String) -> Unit = {}, /** I32: sends the one selected sender's newest message to the carrier; asked and confirmed by the screen first. */ val onReportSpam: (Set) -> Unit = {}, ) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedDetails.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedDetails.kt index ab001800..0ace2a31 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedDetails.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedDetails.kt @@ -29,6 +29,7 @@ fun ruleReasonText(resources: Resources, message: BlockedMessage, rules: Map R.string.spam_reason_rule_number RuleType.PREFIX -> R.string.spam_reason_rule_prefix RuleType.SENDER_ID -> R.string.spam_reason_rule_sender + RuleType.DOMAIN -> R.string.spam_reason_rule_domain } return resources.getString(res, text) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedFilter.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedFilter.kt index f306a1c0..be1dfc80 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedFilter.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedFilter.kt @@ -2,6 +2,8 @@ package com.glooboo.umessage.ui.spam import com.glooboo.umessage.spam.BlockedMessage import com.glooboo.umessage.spam.DecisionReason +import com.glooboo.umessage.spam.TextNormalizer +import com.glooboo.umessage.ui.components.asciiDigits /** * The chip row under the Blocked banner (ID-14): narrows the held messages by why or where they were held. Uses only @@ -36,6 +38,33 @@ object BlockedFilters { fun apply(filter: BlockedFilter, messages: List): List = if (filter == BlockedFilter.All) messages else messages.filter { matches(filter, it) } + /** The digits a number query needs before it is compared with sender numbers. */ + private const val MIN_NUMBER_DIGITS = 2 + + /** + * Whether [message] answers the search [query] (spamui-20): its text or its sender holds the typed words. Letter + * forms, digits and zero-width marks are folded on both sides like the main search ([TextNormalizer.fold]); a query + * of digits and number marks also finds the sender in any written form ("0555 345" finds "+90555345..."). A blank + * query matches everything. + */ + fun matchesQuery(message: BlockedMessage, query: String): Boolean { + val typed = query.trim() + if (typed.isEmpty()) return true + val wanted = TextNormalizer.fold(typed) + if (TextNormalizer.fold(message.body).contains(wanted, ignoreCase = true)) return true + if (TextNormalizer.fold(message.address).contains(wanted, ignoreCase = true)) return true + val numberQuery = typed.all { it.isDigit() || it in " +-()" } + val digits = asciiDigits(typed) + return numberQuery && digits.length >= MIN_NUMBER_DIGITS && asciiDigits(message.address).contains(digits) + } + + /** + * The sender rows of [groups] that answer [query]: a sender stays when any of its messages does, and keeps all of + * its messages, so an action on the row (Not spam, Delete) still acts on the whole sender. + */ + fun searchGroups(groups: List, query: String): List = + if (query.isBlank()) groups else groups.filter { g -> g.messages.any { matchesQuery(it, query) } } + /** * How many senders each chip would list, for the count badges. The list shows one row per sender, so counting * messages made "All 4" sit over 3 rows when one sender had two messages (emulator check, round 4). A sender diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedScreen.kt index 49a062cd..177c2c49 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedScreen.kt @@ -19,6 +19,7 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.relocation.BringIntoViewRequester import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.CircularProgressIndicator @@ -30,6 +31,7 @@ import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MenuDefaults import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.SnackbarDuration import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarResult @@ -47,6 +49,9 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.LocalResources @@ -106,6 +111,7 @@ fun BlockedRoute(onBack: (() -> Unit)?, onOpenRules: () -> Unit, onOpenSettings: onDelete = viewModel::delete, onDeleteAll = viewModel::deleteAll, onSetFilter = viewModel::setFilter, + onSetQuery = viewModel::setQuery, onReportSpam = { selected -> scope.launch { reportToCarrier(context, groups, selected, snackbar) } }, ) } @@ -243,11 +249,14 @@ fun BlockedScreen( var confirmDeleteAll by rememberSaveable { mutableStateOf(false) } var restoredOpen by rememberSaveable { mutableStateOf(false) } var confirmReport by rememberSaveable { mutableStateOf(false) } + // The search box is open while it holds text (it comes back after a rotation or a visit to a thread). + var searching by rememberSaveable { mutableStateOf(state.query.isNotEmpty()) } BackHandler(enabled = state.selecting, onBack = actions.onClearSelection) UMessageScaffold( topBar = { BlockedTopBar( state, actions, + onSearch = { searching = true }, onDeleteAll = { confirmDeleteAll = true }, onReport = { confirmReport = true }, onOpenRestoredLog = { restoredOpen = true }, @@ -267,6 +276,11 @@ fun BlockedScreen( BlockedList( state = state, actions = actions, + searching = searching, + onCloseSearch = { + searching = false + actions.onSetQuery("") + }, modifier = Modifier.padding(top = inner.calculateTopPadding()), bottomInset = inner.calculateBottomPadding(), ) @@ -309,6 +323,7 @@ private fun BlockedTopBar( state: BlockedUiState, actions: BlockedActions, onDeleteAll: () -> Unit, + onSearch: () -> Unit = {}, onReport: () -> Unit = {}, onOpenRestoredLog: () -> Unit = {}, ) { @@ -338,6 +353,11 @@ private fun BlockedTopBar( } else { var menuOpen by remember { mutableStateOf(false) } UMessageTopBar(title = stringResource(R.string.blocked_title), onBack = actions.onBack) { + if (state.heldCount > 0) { + IconButton(onClick = onSearch) { + Icon(Symbols.Search, contentDescription = stringResource(R.string.decm_blocked_search)) + } + } Box { IconButton(onClick = { menuOpen = true }) { Icon(Symbols.MoreVert, contentDescription = stringResource(R.string.spam_more_options)) @@ -381,6 +401,8 @@ private fun BlockedTopBar( private fun BlockedList( state: BlockedUiState, actions: BlockedActions, + searching: Boolean, + onCloseSearch: () -> Unit, modifier: Modifier = Modifier, bottomInset: Dp = 0.dp, ) { @@ -393,6 +415,9 @@ private fun BlockedList( item(key = "stats") { BlockedLine(state.stats, state.mode, onOpenSettings = actions.onOpenSettings) } + if (state.heldCount > 0 && searching) { + item(key = "search") { BlockedSearchField(state.query, actions.onSetQuery, onCloseSearch) } + } if (state.heldCount > 0) { item(key = "tip") { BlockedTip() } if (BlockedFilters.rowShown(state.filter, state.filterCounts)) { @@ -402,6 +427,13 @@ private fun BlockedList( when { // Nothing held: say what uMessage is doing, so a fresh install does not look switched off (ID-17). state.heldCount == 0 -> item(key = "empty") { BlockedEmpty(state.mode) } + state.groups.isEmpty() && state.query.isNotBlank() -> item(key = "search-empty") { + EmptyState( + iconRes = R.drawable.ic_spam_shield, + title = stringResource(R.string.decm_blocked_search_none_title), + body = stringResource(R.string.decm_blocked_search_none_body), + ) + } state.groups.isEmpty() -> item(key = "filter-empty") { FilterEmpty(actions) } else -> items(state.groups, key = { it.address }) { group -> BlockedSenderRow( @@ -423,6 +455,28 @@ private fun BlockedList( } } +/** spamui-20: the search box over the sender rows; the close button clears the text and hides the box. */ +@Composable +private fun BlockedSearchField(query: String, onQuery: (String) -> Unit, onClose: () -> Unit) { + val focus = remember { FocusRequester() } + LaunchedEffect(Unit) { runCatching { focus.requestFocus() } } + OutlinedTextField( + value = query, + onValueChange = onQuery, + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp).focusRequester(focus), + singleLine = true, + placeholder = { Text(stringResource(R.string.decm_blocked_search_hint)) }, + leadingIcon = { Icon(Symbols.Search, contentDescription = null) }, + trailingIcon = { + IconButton(onClick = onClose) { + Icon(Symbols.Close, contentDescription = stringResource(R.string.decm_blocked_search_close)) + } + }, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + shape = RoundedCornerShape(28.dp), + ) +} + /** Text only (U48): the line above has the mode, and it opens the settings. */ @Composable private fun BlockedEmpty(mode: UnknownSenderMode) { diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedThread.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedThread.kt index 1e236659..409a1f80 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedThread.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedThread.kt @@ -139,6 +139,8 @@ class BlockedThreadActions( /** Deletes the chosen messages, with Undo. */ val onDeleteMessages: (Set) -> Unit = {}, val onOpenRules: () -> Unit = {}, + /** "Always allow" of the Why-blocked dialog (spamui-21): an allow rule for the sender, with Undo. */ + val onAlwaysAllow: (String) -> Unit = {}, ) /** @@ -195,6 +197,7 @@ fun BlockedThreadRoute( onReleaseMessages = viewModel::releaseMessages, onDeleteMessages = viewModel::deleteMessages, onOpenRules = onOpenRules, + onAlwaysAllow = viewModel::alwaysAllow, ) } BlockedThreadScreen(address, state, snackbar, actions, moving = moving) @@ -299,7 +302,10 @@ fun BlockedThreadScreen( // The message left (released, deleted or purged) while its dialog was up. if (!state.loading) LaunchedEffect(id) { whyId = null } } else { - WhyBlockedDialog(message, state, actions.onOpenRules, onDismiss = { whyId = null }) + WhyBlockedDialog( + message, state, actions.onOpenRules, onDismiss = { whyId = null }, + onAlwaysAllow = actions.onAlwaysAllow, + ) } } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModel.kt index 033e4f37..0e441581 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModel.kt @@ -70,6 +70,8 @@ data class BlockedUiState( val purgeAfterDays: Int = 30, /** The chip chosen under the banner (ID-14); [groups] only holds what it lets through. */ val filter: BlockedFilter = BlockedFilter.All, + /** The text typed in the search box (spamui-20); [groups] only holds the senders that answer it. */ + val query: String = "", /** How many senders each chip would list, over all held messages (rows, not messages). */ val filterCounts: Map = emptyMap(), /** All held messages, whatever the filter: zero means the tab is truly empty. */ @@ -139,6 +141,9 @@ class BlockedViewModel( private val selected = MutableStateFlow>(emptySet()) private val sims = MutableStateFlow>(emptyList()) + /** The search box's text (spamui-20). Kept while the screen is alive, not stored; the thread ignores it. */ + private val query = MutableStateFlow("") + /** The chip selection survives leaving the screen; a failing preferences read just means "All". */ private val filter = MutableStateFlow( runCatching { @@ -247,8 +252,8 @@ class BlockedViewModel( any = deletes.isNotEmpty() || restores.isNotEmpty(), ) }, - combine(selected, sims) { s, i -> s to i }, - ) { blocked, stats, aux, pending, (sel, simList) -> + combine(selected, sims, query) { s, i, q -> Triple(s, i, q) }, + ) { blocked, stats, aux, pending, (sel, simList, typed) -> val hidden = pending.ids.toSet() val held = blocked.filter { it.id !in hidden } // A SIM chip is only offered with two SIMs; a stored SIM choice that is gone falls back to All. @@ -259,12 +264,14 @@ class BlockedViewModel( chosen is BlockedFilter.Sim && chosen.subscriptionId !in simIds -> BlockedFilter.All else -> chosen } - val groups = groupBySender(BlockedFilters.apply(active, held), senderKeys::keyOf) + val found = groupBySender(BlockedFilters.apply(active, held), senderKeys::keyOf) + val groups = if (ignoreFilter) found else BlockedFilters.searchGroups(found, typed) val keys = groups.map { it.address }.toSet() BlockedUiState( loading = false, groups = groups, filter = active, + query = if (ignoreFilter) "" else typed, filterCounts = BlockedFilters.counts(held, simIds, senderKeys::keyOf), heldCount = held.size, stats = stats, @@ -316,6 +323,12 @@ class BlockedViewModel( } } + /** The search box changed (spamui-20): the list keeps the senders whose messages or number hold [text]. */ + fun setQuery(text: String) { + if (ignoreFilter || query.value == text) return + query.value = text + } + /** Picks a chip under the banner (ID-14) and remembers it. */ fun setFilter(value: BlockedFilter) { if (ignoreFilter || filter.value == value) return @@ -417,6 +430,37 @@ class BlockedViewModel( } } + /** + * "Always allow" of the Why-blocked dialog (spamui-21): stores an allow rule for [address] through the same call + * "Not spam" uses (the sender's own block rules go, as they would be dead weight), without moving any message. + * The snackbar is the allow-only line of [BlockedEvent.Restored], and its Undo removes the rule again. + */ + fun alwaysAllow(address: String) { + if (SenderBlocking.isSpoofable(address)) return + val token = nextToken++ + viewModelScope.launch { + withContext(NonCancellable) { + restoreWork.withLock { + val change = runCatching { SenderBlocking.alwaysAllow(repository, listOf(address)) }.getOrNull() + if (change == null) { + events.trySend(BlockedEvent.Failed) + } else { + val pending = PendingRestore( + ids = emptyList(), addresses = listOf(address), allowAddresses = listOf(address), + receipts = emptyMap(), allowChange = change, announced = true, + ) + pendingRestores.update { it + (token to pending) } + events.trySend(pending.event(token)) + } + } + } + if (pendingRestores.value.containsKey(token)) { + delay(UNDO_WINDOW_MS) + commitRestore(token) + } + } + } + /** The restore and its allow rules as one piece of work; no rule is added when nothing reached the inbox. */ private suspend fun restoreAndAllow(messages: List, allow: List): RestoreWork { val (receipts, logged) = restore(messages) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedWhyDialog.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedWhyDialog.kt index 63a4667d..97b8207a 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedWhyDialog.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedWhyDialog.kt @@ -5,7 +5,10 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.produceState +import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalResources @@ -20,6 +23,8 @@ import com.glooboo.umessage.ui.components.InfoDialog import com.glooboo.umessage.ui.components.hideCodesSetting import com.glooboo.umessage.ui.components.uiLocale import java.time.ZoneId +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext /** * "Why blocked" for one message: the reason (a rule's chip names the rule and opens the rules, SU-22), the @@ -32,6 +37,8 @@ internal fun WhyBlockedDialog( state: BlockedUiState, onOpenRules: () -> Unit, onDismiss: () -> Unit, + /** spamui-21: allows the sender for good; the button shows only while [AlwaysAllowPolicy] offers it. */ + onAlwaysAllow: ((String) -> Unit)? = null, ) { val context = LocalContext.current val resources = LocalResources.current @@ -50,7 +57,22 @@ internal fun WhyBlockedDialog( val purge = remember(message.receivedAt, state.purgeAfterDays, resources) { purgeLeftText(resources, message.receivedAt, System.currentTimeMillis(), state.purgeAfterDays) } - InfoDialog(onDismiss = onDismiss, title = stringResource(R.string.r3b_why_blocked)) { + // Phone-number matching: off the main thread. Until it answers the button is not shown. + val canAllow by produceState(false, message.address, state.rules, onAlwaysAllow) { + value = onAlwaysAllow != null && + withContext(Dispatchers.Default) { AlwaysAllowPolicy.canOffer(state.rules.values, message.address) } + } + val allowButton: (@Composable () -> Unit)? = if (canAllow) { + { + TextButton(onClick = { + onAlwaysAllow?.invoke(message.address) + onDismiss() + }) { Text(stringResource(R.string.decm_always_allow)) } + } + } else { + null + } + InfoDialog(onDismiss = onDismiss, title = stringResource(R.string.r3b_why_blocked), dismissButton = allowButton) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { val openRules: (() -> Unit)? = if (message.reason == DecisionReason.BLOCK_RULE) { fun() { diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/ForwardRulesScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/ForwardRulesScreen.kt index c8be04f0..7967c613 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/ForwardRulesScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/ForwardRulesScreen.kt @@ -462,6 +462,7 @@ private fun conditionHint(type: RuleType): String = stringResource( RuleType.SENDER_ID -> R.string.spam_type_sender_id_hint RuleType.KEYWORD -> R.string.spam_type_keyword_hint RuleType.REGEX -> R.string.spam_type_regex_hint + RuleType.DOMAIN -> R.string.rdec_type_domain_hint }, ) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/KeywordHelpDialog.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/KeywordHelpDialog.kt index 5112349d..d03ed47b 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/KeywordHelpDialog.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/KeywordHelpDialog.kt @@ -51,6 +51,20 @@ internal fun KeywordHelpDialog(onDismiss: () -> Unit) { ExampleChip(stringResource(section.example)) } } + // spam-15: a blocked word blocks the whole sender. + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + stringResource(R.string.rdec_help_warning_head), + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.Bold, + modifier = Modifier.semantics { heading() }, + ) + Text( + stringResource(R.string.rdec_sender_warning), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } } } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleHits.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleHits.kt new file mode 100644 index 00000000..1313e183 --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleHits.kt @@ -0,0 +1,51 @@ +package com.glooboo.umessage.ui.spam + +import android.content.res.Resources +import com.glooboo.umessage.R +import com.glooboo.umessage.spam.SpamRule + +/** How long ago a rule last blocked a message, in the largest whole unit ([count] is 0 for [RuleHitUnit.NOW]). */ +enum class RuleHitUnit { NOW, MINUTES, HOURS, DAYS, MONTHS, YEARS } + +data class RuleHitAge(val unit: RuleHitUnit, val count: Int) + +/** spam-23: "Blocked 12 messages, last 3 days ago" on a rule's row. Nothing is said for a rule that never blocked. */ +object RuleHits { + private const val MINUTE_MS = 60_000L + private const val HOUR_MS = 60 * MINUTE_MS + private const val DAY_MS = 24 * HOUR_MS + private const val DAYS_PER_MONTH = 30L + private const val DAYS_PER_YEAR = 365L + private const val MONTHS_AS_DAYS = 360L + + /** The age of [lastHit] at [now]; null when it never matched (0). A time in the future counts as just now. */ + fun age(lastHit: Long, now: Long): RuleHitAge? { + if (lastHit <= 0L) return null + val ms = now - lastHit + val days = ms / DAY_MS + return when { + ms < MINUTE_MS -> RuleHitAge(RuleHitUnit.NOW, 0) + ms < HOUR_MS -> RuleHitAge(RuleHitUnit.MINUTES, (ms / MINUTE_MS).toInt()) + ms < DAY_MS -> RuleHitAge(RuleHitUnit.HOURS, (ms / HOUR_MS).toInt()) + days < DAYS_PER_MONTH -> RuleHitAge(RuleHitUnit.DAYS, days.toInt()) + days < MONTHS_AS_DAYS -> RuleHitAge(RuleHitUnit.MONTHS, (days / DAYS_PER_MONTH).toInt()) + else -> RuleHitAge(RuleHitUnit.YEARS, (days / DAYS_PER_YEAR).toInt().coerceAtLeast(1)) + } + } + + /** The row line for [rule], or null when it has not blocked anything. */ + fun text(resources: Resources, rule: SpamRule, now: Long = System.currentTimeMillis()): String? { + if (rule.hitCount <= 0) return null + val blocked = resources.getQuantityString(R.plurals.rdec_hits_blocked, rule.hitCount, rule.hitCount) + val age = age(rule.lastHit, now) ?: return blocked + val ago = when (age.unit) { + RuleHitUnit.NOW -> resources.getString(R.string.rdec_age_now) + RuleHitUnit.MINUTES -> resources.getQuantityString(R.plurals.rdec_age_minutes, age.count, age.count) + RuleHitUnit.HOURS -> resources.getQuantityString(R.plurals.rdec_age_hours, age.count, age.count) + RuleHitUnit.DAYS -> resources.getQuantityString(R.plurals.rdec_age_days, age.count, age.count) + RuleHitUnit.MONTHS -> resources.getQuantityString(R.plurals.rdec_age_months, age.count, age.count) + RuleHitUnit.YEARS -> resources.getQuantityString(R.plurals.rdec_age_years, age.count, age.count) + } + return resources.getString(R.string.rdec_hits_last, blocked, ago) + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleLogic.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleLogic.kt index a7b25447..76a1853f 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleLogic.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleLogic.kt @@ -9,6 +9,7 @@ import com.glooboo.umessage.spam.RegexProblem import com.glooboo.umessage.spam.RuleType import com.glooboo.umessage.spam.SpamRule import com.glooboo.umessage.spam.TextNormalizer +import com.glooboo.umessage.spam.engine.DomainMatch enum class RuleError { EMPTY, NUMBER, PREFIX, SENDER_ID, KEYWORD_SHORT, TOO_LONG, MULTILINE, REGEX_INVALID, REGEX_MATCHES_EMPTY, DUPLICATE, @@ -21,6 +22,9 @@ enum class RuleError { /** An allowed keyword skips every block, so very short ones are refused. */ ALLOW_KEYWORD_SHORT, + + /** Not a website name like `example.com`. */ + DOMAIN, } /** Things worth a second look before saving. Each one asks the user to confirm. */ @@ -133,9 +137,34 @@ object RuleValidator { RuleType.KEYWORD -> validateKeyword(kind, trimmed) // Regex is not trimmed on purpose beyond the outer whitespace check above: inner spaces are meaningful. RuleType.REGEX -> validateRegex(trimmed) + RuleType.DOMAIN -> validateDomain(trimmed) } } + private const val MAX_DOMAIN = 253 + private const val MAX_DOMAIN_LABEL = 63 + private val domainName = + Regex("[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\\.[a-z]{2,24}") + + /** + * A website: cleaned exactly as the filter cleans a DOMAIN rule ([DomainMatch.clean]: scheme, path, port, a leading + * "*." or "." and a trailing dot go), then it must be dotted ASCII names ending in letters. What is stored is the + * cleaned name, so "https://Example.com/shop" becomes "example.com". + */ + private fun validateDomain(value: String): RuleValidation { + val cleaned = DomainMatch.clean(value) + val ok = cleaned.length <= MAX_DOMAIN && domainName.matches(cleaned) && + cleaned.split('.').all { it.length <= MAX_DOMAIN_LABEL } + return if (ok) RuleValidation.Valid(cleaned) else RuleValidation.Invalid(RuleError.DOMAIN) + } + + /** + * spam-15: a block rule on words in the message (a keyword or a pattern) also blocks the message's sender, so the + * form says so. Allow rules and the other types do not do that. + */ + fun blocksSender(kind: ListKind, type: RuleType): Boolean = + kind == ListKind.BLOCK && (type == RuleType.KEYWORD || type == RuleType.REGEX) + /** * A sender name: letters of any script, digits, spaces, dots, dashes, underscores and "&", with at least one * letter. Names with spaces ("Bank Melli") and Persian names are real senders. The first character that does @@ -175,7 +204,7 @@ object RuleValidator { */ fun warnings(kind: ListKind, type: RuleType, pattern: String, existing: List, subscriptionId: Int?): List { val result = mutableListOf() - val text = type == RuleType.KEYWORD || type == RuleType.REGEX + val text = type == RuleType.KEYWORD || type == RuleType.REGEX || type == RuleType.DOMAIN if (kind == ListKind.ALLOW && text) result += RuleWarning.ALLOW_SKIPS_BLOCKS if (kind == ListKind.ALLOW && type == RuleType.KEYWORD && isCommonWord(KeywordMatch.bare(pattern))) { result += RuleWarning.COMMON_WORD diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleMatchPicker.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleMatchPicker.kt index 0b57a0f8..16db9faf 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleMatchPicker.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleMatchPicker.kt @@ -18,7 +18,7 @@ import androidx.compose.ui.unit.dp import com.glooboo.umessage.R import com.glooboo.umessage.spam.RuleType -private val commonTypes = listOf(RuleType.NUMBER, RuleType.SENDER_ID, RuleType.KEYWORD) +private val commonTypes = listOf(RuleType.NUMBER, RuleType.SENDER_ID, RuleType.KEYWORD, RuleType.DOMAIN) private val moreTypes = listOf(RuleType.PREFIX, RuleType.REGEX) /** The type said in the plain words of the add-rule sheet ("A word in the message"). */ @@ -28,6 +28,7 @@ private fun matchLabel(type: RuleType): Int = when (type) { RuleType.KEYWORD -> R.string.ux8d_match_word RuleType.PREFIX -> R.string.ux8d_match_prefix RuleType.REGEX -> R.string.ux8d_match_pattern + RuleType.DOMAIN -> R.string.rdec_match_domain } /** The type said once, short, for a rule's row and the type filter ("Word in message"). */ @@ -39,6 +40,7 @@ fun ruleRowTypeLabel(type: RuleType): String = stringResource( RuleType.SENDER_ID -> R.string.ux8d_row_type_sender RuleType.KEYWORD -> R.string.ux8d_row_type_word RuleType.REGEX -> R.string.ux8d_row_type_pattern + RuleType.DOMAIN -> R.string.rdec_row_type_domain }, ) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleNotes.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleNotes.kt index f74e3aa1..9bff5074 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleNotes.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleNotes.kt @@ -59,7 +59,7 @@ object RuleNotes { BLOCKED_BY_YOU -> R.string.e_note_blocked_by_you ALLOWED_BY_YOU -> R.string.e_note_allowed_by_you BLOCKED_FROM_MESSAGE -> R.string.e_note_blocked_from_message - BLOCKED_FROM_KEYWORD -> R.string.e_note_blocked_from_keyword + BLOCKED_FROM_KEYWORD -> R.string.rdec_note_blocked_from_keyword ALLOWED_FROM_KEYWORD -> R.string.e_note_allowed_from_keyword REPORTED_SPAM -> R.string.e_note_reported_spam OLD_WORD_LIST -> R.string.e_note_old_word_list diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RulesOrder.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RulesOrder.kt new file mode 100644 index 00000000..2beed8e1 --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RulesOrder.kt @@ -0,0 +1,48 @@ +package com.glooboo.umessage.ui.spam + +import android.content.Context +import com.glooboo.umessage.spam.SpamRule + +/** + * main-23: the order of the Rules lists. [DEFAULT] is the order the lists always had (by the time the rule was + * added); [NEWEST] puts the rule saved last first, whatever its added time, so a rule just restored or imported is + * at the top. + */ +enum class RulesOrder { + DEFAULT, + NEWEST, + ; + + fun apply(rules: List): List = when (this) { + DEFAULT -> rules.sortedByDescending { it.createdAt } + NEWEST -> rules.sortedByDescending { it.id } + } +} + +/** Remembers the chosen [RulesOrder]. */ +interface RulesOrderStore { + fun load(): RulesOrder + fun save(order: RulesOrder) +} + +class MemoryRulesOrderStore(private var order: RulesOrder = RulesOrder.DEFAULT) : RulesOrderStore { + override fun load(): RulesOrder = order + override fun save(order: RulesOrder) { + this.order = order + } +} + +class AndroidRulesOrderStore(private val context: Context) : RulesOrderStore { + override fun load(): RulesOrder = runCatching { + RulesOrder.valueOf(context.getSharedPreferences(PREFS, 0).getString(KEY, null).orEmpty()) + }.getOrDefault(RulesOrder.DEFAULT) + + override fun save(order: RulesOrder) { + runCatching { context.getSharedPreferences(PREFS, 0).edit().putString(KEY, order.name).apply() } + } + + private companion object { + const val PREFS = "spamless_rules_ui" + const val KEY = "order" + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RulesScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RulesScreen.kt index b65c804e..15a7aff8 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RulesScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RulesScreen.kt @@ -145,6 +145,8 @@ class RulesActions( val onEdit: (SpamRule) -> Unit = {}, val onQuery: (String) -> Unit = {}, val onTypeFilter: (RuleType?) -> Unit = {}, + // main-23 + val onOrder: (RulesOrder) -> Unit = {}, val onToggleSelected: (Long) -> Unit = {}, val onSelectAll: () -> Unit = {}, val onClearSelection: () -> Unit = {}, @@ -210,6 +212,7 @@ fun RulesRoute( onEdit = viewModel::openEdit, onQuery = viewModel::setQuery, onTypeFilter = viewModel::setTypeFilter, + onOrder = viewModel::setOrder, onToggleSelected = viewModel::toggleSelected, onSelectAll = viewModel::selectAllVisible, onClearSelection = viewModel::clearSelection, @@ -402,6 +405,17 @@ private fun RulesTopBar(state: RulesUiState, actions: RulesActions, onTest: () - leadingIcon = { Icon(Symbols.Upload, contentDescription = null) }, onClick = { menuOpen = false; actions.onOpenBackup() }, ) + // main-23: ticked = the newest saved rule comes first; unticked keeps the usual order. + DropdownMenuItem( + text = { Text(stringResource(R.string.rdec_sort_newest)) }, + leadingIcon = { + if (state.order == RulesOrder.NEWEST) Icon(Symbols.Check, contentDescription = null) + }, + onClick = { + menuOpen = false + actions.onOrder(if (state.order == RulesOrder.NEWEST) RulesOrder.DEFAULT else RulesOrder.NEWEST) + }, + ) DropdownMenuItem( text = { Text(stringResource(R.string.w3b_test_menu)) }, leadingIcon = { Icon(Symbols.Search, contentDescription = null) }, @@ -756,6 +770,7 @@ fun ruleTypeLabel(type: RuleType): String = stringResource( RuleType.SENDER_ID -> R.string.spam_type_sender_id RuleType.KEYWORD -> R.string.spam_type_keyword RuleType.REGEX -> R.string.spam_type_regex + RuleType.DOMAIN -> R.string.rdec_type_domain }, ) @@ -765,6 +780,7 @@ private fun ruleTypeIcon(type: RuleType): ImageVector = when (type) { RuleType.SENDER_ID -> Symbols.Sms RuleType.KEYWORD -> Symbols.Tag RuleType.REGEX -> Symbols.Code + RuleType.DOMAIN -> Symbols.Language } /** @@ -897,6 +913,16 @@ private fun RuleRowText(rule: SpamRule, sims: List, overridden: Boolean maxLines = 2, overflow = TextOverflow.Ellipsis, ) + // spam-23: how many messages the rule has blocked and when it last did; nothing for a rule that never did. + RuleHits.text(LocalContext.current.resources, rule)?.let { + Text( + it, + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } if (overridden) { InfoChip( stringResource(R.string.w3b_overridden_chip), @@ -916,6 +942,7 @@ private fun typeHelp(kind: ListKind, type: RuleType): String = stringResource( RuleType.SENDER_ID -> R.string.rules2_type_sender_id_help RuleType.KEYWORD -> if (kind == ListKind.ALLOW) R.string.spam_type_keyword_allow_help else R.string.spam_type_keyword_help RuleType.REGEX -> R.string.rules2_type_regex_help + RuleType.DOMAIN -> R.string.rdec_type_domain_help }, ) @@ -927,6 +954,7 @@ private fun typeHint(type: RuleType): String = stringResource( RuleType.SENDER_ID -> R.string.spam_type_sender_id_hint RuleType.KEYWORD -> R.string.spam_type_keyword_hint RuleType.REGEX -> R.string.spam_type_regex_hint + RuleType.DOMAIN -> R.string.rdec_type_domain_hint }, ) @@ -942,6 +970,7 @@ internal fun errorText(error: RuleValidation.Invalid): String = when (error.erro RuleError.TOO_LONG -> stringResource(R.string.spam_err_too_long) RuleError.MULTILINE -> stringResource(R.string.spam_err_multiline) RuleError.DUPLICATE -> stringResource(R.string.spam_err_duplicate) + RuleError.DOMAIN -> stringResource(R.string.rdec_err_domain) RuleError.ALLOW_KEYWORD_SHORT -> stringResource(R.string.spam_err_allow_keyword_short) else -> regexErrorText(error) } @@ -985,6 +1014,25 @@ private fun RuleWarnings(warnings: List) { } } +/** The "heads up" under a block-by-words rule: the sender is blocked too, and how to undo it. */ +@Composable +private fun SenderBlockNote() { + val colors = MaterialTheme.colorScheme + Row(horizontalArrangement = Arrangement.spacedBy(12.dp), modifier = Modifier.fillMaxWidth()) { + Icon( + Symbols.Info, + contentDescription = null, + tint = colors.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + Text( + stringResource(R.string.rdec_sender_warning), + style = MaterialTheme.typography.bodyMedium, + color = colors.onSurfaceVariant, + ) + } +} + /** Asks before saving a rule with warnings. A block of an allowed value offers to remove the allow rule. */ @Composable private fun ConfirmRuleDialog(form: RuleForm, actions: RulesActions) { @@ -1073,6 +1121,9 @@ fun AddRuleSheet( if (error == null && form.warnings.isNotEmpty()) RuleWarnings(form.warnings) + // spam-15: a blocked word or pattern blocks the whole sender; said where it is turned on. + if (RuleValidator.blocksSender(form.kind, form.type)) SenderBlockNote() + if (form.saveFailed) { Text( stringResource(R.string.spam_sheet_save_failed), @@ -1140,10 +1191,10 @@ private fun RuleValueField(form: RuleForm, error: RuleValidation.Invalid?, onPat keyboardOptions = KeyboardOptions( capitalization = KeyboardCapitalization.None, autoCorrectEnabled = false, - keyboardType = if (form.type.isSender && form.type != RuleType.SENDER_ID) { - KeyboardType.Phone - } else { - KeyboardType.Text + keyboardType = when { + form.type.isSender && form.type != RuleType.SENDER_ID -> KeyboardType.Phone + form.type == RuleType.DOMAIN -> KeyboardType.Uri + else -> KeyboardType.Text }, ), trailingIcon = { @@ -1185,6 +1236,7 @@ private fun valueLabel(type: RuleType): Int = when (type) { RuleType.SENDER_ID -> R.string.e_value_sender RuleType.KEYWORD -> R.string.e_value_keyword RuleType.REGEX -> R.string.e_value_pattern + RuleType.DOMAIN -> R.string.rdec_value_domain } /** Share of the screen height a rule sheet may take, so the status bar stays visible above it. */ diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RulesViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RulesViewModel.kt index 3ed5d8fa..7686772f 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RulesViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RulesViewModel.kt @@ -83,6 +83,8 @@ data class RulesUiState( /** Search text and type filter (SU-09). */ val query: String = "", val typeFilter: RuleType? = null, + /** main-23: the order of both lists. */ + val order: RulesOrder = RulesOrder.DEFAULT, /** Rules picked with a long press, all on the current tab. */ val selected: Set = emptySet(), /** The old Fossify lists not yet moved into rules, shown read-only on the Blocked tab. */ @@ -140,6 +142,7 @@ class RulesViewModel( private val legacyStore: LegacyBlockStore = NoLegacyBlockStore, private val io: CoroutineDispatcher = Dispatchers.IO, private val previewSource: RulePreviewSource = NoRulePreviewSource, + private val orderStore: RulesOrderStore = MemoryRulesOrderStore(), ) : AndroidViewModel(application) { private data class View( @@ -147,6 +150,7 @@ class RulesViewModel( val query: String = "", val typeFilter: RuleType? = null, val selected: Set = emptySet(), + val order: RulesOrder = RulesOrder.DEFAULT, ) private data class Extras( @@ -155,7 +159,7 @@ class RulesViewModel( val migration: MigrationDialog? = null, ) - private val view = MutableStateFlow(View()) + private val view = MutableStateFlow(View(order = orderStore.load())) private val form = MutableStateFlow(null) private val extras = MutableStateFlow(Extras()) private val events = Channel(Channel.BUFFERED) @@ -167,7 +171,7 @@ class RulesViewModel( val state: StateFlow = combine( repository.rules, view, form, extras, preview ) { rules, view, form, extras, preview -> - val sorted = rules.sortedByDescending { it.createdAt } + val sorted = view.order.apply(rules) val ids = sorted.map { it.id }.toSet() RulesUiState( loading = false, @@ -178,6 +182,7 @@ class RulesViewModel( form = form, query = view.query, typeFilter = view.typeFilter, + order = view.order, selected = view.selected intersect ids, legacy = extras.legacy, migration = extras.migration, @@ -202,6 +207,12 @@ class RulesViewModel( fun setQuery(query: String) = view.update { it.copy(query = query.take(MAX_QUERY)) } fun setTypeFilter(type: RuleType?) = view.update { it.copy(typeFilter = type) } + /** main-23: picks the order of the lists and remembers it for the next visit. */ + fun setOrder(order: RulesOrder) { + view.update { it.copy(order = order) } + orderStore.save(order) + } + fun toggleSelected(id: Long) = view.update { it.copy(selected = if (id in it.selected) it.selected - id else it.selected + id) } @@ -556,6 +567,7 @@ class RulesViewModel( RulesViewModel( app, SpamRepositoryProvider.get(app), AndroidLegacyBlockStore(app), previewSource = AndroidRulePreviewSource(app), + orderStore = AndroidRulesOrderStore(app), ) } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadBubbles.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadBubbles.kt index 21944d33..d06c1235 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadBubbles.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadBubbles.kt @@ -1,3 +1,5 @@ +@file:Suppress("TooManyFunctions") + package com.glooboo.umessage.ui.thread import com.glooboo.umessage.ui.components.uiLocale @@ -49,6 +51,7 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.glooboo.umessage.R +import com.glooboo.umessage.messaging.SmsFailureReason import com.glooboo.umessage.models.Message import com.glooboo.umessage.models.MessageKey import java.time.ZoneId @@ -124,7 +127,7 @@ fun ThreadRowItem(row: ThreadRow, vm: ThreadViewModel, actions: ThreadActions) { is ThreadRow.UnreadDivider -> UnreadDivider() is ThreadRow.Failed -> StatusLine( - text = stringResource(R.string.thread_status_failed), + text = failedStatusText(row.reasonCode), icon = Symbols.Error, color = MaterialTheme.colorScheme.error, onClick = { actions.onRetry(row.message, row.text) }, @@ -132,6 +135,15 @@ fun ThreadRowItem(row: ThreadRow, vm: ThreadViewModel, actions: ThreadActions) { } } +/** "Not sent. Tap to retry." and, on a second line, why the phone said it failed (thread-27) when that is known. */ +@Composable +private fun failedStatusText(reasonCode: Int): String { + val base = stringResource(R.string.thread_status_failed) + val context = LocalContext.current + val reason = remember(reasonCode) { SmsFailureReason.text(context, reasonCode) } + return if (reason == null) base else base + "\n" + reason +} + @Composable private fun DateHeader(row: ThreadRow.DateHeader, showSim: Boolean) { val context = LocalContext.current diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadItemsBuilder.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadItemsBuilder.kt index 09efe23b..714b98fe 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadItemsBuilder.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadItemsBuilder.kt @@ -1,122 +1,138 @@ -package com.glooboo.umessage.ui.thread - -import android.provider.Telephony -import com.glooboo.umessage.extensions.toSortedMessages -import com.glooboo.umessage.models.Message -import com.glooboo.umessage.models.ThreadItem -import com.glooboo.umessage.models.ThreadItem.ThreadDateTime -import com.glooboo.umessage.models.ThreadItem.ThreadError -import com.glooboo.umessage.models.ThreadItem.ThreadSending -import com.glooboo.umessage.models.ThreadItem.ThreadSent -import com.glooboo.umessage.models.ThreadItem.ThreadUnreadDivider - -/** - * The chat rows for a list of messages, and the unread messages among them that the user has now seen. [reactions] - * (I30) holds the iPhone reactions of each message, by [Message.getStableId]; their texts are not in [items]. - */ -data class ThreadItems( - val items: List, - val newlyRead: List, - val reactions: Map> = emptyMap(), -) - -/** - * Turns the loaded messages into chat rows: a date header when more than [MIN_DATE_TIME_DIFF_SECS] passed or the - * SIM changed, then the message, its "failed" or "sending" line, and "sent"/"delivered" under the newest one. - * - * [simLabels] maps a subscription id to the SIM number shown in the header ("1", "2"); unknown ones show "?". - * [deliveryReportsOn]: the "delivery reports" setting; without it the newest sent message only says "Sent". - * [seen] (TU-11): only while the user can see the chat are unread messages returned in [ThreadItems.newlyRead], for - * the caller to mark read. - * [firstUnreadId] (I26): the [Message.getStableId] of the message that gets an "Unread messages" line above it, under - * its date header; see [firstUnreadMessageId]. - * [showTapbacks] (I30): iPhone reaction texts such as `Liked “...”` leave the list and count on the message they name. - * [undownloadedMms] (Q40): ids of received MMS that are only a notification-ind, with the carrier's expiry in seconds; - * each shows a "Tap to download" row in place of its empty bubble. - */ -fun buildThreadItems( - messages: List, - simLabels: Map, - seen: Boolean, - deliveryReportsOn: Boolean = true, - firstUnreadId: Long? = null, - showTapbacks: Boolean = false, - undownloadedMms: Map = emptyMap(), -): ThreadItems { - val startNanos = System.nanoTime() - val sorted = messages.toSortedMessages() - val tapbacks = if (showTapbacks) applyTapbacks(sorted) else TapbackResult.None - var dividerPending = false - val items = ArrayList(sorted.size + sorted.size / ITEMS_HEADROOM_DIVISOR + ITEMS_HEADROOM) - val newlyRead = ArrayList() - var prevDateTime = 0 - var prevSIMId = -2 - // Scheduled messages sort last by their future date; the "Sent" row belongs to the last one that is not. - val lastRealIndex = sorted.indexOfLast { !it.isScheduled } - sorted.forEachIndexed { i, message -> - if (message.getStableId() in tapbacks.hidden) { - // A hidden reaction is marked read like any message; the unread line moves to the next one shown. - if (!message.read && seen) newlyRead.add(message) - if (message.getStableId() == firstUnreadId) dividerPending = true - return@forEachIndexed - } - if (shouldShowThreadDateTime(message, prevDateTime, prevSIMId)) { - items.add(ThreadDateTime(message.date, simLabels[message.subscriptionId] ?: "?")) - prevDateTime = message.date - } - if (firstUnreadId != null && (dividerPending || message.getStableId() == firstUnreadId)) { - items.add(ThreadUnreadDivider(firstUnreadId)) - dividerPending = false - } - val notDownloaded = if (message.isMMS) undownloadedMms[message.id] else null - if (notDownloaded != null) { - items.add(ThreadItem.ThreadMmsDownload(message.id, notDownloaded)) - } else { - items.add(message) - } - - if (message.type == Telephony.Sms.MESSAGE_TYPE_FAILED) { - items.add(ThreadError(message.id, message.body, message.isMMS)) - } - if (message.type == Telephony.Sms.MESSAGE_TYPE_OUTBOX || - (message.type == Telephony.Sms.MESSAGE_TYPE_QUEUED && !message.isScheduled) - ) { - items.add(ThreadSending(message.id)) - } - if (!message.read && seen) newlyRead.add(message) - - if (i == lastRealIndex && message.type == Telephony.Sms.MESSAGE_TYPE_SENT) { - // "Delivered" only while delivery reports are on: a network can report delivery the app never asked for. - // An MMS has no delivery report: its status column is empty and reads as 0, which is not "delivered". - val delivered = deliveryReportsOn && !message.isMMS && message.status == Telephony.Sms.STATUS_COMPLETE - val deliveryFailed = !message.isMMS && isDeliveryFailed(message.status) - items.add( - ThreadSent( - messageId = message.id, delivered = delivered, deliveryFailed = deliveryFailed, - isMms = message.isMMS, - ), - ) - } - prevSIMId = message.subscriptionId - } - return ThreadItems(items, newlyRead, tapbacks.reactions).also { - logSlowThreadBuild(startNanos, sorted.size, items.size) - } -} - -/** A delivery report of failure (TP-ST 64 or more) is stored as [Telephony.Sms.STATUS_FAILED] or above. */ -internal fun isDeliveryFailed(status: Int): Boolean = status >= Telephony.Sms.STATUS_FAILED - -/** The oldest received message that is still unread, or null: where the "Unread messages" line goes (I26). */ -fun firstUnreadMessageId(messages: List): Long? = - messages.toSortedMessages().firstOrNull { it.isReceivedMessage() && !it.read && !it.isScheduled }?.getStableId() - -private fun shouldShowThreadDateTime(message: Message, prevDateTime: Int, prevSIMId: Int): Boolean { - val isSentFromDifferentKnownSIM = prevSIMId != -1 && message.subscriptionId != -1 && prevSIMId != message.subscriptionId - return message.date - prevDateTime > MIN_DATE_TIME_DIFF_SECS || isSentFromDifferentKnownSIM -} - -/** A new date header shows only after this many seconds without messages. */ -internal const val MIN_DATE_TIME_DIFF_SECS = 300 -private const val ITEMS_HEADROOM_DIVISOR = 8 -private const val ITEMS_HEADROOM = 4 +package com.glooboo.umessage.ui.thread + +import android.provider.Telephony +import com.glooboo.umessage.extensions.toSortedMessages +import com.glooboo.umessage.models.Message +import com.glooboo.umessage.models.ThreadItem +import com.glooboo.umessage.models.ThreadItem.ThreadDateTime +import com.glooboo.umessage.models.ThreadItem.ThreadError +import com.glooboo.umessage.models.ThreadItem.ThreadSending +import com.glooboo.umessage.models.ThreadItem.ThreadSent +import com.glooboo.umessage.models.ThreadItem.ThreadUnreadDivider + +/** + * The chat rows for a list of messages, and the unread messages among them that the user has now seen. [reactions] + * (I30) holds the iPhone reactions of each message, by [Message.getStableId]; their texts are not in [items]. + */ +data class ThreadItems( + val items: List, + val newlyRead: List, + val reactions: Map> = emptyMap(), +) + +/** + * Turns the loaded messages into chat rows: a date header when more than [MIN_DATE_TIME_DIFF_SECS] passed or the + * SIM changed, then the message, its "failed" or "sending" line, and "sent"/"delivered" under the newest one. + * + * [simLabels] maps a subscription id to the SIM number shown in the header ("1", "2"); unknown ones show "?". + * [deliveryReportsOn]: the "delivery reports" setting; without it the newest sent message only says "Sent". + * [seen] (TU-11): only while the user can see the chat are unread messages returned in [ThreadItems.newlyRead], for + * the caller to mark read. + * [firstUnreadId] (I26): the [Message.getStableId] of the message that gets an "Unread messages" line above it, under + * its date header; see [firstUnreadMessageId]. + * [showTapbacks] (I30): iPhone reaction texts such as `Liked “...”` leave the list and count on the message they name. + * [undownloadedMms] (Q40): ids of received MMS that are only a notification-ind, with the carrier's expiry in seconds; + * each shows a "Tap to download" row in place of its empty bubble. + * [failureCodes] (thread-27): the stored send-report code of each failed text, by message id. + */ +fun buildThreadItems( + messages: List, + simLabels: Map, + seen: Boolean, + deliveryReportsOn: Boolean = true, + firstUnreadId: Long? = null, + showTapbacks: Boolean = false, + undownloadedMms: Map = emptyMap(), + failureCodes: Map = emptyMap(), +): ThreadItems { + val startNanos = System.nanoTime() + val sorted = messages.toSortedMessages() + val tapbacks = if (showTapbacks) applyTapbacks(sorted) else TapbackResult.None + var dividerPending = false + val items = ArrayList(sorted.size + sorted.size / ITEMS_HEADROOM_DIVISOR + ITEMS_HEADROOM) + val newlyRead = ArrayList() + var prevDateTime = 0 + var prevSIMId = -2 + // Scheduled messages sort last by their future date; the "Sent" row belongs to the last one that is not. + val lastRealIndex = sorted.indexOfLast { !it.isScheduled } + sorted.forEachIndexed { i, message -> + if (message.getStableId() in tapbacks.hidden) { + // A hidden reaction is marked read like any message; the unread line moves to the next one shown. + if (!message.read && seen) newlyRead.add(message) + if (message.getStableId() == firstUnreadId) dividerPending = true + return@forEachIndexed + } + if (shouldShowThreadDateTime(message, prevDateTime, prevSIMId)) { + items.add(ThreadDateTime(message.date, simLabels[message.subscriptionId] ?: "?")) + prevDateTime = message.date + } + if (firstUnreadId != null && (dividerPending || message.getStableId() == firstUnreadId)) { + items.add(ThreadUnreadDivider(firstUnreadId)) + dividerPending = false + } + items.add(message.bubbleItem(undownloadedMms)) + items.addStatusRows(message, i == lastRealIndex, deliveryReportsOn, failureCodes) + if (!message.read && seen) newlyRead.add(message) + prevSIMId = message.subscriptionId + } + return ThreadItems(items, newlyRead, tapbacks.reactions).also { + logSlowThreadBuild(startNanos, sorted.size, items.size) + } +} + +/** The message itself, or the "Tap to download" row of a received MMS that is only a notification-ind. */ +private fun Message.bubbleItem(undownloadedMms: Map): ThreadItem { + val notDownloaded = if (isMMS) undownloadedMms[id] else null + return if (notDownloaded != null) ThreadItem.ThreadMmsDownload(id, notDownloaded) else this +} + +/** The rows that follow a message: its send error, the sending spinner and, on the last real one, "Sent". */ +private fun MutableList.addStatusRows( + message: Message, + isLastReal: Boolean, + deliveryReportsOn: Boolean, + failureCodes: Map, +) { + if (message.type == Telephony.Sms.MESSAGE_TYPE_FAILED) { + add( + ThreadError( + message.id, message.body, message.isMMS, + if (message.isMMS) 0 else failureCodes[message.id] ?: 0, + ), + ) + } + if (message.type == Telephony.Sms.MESSAGE_TYPE_OUTBOX || + (message.type == Telephony.Sms.MESSAGE_TYPE_QUEUED && !message.isScheduled) + ) { + add(ThreadSending(message.id)) + } + if (isLastReal && message.type == Telephony.Sms.MESSAGE_TYPE_SENT) { + // "Delivered" only while delivery reports are on: a network can report delivery the app never asked for. + // An MMS has no delivery report: its status column is empty and reads as 0, which is not "delivered". + val delivered = deliveryReportsOn && !message.isMMS && message.status == Telephony.Sms.STATUS_COMPLETE + val deliveryFailed = !message.isMMS && isDeliveryFailed(message.status) + add( + ThreadSent( + messageId = message.id, delivered = delivered, deliveryFailed = deliveryFailed, + isMms = message.isMMS, + ), + ) + } +} + +/** A delivery report of failure (TP-ST 64 or more) is stored as [Telephony.Sms.STATUS_FAILED] or above. */ +internal fun isDeliveryFailed(status: Int): Boolean = status >= Telephony.Sms.STATUS_FAILED + +/** The oldest received message that is still unread, or null: where the "Unread messages" line goes (I26). */ +fun firstUnreadMessageId(messages: List): Long? = + messages.toSortedMessages().firstOrNull { it.isReceivedMessage() && !it.read && !it.isScheduled }?.getStableId() + +private fun shouldShowThreadDateTime(message: Message, prevDateTime: Int, prevSIMId: Int): Boolean { + val isSentFromDifferentKnownSIM = prevSIMId != -1 && message.subscriptionId != -1 && prevSIMId != message.subscriptionId + return message.date - prevDateTime > MIN_DATE_TIME_DIFF_SECS || isSentFromDifferentKnownSIM +} + +/** A new date header shows only after this many seconds without messages. */ +internal const val MIN_DATE_TIME_DIFF_SECS = 300 +private const val ITEMS_HEADROOM_DIVISOR = 8 +private const val ITEMS_HEADROOM = 4 diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadRows.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadRows.kt index 2b612164..c238dc26 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadRows.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadRows.kt @@ -39,7 +39,12 @@ sealed interface ThreadRow { /** Q40: a picture message that was never downloaded, with its "Tap to download" action. */ data class MmsDownload(val messageId: Long, val expirySeconds: Long, override val key: String) : ThreadRow - data class Failed(val message: MessageKey, val text: String, override val key: String) : ThreadRow + data class Failed( + val message: MessageKey, + val text: String, + override val key: String, + val reasonCode: Int = 0, + ) : ThreadRow data class Sent( val messageId: Long, @@ -111,7 +116,8 @@ fun buildThreadRows(items: List, isGroup: Boolean): List is ThreadItem.ThreadError -> rows.add( ThreadRow.Failed( - item.key, item.messageText, uniqueKey("e${item.messageId}${if (item.isMMS) "m" else "s"}") + item.key, item.messageText, uniqueKey("e${item.messageId}${if (item.isMMS) "m" else "s"}"), + item.reasonCode, ) ) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSimController.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSimController.kt index 91a1aabb..453e7188 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSimController.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSimController.kt @@ -32,7 +32,9 @@ class ThreadSimController(private val context: Context, private val vm: ThreadVi /** Reads the active SIMs and picks one for [recipients]; [lastMessage] is the thread's newest message. */ @SuppressLint("MissingPermission") fun load(recipients: ThreadRecipients, lastMessage: Message?): Boolean { - val active = context.subscriptionManagerCompat().activeSubscriptionInfoList ?: return false + // Thread-17: without the phone permission the SIMs cannot be read; the chat works with the default SIM. + val active = runCatching { context.subscriptionManagerCompat().activeSubscriptionInfoList }.getOrNull() + ?: return false if (active.size <= 1) return false sims.clear() val names = SimNames(context.composerPrefs) diff --git a/app/src/main/res/values-fa/strings_decisions_backup.xml b/app/src/main/res/values-fa/strings_decisions_backup.xml new file mode 100644 index 00000000..ad670d7a --- /dev/null +++ b/app/src/main/res/values-fa/strings_decisions_backup.xml @@ -0,0 +1,4 @@ + + + کلمه‌های اسپم برای افزودن: %1$d. کلمه‌هایی که از قبل دارید رد می‌شوند. + diff --git a/app/src/main/res/values-fa/strings_decisions_blocked_domain.xml b/app/src/main/res/values-fa/strings_decisions_blocked_domain.xml new file mode 100644 index 00000000..cc0407ff --- /dev/null +++ b/app/src/main/res/values-fa/strings_decisions_blocked_domain.xml @@ -0,0 +1,4 @@ + + + قانون: لینک‌های %1$s + diff --git a/app/src/main/res/values-fa/strings_decisions_main.xml b/app/src/main/res/values-fa/strings_decisions_main.xml new file mode 100644 index 00000000..3b78b28a --- /dev/null +++ b/app/src/main/res/values-fa/strings_decisions_main.xml @@ -0,0 +1,14 @@ + + + + %d گفتگو خوانده شد + %d گفتگو خوانده شد + + پیام‌های اسپم + جستجو در پیام‌های اسپم + جستجو با فرستنده یا متن + بستن جستجو + چیزی پیدا نشد + هیچ فرستنده یا پیام اسپمی با چیزی که نوشتید جور نیست. + همیشه مجاز + diff --git a/app/src/main/res/values-fa/strings_decisions_rules.xml b/app/src/main/res/values-fa/strings_decisions_rules.xml new file mode 100644 index 00000000..beae90e4 --- /dev/null +++ b/app/src/main/res/values-fa/strings_decisions_rules.xml @@ -0,0 +1,47 @@ + + + + لینک یک سایت + لینک در پیام + سایت + سایت + هر پیامی که لینک این سایت را داشته باشد بلاک می‌شود، با زیرسایت‌هایی مثل www.example.com. + example.com + نام یک سایت مثل example.com را وارد کنید + + + + %d پیام بلاک شد + %d پیام بلاک شد + + %1$s، آخرین بار %2$s + همین الان + + %d دقیقه پیش + %d دقیقه پیش + + + %d ساعت پیش + %d ساعت پیش + + + %d روز پیش + %d روز پیش + + + %d ماه پیش + %d ماه پیش + + + %d سال پیش + %d سال پیش + + + + جدیدترین اول + + + حواستان باشد: این کار کل فرستنده را بلاک می‌کند، نه فقط همین پیام. اگر یک بانک یا فروشگاه یک شماره را هم برای کدها و هم برای تبلیغ‌ها استفاده کند، پیام‌های واقعی‌اش را هم دیگر نمی‌گیرید. می‌توانید فرستنده را در صفحهٔ اسپم از بلاک درآورید. + بلاک کردن یک کلمه، فرستنده را بلاک می‌کند + بلاک‌شده از روی کلمهٔ کلیدی (کل فرستنده بلاک شده) + diff --git a/app/src/main/res/values-fa/strings_decisions_thread.xml b/app/src/main/res/values-fa/strings_decisions_thread.xml new file mode 100644 index 00000000..0d1a0125 --- /dev/null +++ b/app/src/main/res/values-fa/strings_decisions_thread.xml @@ -0,0 +1,4 @@ + + + گوشی خطای کلی گزارش کرد (کد %1$d) + diff --git a/app/src/main/res/values/strings_decisions_backup.xml b/app/src/main/res/values/strings_decisions_backup.xml new file mode 100644 index 00000000..d23f39e4 --- /dev/null +++ b/app/src/main/res/values/strings_decisions_backup.xml @@ -0,0 +1,4 @@ + + + Blocked words to add: %1$d. Words you already have are skipped. + diff --git a/app/src/main/res/values/strings_decisions_blocked_domain.xml b/app/src/main/res/values/strings_decisions_blocked_domain.xml new file mode 100644 index 00000000..3871c4a0 --- /dev/null +++ b/app/src/main/res/values/strings_decisions_blocked_domain.xml @@ -0,0 +1,4 @@ + + + Rule: links to %1$s + diff --git a/app/src/main/res/values/strings_decisions_main.xml b/app/src/main/res/values/strings_decisions_main.xml new file mode 100644 index 00000000..2c932fc6 --- /dev/null +++ b/app/src/main/res/values/strings_decisions_main.xml @@ -0,0 +1,21 @@ + + + + + %d chat marked as read + %d chats marked as read + + + + Blocked messages + + + Search blocked messages + Search by sender or text + Close search + Nothing found + No blocked sender or message matches what you typed. + + + Always allow + diff --git a/app/src/main/res/values/strings_decisions_rules.xml b/app/src/main/res/values/strings_decisions_rules.xml new file mode 100644 index 00000000..a3c6db99 --- /dev/null +++ b/app/src/main/res/values/strings_decisions_rules.xml @@ -0,0 +1,47 @@ + + + + A website link + Link in message + Website + Website + Blocks every message that links to this website, including its subdomains such as www.example.com. + example.com + Enter a website name like example.com + + + + Blocked %d message + Blocked %d messages + + %1$s, last %2$s + a moment ago + + %d minute ago + %d minutes ago + + + %d hour ago + %d hours ago + + + %d day ago + %d days ago + + + %d month ago + %d months ago + + + %d year ago + %d years ago + + + + Newest first + + + Heads up: this blocks the whole sender, not just the message. If a bank or shop uses one number for both codes and ads, you will stop getting its real messages too. You can unblock a sender in the Spam screen. + Blocking a word blocks the sender + Blocked from a keyword (the whole sender is blocked) + diff --git a/app/src/main/res/values/strings_decisions_thread.xml b/app/src/main/res/values/strings_decisions_thread.xml new file mode 100644 index 00000000..692ca7fa --- /dev/null +++ b/app/src/main/res/values/strings_decisions_thread.xml @@ -0,0 +1,7 @@ + + + + + The phone reported a general failure (code %1$d) + + diff --git a/app/src/test/kotlin/com/glooboo/umessage/backup/SettingsBackupFormatTest.kt b/app/src/test/kotlin/com/glooboo/umessage/backup/SettingsBackupFormatTest.kt index 2ea0cefd..113d39c0 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/backup/SettingsBackupFormatTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/backup/SettingsBackupFormatTest.kt @@ -38,6 +38,37 @@ class SettingsBackupFormatTest { assertThat(back.settings).isEqualTo(settings) } + @Test fun blockedKeywordsRoundTrip() { + val content = BackupContent(rules, emptyList(), settings, blockedKeywords = listOf("lottery", "تخفیف")) + val back = SettingsBackupFormat.decode(SettingsBackupFormat.encode(content, 1)) + assertThat(back.blockedKeywords).containsExactly("lottery", "تخفیف").inOrder() + } + + @Test fun anOldFileWithoutKeywordsGivesNoneAndSoRemovesNone() { + val text = SettingsBackupFormat.encode(BackupContent(rules, emptyList(), settings), 1) + assertThat(text).doesNotContain("blockedKeywords") + val back = SettingsBackupFormat.decode(text) + assertThat(back.blockedKeywords).isEmpty() + // Nothing to add and the phone's own words are never compared for removal. + assertThat(SettingsBackupFormat.newKeywords(back.blockedKeywords, setOf("mine"))).isEmpty() + } + + @Test fun keywordsOfTheFileAreCleanedAndTolerated() { + val text = """ + {"app":"spamless","kind":"settings-backup","version":1, + "blockedKeywords":[" Win ","win","x","two\nlines",5,null,"ok word"]} + """.trimIndent() + assertThat(SettingsBackupFormat.decode(text).blockedKeywords).containsExactly("Win", "ok word").inOrder() + val bad = SettingsBackupFormat.decode( + """{"app":"spamless","kind":"settings-backup","version":1,"blockedKeywords":"nope"}""", + ) + assertThat(bad.blockedKeywords).isEmpty() + } + + @Test fun newKeywordsSkipsTheOnesAlreadyOnThePhoneInAnyCase() { + assertThat(SettingsBackupFormat.newKeywords(listOf("Win", "free"), setOf("win"))).containsExactly("free") + } + @Test fun containsNoLockData() { val text = SettingsBackupFormat.encode(BackupContent(rules, listOf(forward), settings), 1).lowercase() assertThat(text).doesNotContain("pin") diff --git a/app/src/test/kotlin/com/glooboo/umessage/helpers/MessagesBackupTest.kt b/app/src/test/kotlin/com/glooboo/umessage/helpers/MessagesBackupTest.kt index 08b81d4d..79efef4a 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/helpers/MessagesBackupTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/helpers/MessagesBackupTest.kt @@ -270,7 +270,7 @@ class MessagesBackupTest { } @Test - fun xmlBackup_givesOneSummaryWithBadRowsAndPictureMessagesCounted() { + fun xmlBackup_givesOneSummaryWithBadRowsAndAPictureMessageWithoutAddressFailing() { val store = FakeMessageStore.install() val xml = """ @@ -285,11 +285,87 @@ class MessagesBackupTest { val summary = importer().import(xml.byteInputStream(), all) assertThat(summary.added).isEqualTo(2) assertThat(summary.damaged).isEqualTo(2) - assertThat(summary.unsupportedMms).isEqualTo(1) + assertThat(summary.failed).isEqualTo(1) assertThat(store.rows("sms").map { it["body"] }).containsExactly("one", "سلام 👋").inOrder() val text = BackupSummaryText.import(context, summary) assertThat(text).contains("Added: 2") - assertThat(text).contains("not supported") + assertThat(text).contains("Could not be restored: 1") + } + + private val xmlPhoto = Base64.getEncoder().encodeToString(photo) + + private fun xmlMms(parts: String, attrs: String = "date=\"4000000000000\" msg_box=\"1\" m_type=\"132\"") = """ + + + + $parts + + + + + + + """.trimIndent() + + @Test + fun xmlBackup_restoresAPictureMessageWithItsAttachment_andSkipsItTheSecondTime() { + val store = FakeMessageStore.install() + val xml = xmlMms( + "" + + "", + ) + val first = importer().import(xml.byteInputStream(), all) + assertThat(first.added).isEqualTo(1) + assertThat(first.unsupportedMms).isEqualTo(0) + assertThat(store.count("pdu")).isEqualTo(1) + assertThat(store.count("part")).isEqualTo(2) + // SMS Backup & Restore writes MMS times in milliseconds; the provider keeps seconds. + assertThat(store.rows("pdu").single()["date"]).isEqualTo(4_000_000_000L) + val image = store.rows("part").single { it["ct"] == "image/jpeg" }["_id"] as Long + assertThat(store.partBytes(image)).isEqualTo(photo) + + val second = importer().import(xml.byteInputStream(), all) + assertThat(second.added).isEqualTo(0) + assertThat(second.duplicates).isEqualTo(1) + assertThat(store.count("pdu")).isEqualTo(1) + assertThat(store.count("part")).isEqualTo(2) + } + + @Test + fun xmlBackup_pictureMessagesAreLeftOut_whenOnlySmsIsChosen() { + val store = FakeMessageStore.install() + val xml = xmlMms("") + val summary = importer().import(xml.byteInputStream(), MessagesImporter.Options(sms = true, mms = false)) + assertThat(summary.skippedByChoice).isEqualTo(1) + assertThat(store.count("pdu")).isEqualTo(0) + } + + @Test + fun xmlBackup_anAttachmentOverTheSizeLimit_isLeftOutAndTheMessageSaysSo() { + val store = FakeMessageStore.install() + val huge = "A".repeat(19_000_001) + val xml = xmlMms( + "", + ) + val summary = importer().import(xml.byteInputStream(), all) + assertThat(summary.incomplete).isEqualTo(1) + assertThat(store.rows("part").map { it["ct"] }).containsExactly("text/plain") + } + + @Test + fun xmlBackup_aPictureMessageWithoutDate_isDamaged_andTheNextEntriesStillImport() { + val store = FakeMessageStore.install() + val xml = """ + + + + + + """.trimIndent() + val summary = importer().import(xml.byteInputStream(), all) + assertThat(summary.damaged).isEqualTo(1) + assertThat(summary.added).isEqualTo(1) + assertThat(store.rows("sms").map { it["body"] }).containsExactly("after") } @Test diff --git a/app/src/test/kotlin/com/glooboo/umessage/helpers/OtpCodesTest.kt b/app/src/test/kotlin/com/glooboo/umessage/helpers/OtpCodesTest.kt index d72cf175..2abf0145 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/helpers/OtpCodesTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/helpers/OtpCodesTest.kt @@ -142,6 +142,30 @@ class OtpCodesTest { assertThat(OtpCodeExtractor.extract(body)).isEqualTo("333333") } + @Test + fun anAlphanumericCodeNextToAKeywordIsCopiedAndMasked() { + val body = "Your code is ab12cd" + assertThat(OtpCodes.looksLikeCode(body)).isTrue() + assertThat(OtpCodes.primary(body)).isEqualTo(CodeToken(CodeKind.Code, "ab12cd")) + assertThat(OtpCodeExtractor.extract(body)).isEqualTo("ab12cd") + assertThat(detectCopyTokens(body)).containsExactly(CopyToken(CopyKind.Code, "ab12cd")) + assertThat(CodeMasker.mask(body)).isEqualTo("Your code is ••••") + assertThat(CodeMasker.maskForForward(body)).isEqualTo("Your code is ****") + } + + @Test + fun anAlphanumericCodeIsOnlyOfferedWithAKeywordInItsSentence() { + assertThat(OtpCodes.tokens("Your order ab12cd has shipped")).isEmpty() + assertThat(OtpCodes.tokens("Order a1b2c3. Verify your email address in the app")).isEmpty() + assertThat(OtpCodes.looksLikeCode("Promo code ab12cd")).isFalse() + } + + @Test + fun aDigitCodeAndAnAlphanumericOneInOneMessageAreBothOffered() { + val tokens = OtpCodes.tokens("Use 333333 to log in. Your OTP is ab12cd") + assertThat(tokens.map { it.value }).containsExactly("333333", "ab12cd").inOrder() + } + @Test fun aNumberWithoutAKeywordNextToItIsNoSecondCode() { assertThat(OtpCodes.tokens("Your OTP is 4821. Ref 998877 for support").map { it.value }) diff --git a/app/src/test/kotlin/com/glooboo/umessage/helpers/SmsXmlWriterTest.kt b/app/src/test/kotlin/com/glooboo/umessage/helpers/SmsXmlWriterTest.kt index 2978f1bd..e2617d52 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/helpers/SmsXmlWriterTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/helpers/SmsXmlWriterTest.kt @@ -135,7 +135,7 @@ class SmsXmlWriterTest { } @Test - fun readerExport_asXml_holdsSmsAndMms_andTheImporterRestoresTheTexts() { + fun readerExport_asXml_holdsSmsAndMms_andTheImporterRestoresBoth() { val source = FakeMessageStore.install() val ali = source.threadIdFor("+447121111111") source.addSms("+447121111111", "see you at 5 🙂", 2_000, type = 2, threadId = ali) @@ -166,8 +166,9 @@ class SmsXmlWriterTest { val target = FakeMessageStore.install() val summary = MessagesImporter(context, MessagesWriter(context) { emptyList() }) .import(xml.byteInputStream(), all) - assertThat(summary.added).isEqualTo(2) - assertThat(summary.unsupportedMms).isEqualTo(1) + assertThat(summary.added).isEqualTo(3) + assertThat(summary.unsupportedMms).isEqualTo(0) + assertThat(target.count("pdu")).isEqualTo(1) assertThat(target.rows("sms", orderBy = "date").map { it["body"] }) .containsExactly("سلام، خوبی؟", "see you at 5 🙂").inOrder() } diff --git a/app/src/test/kotlin/com/glooboo/umessage/spam/data/PendingSmsReplayTest.kt b/app/src/test/kotlin/com/glooboo/umessage/spam/data/PendingSmsReplayTest.kt index f5c24c4b..92cdd97f 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/spam/data/PendingSmsReplayTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/spam/data/PendingSmsReplayTest.kt @@ -214,4 +214,43 @@ class PendingSmsReplayTest { val incoming = IncomingMessage("+447121234567", "hi", 1) assertFalse(SpamEngine.storeBlocked(app, incoming, FilterDecision.Block(DecisionReason.UNKNOWN_SENDER))) } + + /** spam-2: a restored message is the user's decision, so a replay does not filter (and re-block) it again. */ + @Test fun approvedRowIsDeliveredEvenIfTheFilterWouldBlockItAgain() { + decide = { FilterDecision.Block(DecisionReason.BLOCK_RULE, 5L) } + addPending(pending(body = "Restored text").copy(approved = true)) + replay() + assertEquals("Restored text", FakeSmsProvider.inserted.single().getAsString(Telephony.Sms.BODY)) + assertTrue(offMainThread { dao.getPending() }.isEmpty()) + assertTrue(offMainThread { dao.getAllBlocked() }.isEmpty()) + } + + @Test fun approvedRowIsDeliveredEvenWhenAnIdenticalTextWasBlockedMeanwhile() { + val row = pending(body = "Same text").copy(approved = true) + val incoming = IncomingMessage(row.address, row.body, row.subscriptionId, receivedAt = row.date) + assertTrue(offMainThread { SpamEngine.storeBlocked(app, incoming, FilterDecision.Block(DecisionReason.UNKNOWN_SENDER)) }) + addPending(row) + replay() + assertEquals(1, FakeSmsProvider.inserted.size) + assertTrue(offMainThread { dao.getPending() }.isEmpty()) + } + + @Test fun approvedRowStaysQueuedWhenTheInboxInsertFails() { + FakeSmsProvider.failInserts = true + addPending(pending().copy(approved = true)) + replay() + assertEquals(1, offMainThread { dao.getPending() }.size) + FakeSmsProvider.failInserts = false + replay() + assertEquals(1, FakeSmsProvider.inserted.size) + assertTrue(offMainThread { dao.getPending() }.isEmpty()) + } + + @Test fun anOrdinaryRowIsStillFiltered() { + decide = { FilterDecision.Block(DecisionReason.UNKNOWN_SENDER) } + addPending(pending()) + replay() + assertTrue(FakeSmsProvider.inserted.isEmpty()) + assertEquals(1, offMainThread { dao.getAllBlocked() }.size) + } } diff --git a/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamDatabaseMigrationTest.kt b/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamDatabaseMigrationTest.kt index 3fcccffb..dc719fe4 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamDatabaseMigrationTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamDatabaseMigrationTest.kt @@ -379,7 +379,7 @@ class SpamDatabaseMigrationTest { private companion object { const val TEST_DB = "spam-migration-test.db" const val OTHER_DB = "spam-migration-other.db" - const val LATEST = 7 + const val LATEST = 8 const val NEWER = SpamDatabase.VERSION + 1 const val FILE = "0f9c2a3e-1111-2222-3333-444455556666" } diff --git a/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamRuleStatsMigrationTest.kt b/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamRuleStatsMigrationTest.kt new file mode 100644 index 00000000..4d6c9c69 --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamRuleStatsMigrationTest.kt @@ -0,0 +1,106 @@ +package com.glooboo.umessage.spam.data + +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.glooboo.umessage.spam.ListKind +import com.glooboo.umessage.spam.RuleType +import com.glooboo.umessage.testing.migrationTestHelper +import com.glooboo.umessage.testing.offMainThread +import com.google.common.truth.Truth.assertThat +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +/** + * Schema 8 adds pending_sms.approved and spam_rules.hitCount / lastHit. Rows that exist keep behavior: nothing is + * approved, no rule has a hit. The DOMAIN rule type needs no column (types are stored by name). + */ +@RunWith(AndroidJUnit4::class) +class SpamRuleStatsMigrationTest { + + @get:Rule + val helper = migrationTestHelper(SpamDatabase::class.java) + + private val context: Context = ApplicationProvider.getApplicationContext() + + @Before + @After + fun deleteFiles() { + context.getDatabasePath(TEST_DB).parentFile + ?.listFiles { _, name -> name.startsWith(TEST_DB) } + ?.forEach { it.delete() } + } + + @Test + fun migratesFromVersionSevenKeepingRowsWithDefaults() { + helper.createDatabase(TEST_DB, 7).use { db -> + db.execSQL( + "INSERT INTO spam_rules (id, kind, type, pattern, subscriptionId, note, createdAt) " + + "VALUES (1, 'BLOCK', 'KEYWORD', 'lottery', NULL, 'n', 1000)" + ) + db.execSQL( + "INSERT INTO pending_sms (address, subject, body, date, subscriptionId, status, createdAt, dateSent) " + + "VALUES ('Shop', '', 'queued', 5000, 1, 0, 6000, 4000)" + ) + } + + helper.runMigrationsAndValidate(TEST_DB, 8, true, *SpamDatabase.ALL_MIGRATIONS).use { db -> + db.query("SELECT pattern, note, hitCount, lastHit FROM spam_rules WHERE id = 1").use { + assertThat(it.moveToFirst()).isTrue() + assertThat(it.getString(0)).isEqualTo("lottery") + assertThat(it.getString(1)).isEqualTo("n") + assertThat(it.getInt(2)).isEqualTo(0) + assertThat(it.getLong(3)).isEqualTo(0L) + } + db.query("SELECT body, dateSent, approved FROM pending_sms").use { + assertThat(it.moveToFirst()).isTrue() + assertThat(it.getString(0)).isEqualTo("queued") + assertThat(it.getLong(1)).isEqualTo(4000L) + assertThat(it.getInt(2)).isEqualTo(0) + } + } + } + + @Test + fun migratedRowsReadThroughRoomWithNoHitsAndNotApproved(): Unit = offMainThread { + helper.createDatabase(TEST_DB, 7).use { db -> + db.execSQL( + "INSERT INTO spam_rules (id, kind, type, pattern, subscriptionId, note, createdAt) " + + "VALUES (1, 'BLOCK', 'PREFIX', '+91', NULL, '', 1000)" + ) + db.execSQL( + "INSERT INTO pending_sms (address, subject, body, date, subscriptionId, status, createdAt) " + + "VALUES ('Shop', '', 'queued', 5000, 1, 0, 6000)" + ) + } + val db = SpamDatabase.build(context, TEST_DB) + try { + val rule = db.spamDao().getRules().single().toRule() + assertThat(rule.hitCount).isEqualTo(0) + assertThat(rule.lastHit).isEqualTo(0L) + assertThat(db.spamDao().getPending().single().approved).isFalse() + + // A DOMAIN rule and a counted hit round-trip on the migrated file. + val domain = db.spamDao().insertRule( + SpamRuleEntity( + kind = ListKind.BLOCK, type = RuleType.DOMAIN, pattern = "example.com", + subscriptionId = null, note = "", createdAt = 2, + ) + ) + db.spamDao().recordRuleHit(domain, 777L) + val counted = db.spamDao().getRule(domain)!!.toRule() + assertThat(counted.type).isEqualTo(RuleType.DOMAIN) + assertThat(counted.hitCount).isEqualTo(1) + assertThat(counted.lastHit).isEqualTo(777L) + } finally { + db.close() + } + } + + private companion object { + const val TEST_DB = "rule-stats-migration-test.db" + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamRuleStatsTest.kt b/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamRuleStatsTest.kt new file mode 100644 index 00000000..59ba6fa9 --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamRuleStatsTest.kt @@ -0,0 +1,139 @@ +package com.glooboo.umessage.spam.data + +import android.app.Application +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.glooboo.umessage.spam.BlockedMessage +import com.glooboo.umessage.spam.DecisionReason +import com.glooboo.umessage.spam.ListKind +import com.glooboo.umessage.spam.RuleType +import com.glooboo.umessage.spam.SpamRule +import com.glooboo.umessage.spam.engine.NumberNormalizer +import kotlinx.coroutines.test.runTest +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith + +/** Schema 8 data behavior: rule hit counters (spam-23), the approved flag of restored SMS (spam-2), DOMAIN rules. */ +@RunWith(AndroidJUnit4::class) +class SpamRuleStatsTest { + + private val app: Application = ApplicationProvider.getApplicationContext() + private lateinit var db: SpamDatabase + private lateinit var repo: DefaultSpamRepository + + private val dao get() = db.spamDao() + + @Before fun setUp() { + db = Room.inMemoryDatabaseBuilder(app, SpamDatabase::class.java).allowMainThreadQueries().build() + val platform = object : SpamPlatform { + override fun notifyBlocked(message: BlockedMessage) = Unit + // The inbox insert "fails", so the restore leaves its pending row behind to look at. + override fun deliverRestored(pending: PendingSmsEntity): Long? = null + override fun deliverRestoredMms(message: BlockedMessage): Long? = null + override fun removeRestored(id: Long, isMms: Boolean) = false + override fun deleteMedia(names: Collection) = Unit + override fun sweepMedia(keep: Set) = Unit + } + repo = DefaultSpamRepository(platform, db, SpamSettingsStore(app), NumberNormalizer { "GB" }) + } + + @After fun tearDown() = db.close() + + private fun blocked( + ruleId: Long?, + reason: DecisionReason = DecisionReason.BLOCK_RULE, + body: String = "win a prize", + ) = + BlockedMessage( + address = "+447121234567", body = body, subscriptionId = 1, isMms = false, + receivedAt = 1_000_000L, reason = reason, ruleId = ruleId, + ) + + private fun stored(id: Long) = dao.getRule(id)!!.toRule() + + @Test fun aNewRuleHasNoHits() = runTest { + val id = repo.addRule(SpamRule(kind = ListKind.BLOCK, type = RuleType.KEYWORD, pattern = "prize")) + assertEquals(0, stored(id).hitCount) + assertEquals(0L, stored(id).lastHit) + } + + @Test fun aBlockedMessageCountsAHitOnItsRule() = runTest { + val id = repo.addRule(SpamRule(kind = ListKind.BLOCK, type = RuleType.KEYWORD, pattern = "prize")) + val before = System.currentTimeMillis() + repo.storeBlocked(blocked(id, body = "first")) + repo.storeBlocked(blocked(id, body = "second")) + val rule = stored(id) + assertEquals(2, rule.hitCount) + assertTrue(rule.lastHit >= before) + // The model the screens read carries the counters too. + assertEquals(2, repo.currentRules().single().hitCount) + } + + @Test fun aDuplicateCopyIsNotANewHit() = runTest { + val id = repo.addRule(SpamRule(kind = ListKind.BLOCK, type = RuleType.KEYWORD, pattern = "prize")) + repo.storeBlocked(blocked(id)) + repo.storeBlocked(blocked(id)) + assertEquals(1, stored(id).hitCount) + } + + @Test fun onlyRuleBlocksCountAndOnlyOnTheirOwnRule() = runTest { + val a = repo.addRule(SpamRule(kind = ListKind.BLOCK, type = RuleType.KEYWORD, pattern = "prize")) + val b = repo.addRule(SpamRule(kind = ListKind.BLOCK, type = RuleType.KEYWORD, pattern = "gift")) + repo.storeBlocked(blocked(null, DecisionReason.UNKNOWN_SENDER, body = "unknown")) + repo.storeBlocked(blocked(a)) + repo.storeBlocked(blocked(9_999L, body = "rule that is gone")) + assertEquals(1, stored(a).hitCount) + assertEquals(0, stored(b).hitCount) + } + + @Test fun editingARuleKeepsItsCounters() = runTest { + val id = repo.addRule(SpamRule(kind = ListKind.BLOCK, type = RuleType.KEYWORD, pattern = "prize")) + repo.storeBlocked(blocked(id)) + val stale = stored(id).copy(hitCount = 0, lastHit = 0L, pattern = "prizes", note = "edited") + repo.updateRule(stale) + val rule = stored(id) + assertEquals("prizes", rule.pattern) + assertEquals(1, rule.hitCount) + assertTrue(rule.lastHit > 0L) + } + + @Test fun aRestoredRuleKeepsItsCounters() = runTest { + repo.restoreRules(listOf(SpamRule(7, ListKind.BLOCK, RuleType.KEYWORD, "prize", hitCount = 4, lastHit = 55L))) + assertEquals(4, stored(7).hitCount) + assertEquals(55L, stored(7).lastHit) + } + + @Test fun aRestoredSmsIsQueuedAsApproved() = runTest { + val id = repo.storeBlocked(blocked(null, DecisionReason.UNKNOWN_SENDER)) + repo.restore(id) + val queued = dao.getPending().single() + assertTrue(queued.approved) + assertEquals("win a prize", queued.body) + } + + @Test fun anIncomingSmsIsNotApprovedByDefault() { + val id = dao.insertPending( + PendingSmsEntity( + address = "Shop", subject = "", body = "hi", date = 1L, subscriptionId = 1, status = 0, createdAt = 1L, + ) + ) + assertFalse(dao.getPending().single { it.id == id }.approved) + } + + @Test fun aDomainRuleIsStoredCleanedAndNotDuplicated() = runTest { + val first = repo.addRule( + SpamRule(kind = ListKind.BLOCK, type = RuleType.DOMAIN, pattern = "https://Example.COM/path"), + ) + val again = repo.addRule(SpamRule(kind = ListKind.BLOCK, type = RuleType.DOMAIN, pattern = "*.example.com")) + assertEquals(first, again) + val rule = stored(first) + assertEquals(RuleType.DOMAIN, rule.type) + assertEquals("example.com", rule.pattern) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/spam/engine/DefaultSpamFilterTest.kt b/app/src/test/kotlin/com/glooboo/umessage/spam/engine/DefaultSpamFilterTest.kt index e4babd5b..30203baf 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/spam/engine/DefaultSpamFilterTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/spam/engine/DefaultSpamFilterTest.kt @@ -607,4 +607,78 @@ class DefaultSpamFilterTest { assertAllow(DecisionReason.MODE_OFF, f.evaluate(msg(body = body))) assertBlock(DecisionReason.BLOCK_RULE, 14, f.evaluate(msg(body = "tail-marker"))) } + + // spam-6: a saved contact is not held by keyword, regex, prefix or domain block rules; exact blocks still apply. + + private val contactNumber = "+919876543210" + + @Test fun aContactIsNotBlockedByAKeywordRule() { + val f = filter( + rules = listOf(rule(ListKind.BLOCK, RuleType.KEYWORD, "hello", id = 3)), + contacts = setOf(contactNumber), + ) + assertAllow(DecisionReason.CONTACT, f.evaluate(msg())) + } + + @Test fun aContactIsNotBlockedByRegexPrefixOrDomainRules() { + val rules = listOf( + rule(ListKind.BLOCK, RuleType.REGEX, "hel+o", id = 1), + rule(ListKind.BLOCK, RuleType.PREFIX, "+9198", id = 2), + rule(ListKind.BLOCK, RuleType.DOMAIN, "example.com", id = 3), + ) + val f = filter(rules = rules, contacts = setOf(contactNumber)) + assertAllow(DecisionReason.CONTACT, f.evaluate(msg(body = "hello see www.example.com"))) + } + + @Test fun aContactIsStillBlockedByItsExactNumber() { + val f = filter( + rules = listOf(rule(ListKind.BLOCK, RuleType.NUMBER, contactNumber, id = 4)), + contacts = setOf(contactNumber), + ) + assertBlock(DecisionReason.BLOCK_RULE, 4, f.evaluate(msg())) + } + + @Test fun aLaterRuleStillBlocksAContactByNumberWhenAKeywordRuleWasSkipped() { + val rules = listOf( + rule(ListKind.BLOCK, RuleType.KEYWORD, "hello", id = 1), + rule(ListKind.BLOCK, RuleType.NUMBER, contactNumber, id = 2), + ) + val f = filter(rules = rules, contacts = setOf(contactNumber)) + assertBlock(DecisionReason.BLOCK_RULE, 2, f.evaluate(msg())) + } + + @Test fun aNonContactIsStillBlockedByPatternRules() { + val rules = listOf( + rule(ListKind.BLOCK, RuleType.PREFIX, "+9198", id = 2), + rule(ListKind.BLOCK, RuleType.KEYWORD, "hello", id = 3), + ) + assertBlock(DecisionReason.BLOCK_RULE, 2, filter(rules = rules).evaluate(msg())) + assertBlock(DecisionReason.BLOCK_RULE, 3, filter(rules = rules.drop(1)).evaluate(msg())) + } + + @Test fun aSenderIdIsBlockedByKeywordRulesAsBefore() { + val f = filter( + rules = listOf(rule(ListKind.BLOCK, RuleType.KEYWORD, "hello", id = 3)), + contacts = setOf(contactNumber), + ) + assertBlock(DecisionReason.BLOCK_RULE, 3, f.evaluate(msg(address = "VM-SHOP"))) + } + + @Test fun aContactIsNotBlockedByALegacyKeywordButAStrangerIs() { + val legacy = FakeLegacy(keywords = listOf("hello")) + assertAllow(DecisionReason.CONTACT, filter(contacts = setOf(contactNumber), legacy = legacy).evaluate(msg())) + assertBlock(DecisionReason.BLOCK_RULE, null, filter(legacy = legacy).evaluate(msg())) + } + + @Test fun aContactIsStillBlockedByALegacyBlockedNumber() { + val legacy = FakeLegacy(blockedNumbers = setOf(contactNumber)) + val f = filter(contacts = setOf(contactNumber), legacy = legacy) + assertBlock(DecisionReason.BLOCK_RULE, null, f.evaluate(msg())) + } + + @Test fun aDomainBlockRuleBlocksAMessageWithThatLinkAndNamesTheRule() { + val f = filter(rules = listOf(rule(ListKind.BLOCK, RuleType.DOMAIN, "example.com", id = 9))) + assertBlock(DecisionReason.BLOCK_RULE, 9, f.evaluate(msg(body = "win at http://promo.example.com/x"))) + assertAllow(DecisionReason.MODE_OFF, f.evaluate(msg(body = "win at example.org"))) + } } diff --git a/app/src/test/kotlin/com/glooboo/umessage/spam/engine/DomainMatchTest.kt b/app/src/test/kotlin/com/glooboo/umessage/spam/engine/DomainMatchTest.kt new file mode 100644 index 00000000..cab54b3d --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/spam/engine/DomainMatchTest.kt @@ -0,0 +1,82 @@ +package com.glooboo.umessage.spam.engine + +import com.glooboo.umessage.spam.IncomingMessage +import com.glooboo.umessage.spam.ListKind +import com.glooboo.umessage.spam.RuleType +import com.glooboo.umessage.spam.SpamRule +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** spam-22: the DOMAIN rule type matches the hosts of links in a message body, subdomains included. */ +class DomainMatchTest { + + private fun hit(body: String, domain: String, disguised: Boolean = true) = + DomainMatch.matches(body, domain, disguised) + + @Test fun matchesTheDomainInALink() { + assertTrue(hit("Claim now https://example.com/win?id=1", "example.com")) + assertTrue(hit("go to example.com", "example.com")) + assertTrue(hit("EXAMPLE.COM/Prize", "example.com")) + } + + @Test fun matchesSubdomains() { + assertTrue(hit("http://www.example.com/a", "example.com")) + assertTrue(hit("see login.secure.example.com now", "example.com")) + assertTrue(hit("see login.secure.example.com now", "secure.example.com")) + } + + @Test fun doesNotMatchOtherDomains() { + assertFalse(hit("visit notexample.com", "example.com")) + assertFalse(hit("visit example.com.evil.net/x", "example.com")) + assertFalse(hit("visit example.org", "example.com")) + assertFalse(hit("visit www.example.com", "login.example.com")) + } + + @Test fun anEmailAddressIsNotALink() { + assertFalse(hit("write to bob@example.com", "example.com")) + } + + @Test fun readsDisguisedDotsOnlyWhenAsked() { + assertTrue(hit("pay at example[.]com", "example.com")) + assertTrue(hit("pay at example(dot)com", "example.com")) + assertFalse(hit("pay at example[.]com", "example.com", disguised = false)) + } + + @Test fun readsPersianDigitsAndTextAroundTheLink() { + assertTrue(hit("لینک: shop123.example.com/۱۲۳ را بزنید", "example.com")) + } + + @Test fun aPatternIsCleanedLikeItIsStored() { + assertEquals("example.com", DomainMatch.clean(" https://Example.com/path?q=1 ")) + assertEquals("example.com", DomainMatch.clean("*.example.com")) + assertEquals("example.com", DomainMatch.clean(".example.com.")) + assertEquals("example.com", DomainMatch.clean("example.com:8080")) + assertTrue(hit("example.com/x", "HTTPS://Example.com/")) + } + + @Test fun aPatternWithoutADotNeverMatches() { + assertFalse(hit("visit example.com", "com")) + assertFalse(hit("visit example.com", "")) + } + + @Test fun hostsListsEveryLinkLowerCased() { + assertEquals( + listOf("a.example.com", "bit.ly"), + DomainMatch.hosts("Open A.Example.com or https://bit.ly/x"), + ) + } + + @Test fun theRuleMatcherUsesItForBlockAndAllowRules() { + val matcher = RuleMatcher(NumberNormalizer { "IN" }) + val message = IncomingMessage("VM-SHOP", "Offer at deals.example.com and pay at shop[.]test", 1) + fun rule(kind: ListKind, domain: String) = SpamRule(1, kind, RuleType.DOMAIN, domain) + assertTrue(matcher.matches(rule(ListKind.BLOCK, "example.com"), message)) + assertTrue(matcher.matches(rule(ListKind.ALLOW, "example.com"), message)) + // A disguised link counts for a block rule but cannot borrow an allowed domain. + assertTrue(matcher.matches(rule(ListKind.BLOCK, "shop.test"), message)) + assertFalse(matcher.matches(rule(ListKind.ALLOW, "shop.test"), message)) + assertFalse(matcher.matches(rule(ListKind.BLOCK, " "), message)) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/spam/engine/OtpDetectorTest.kt b/app/src/test/kotlin/com/glooboo/umessage/spam/engine/OtpDetectorTest.kt index d2cefb1c..773020e9 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/spam/engine/OtpDetectorTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/spam/engine/OtpDetectorTest.kt @@ -90,6 +90,47 @@ class OtpDetectorTest { assertFalse(otp("Meet at 1830")) } + @Test fun alphanumericCodesNextToAKeywordAreCodes() { + assertTrue(otp("Your code is ab12cd")) + assertTrue(otp("Your verification code is X7K2M9")) + assertTrue(otp("ab12cd is your login code")) + assertTrue(otp("Use 12ab34 to verify your account")) + assertTrue(otp("Your OTP is a1b2c3")) + assertTrue(otp("Your code is ab12cd. It expires in 5 minutes")) + assertTrue(otp("رمز ورود: ab12cd")) + } + + @Test fun alphanumericTokensWithoutAKeywordAreNotCodes() { + assertFalse(otp("ab12cd")) + assertFalse(otp("Your order ab12cd has shipped")) + assertFalse(otp("Meet me at gate a1b2c3")) + assertFalse(otp("Tracking id: 1z2y3x4w")) + } + + @Test fun theKeywordMustShareTheSentenceWithAnAlphanumericCode() { + assertFalse(otp("Order a1b2c3. Verify your email address in the app")) + assertFalse(otp("Verify your email address.\nOrder a1b2c3 is on its way")) + } + + @Test fun promoAndShapeVetoesApplyToAlphanumericCodes() { + assertFalse(otp("Promo code ab12cd")) + assertFalse(otp("Use code SAVE20 at checkout")) + assertFalse(otp("Reward code ab12cd for you")) + assertFalse(otp("Your code will be sent at 10h30")) + assertFalse(otp("Verify by 10am tomorrow, code expires 5pm")) + assertFalse(otp("Verify your 3rd attempt, code for mp3s")) + assertFalse(otp("Your code is abcdef")) + assertFalse(otp("Your code is ab1c")) + assertFalse(otp("Your code is ab12cd34ef")) + assertFalse(otp("Verify your login at example.com/ab12cd")) + assertFalse(otp("Verify your login, write to ab12cd@example.com")) + } + + @Test fun anAlphanumericCodeKeepsTheRulesOfTheGenericWord() { + assertTrue(otp("Reward OTP ab12cd")) + assertFalse(otp("Offer code ab12cd")) + } + @Test fun normalizeDigitsMapsAllDecimalScripts() { assertEquals("12345 and 6789", OtpDetector.normalizeDigits("۱۲۳۴۵ and ٦٧٨٩")) assertEquals("plain 42", OtpDetector.normalizeDigits("plain 42")) diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/conversations/MarkAllReadTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/conversations/MarkAllReadTest.kt new file mode 100644 index 00000000..fd3336eb --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/conversations/MarkAllReadTest.kt @@ -0,0 +1,35 @@ +package com.glooboo.umessage.ui.conversations + +import com.glooboo.umessage.models.Conversation +import org.junit.Assert.assertEquals +import org.junit.Test + +/** main-21: "Mark all read" changes exactly the unread chats of the list, so Undo can restore exactly those. */ +class MarkAllReadTest { + + private fun conversation(id: Long, read: Boolean) = Conversation( + threadId = id, snippet = "", date = 0, read = read, title = "t$id", photoUri = "", + isGroupConversation = false, phoneNumber = "+1$id", + ) + + private val all = listOf( + conversation(1, read = false), conversation(2, read = true), + conversation(3, read = false), conversation(4, read = false), + ) + + @Test + fun onlyUnreadChatsAreChanged() { + assertEquals(listOf(1L, 3L, 4L), unreadThreadsToMarkRead(all, emptySet())) + } + + @Test + fun hiddenAndPendingChatsAreLeftAlone() { + // 3 is behind the app lock, 4 waits for its archive or delete to finish: neither is touched nor restored. + assertEquals(listOf(1L), unreadThreadsToMarkRead(all, setOf(3L, 4L))) + } + + @Test + fun nothingUnreadChangesNothing() { + assertEquals(emptyList(), unreadThreadsToMarkRead(listOf(conversation(2, read = true)), emptySet())) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/main/BlockedHitTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/main/BlockedHitTest.kt new file mode 100644 index 00000000..c5c99bb5 --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/main/BlockedHitTest.kt @@ -0,0 +1,54 @@ +package com.glooboo.umessage.ui.main + +import com.glooboo.umessage.spam.BlockedMessage +import com.glooboo.umessage.spam.DecisionReason +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +/** main-22: the spam section of the main search. */ +class BlockedHitTest { + + private fun msg(id: Long, address: String, body: String, at: Long) = + BlockedMessage(id, address, body, 1, false, at, DecisionReason.UNKNOWN_SENDER) + + private val held = listOf( + msg(1, "+14155550133", "Win a free prize now", 1000), + msg(2, "+14155550133", "free again", 3000), + msg(3, "BANK-X", "Your free code", 2000), + msg(4, "+442071838750", "Meeting moved", 4000), + ) + + private fun hits(query: String, hidden: Set = emptySet()) = buildBlockedHits( + held, query, keyOf = { it }, hiddenSenderKeys = hidden, title = { it }, formatDate = { "t$it" }, + ) + + @Test + fun oneHitPerSenderNewestFirstWithTheMatchCount() { + val found = hits("free") + assertThat(found.map { it.address }).containsExactly("+14155550133", "BANK-X").inOrder() + assertThat(found.first().count).isEqualTo(2) + assertThat(found.first().snippet).isEqualTo("free again") + assertThat(found.first().date).isEqualTo("t3000") + } + + @Test + fun aSenderWithAChatHiddenBehindTheLockIsNotFound() { + assertThat(hits("free", hidden = setOf("+14155550133")).map { it.address }).containsExactly("BANK-X") + } + + @Test + fun nothingMatchingGivesNoHits() { + assertThat(hits("zzz")).isEmpty() + } + + @Test + fun theSectionIsOnlyShownForTypedTextWithoutATile() { + val state = MainSearchState() + state.blockedHits = hits("free") + assertThat(state.shownBlockedHits(typed = true)).hasSize(2) + assertThat(state.shownBlockedHits(typed = false)).isEmpty() + state.filter = InboxFilter.Unread + assertThat(state.shownBlockedHits(typed = true)).isEmpty() + assertThat(noHits(emptyList(), emptyList(), emptyList(), hits("free"))).isFalse() + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/main/InboxMenuPolicyTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/main/InboxMenuPolicyTest.kt index 811811c2..c1ecde29 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/main/InboxMenuPolicyTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/main/InboxMenuPolicyTest.kt @@ -12,7 +12,18 @@ class InboxMenuPolicyTest { bin: Boolean = false, scheduled: Int = 0, tabShown: Boolean = false, - ) = InboxMenuInputs(archiveAvailable, archived, bin, scheduled, tabShown) + unread: Int = 0, + ) = InboxMenuInputs(archiveAvailable, archived, bin, scheduled, tabShown, unread) + + /** main-21: Mark all read is the first entry, and only while some chat is unread. */ + @Test + fun markAllReadIsFirstAndOnlyWhileSomethingIsUnread() { + assertFalse(InboxMenuItem.MarkAllRead in InboxMenuPolicy.entries(inputs(bin = true, unread = 0))) + val entries = InboxMenuPolicy.entries(inputs(bin = true, archived = 2, unread = 3)) + assertEquals(InboxMenuItem.MarkAllRead, entries.first()) + assertEquals(InboxMenuItem.Settings, entries.last()) + assertEquals(1, entries.count { it == InboxMenuItem.MarkAllRead }) + } @Test fun anEmptyInboxWithTheArchivedTabOffersOnlyStarredAndSettings() { diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/main/MainSearchViewModelTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/main/MainSearchViewModelTest.kt index 8f9b905a..27ce74a4 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/main/MainSearchViewModelTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/main/MainSearchViewModelTest.kt @@ -45,6 +45,23 @@ class MainSearchViewModelTest { listOf(result(query)) } runNoteSearch = { emptyList() } + runBlockedSearch = { emptyList() } + } + + /** main-22: blocked messages are searched with the notes and cleared with them. */ + @Test + fun blockedMessagesAreFoundWithTheMessagesAndClearedWithThem() = runTest(dispatcher) { + val vm = viewModel().apply { + runBlockedSearch = { query -> + listOf(BlockedHit("+14155550133", "+1 415 555 0133", "free $query", "Mon", 2)) + } + } + vm.onQueryChange("prize") + advanceUntilIdle() + assertThat(vm.state.blockedHits.map { it.snippet }).containsExactly("free prize") + + vm.onQueryChange("p") + assertThat(vm.state.blockedHits).isEmpty() } @Test diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/AlwaysAllowPolicyTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/AlwaysAllowPolicyTest.kt new file mode 100644 index 00000000..5e429ae1 --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/AlwaysAllowPolicyTest.kt @@ -0,0 +1,31 @@ +package com.glooboo.umessage.ui.spam + +import com.glooboo.umessage.spam.ListKind +import com.glooboo.umessage.spam.RuleType +import com.glooboo.umessage.spam.SpamRule +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +/** spamui-21: when the Why-blocked dialog offers "Always allow". */ +class AlwaysAllowPolicyTest { + + private val number = "+14155550133" + + @Test + fun aNumberWithoutAnAllowRuleIsOffered() { + assertThat(AlwaysAllowPolicy.canOffer(emptyList(), number)).isTrue() + val block = SpamRule(1, ListKind.BLOCK, RuleType.NUMBER, number) + assertThat(AlwaysAllowPolicy.canOffer(listOf(block), number)).isTrue() + } + + @Test + fun aSenderThatIsAllowedAlreadyIsNotOffered() { + val allow = SpamRule(2, ListKind.ALLOW, RuleType.NUMBER, number) + assertThat(AlwaysAllowPolicy.canOffer(listOf(allow), number)).isFalse() + } + + @Test + fun aNameAnyoneCanFakeIsNeverOffered() { + assertThat(AlwaysAllowPolicy.canOffer(emptyList(), "BANK-X")).isFalse() + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedSearchTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedSearchTest.kt new file mode 100644 index 00000000..db47615c --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedSearchTest.kt @@ -0,0 +1,56 @@ +package com.glooboo.umessage.ui.spam + +import com.glooboo.umessage.spam.BlockedMessage +import com.glooboo.umessage.spam.DecisionReason +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +/** spamui-20: the search box of the Blocked screen filters the sender rows by sender and text. */ +class BlockedSearchTest { + + private fun msg(id: Long, address: String, body: String, at: Long = 1000L + id) = + BlockedMessage(id, address, body, 1, false, at, DecisionReason.UNKNOWN_SENDER) + + private val all = listOf( + msg(1, "+14155550133", "Win a free prize"), + msg(2, "+14155550133", "Second note"), + msg(3, "BANK-X", "Your code is 482913"), + msg(4, "+442071838750", "Meeting moved"), + ) + + @Test + fun aBlankQueryMatchesEverything() { + assertThat(all.all { BlockedFilters.matchesQuery(it, "") }).isTrue() + assertThat(all.all { BlockedFilters.matchesQuery(it, " ") }).isTrue() + } + + @Test + fun textIsMatchedWithoutRegardToCase() { + assertThat(all.filter { BlockedFilters.matchesQuery(it, "FREE PRIZE") }.map { it.id }).containsExactly(1L) + } + + @Test + fun theSenderIsMatchedByNameOrByNumberInAnyWrittenForm() { + assertThat(all.filter { BlockedFilters.matchesQuery(it, "bank") }.map { it.id }).containsExactly(3L) + assertThat(all.filter { BlockedFilters.matchesQuery(it, "415 555") }.map { it.id }).containsExactly(1L, 2L) + assertThat(all.filter { BlockedFilters.matchesQuery(it, "(207)183") }.map { it.id }).containsExactly(4L) + } + + @Test + fun persianLetterFormsAndDigitsAreFolded() { + val persian = msg(5, "+989121234567", "کد تایید 1234") + assertThat(BlockedFilters.matchesQuery(persian, "تاييد")).isTrue() + assertThat(BlockedFilters.matchesQuery(persian, "۱۲۳۴")).isTrue() + } + + /** A sender stays when one message matches and keeps ALL its messages, so Not spam still moves the whole sender. */ + @Test + fun aSenderRowKeepsAllItsMessages() { + val groups = groupBySender(all) + val found = BlockedFilters.searchGroups(groups, "free prize") + assertThat(found.map { it.address }).containsExactly("+14155550133") + assertThat(found.single().messages.map { it.id }).containsExactly(1L, 2L) + assertThat(BlockedFilters.searchGroups(groups, "nothing like this")).isEmpty() + assertThat(BlockedFilters.searchGroups(groups, "")).isEqualTo(groups) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModelActionsTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModelActionsTest.kt index aec4bbb6..5a861b5e 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModelActionsTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModelActionsTest.kt @@ -85,6 +85,33 @@ class BlockedViewModelActionsTest { assertThat(events).hasSize(1) } + /** spamui-21: the Why-blocked dialog's button stores the allow rule and leaves every message where it is. */ + @Test + fun alwaysAllowStoresTheRuleWithoutMovingMessagesAndUndoRemovesIt() { + vm.alwaysAllow(NUMBER) + awaitUntil { events.isNotEmpty() } + val event = events.single() as BlockedEvent.Restored + assertThat(event.count).isEqualTo(0) + assertThat(event.allowed).isEqualTo(1) + assertThat(allowRules().single().pattern).isEqualTo(NUMBER) + assertThat(allowRules().single().type).isEqualTo(RuleType.NUMBER) + assertThat(blocked()).hasSize(3) + assertThat(snack(event)).isEqualTo(app.resources.getQuantityString(R.plurals.spam_snack_allowed_only, 1, 1)) + + vm.undoRestore(event.token) + awaitUntil { allowRules().isEmpty() } + assertThat(blocked()).hasSize(3) + assertThat(rules().map { it.id }).contains(7L) + } + + @Test + fun alwaysAllowForANameAnyoneCanFakeDoesNothing() { + vm.alwaysAllow(SENDER_ID) + idleMain() + assertThat(allowRules()).isEmpty() + assertThat(events).isEmpty() + } + /** A name anyone can send under is never allowed: the messages move and no rule is made. */ @Test fun aSpoofableSenderOnlyMoves() { diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModelReview2Test.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModelReview2Test.kt index cc79d7bc..8149f4d4 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModelReview2Test.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModelReview2Test.kt @@ -101,8 +101,8 @@ class BlockedViewModelReview2Test { fun undoOfReleaseOnceBringsTheMessageBackAndUnlistsIt() { vm.releaseOnce(1) awaitUntil { events.isNotEmpty() } + awaitUntil { vm.state.value.restored.size == 1 } assertThat(blocked().none { it.id == 1L }).isTrue() - assertThat(vm.state.value.restored).hasSize(1) vm.undoRestore((events.single() as BlockedEvent.Restored).token) awaitUntil { LONE in vm.state.value.groups.map { it.address } } diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/RulesDecisionsTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/RulesDecisionsTest.kt new file mode 100644 index 00000000..9765caec --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/RulesDecisionsTest.kt @@ -0,0 +1,252 @@ +package com.glooboo.umessage.ui.spam + +import android.app.Application +import android.os.Looper +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.glooboo.umessage.spam.BlockedMessage +import com.glooboo.umessage.spam.ListKind +import com.glooboo.umessage.spam.RuleType +import com.glooboo.umessage.spam.SpamRepository +import com.glooboo.umessage.spam.SpamRule +import com.glooboo.umessage.spam.SpamSettings +import com.glooboo.umessage.spam.SpamStats +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import org.junit.After +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Shadows.shadowOf + +/** Rules screen decisions: website rules (spam-22), hit counts (spam-23), newest-first order (main-23), spam-15. */ +@RunWith(AndroidJUnit4::class) +class RulesDecisionsTest { + + private class Repo(initial: List) : SpamRepository { + val rulesState = MutableStateFlow(initial) + private var nextId = 100L + + override val blocked: Flow> = flowOf(emptyList()) + override val rules: Flow> = rulesState + override val settings: Flow = flowOf(SpamSettings()) + override val stats: Flow = flowOf(SpamStats(0, 0, 0)) + + override suspend fun addRule(rule: SpamRule): Long { + val id = nextId++ + rulesState.update { it + rule.copy(id = id) } + return id + } + + override suspend fun updateRule(rule: SpamRule): Long { + rulesState.update { list -> list.map { if (it.id == rule.id) rule else it } } + return rule.id + } + + override suspend fun removeRule(id: Long) = rulesState.update { list -> list.filterNot { it.id == id } } + override suspend fun updateSettings(transform: (SpamSettings) -> SpamSettings) = Unit + override suspend fun storeBlocked(message: BlockedMessage): Long = 0 + override suspend fun markNotSpam(blockedId: Long) = com.glooboo.umessage.spam.RestoreOutcome.NOT_FOUND + override suspend fun blockSender(blockedId: Long) = Unit + override suspend fun deleteBlocked(ids: List) = Unit + override suspend fun purgeExpired() = Unit + } + + private val app: Application = ApplicationProvider.getApplicationContext() + private val scope = CoroutineScope(Job() + Dispatchers.Main) + private lateinit var vm: RulesViewModel + + @After + fun tearDown() = scope.cancel() + + private fun start(rules: List = emptyList(), store: RulesOrderStore = MemoryRulesOrderStore()): Repo { + val repo = Repo(rules) + vm = RulesViewModel(app, repo, orderStore = store) + scope.launch { vm.state.collect { } } + awaitUntil { !vm.state.value.loading } + return repo + } + + private fun idleMain() = shadowOf(Looper.getMainLooper()).idle() + + private fun awaitUntil(condition: () -> Boolean) { + val deadline = System.currentTimeMillis() + 5_000 + while (true) { + idleMain() + if (condition()) return + check(System.currentTimeMillis() < deadline) { "condition not met; state=${vm.state.value}" } + Thread.sleep(10) + } + } + + private fun domain(value: String) = RuleValidator.validate(ListKind.BLOCK, RuleType.DOMAIN, value) + + // region spam-22 + + @Test + fun domainIsCleanedTheSameWayTheEngineCleansIt() { + assertThat(domain("example.com")).isEqualTo(RuleValidation.Valid("example.com")) + assertThat(domain(" HTTPS://Example.COM/shop?x=1 ")).isEqualTo(RuleValidation.Valid("example.com")) + assertThat(domain("*.example.com")).isEqualTo(RuleValidation.Valid("example.com")) + assertThat(domain("example[.]com")).isEqualTo(RuleValidation.Valid("example.com")) + assertThat(domain("www.example.com:8080/")).isEqualTo(RuleValidation.Valid("www.example.com")) + assertThat(domain("sub.example.co.uk.")).isEqualTo(RuleValidation.Valid("sub.example.co.uk")) + } + + @Test + fun domainWithoutADotOrWithJunkIsRefused() { + listOf( + "example", "localhost", "exa mple.com", "example.c", "-example.com", "exa_mple.com", "exam!ple.com", + "a..com", + ) + .forEach { assertThat(domain(it)).isEqualTo(RuleValidation.Invalid(RuleError.DOMAIN)) } + assertThat(domain("")).isEqualTo(RuleValidation.Invalid(RuleError.EMPTY)) + assertThat(domain("a".repeat(64) + ".com")).isEqualTo(RuleValidation.Invalid(RuleError.DOMAIN)) + } + + @Test + fun allowingADomainAsksForConfirmationLikeAnAllowedWord() { + assertThat(RuleValidator.warnings(ListKind.ALLOW, RuleType.DOMAIN, "example.com", emptyList(), null)) + .containsExactly(RuleWarning.ALLOW_SKIPS_BLOCKS) + assertThat(RuleValidator.warnings(ListKind.BLOCK, RuleType.DOMAIN, "example.com", emptyList(), null)).isEmpty() + } + + @Test + fun domainFormSavesTheCleanedNameAndSpotsDuplicates() { + val repo = start(listOf(SpamRule(1, ListKind.BLOCK, RuleType.DOMAIN, "example.com"))) + vm.selectTab(ListKind.BLOCK) + vm.openForm() + vm.setType(RuleType.DOMAIN) + vm.setPattern("https://Shop.Example.org/a") + idleMain() + assertThat(vm.state.value.form!!.canSubmit).isTrue() + vm.submitForm() + awaitUntil { vm.state.value.form == null } + assertThat(repo.rulesState.value.map { it.pattern }).containsExactly("example.com", "shop.example.org") + + vm.openForm() + vm.setType(RuleType.DOMAIN) + vm.setPattern("http://EXAMPLE.com") + idleMain() + assertThat(vm.state.value.form!!.visibleError?.error).isEqualTo(RuleError.DUPLICATE) + } + + @Test + fun domainRulesAreFoundBySearchAndTypeFilter() { + val rule = SpamRule(1, ListKind.BLOCK, RuleType.DOMAIN, "example.com") + assertThat(RuleSearch.matches(rule, "example")).isTrue() + assertThat(RuleSearch.matches(rule, "example", RuleType.DOMAIN)).isTrue() + assertThat(RuleSearch.matches(rule, "example", RuleType.KEYWORD)).isFalse() + assertThat(RulesSearchPolicy.chipTypes(listOf(rule, rule.copy(id = 2, type = RuleType.NUMBER)), null)) + .containsExactly(RuleType.NUMBER, RuleType.DOMAIN) + } + + @Test + fun domainRulesSurviveTheRulesFileRoundTrip() { + val text = RuleTextCodec.encode(listOf(SpamRule(1, ListKind.BLOCK, RuleType.DOMAIN, "example.com"))) + val parsed = RuleTextCodec.decode(text) + assertThat(parsed.invalidLines).isEqualTo(0) + assertThat(parsed.rules.single().type).isEqualTo(RuleType.DOMAIN) + } + + // endregion + + // region spam-23 + + private val day = 24L * 60 * 60 * 1000 + private val now = 1_800_000_000_000L + + @Test + fun hitAgeUsesTheLargestWholeUnit() { + assertThat(RuleHits.age(0, now)).isNull() + assertThat(RuleHits.age(now - 30_000, now)).isEqualTo(RuleHitAge(RuleHitUnit.NOW, 0)) + assertThat(RuleHits.age(now + 5_000, now)).isEqualTo(RuleHitAge(RuleHitUnit.NOW, 0)) + assertThat(RuleHits.age(now - 5 * 60_000, now)).isEqualTo(RuleHitAge(RuleHitUnit.MINUTES, 5)) + assertThat(RuleHits.age(now - 3 * 3_600_000, now)).isEqualTo(RuleHitAge(RuleHitUnit.HOURS, 3)) + assertThat(RuleHits.age(now - 3 * day, now)).isEqualTo(RuleHitAge(RuleHitUnit.DAYS, 3)) + assertThat(RuleHits.age(now - 29 * day, now)).isEqualTo(RuleHitAge(RuleHitUnit.DAYS, 29)) + assertThat(RuleHits.age(now - 65 * day, now)).isEqualTo(RuleHitAge(RuleHitUnit.MONTHS, 2)) + assertThat(RuleHits.age(now - 400 * day, now)).isEqualTo(RuleHitAge(RuleHitUnit.YEARS, 1)) + } + + @Test + fun hitTextIsEmptyForNoHitsAndNamesCountAndAge() { + val res = app.resources + val none = SpamRule(1, ListKind.BLOCK, RuleType.KEYWORD, "win") + assertThat(RuleHits.text(res, none, now)).isNull() + // A last-hit time without a count says nothing either. + assertThat(RuleHits.text(res, none.copy(lastHit = now - day), now)).isNull() + + val many = none.copy(hitCount = 12, lastHit = now - 3 * day) + assertThat(RuleHits.text(res, many, now)).isEqualTo("Blocked 12 messages, last 3 days ago") + assertThat(RuleHits.text(res, many.copy(hitCount = 1, lastHit = now - 3_600_000), now)) + .isEqualTo("Blocked 1 message, last 1 hour ago") + // Hits counted before the time was stored: the count alone. + assertThat(RuleHits.text(res, many.copy(lastHit = 0), now)).isEqualTo("Blocked 12 messages") + } + + // endregion + + // region main-23 + + private val old = SpamRule(1, ListKind.BLOCK, RuleType.KEYWORD, "a", createdAt = 500) + private val restoredLater = SpamRule(2, ListKind.BLOCK, RuleType.KEYWORD, "b", createdAt = 100) + private val newest = SpamRule(3, ListKind.BLOCK, RuleType.KEYWORD, "c", createdAt = 300) + + @Test + fun defaultOrderIsByAddedTimeAndNewestOrderByLastSaved() { + val rules = listOf(old, restoredLater, newest) + assertThat(RulesOrder.DEFAULT.apply(rules).map { it.id }).containsExactly(1L, 3L, 2L).inOrder() + assertThat(RulesOrder.NEWEST.apply(rules).map { it.id }).containsExactly(3L, 2L, 1L).inOrder() + } + + @Test + fun orderChoiceReordersTheListsAndIsRemembered() { + val store = MemoryRulesOrderStore() + start(listOf(old, restoredLater, newest), store) + assertThat(vm.state.value.order).isEqualTo(RulesOrder.DEFAULT) + assertThat(vm.state.value.blocked.map { it.id }).containsExactly(1L, 3L, 2L).inOrder() + + vm.setOrder(RulesOrder.NEWEST) + awaitUntil { + vm.state.value.order == RulesOrder.NEWEST && vm.state.value.blocked.map { it.id } == listOf(3L, 2L, 1L) + } + assertThat(vm.state.value.blocked.map { it.id }).containsExactly(3L, 2L, 1L).inOrder() + assertThat(store.load()).isEqualTo(RulesOrder.NEWEST) + + // A new screen starts with the remembered order. + start(listOf(old, restoredLater, newest), store) + awaitUntil { vm.state.value.blocked.map { it.id } == listOf(3L, 2L, 1L) } + assertThat(vm.state.value.order).isEqualTo(RulesOrder.NEWEST) + assertThat(vm.state.value.blocked.map { it.id }).containsExactly(3L, 2L, 1L).inOrder() + } + + // endregion + + // region spam-15 + + @Test + fun onlyBlockedWordsAndPatternsBlockTheSender() { + assertThat(RuleValidator.blocksSender(ListKind.BLOCK, RuleType.KEYWORD)).isTrue() + assertThat(RuleValidator.blocksSender(ListKind.BLOCK, RuleType.REGEX)).isTrue() + assertThat(RuleValidator.blocksSender(ListKind.ALLOW, RuleType.KEYWORD)).isFalse() + assertThat(RuleValidator.blocksSender(ListKind.BLOCK, RuleType.NUMBER)).isFalse() + assertThat(RuleValidator.blocksSender(ListKind.BLOCK, RuleType.DOMAIN)).isFalse() + } + + @Test + fun theAutomaticKeywordNoteStillMapsToItsCodeAndNowSaysTheSenderIsBlocked() { + assertThat(RuleNotes.codeOf("Blocked from a keyword")).isEqualTo(RuleNotes.BLOCKED_FROM_KEYWORD) + val text = RuleNotes.display(app.resources, RuleNotes.BLOCKED_FROM_KEYWORD) + assertThat(text).contains("whole sender") + } + + // endregion +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/thread/FailureReasonTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/FailureReasonTest.kt new file mode 100644 index 00000000..b23495d5 --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/FailureReasonTest.kt @@ -0,0 +1,61 @@ +package com.glooboo.umessage.ui.thread + +import android.provider.Telephony.Sms +import android.telephony.SmsManager +import com.glooboo.umessage.R +import com.glooboo.umessage.messaging.smsSendingErrorRes +import com.glooboo.umessage.models.Message +import com.glooboo.umessage.models.ThreadItem +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +/** Thread-27: the failed row carries the phone's stored reason, for texts only. */ +class FailureReasonTest { + + private fun failed(id: Long, isMms: Boolean = false) = Message( + id = id, body = "hi", type = Sms.MESSAGE_TYPE_FAILED, status = Sms.STATUS_NONE, participants = ArrayList(), + date = 100, read = true, threadId = 1, isMMS = isMms, attachment = null, senderPhoneNumber = "", + senderName = "", senderPhotoUri = "", subscriptionId = -1, + ) + + private fun errors(vararg messages: Message, codes: Map) = + buildThreadItems(messages.toList(), emptyMap(), seen = false, failureCodes = codes) + .items.filterIsInstance() + + @Test + fun aFailedTextCarriesItsStoredCode() { + val error = errors(failed(1), codes = mapOf(1L to SmsManager.RESULT_ERROR_NO_SERVICE)).single() + assertThat(error.reasonCode).isEqualTo(SmsManager.RESULT_ERROR_NO_SERVICE) + } + + @Test + fun aFailedTextWithoutAStoredCodeHasNone() { + assertThat(errors(failed(1), codes = emptyMap()).single().reasonCode).isEqualTo(0) + } + + @Test + fun aPictureMessageNeverTakesATextsCode() { + // Ids of texts and picture messages can be equal; the code belongs to the text only. + assertThat(errors(failed(1, isMms = true), codes = mapOf(1L to 4)).single().reasonCode).isEqualTo(0) + } + + @Test + fun theReasonRowsFollowTheItems() { + val items = buildThreadItems(listOf(failed(1)), emptyMap(), seen = false, failureCodes = mapOf(1L to 2)).items + val row = buildThreadRows(items, isGroup = false).filterIsInstance().single() + assertThat(row.reasonCode).isEqualTo(2) + } + + @Test + fun theCommonReasonsHaveTheirOwnWords() { + assertThat(smsSendingErrorRes(SmsManager.RESULT_ERROR_RADIO_OFF)).isEqualTo(R.string.error_radio_turned_off) + assertThat(smsSendingErrorRes(SmsManager.RESULT_ERROR_NO_SERVICE)) + .isEqualTo(R.string.error_service_is_unavailable) + } + + @Test + fun aGeneralFailureNamesNothingSpecific() { + assertThat(smsSendingErrorRes(SmsManager.RESULT_ERROR_GENERIC_FAILURE)) + .isEqualTo(R.string.message_not_sent_short) + } +} From 3e6a6f51605eac7be1cde69b219bfa9bc9ff78da Mon Sep 17 00:00:00 2001 From: Sajad <220944007+MyNameIsGlooboo@users.noreply.github.com> Date: Thu, 12 Nov 2026 07:32:50 +0000 Subject: [PATCH 3/5] Translate the new decided-item strings into 20 languages Co-Authored-By: Claude Sonnet 5.5 --- .../res/values-ar/strings_decisions_i18n.xml | 82 +++++++++++++++++++ .../res/values-bn/strings_decisions_i18n.xml | 54 ++++++++++++ .../res/values-de/strings_decisions_i18n.xml | 54 ++++++++++++ .../res/values-es/strings_decisions_i18n.xml | 54 ++++++++++++ .../res/values-fr/strings_decisions_i18n.xml | 54 ++++++++++++ .../res/values-hi/strings_decisions_i18n.xml | 54 ++++++++++++ .../res/values-in/strings_decisions_i18n.xml | 47 +++++++++++ .../res/values-it/strings_decisions_i18n.xml | 54 ++++++++++++ .../res/values-ja/strings_decisions_i18n.xml | 47 +++++++++++ .../res/values-ko/strings_decisions_i18n.xml | 47 +++++++++++ .../res/values-pl/strings_decisions_i18n.xml | 68 +++++++++++++++ .../values-pt-rBR/strings_decisions_i18n.xml | 54 ++++++++++++ .../res/values-ru/strings_decisions_i18n.xml | 68 +++++++++++++++ .../res/values-th/strings_decisions_i18n.xml | 47 +++++++++++ .../res/values-tr/strings_decisions_i18n.xml | 47 +++++++++++ .../res/values-uk/strings_decisions_i18n.xml | 68 +++++++++++++++ .../res/values-ur/strings_decisions_i18n.xml | 54 ++++++++++++ .../res/values-vi/strings_decisions_i18n.xml | 47 +++++++++++ .../values-zh-rCN/strings_decisions_i18n.xml | 47 +++++++++++ .../values-zh-rTW/strings_decisions_i18n.xml | 47 +++++++++++ 20 files changed, 1094 insertions(+) create mode 100644 app/src/main/res/values-ar/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-bn/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-de/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-es/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-fr/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-hi/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-in/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-it/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-ja/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-ko/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-pl/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-pt-rBR/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-ru/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-th/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-tr/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-uk/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-ur/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-vi/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-zh-rCN/strings_decisions_i18n.xml create mode 100644 app/src/main/res/values-zh-rTW/strings_decisions_i18n.xml diff --git a/app/src/main/res/values-ar/strings_decisions_i18n.xml b/app/src/main/res/values-ar/strings_decisions_i18n.xml new file mode 100644 index 00000000..c66279dd --- /dev/null +++ b/app/src/main/res/values-ar/strings_decisions_i18n.xml @@ -0,0 +1,82 @@ + + + + لم تُعلَّم أي محادثة كمقروءة (%d) + عُلِّمت محادثة واحدة (%d) كمقروءة + عُلِّمت محادثتان (%d) كمقروءتين + عُلِّمت %d محادثات كمقروءة + عُلِّمت %d محادثة كمقروءة + عُلِّمت %d محادثة كمقروءة + + الرسائل المحظورة + البحث في الرسائل المحظورة + ابحث بالمرسل أو النص + إغلاق البحث + لم يُعثر على شيء + لا يوجد مرسل أو رسالة محظورة تطابق ما كتبته. + السماح دائمًا + الكلمات المحظورة التي ستُضاف: %1$d. الكلمات الموجودة عندك أصلًا تُتخطّى. + أبلغ الهاتف عن فشل عام (الرمز %1$d) + رابط موقع إلكتروني + رابط داخل الرسالة + موقع إلكتروني + موقع إلكتروني + يحظر كل رسالة تحتوي على رابط لهذا الموقع، بما في ذلك نطاقاته الفرعية مثل www.example.com. + example.com + اكتب اسم موقع مثل example.com + + لم تُحظر أي رسالة (%d) + حُظرت رسالة واحدة (%d) + حُظرت رسالتان (%d) + حُظرت %d رسائل + حُظرت %d رسالة + حُظرت %d رسالة + + %1$s، وآخرها %2$s + قبل لحظات + + قبل %d دقيقة + قبل دقيقة (%d) + قبل دقيقتين (%d) + قبل %d دقائق + قبل %d دقيقة + قبل %d دقيقة + + + قبل %d ساعة + قبل ساعة (%d) + قبل ساعتين (%d) + قبل %d ساعات + قبل %d ساعة + قبل %d ساعة + + + قبل %d يوم + قبل يوم (%d) + قبل يومين (%d) + قبل %d أيام + قبل %d يومًا + قبل %d يوم + + + قبل %d شهر + قبل شهر (%d) + قبل شهرين (%d) + قبل %d أشهر + قبل %d شهرًا + قبل %d شهر + + + قبل %d سنة + قبل سنة (%d) + قبل سنتين (%d) + قبل %d سنوات + قبل %d سنة + قبل %d سنة + + الأحدث أولًا + تنبيه: هذا يحظر المرسل كله، لا الرسالة فقط. إذا كان بنك أو متجر يستخدم رقمًا واحدًا للرموز والإعلانات، فلن تصلك رسائله الحقيقية أيضًا. يمكنك إلغاء حظر المرسل من شاشة الرسائل المزعجة. + حظر كلمة يحظر المرسل + محظورة بسبب كلمة رئيسية (المرسل كله محظور) + قاعدة: روابط إلى %1$s + diff --git a/app/src/main/res/values-bn/strings_decisions_i18n.xml b/app/src/main/res/values-bn/strings_decisions_i18n.xml new file mode 100644 index 00000000..67307d27 --- /dev/null +++ b/app/src/main/res/values-bn/strings_decisions_i18n.xml @@ -0,0 +1,54 @@ + + + + %dটি চ্যাট পড়া হিসেবে মার্ক করা হয়েছে + %dটি চ্যাট পড়া হিসেবে মার্ক করা হয়েছে + + ব্লক করা বার্তা + ব্লক করা বার্তা খুঁজুন + প্রেরক বা লেখা দিয়ে খুঁজুন + খোঁজা বন্ধ করুন + কিছু পাওয়া যায়নি + আপনি যা লিখেছেন তার সঙ্গে মেলে এমন কোনো ব্লক করা প্রেরক বা বার্তা নেই। + সবসময় অনুমতি দিন + যোগ হবে এমন ব্লক করা শব্দ: %1$dটি। যে শব্দ আগে থেকেই আছে সেগুলো বাদ যাবে। + ফোন একটি সাধারণ ত্রুটি জানিয়েছে (কোড %1$d) + ওয়েবসাইটের লিংক + বার্তার ভেতরের লিংক + ওয়েবসাইট + ওয়েবসাইট + এই ওয়েবসাইটের লিংক আছে এমন প্রতিটি বার্তা ব্লক করে, www.example.com-এর মতো সাবডোমেনসহ। + example.com + example.com-এর মতো ওয়েবসাইটের নাম লিখুন + + %dটি বার্তা ব্লক করেছে + %dটি বার্তা ব্লক করেছে + + %1$s, শেষবার %2$s + এইমাত্র + + %d মিনিট আগে + %d মিনিট আগে + + + %d ঘণ্টা আগে + %d ঘণ্টা আগে + + + %d দিন আগে + %d দিন আগে + + + %d মাস আগে + %d মাস আগে + + + %d বছর আগে + %d বছর আগে + + নতুনগুলো আগে + সতর্কতা: এতে শুধু বার্তা নয়, পুরো প্রেরকই ব্লক হয়ে যায়। কোনো ব্যাংক বা দোকান কোড আর বিজ্ঞাপন, দুটোর জন্যই একই নম্বর ব্যবহার করলে তাদের আসল বার্তাও আর আসবে না। স্প্যাম স্ক্রিন থেকে প্রেরককে আনব্লক করতে পারবেন। + শব্দ ব্লক করলে প্রেরকও ব্লক হয় + কিওয়ার্ডের কারণে ব্লক করা হয়েছে (পুরো প্রেরক ব্লক) + নিয়ম: %1$s-এর লিংক + diff --git a/app/src/main/res/values-de/strings_decisions_i18n.xml b/app/src/main/res/values-de/strings_decisions_i18n.xml new file mode 100644 index 00000000..ac0f7271 --- /dev/null +++ b/app/src/main/res/values-de/strings_decisions_i18n.xml @@ -0,0 +1,54 @@ + + + + %d Chat als gelesen markiert + %d Chats als gelesen markiert + + Blockierte Nachrichten + Blockierte Nachrichten durchsuchen + Nach Absender oder Text suchen + Suche schließen + Nichts gefunden + Kein blockierter Absender und keine blockierte Nachricht passt zu deiner Eingabe. + Immer erlauben + Neue blockierte Wörter: %1$d. Wörter, die du schon hast, werden übersprungen. + Das Handy hat einen allgemeinen Fehler gemeldet (Code %1$d) + Ein Website-Link + Link in der Nachricht + Website + Website + Blockiert jede Nachricht, die auf diese Website verlinkt, auch auf ihre Subdomains wie www.example.com. + example.com + Gib einen Website-Namen wie example.com ein + + %d Nachricht blockiert + %d Nachrichten blockiert + + %1$s, zuletzt %2$s + gerade eben + + vor %d Minute + vor %d Minuten + + + vor %d Stunde + vor %d Stunden + + + vor %d Tag + vor %d Tagen + + + vor %d Monat + vor %d Monaten + + + vor %d Jahr + vor %d Jahren + + Neueste zuerst + Achtung: Das blockiert den ganzen Absender, nicht nur die Nachricht. Wenn eine Bank oder ein Shop dieselbe Nummer für Codes und Werbung nutzt, bekommst du auch seine echten Nachrichten nicht mehr. Einen Absender kannst du im Spam-Bildschirm wieder entblocken. + Ein Wort zu blockieren blockiert den Absender + Wegen eines Schlüsselworts blockiert (der ganze Absender ist blockiert) + Regel: Links zu %1$s + diff --git a/app/src/main/res/values-es/strings_decisions_i18n.xml b/app/src/main/res/values-es/strings_decisions_i18n.xml new file mode 100644 index 00000000..04fa8609 --- /dev/null +++ b/app/src/main/res/values-es/strings_decisions_i18n.xml @@ -0,0 +1,54 @@ + + + + %d chat marcado como leído + %d chats marcados como leídos + + Mensajes bloqueados + Buscar mensajes bloqueados + Buscar por remitente o texto + Cerrar búsqueda + No se encontró nada + Ningún remitente ni mensaje bloqueado coincide con lo que escribiste. + Permitir siempre + Palabras bloqueadas por añadir: %1$d. Las que ya tienes se omiten. + El teléfono informó de un fallo general (código %1$d) + Un enlace a un sitio web + Enlace en el mensaje + Sitio web + Sitio web + Bloquea todos los mensajes que enlacen a este sitio web, incluidos sus subdominios como www.example.com. + example.com + Escribe un nombre de sitio web como example.com + + %d mensaje bloqueado + %d mensajes bloqueados + + %1$s, el último %2$s + hace un momento + + hace %d minuto + hace %d minutos + + + hace %d hora + hace %d horas + + + hace %d día + hace %d días + + + hace %d mes + hace %d meses + + + hace %d año + hace %d años + + Más recientes primero + Ojo: esto bloquea a todo el remitente, no solo el mensaje. Si un banco o una tienda usa el mismo número para códigos y publicidad, dejarás de recibir también sus mensajes reales. Puedes desbloquear a un remitente en la pantalla de spam. + Bloquear una palabra bloquea al remitente + Bloqueado por una palabra clave (se bloquea a todo el remitente) + Regla: enlaces a %1$s + diff --git a/app/src/main/res/values-fr/strings_decisions_i18n.xml b/app/src/main/res/values-fr/strings_decisions_i18n.xml new file mode 100644 index 00000000..8f151f3d --- /dev/null +++ b/app/src/main/res/values-fr/strings_decisions_i18n.xml @@ -0,0 +1,54 @@ + + + + %d discussion marquée comme lue + %d discussions marquées comme lues + + Messages bloqués + Rechercher dans les messages bloqués + Rechercher par expéditeur ou texte + Fermer la recherche + Aucun résultat + Aucun expéditeur ni message bloqué ne correspond à votre saisie. + Toujours autoriser + Mots bloqués à ajouter : %1$d. Les mots que vous avez déjà sont ignorés. + Le téléphone a signalé une erreur générale (code %1$d) + Un lien vers un site web + Lien dans le message + Site web + Site web + Bloque tous les messages qui contiennent un lien vers ce site, y compris ses sous-domaines comme www.example.com. + example.com + Saisissez un nom de site comme example.com + + %d message bloqué + %d messages bloqués + + %1$s, dernier %2$s + à l\'instant + + il y a %d minute + il y a %d minutes + + + il y a %d heure + il y a %d heures + + + il y a %d jour + il y a %d jours + + + il y a %d mois + il y a %d mois + + + il y a %d an + il y a %d ans + + Les plus récents d\'abord + Attention : cela bloque tout l\'expéditeur, pas seulement le message. Si une banque ou une boutique utilise le même numéro pour ses codes et ses pubs, vous ne recevrez plus non plus ses vrais messages. Vous pouvez débloquer un expéditeur dans l\'écran Spam. + Bloquer un mot bloque l\'expéditeur + Bloqué à cause d\'un mot-clé (tout l\'expéditeur est bloqué) + Règle : liens vers %1$s + diff --git a/app/src/main/res/values-hi/strings_decisions_i18n.xml b/app/src/main/res/values-hi/strings_decisions_i18n.xml new file mode 100644 index 00000000..6cedc50d --- /dev/null +++ b/app/src/main/res/values-hi/strings_decisions_i18n.xml @@ -0,0 +1,54 @@ + + + + %d चैट पढ़ी हुई मार्क की गई + %d चैट पढ़ी हुई मार्क की गईं + + ब्लॉक किए गए मैसेज + ब्लॉक किए गए मैसेज खोजें + भेजने वाले या टेक्स्ट से खोजें + खोज बंद करें + कुछ नहीं मिला + आपने जो लिखा, उससे कोई ब्लॉक किया गया भेजने वाला या मैसेज मेल नहीं खाता. + हमेशा अनुमति दें + जोड़े जाने वाले ब्लॉक शब्द: %1$d. जो शब्द पहले से हैं, उन्हें छोड़ दिया जाएगा. + फ़ोन ने सामान्य गड़बड़ी बताई (कोड %1$d) + किसी वेबसाइट का लिंक + मैसेज में लिंक + वेबसाइट + वेबसाइट + इस वेबसाइट का लिंक वाले हर मैसेज को ब्लॉक करता है, इसके सबडोमेन (जैसे www.example.com) भी शामिल हैं. + example.com + example.com जैसा वेबसाइट का नाम डालें + + %d मैसेज ब्लॉक किया + %d मैसेज ब्लॉक किए + + %1$s, आखिरी बार %2$s + अभी-अभी + + %d मिनट पहले + %d मिनट पहले + + + %d घंटा पहले + %d घंटे पहले + + + %d दिन पहले + %d दिन पहले + + + %d महीना पहले + %d महीने पहले + + + %d साल पहले + %d साल पहले + + सबसे नए पहले + ध्यान दें: इससे सिर्फ़ मैसेज नहीं, पूरा भेजने वाला ब्लॉक हो जाता है. अगर कोई बैंक या दुकान कोड और विज्ञापन दोनों के लिए एक ही नंबर इस्तेमाल करती है, तो उसके असली मैसेज भी आने बंद हो जाएँगे. भेजने वाले को आप स्पैम स्क्रीन में अनब्लॉक कर सकते हैं. + शब्द ब्लॉक करने से भेजने वाला ब्लॉक होता है + कीवर्ड की वजह से ब्लॉक (पूरा भेजने वाला ब्लॉक है) + नियम: %1$s के लिंक + diff --git a/app/src/main/res/values-in/strings_decisions_i18n.xml b/app/src/main/res/values-in/strings_decisions_i18n.xml new file mode 100644 index 00000000..0d62e77a --- /dev/null +++ b/app/src/main/res/values-in/strings_decisions_i18n.xml @@ -0,0 +1,47 @@ + + + + %d obrolan ditandai sudah dibaca + + Pesan yang diblokir + Cari pesan yang diblokir + Cari berdasarkan pengirim atau teks + Tutup pencarian + Tidak ditemukan + Tidak ada pengirim atau pesan yang diblokir yang cocok dengan yang kamu ketik. + Selalu izinkan + Kata terblokir yang akan ditambahkan: %1$d. Kata yang sudah kamu punya dilewati. + Ponsel melaporkan kegagalan umum (kode %1$d) + Tautan situs web + Tautan dalam pesan + Situs web + Situs web + Memblokir setiap pesan yang berisi tautan ke situs web ini, termasuk subdomainnya seperti www.example.com. + example.com + Masukkan nama situs web seperti example.com + + %d pesan diblokir + + %1$s, terakhir %2$s + baru saja + + %d menit lalu + + + %d jam lalu + + + %d hari lalu + + + %d bulan lalu + + + %d tahun lalu + + Terbaru dulu + Perhatian: ini memblokir seluruh pengirim, bukan hanya pesannya. Kalau bank atau toko memakai satu nomor untuk kode dan iklan, pesan aslinya juga tidak akan masuk lagi. Kamu bisa membuka blokir pengirim di layar Spam. + Memblokir kata berarti memblokir pengirim + Diblokir karena kata kunci (seluruh pengirim diblokir) + Aturan: tautan ke %1$s + diff --git a/app/src/main/res/values-it/strings_decisions_i18n.xml b/app/src/main/res/values-it/strings_decisions_i18n.xml new file mode 100644 index 00000000..0e563d53 --- /dev/null +++ b/app/src/main/res/values-it/strings_decisions_i18n.xml @@ -0,0 +1,54 @@ + + + + %d chat segnata come letta + %d chat segnate come lette + + Messaggi bloccati + Cerca nei messaggi bloccati + Cerca per mittente o testo + Chiudi la ricerca + Nessun risultato + Nessun mittente o messaggio bloccato corrisponde a quello che hai scritto. + Consenti sempre + Parole bloccate da aggiungere: %1$d. Quelle che hai già vengono saltate. + Il telefono ha segnalato un errore generico (codice %1$d) + Un link a un sito web + Link nel messaggio + Sito web + Sito web + Blocca ogni messaggio che contiene un link a questo sito, compresi i suoi sottodomini come www.example.com. + example.com + Inserisci il nome di un sito come example.com + + %d messaggio bloccato + %d messaggi bloccati + + %1$s, l\'ultimo %2$s + poco fa + + %d minuto fa + %d minuti fa + + + %d ora fa + %d ore fa + + + %d giorno fa + %d giorni fa + + + %d mese fa + %d mesi fa + + + %d anno fa + %d anni fa + + Prima i più recenti + Attenzione: questo blocca tutto il mittente, non solo il messaggio. Se una banca o un negozio usa lo stesso numero per codici e pubblicità, non riceverai più nemmeno i suoi messaggi veri. Puoi sbloccare un mittente nella schermata Spam. + Bloccare una parola blocca il mittente + Bloccato da una parola chiave (è bloccato tutto il mittente) + Regola: link a %1$s + diff --git a/app/src/main/res/values-ja/strings_decisions_i18n.xml b/app/src/main/res/values-ja/strings_decisions_i18n.xml new file mode 100644 index 00000000..700f6f7b --- /dev/null +++ b/app/src/main/res/values-ja/strings_decisions_i18n.xml @@ -0,0 +1,47 @@ + + + + %d件のチャットを既読にしました + + ブロックしたメッセージ + ブロックしたメッセージを検索 + 送信者または本文で検索 + 検索を閉じる + 見つかりませんでした + 入力した内容に一致するブロック済みの送信者やメッセージはありません。 + 常に許可 + 追加するブロックワード:%1$d件。すでにあるワードはスキップされます。 + 端末から一般的なエラーが報告されました(コード%1$d) + ウェブサイトへのリンク + メッセージ内のリンク + ウェブサイト + ウェブサイト + このウェブサイトへのリンクを含むメッセージをすべてブロックします。www.example.comのようなサブドメインも対象です。 + example.com + example.comのようなウェブサイト名を入力してください + + %d件のメッセージをブロック + + %1$s、最後は%2$s + たった今 + + %d分前 + + + %d時間前 + + + %d日前 + + + %dか月前 + + + %d年前 + + 新しい順 + ご注意:これはメッセージだけでなく、送信者をまるごとブロックします。銀行やお店が認証コードと広告に同じ番号を使っている場合、本物のメッセージも届かなくなります。送信者のブロックは迷惑メッセージ画面で解除できます。 + ワードをブロックすると送信者もブロックされます + キーワードによりブロック(送信者全体がブロックされています) + ルール:%1$sへのリンク + diff --git a/app/src/main/res/values-ko/strings_decisions_i18n.xml b/app/src/main/res/values-ko/strings_decisions_i18n.xml new file mode 100644 index 00000000..4af04769 --- /dev/null +++ b/app/src/main/res/values-ko/strings_decisions_i18n.xml @@ -0,0 +1,47 @@ + + + + 채팅 %d개를 읽음으로 표시했어요 + + 차단된 메시지 + 차단된 메시지 검색 + 발신자 또는 내용으로 검색 + 검색 닫기 + 결과가 없어요 + 입력한 내용과 일치하는 차단된 발신자나 메시지가 없어요. + 항상 허용 + 추가할 차단 단어: %1$d개. 이미 있는 단어는 건너뛰어요. + 휴대폰에서 일반 오류를 알려 왔어요(코드 %1$d) + 웹사이트 링크 + 메시지 속 링크 + 웹사이트 + 웹사이트 + 이 웹사이트로 연결되는 링크가 있는 메시지를 모두 차단해요. www.example.com 같은 하위 도메인도 포함돼요. + example.com + example.com 같은 웹사이트 이름을 입력하세요 + + 메시지 %d건 차단 + + %1$s, 마지막은 %2$s + 방금 + + %d분 전 + + + %d시간 전 + + + %d일 전 + + + %d개월 전 + + + %d년 전 + + 최신순 + 주의: 메시지 하나가 아니라 발신자 전체를 차단해요. 은행이나 쇼핑몰이 인증번호와 광고에 같은 번호를 쓰면 정상 메시지도 받지 못하게 돼요. 스팸 화면에서 발신자 차단을 해제할 수 있어요. + 단어를 차단하면 발신자가 차단돼요 + 키워드로 차단됨(발신자 전체가 차단돼요) + 규칙: %1$s(으)로 연결되는 링크 + diff --git a/app/src/main/res/values-pl/strings_decisions_i18n.xml b/app/src/main/res/values-pl/strings_decisions_i18n.xml new file mode 100644 index 00000000..fe4764e1 --- /dev/null +++ b/app/src/main/res/values-pl/strings_decisions_i18n.xml @@ -0,0 +1,68 @@ + + + Słowa do zablokowania do dodania: %1$d. Słowa, które już masz, są pomijane. + Reguła: linki do %1$s + Zablokowane wiadomości + Szukaj w zablokowanych wiadomościach + Szukaj po nadawcy lub treści + Zamknij wyszukiwanie + Nic nie znaleziono + Żaden zablokowany nadawca ani wiadomość nie pasuje do wpisanego tekstu. + Zawsze zezwalaj + Link do strony + Link w wiadomości + Strona + Strona + Blokuje każdą wiadomość z linkiem do tej strony, także do jej subdomen, np. www.example.com. + example.com + Wpisz nazwę strony, np. example.com + %1$s, ostatnio %2$s + przed chwilą + Najpierw najnowsze + Uwaga: to blokuje całego nadawcę, a nie tylko tę wiadomość. Jeśli bank lub sklep używa jednego numeru do kodów i do reklam, przestaniesz dostawać także jego prawdziwe wiadomości. Nadawcę możesz odblokować na ekranie Spam. + Zablokowanie słowa blokuje nadawcę + Zablokowano przez słowo kluczowe (zablokowany jest cały nadawca) + Telefon zgłosił ogólny błąd (kod %1$d) + + %d czat oznaczony jako przeczytany + %d czaty oznaczone jako przeczytane + %d czatów oznaczonych jako przeczytane + %d czatu oznaczonego jako przeczytane + + + Zablokowano %d wiadomość + Zablokowano %d wiadomości + Zablokowano %d wiadomości + Zablokowano %d wiadomości + + + %d minutę temu + %d minuty temu + %d minut temu + %d minuty temu + + + %d godzinę temu + %d godziny temu + %d godzin temu + %d godziny temu + + + %d dzień temu + %d dni temu + %d dni temu + %d dnia temu + + + %d miesiąc temu + %d miesiące temu + %d miesięcy temu + %d miesiąca temu + + + %d rok temu + %d lata temu + %d lat temu + %d roku temu + + diff --git a/app/src/main/res/values-pt-rBR/strings_decisions_i18n.xml b/app/src/main/res/values-pt-rBR/strings_decisions_i18n.xml new file mode 100644 index 00000000..1833750c --- /dev/null +++ b/app/src/main/res/values-pt-rBR/strings_decisions_i18n.xml @@ -0,0 +1,54 @@ + + + Palavras bloqueadas a adicionar: %1$d. As palavras que você já tem são ignoradas. + Regra: links para %1$s + Mensagens bloqueadas + Pesquisar mensagens bloqueadas + Pesquise por remetente ou texto + Fechar pesquisa + Nada encontrado + Nenhum remetente ou mensagem bloqueada corresponde ao que você digitou. + Sempre permitir + Um link de site + Link na mensagem + Site + Site + Bloqueia toda mensagem que tenha link para este site, inclusive de subdomínios, como www.example.com. + example.com + Digite o nome de um site, como example.com + %1$s, última vez %2$s + agora há pouco + Mais recentes primeiro + Atenção: isso bloqueia o remetente inteiro, não só a mensagem. Se um banco ou loja usa o mesmo número para códigos e propagandas, você também deixará de receber as mensagens verdadeiras dele. Você pode desbloquear um remetente na tela Spam. + Bloquear uma palavra bloqueia o remetente + Bloqueado por uma palavra-chave (o remetente inteiro está bloqueado) + O celular informou uma falha geral (código %1$d) + + %d conversa marcada como lida + %d conversas marcadas como lidas + + + %d mensagem bloqueada + %d mensagens bloqueadas + + + há %d minuto + há %d minutos + + + há %d hora + há %d horas + + + há %d dia + há %d dias + + + há %d mês + há %d meses + + + há %d ano + há %d anos + + diff --git a/app/src/main/res/values-ru/strings_decisions_i18n.xml b/app/src/main/res/values-ru/strings_decisions_i18n.xml new file mode 100644 index 00000000..30065833 --- /dev/null +++ b/app/src/main/res/values-ru/strings_decisions_i18n.xml @@ -0,0 +1,68 @@ + + + Заблокированных слов для добавления: %1$d. Слова, которые у вас уже есть, пропускаются. + Правило: ссылки на %1$s + Заблокированные сообщения + Поиск по заблокированным сообщениям + Поиск по отправителю или тексту + Закрыть поиск + Ничего не найдено + Ни один заблокированный отправитель или сообщение не подходит под ваш запрос. + Всегда разрешать + Ссылка на сайт + Ссылка в сообщении + Сайт + Сайт + Блокирует все сообщения со ссылкой на этот сайт, в том числе на его поддомены, например www.example.com. + example.com + Введите название сайта, например example.com + %1$s, последнее: %2$s + только что + Сначала новые + Внимание: так блокируется весь отправитель, а не только это сообщение. Если банк или магазин присылает коды и рекламу с одного номера, вы перестанете получать и его настоящие сообщения. Разблокировать отправителя можно на экране «Спам». + Блокировка слова блокирует отправителя + Заблокировано по ключевому слову (заблокирован весь отправитель) + Телефон сообщил об общей ошибке (код %1$d) + + %d чат отмечен как прочитанный + %d чата отмечены как прочитанные + %d чатов отмечено как прочитанные + %d чата отмечено как прочитанные + + + Заблокировано %d сообщение + Заблокировано %d сообщения + Заблокировано %d сообщений + Заблокировано %d сообщения + + + %d минуту назад + %d минуты назад + %d минут назад + %d минуты назад + + + %d час назад + %d часа назад + %d часов назад + %d часа назад + + + %d день назад + %d дня назад + %d дней назад + %d дня назад + + + %d месяц назад + %d месяца назад + %d месяцев назад + %d месяца назад + + + %d год назад + %d года назад + %d лет назад + %d года назад + + diff --git a/app/src/main/res/values-th/strings_decisions_i18n.xml b/app/src/main/res/values-th/strings_decisions_i18n.xml new file mode 100644 index 00000000..203122d3 --- /dev/null +++ b/app/src/main/res/values-th/strings_decisions_i18n.xml @@ -0,0 +1,47 @@ + + + คำที่บล็อกและจะเพิ่ม: %1$d คำ คำที่คุณมีอยู่แล้วจะถูกข้ามไป + กฎ: ลิงก์ไปยัง %1$s + ข้อความที่ถูกบล็อก + ค้นหาข้อความที่ถูกบล็อก + ค้นหาจากผู้ส่งหรือข้อความ + ปิดการค้นหา + ไม่พบอะไร + ไม่มีผู้ส่งหรือข้อความที่ถูกบล็อกตรงกับที่คุณพิมพ์ + อนุญาตเสมอ + ลิงก์เว็บไซต์ + ลิงก์ในข้อความ + เว็บไซต์ + เว็บไซต์ + บล็อกทุกข้อความที่มีลิงก์ไปยังเว็บไซต์นี้ รวมถึงซับโดเมน เช่น www.example.com + example.com + ใส่ชื่อเว็บไซต์ เช่น example.com + %1$s ล่าสุด %2$s + เมื่อสักครู่ + ใหม่สุดก่อน + โปรดทราบ: การทำแบบนี้จะบล็อกผู้ส่งทั้งหมด ไม่ใช่แค่ข้อความนี้ ถ้าธนาคารหรือร้านค้าใช้เบอร์เดียวกันส่งทั้งรหัสและโฆษณา คุณจะไม่ได้รับข้อความจริงของเขาด้วย คุณปลดบล็อกผู้ส่งได้ในหน้าสแปม + การบล็อกคำจะบล็อกผู้ส่งด้วย + ถูกบล็อกจากคำสำคัญ (บล็อกผู้ส่งทั้งหมด) + โทรศัพท์แจ้งว่าเกิดข้อผิดพลาดทั่วไป (รหัส %1$d) + + ทำเครื่องหมายว่าอ่านแล้ว %d แชต + + + บล็อกไปแล้ว %d ข้อความ + + + %d นาทีที่แล้ว + + + %d ชั่วโมงที่แล้ว + + + %d วันที่แล้ว + + + %d เดือนที่แล้ว + + + %d ปีที่แล้ว + + diff --git a/app/src/main/res/values-tr/strings_decisions_i18n.xml b/app/src/main/res/values-tr/strings_decisions_i18n.xml new file mode 100644 index 00000000..324a5318 --- /dev/null +++ b/app/src/main/res/values-tr/strings_decisions_i18n.xml @@ -0,0 +1,47 @@ + + + Eklenecek engellenen kelime sayısı: %1$d. Zaten olan kelimeler atlanır. + Kural: %1$s bağlantıları + Engellenen mesajlar + Engellenen mesajlarda ara + Gönderene veya metne göre ara + Aramayı kapat + Bir şey bulunamadı + Yazdığınızla eşleşen engellenmiş gönderen ya da mesaj yok. + Her zaman izin ver + Bir web sitesi bağlantısı + Mesajdaki bağlantı + Web sitesi + Web sitesi + Bu web sitesine bağlantı veren her mesajı engeller, www.example.com gibi alt alan adları da dahil. + example.com + example.com gibi bir web sitesi adı girin + %1$s, son: %2$s + az önce + Önce en yeni + Dikkat: Bu, yalnızca mesajı değil gönderenin tamamını engeller. Bir banka ya da mağaza kodlar ve reklamlar için aynı numarayı kullanıyorsa, onun gerçek mesajlarını da almazsınız. Bir göndereni Spam ekranından engelden çıkarabilirsiniz. + Kelime engellemek göndereni engeller + Anahtar kelimeyle engellendi (gönderenin tamamı engelli) + Telefon genel bir hata bildirdi (kod %1$d) + + %d sohbet okundu olarak işaretlendi + + + %d mesaj engellendi + + + %d dakika önce + + + %d saat önce + + + %d gün önce + + + %d ay önce + + + %d yıl önce + + diff --git a/app/src/main/res/values-uk/strings_decisions_i18n.xml b/app/src/main/res/values-uk/strings_decisions_i18n.xml new file mode 100644 index 00000000..7fe11842 --- /dev/null +++ b/app/src/main/res/values-uk/strings_decisions_i18n.xml @@ -0,0 +1,68 @@ + + + Заблокованих слів для додавання: %1$d. Слова, які у вас уже є, пропускаються. + Правило: посилання на %1$s + Заблоковані повідомлення + Пошук у заблокованих повідомленнях + Пошук за відправником або текстом + Закрити пошук + Нічого не знайдено + Жоден заблокований відправник чи повідомлення не збігається з тим, що ви ввели. + Завжди дозволяти + Посилання на сайт + Посилання в повідомленні + Сайт + Сайт + Блокує всі повідомлення з посиланням на цей сайт, зокрема на його піддомени, наприклад www.example.com. + example.com + Введіть назву сайту, наприклад example.com + %1$s, востаннє: %2$s + щойно + Спочатку нові + Увага: так блокується весь відправник, а не лише це повідомлення. Якщо банк або магазин надсилає коди й рекламу з одного номера, ви перестанете отримувати й його справжні повідомлення. Розблокувати відправника можна на екрані «Спам». + Блокування слова блокує відправника + Заблоковано за ключовим словом (заблоковано всього відправника) + Телефон повідомив про загальну помилку (код %1$d) + + %d чат позначено як прочитаний + %d чати позначено як прочитані + %d чатів позначено як прочитані + %d чату позначено як прочитані + + + Заблоковано %d повідомлення + Заблоковано %d повідомлення + Заблоковано %d повідомлень + Заблоковано %d повідомлення + + + %d хвилину тому + %d хвилини тому + %d хвилин тому + %d хвилини тому + + + %d годину тому + %d години тому + %d годин тому + %d години тому + + + %d день тому + %d дні тому + %d днів тому + %d дня тому + + + %d місяць тому + %d місяці тому + %d місяців тому + %d місяця тому + + + %d рік тому + %d роки тому + %d років тому + %d року тому + + diff --git a/app/src/main/res/values-ur/strings_decisions_i18n.xml b/app/src/main/res/values-ur/strings_decisions_i18n.xml new file mode 100644 index 00000000..690ff6b4 --- /dev/null +++ b/app/src/main/res/values-ur/strings_decisions_i18n.xml @@ -0,0 +1,54 @@ + + + شامل کرنے کے لیے بلاک کیے گئے الفاظ: %1$d۔ جو الفاظ پہلے سے موجود ہیں انہیں چھوڑ دیا جائے گا۔ + اصول: %1$s کے لنکس + بلاک کیے گئے پیغامات + بلاک کیے گئے پیغامات میں تلاش کریں + بھیجنے والے یا متن سے تلاش کریں + تلاش بند کریں + کچھ نہیں ملا + آپ کے لکھے سے کوئی بلاک شدہ بھیجنے والا یا پیغام میل نہیں کھاتا۔ + ہمیشہ اجازت دیں + ویب سائٹ کا لنک + پیغام میں لنک + ویب سائٹ + ویب سائٹ + اس ویب سائٹ کا لنک رکھنے والا ہر پیغام بلاک کر دیتا ہے، اس کے سب ڈومینز جیسے www.example.com سمیت۔ + example.com + ویب سائٹ کا نام لکھیں، جیسے example.com + %1$s، آخری بار %2$s + ابھی ابھی + پہلے سب سے نئے + دھیان رکھیں: اس سے پورا بھیجنے والا بلاک ہو جاتا ہے، صرف یہ پیغام نہیں۔ اگر کوئی بینک یا دکان کوڈز اور اشتہارات کے لیے ایک ہی نمبر استعمال کرتی ہے تو اس کے اصلی پیغامات بھی آنا بند ہو جائیں گے۔ آپ کسی بھیجنے والے کو اسپیم اسکرین میں انبلاک کر سکتے ہیں۔ + لفظ بلاک کرنے سے بھیجنے والا بلاک ہو جاتا ہے + کلیدی لفظ کی وجہ سے بلاک (پورا بھیجنے والا بلاک ہے) + فون نے عمومی خرابی بتائی (کوڈ %1$d) + + %d چیٹ پڑھی ہوئی نشان زد + %d چیٹس پڑھی ہوئی نشان زد + + + %d پیغام بلاک کیا + %d پیغامات بلاک کیے + + + %d منٹ پہلے + %d منٹ پہلے + + + %d گھنٹہ پہلے + %d گھنٹے پہلے + + + %d دن پہلے + %d دن پہلے + + + %d مہینہ پہلے + %d مہینے پہلے + + + %d سال پہلے + %d سال پہلے + + diff --git a/app/src/main/res/values-vi/strings_decisions_i18n.xml b/app/src/main/res/values-vi/strings_decisions_i18n.xml new file mode 100644 index 00000000..55474058 --- /dev/null +++ b/app/src/main/res/values-vi/strings_decisions_i18n.xml @@ -0,0 +1,47 @@ + + + Số từ bị chặn sẽ thêm: %1$d. Những từ bạn đã có sẽ được bỏ qua. + Quy tắc: liên kết đến %1$s + Tin nhắn bị chặn + Tìm trong tin nhắn bị chặn + Tìm theo người gửi hoặc nội dung + Đóng tìm kiếm + Không tìm thấy gì + Không có người gửi hay tin nhắn bị chặn nào khớp với nội dung bạn nhập. + Luôn cho phép + Liên kết đến một trang web + Liên kết trong tin nhắn + Trang web + Trang web + Chặn mọi tin nhắn có liên kết đến trang web này, kể cả các tên miền phụ như www.example.com. + example.com + Nhập tên trang web, ví dụ example.com + %1$s, lần gần nhất %2$s + vừa xong + Mới nhất trước + Lưu ý: cách này chặn cả người gửi chứ không chỉ tin nhắn này. Nếu ngân hàng hay cửa hàng dùng chung một số cho cả mã xác nhận lẫn quảng cáo, bạn sẽ không nhận được cả tin nhắn thật của họ. Bạn có thể bỏ chặn người gửi trong màn hình Tin rác. + Chặn một từ sẽ chặn cả người gửi + Bị chặn do từ khóa (chặn cả người gửi) + Điện thoại báo lỗi chung (mã %1$d) + + Đã đánh dấu %d cuộc trò chuyện là đã đọc + + + Đã chặn %d tin nhắn + + + %d phút trước + + + %d giờ trước + + + %d ngày trước + + + %d tháng trước + + + %d năm trước + + diff --git a/app/src/main/res/values-zh-rCN/strings_decisions_i18n.xml b/app/src/main/res/values-zh-rCN/strings_decisions_i18n.xml new file mode 100644 index 00000000..2feacce9 --- /dev/null +++ b/app/src/main/res/values-zh-rCN/strings_decisions_i18n.xml @@ -0,0 +1,47 @@ + + + 要添加的屏蔽词:%1$d 个。已有的词会被跳过。 + 规则:指向 %1$s 的链接 + 被屏蔽的消息 + 搜索被屏蔽的消息 + 按发件人或内容搜索 + 关闭搜索 + 没有找到 + 没有被屏蔽的发件人或消息与你输入的内容匹配。 + 始终允许 + 网站链接 + 消息中的链接 + 网站 + 网站 + 屏蔽所有带有此网站链接的消息,包括它的子域名,例如 www.example.com。 + example.com + 请输入网站名称,例如 example.com + %1$s,最近一次:%2$s + 刚刚 + 最新的在前 + 注意:这会屏蔽整个发件人,而不只是这条消息。如果银行或商店用同一个号码发验证码和广告,你也会收不到它的正常消息。你可以在垃圾短信页面解除对发件人的屏蔽。 + 屏蔽词会屏蔽发件人 + 因关键词被屏蔽(整个发件人都被屏蔽) + 手机报告了一般性故障(代码 %1$d) + + 已将 %d 个对话标为已读 + + + 已屏蔽 %d 条消息 + + + %d 分钟前 + + + %d 小时前 + + + %d 天前 + + + %d 个月前 + + + %d 年前 + + diff --git a/app/src/main/res/values-zh-rTW/strings_decisions_i18n.xml b/app/src/main/res/values-zh-rTW/strings_decisions_i18n.xml new file mode 100644 index 00000000..f4455863 --- /dev/null +++ b/app/src/main/res/values-zh-rTW/strings_decisions_i18n.xml @@ -0,0 +1,47 @@ + + + 要新增的封鎖字詞:%1$d 個。已有的字詞會略過。 + 規則:連到 %1$s 的連結 + 被封鎖的訊息 + 搜尋被封鎖的訊息 + 依寄件者或內容搜尋 + 關閉搜尋 + 找不到結果 + 沒有被封鎖的寄件者或訊息符合你輸入的內容。 + 一律允許 + 網站連結 + 訊息中的連結 + 網站 + 網站 + 封鎖所有含有此網站連結的訊息,包括它的子網域,例如 www.example.com。 + example.com + 請輸入網站名稱,例如 example.com + %1$s,最近一次:%2$s + 剛剛 + 最新的在前 + 注意:這會封鎖整個寄件者,而不只是這則訊息。如果銀行或商店用同一個號碼發驗證碼和廣告,你也會收不到它的正常訊息。你可以在垃圾訊息頁面解除封鎖寄件者。 + 封鎖字詞會封鎖寄件者 + 因關鍵字被封鎖(整個寄件者都被封鎖) + 手機回報一般性失敗(代碼 %1$d) + + 已將 %d 個對話標為已讀 + + + 已封鎖 %d 則訊息 + + + %d 分鐘前 + + + %d 小時前 + + + %d 天前 + + + %d 個月前 + + + %d 年前 + + From aeb98377954bd39f763aee401c00b1e92ef3b7e8 Mon Sep 17 00:00:00 2001 From: Sajad <220944007+MyNameIsGlooboo@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:05:06 +0000 Subject: [PATCH 4/5] Apply minor review findings (triage section 4) Backup/settings, core sending and reminders, helpers and main list, misc and thread, spam engine and Blocked screen fixes. Skipped with reason: backup-17, spam-8b, spam-12, spam-16, spam-18, spam-20, helpers-18 (needs schema), helpers-23; partly done: spamui-17, core-13, core-16. Co-Authored-By: Claude Sonnet 5.5 --- .../activities/ConversationDetailsActivity.kt | 5 ++ .../glooboo/umessage/activities/MainRoutes.kt | 1 + .../ManageBlockedKeywordsActivity.kt | 82 +++++++++++++------ .../activities/NewConversationActivity.kt | 6 ++ .../umessage/activities/SettingsActivity.kt | 26 +++++- .../umessage/activities/ThreadActivity.kt | 7 ++ .../umessage/dialogs/ScheduleMessageDialog.kt | 3 +- .../glooboo/umessage/extensions/Context.kt | 17 ++-- .../umessage/helpers/ConversationListSync.kt | 25 +++++- .../helpers/smartreply/SmartReplyPolicy.kt | 3 +- .../glooboo/umessage/messaging/Messaging.kt | 22 +++++ .../messaging/ScheduledAttachments.kt | 7 +- .../glooboo/umessage/messaging/SentParts.kt | 3 + .../glooboo/umessage/messaging/StaleOutbox.kt | 3 + .../glooboo/umessage/models/Conversation.kt | 9 +- .../umessage/receivers/MmsPushReceiver.kt | 2 +- .../glooboo/umessage/receivers/MmsReceiver.kt | 17 +++- .../umessage/receivers/ReminderReceiver.kt | 9 +- .../receivers/ScheduledMessageReceiver.kt | 25 +++++- .../services/HeadlessSmsSendService.kt | 16 +++- .../glooboo/umessage/spam/TextNormalizer.kt | 9 ++ .../spam/data/DefaultSpamRepository.kt | 3 + .../umessage/spam/data/ForwardDelivery.kt | 9 +- .../umessage/spam/data/SpamSettingsStore.kt | 6 ++ .../spam/engine/AndroidSpamEnvironment.kt | 5 +- .../umessage/spam/engine/SpamEngine.kt | 11 ++- .../umessage/spam/mms/BlockedMmsDownloader.kt | 19 ++++- .../umessage/spam/mms/BlockedMmsPolicy.kt | 21 +++++ .../glooboo/umessage/spam/mms/MmsPushGate.kt | 15 +++- .../ui/components/PhoneNumberDisplay.kt | 28 +++++-- .../umessage/ui/components/SettingsRows.kt | 8 ++ .../ui/conversations/ContactAvatar.kt | 18 +++- .../ui/conversations/ConversationsModels.kt | 1 + .../ui/conversations/ConversationsScreen.kt | 6 +- .../conversations/ConversationsViewModel.kt | 14 +++- .../ui/conversations/ThreadSimCache.kt | 27 ++++-- .../umessage/ui/forwarded/ForwardedModels.kt | 3 + .../umessage/ui/forwarded/ForwardedScreen.kt | 5 ++ .../ui/forwarded/ForwardedViewModel.kt | 19 ++++- .../glooboo/umessage/ui/labels/LabelsState.kt | 4 +- .../umessage/ui/labels/LabelsViewModel.kt | 7 +- .../glooboo/umessage/ui/main/MainSearch.kt | 4 + .../umessage/ui/main/MainSearchViewModel.kt | 1 + .../ui/newconversation/ContactListLogic.kt | 9 +- .../ui/scheduled/ScheduledStateReader.kt | 17 +++- .../umessage/ui/settings/SimNamesDialog.kt | 26 ++++-- .../glooboo/umessage/ui/spam/BlockedHints.kt | 6 +- .../glooboo/umessage/ui/spam/BlockedScreen.kt | 6 +- .../glooboo/umessage/ui/spam/BlockedThread.kt | 10 ++- .../umessage/ui/spam/BlockedViewModel.kt | 11 ++- .../umessage/ui/spam/CarrierReportUi.kt | 2 +- .../umessage/ui/spam/ForwardOwnNumbers.kt | 45 ++++++---- .../glooboo/umessage/ui/spam/PatternBlock.kt | 2 +- .../umessage/ui/theme/UMessageTheme.kt | 2 +- .../ui/thread/ThreadPeopleController.kt | 6 +- .../umessage/ui/thread/ThreadRecipients.kt | 13 +++ .../umessage/ui/thread/ThreadScreen.kt | 3 +- .../umessage/ui/thread/ThreadViewModel.kt | 7 ++ .../main/res/values-fa/strings_minor_core.xml | 4 + .../main/res/values-fa/strings_minor_mt.xml | 4 + .../main/res/values-fa/strings_minor_sui.xml | 6 ++ .../main/res/values/strings_minor_core.xml | 4 + app/src/main/res/values/strings_minor_mt.xml | 4 + app/src/main/res/values/strings_minor_sui.xml | 6 ++ .../com/glooboo/umessage/MinorHmTest.kt | 49 +++++++++++ .../smartreply/SmartReplyPolicyTest.kt | 2 + .../messaging/ScheduledAttachmentsTest.kt | 3 +- .../spam/data/DefaultSpamRepositoryTest.kt | 14 +++- .../spam/data/SpamSettingsStoreTest.kt | 7 ++ .../umessage/spam/mms/BlockedMmsPolicyTest.kt | 20 +++++ .../umessage/ui/spam/BlockedHintsTest.kt | 6 ++ .../umessage/ui/spam/BlockedRound2S1Test.kt | 4 +- .../ui/spam/BlockedViewModelActionsTest.kt | 2 +- .../ui/thread/ThreadViewModelStateTest.kt | 3 +- .../umessage/ui/thread/TypedNumberTest.kt | 27 ++++++ 75 files changed, 731 insertions(+), 130 deletions(-) create mode 100644 app/src/main/kotlin/com/glooboo/umessage/spam/mms/BlockedMmsPolicy.kt create mode 100644 app/src/main/res/values-fa/strings_minor_core.xml create mode 100644 app/src/main/res/values-fa/strings_minor_mt.xml create mode 100644 app/src/main/res/values-fa/strings_minor_sui.xml create mode 100644 app/src/main/res/values/strings_minor_core.xml create mode 100644 app/src/main/res/values/strings_minor_mt.xml create mode 100644 app/src/main/res/values/strings_minor_sui.xml create mode 100644 app/src/test/kotlin/com/glooboo/umessage/MinorHmTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/spam/mms/BlockedMmsPolicyTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/ui/thread/TypedNumberTest.kt diff --git a/app/src/main/kotlin/com/glooboo/umessage/activities/ConversationDetailsActivity.kt b/app/src/main/kotlin/com/glooboo/umessage/activities/ConversationDetailsActivity.kt index 201baa92..12bb2fbb 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/ConversationDetailsActivity.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/ConversationDetailsActivity.kt @@ -184,6 +184,11 @@ class ConversationDetailsActivity : ComposeSimpleActivity() { override fun onResume() { super.onResume() hiddenGate.check() + // The system notification settings can change both while this page is in the background. + if (threadId != 0L) { + customNotifications = config.customNotifications.contains(threadId.toString()) + refreshMute() + } } /** CL-23: shows the search page and loads this chat's messages for it (once). */ diff --git a/app/src/main/kotlin/com/glooboo/umessage/activities/MainRoutes.kt b/app/src/main/kotlin/com/glooboo/umessage/activities/MainRoutes.kt index 836fb756..78144205 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/MainRoutes.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/MainRoutes.kt @@ -80,6 +80,7 @@ class MainRoutes(private val activity: BaseSimpleActivity) { onUndoDelete = viewModel::undoDelete, onCommitDelete = viewModel::commitDelete, onUndoArchive = viewModel::undoArchive, + onCommitArchive = viewModel::commitArchive, onNewConversation = ::openNewConversation, ) diff --git a/app/src/main/kotlin/com/glooboo/umessage/activities/ManageBlockedKeywordsActivity.kt b/app/src/main/kotlin/com/glooboo/umessage/activities/ManageBlockedKeywordsActivity.kt index ecce18a6..f997a0cb 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/ManageBlockedKeywordsActivity.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/ManageBlockedKeywordsActivity.kt @@ -26,9 +26,10 @@ import org.fossify.commons.extensions.showErrorToast import org.fossify.commons.extensions.toast import org.fossify.commons.helpers.ExportResult import org.fossify.commons.helpers.ensureBackgroundThread -import java.io.FileOutputStream +import java.io.InputStream import java.io.OutputStream +@Suppress("TooManyFunctions") class ManageBlockedKeywordsActivity : ComposeSimpleActivity() { private var keywords by mutableStateOf>(emptyList()) @@ -104,37 +105,53 @@ class ManageBlockedKeywordsActivity : ComposeSimpleActivity() { private fun tryImportBlockedKeywordsFromFile(uri: Uri) { when (uri.scheme) { - "file" -> importBlockedKeywords(uri.path!!) - "content" -> { - val tempFile = getTempFile("blocked", "blocked_keywords.txt") - if (tempFile == null) { - toast(org.fossify.commons.R.string.unknown_error_occurred) - return - } + "file" -> uri.path?.let(::importBlockedKeywords) + ?: toast(org.fossify.commons.R.string.invalid_file_format) + + "content" -> importFromContent(uri) + else -> toast(org.fossify.commons.R.string.invalid_file_format) + } + } - try { - val inputStream = contentResolver.openInputStream(uri) - val out = FileOutputStream(tempFile) - inputStream!!.copyTo(out) - importBlockedKeywords(tempFile.absolutePath) - } catch (e: Exception) { - showErrorToast(e) + /** Copies the picked file to a temp file off the main thread (closing both streams, size capped), then imports. */ + private fun importFromContent(uri: Uri) { + val tempFile = getTempFile("blocked", "blocked_keywords.txt") + if (tempFile == null) { + toast(org.fossify.commons.R.string.unknown_error_occurred) + return + } + ensureBackgroundThread { + try { + val input = contentResolver.openInputStream(uri) ?: error("No input stream") + val copied = input.use { source -> + tempFile.outputStream().use { out -> source.copyAtMost(out, MAX_IMPORT_BYTES) } } + if (copied) { + BlockedKeywordsImporter(this).importBlockedKeywords(tempFile.absolutePath).let(::showImportResult) + updateBlockedKeywords() + } else { + toast(org.fossify.commons.R.string.invalid_file_format) + } + } catch (e: Exception) { + showErrorToast(e) + } finally { + tempFile.delete() } - - else -> toast(org.fossify.commons.R.string.invalid_file_format) } } + private fun showImportResult(result: BlockedKeywordsImporter.ImportResult) { + toast( + when (result) { + BlockedKeywordsImporter.ImportResult.IMPORT_OK -> org.fossify.commons.R.string.importing_successful + BlockedKeywordsImporter.ImportResult.IMPORT_FAIL -> org.fossify.commons.R.string.no_items_found + }, + ) + } + private fun importBlockedKeywords(path: String) { ensureBackgroundThread { - val result = BlockedKeywordsImporter(this).importBlockedKeywords(path) - toast( - when (result) { - BlockedKeywordsImporter.ImportResult.IMPORT_OK -> org.fossify.commons.R.string.importing_successful - BlockedKeywordsImporter.ImportResult.IMPORT_FAIL -> org.fossify.commons.R.string.no_items_found - }, - ) + showImportResult(BlockedKeywordsImporter(this).importBlockedKeywords(path)) updateBlockedKeywords() } } @@ -196,3 +213,20 @@ class ManageBlockedKeywordsActivity : ComposeSimpleActivity() { updateBlockedKeywords() } } + +/** A keyword list is small: anything bigger than this is not one. */ +private const val MAX_IMPORT_BYTES = 1_000_000L +private const val COPY_BUFFER_BYTES = 8 * 1024 + +/** Copies at most [limit] bytes; false (with the copy cut short) when the source has more. */ +private fun InputStream.copyAtMost(out: OutputStream, limit: Long): Boolean { + val buffer = ByteArray(COPY_BUFFER_BYTES) + var total = 0L + while (true) { + val read = read(buffer) + if (read < 0) return true + total += read + if (total > limit) return false + out.write(buffer, 0, read) + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/activities/NewConversationActivity.kt b/app/src/main/kotlin/com/glooboo/umessage/activities/NewConversationActivity.kt index afd83416..2388e7f1 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/NewConversationActivity.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/NewConversationActivity.kt @@ -192,6 +192,9 @@ class NewConversationActivity : ComposeSimpleActivity() { * Opens the chat and closes this picker, so Back from the chat returns to the list (MC-10). When Android can't make * a chat for the number (thread id 0) it says so and the picker stays (MC-07); a link from another app closes. */ + /** Set while a chat is being opened, so a double tap cannot start the thread twice (cleared on failure). */ + private var launching = false + private fun launchThreadActivity(phoneNumber: String, name: String, body: String = "", finishAfter: Boolean = false) { hideKeyboard() val numbers = phoneNumber.split(";").map { it.trim() }.filter { it.isNotEmpty() }.toSet() @@ -202,9 +205,12 @@ class NewConversationActivity : ComposeSimpleActivity() { } val number = if (numbers.size == 1) numbers.first() else Gson().toJson(numbers) // getOrCreateThreadId is a Telephony provider round trip: keep it off the main thread. + if (launching) return + launching = true lifecycleScope.launch { val threadId = withContext(Dispatchers.IO) { runCatching { getThreadId(numbers) }.getOrDefault(0L) } if (threadId <= 0L) { + launching = false toast(R.string.new_conversation_invalid_number, length = Toast.LENGTH_LONG) if (finishAfter) finish() return@launch diff --git a/app/src/main/kotlin/com/glooboo/umessage/activities/SettingsActivity.kt b/app/src/main/kotlin/com/glooboo/umessage/activities/SettingsActivity.kt index 45411bee..a37d6fec 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/SettingsActivity.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/SettingsActivity.kt @@ -14,6 +14,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.combine import com.glooboo.umessage.dialogs.showAppLockDialog import org.fossify.commons.extensions.getBlockedNumbers @@ -57,6 +58,7 @@ import com.glooboo.umessage.helpers.w3aPrefs import com.glooboo.umessage.backup.SettingsBackup import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import android.widget.Toast import com.glooboo.umessage.spam.engine.SpamEngine import android.content.ClipData @@ -80,6 +82,7 @@ import com.glooboo.umessage.ui.settings.LongMmsSettingDialog import com.glooboo.umessage.ui.settings.longMmsLabel import com.glooboo.umessage.ui.settings.SettingsScreen import com.glooboo.umessage.ui.settings.SettingsUiState +import com.glooboo.umessage.ui.settings.SimCard import com.glooboo.umessage.ui.settings.SimCards import com.glooboo.umessage.ui.settings.SimMessagesDialog import com.glooboo.umessage.ui.settings.SpamSummary @@ -110,6 +113,7 @@ import com.glooboo.umessage.ui.settings.RestoreSummary * Compose-hosted settings. Every option writes the same Config keys as the former View screen. * Stays a [SimpleActivity] because the commons security dialog needs one. */ +@Suppress("LargeClass") class SettingsActivity : ComposeSimpleActivity() { private var blockedNumbersAtPause = -1 private var recycleBinMessages = 0 @@ -194,11 +198,15 @@ class SettingsActivity : ComposeSimpleActivity() { } private val phoneStatePermission = - registerForActivityResult(ActivityResultContracts.RequestPermission()) { refreshState() } + registerForActivityResult(ActivityResultContracts.RequestPermission()) { + refreshState() + refreshSims() + } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) refreshState() + refreshSims() // Bug 7: another screen can open a page directly (the forward editor opens App lock). val initialPage = (intent?.getStringExtra(EXTRA_PAGE) ?.let { name -> SettingsPage.entries.firstOrNull { it.name == name } } ?: SettingsPage.Main) @@ -215,6 +223,7 @@ class SettingsActivity : ComposeSimpleActivity() { override fun onResume() { super.onResume() refreshState() + refreshSims() loadRecycleBinCount() loadForwardingAndArchived() reportInterruptedBackup() @@ -249,11 +258,24 @@ class SettingsActivity : ComposeSimpleActivity() { } } + /** The SIM list, read off the main thread (the subscription service can be slow) and kept for [refreshState]. */ + private var sims: List = emptyList() + + private fun refreshSims() { + lifecycleScope.launch { + val loaded = withContext(Dispatchers.IO) { SimCards.load(this@SettingsActivity) } + if (loaded != sims) { + sims = loaded + uiState = uiState.copy(sims = loaded) + } + } + } + private fun refreshState() { uiState = SettingsUiState( simPermissionGranted = SimCards.hasPermission(this), showOldBlockedWords = config.blockedKeywords.isNotEmpty(), - sims = SimCards.load(this), + sims = sims, defaultSimId = config.defaultSimId, lockScreenLabel = lockScreenLabel(), forwardingAvailable = ForwardingAvailability.isAvailable(this), diff --git a/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt b/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt index 77a56d2f..e20f0700 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt @@ -183,7 +183,9 @@ import java.io.File open class ThreadActivity : ComposeSimpleActivity() { private val vm: ThreadViewModel by viewModels() + @Volatile private var threadId = 0L + private val refreshLock = Any() /** B06: a hidden chat asks for the app lock before it shows. */ private val hiddenGate = HiddenChatGate(this) { threadId } @@ -1632,6 +1634,11 @@ open class ThreadActivity : ComposeSimpleActivity() { @Subscribe(threadMode = ThreadMode.ASYNC) fun refreshMessages(@Suppress("unused") event: Events.RefreshMessages) { + // ASYNC events run on a pool: one refresh at a time, so an older read cannot publish over a newer one. + synchronized(refreshLock) { refreshMessagesLocked() } + } + + private fun refreshMessagesLocked() { if (isRecycleBin) { return } diff --git a/app/src/main/kotlin/com/glooboo/umessage/dialogs/ScheduleMessageDialog.kt b/app/src/main/kotlin/com/glooboo/umessage/dialogs/ScheduleMessageDialog.kt index ffebbc98..17238a71 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/dialogs/ScheduleMessageDialog.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/dialogs/ScheduleMessageDialog.kt @@ -131,6 +131,7 @@ private fun TimeStep( TextButton( onClick = { val candidate = initial.withHour(timeState.hour).withMinute(timeState.minute) + .withSecond(0).withNano(0) // Stay on the time picker, like before: the time must still be in the future. if (isFuture(candidate)) onConfirm(candidate) else activity.toast(futureError) }, @@ -246,7 +247,7 @@ private fun ScheduleFlow( ) { val isNew = initial == null var repeat by remember { mutableStateOf(initialRepeat) } - var dateTime by remember { mutableStateOf(initial ?: LocalDateTime.now().plusHours(1)) } + var dateTime by remember { mutableStateOf(initial ?: LocalDateTime.now().plusHours(1).withSecond(0).withNano(0)) } // TH-25: a new message starts at the summary with quick presets; the calendar and clock are one tap away. var step by remember { mutableStateOf(Step.Preview) } // A new message walks date -> time -> summary; once the date is set it is no longer "new" for the date picker. diff --git a/app/src/main/kotlin/com/glooboo/umessage/extensions/Context.kt b/app/src/main/kotlin/com/glooboo/umessage/extensions/Context.kt index 0fb13941..61c24cc8 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/extensions/Context.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/extensions/Context.kt @@ -629,10 +629,9 @@ fun Context.getMmsAttachments( val mimetype = cursor.getStringValue(Mms.Part.CONTENT_TYPE) ?: "" val messageAttachment = result.getOrPut(id) { MessageAttachment(id, "", arrayListOf()) } if (mimetype == "text/plain") { - messageAttachment.text = cursor - .getStringValue(Mms.Part.TEXT) - ?.take(MAX_MESSAGE_LENGTH) - .orEmpty() + val part = cursor.getStringValue(Mms.Part.TEXT).orEmpty() + // Several text slides are joined in order instead of the last one replacing the rest. + messageAttachment.text = joinMmsText(messageAttachment.text, part) } else if (mimetype.startsWith("image/") || mimetype.startsWith("video/")) { val fileUri = Uri.withAppendedPath(uri, partId.toString()) messageAttachment.attachments.add( @@ -784,6 +783,14 @@ fun Context.getThreadParticipants( return participants } +/** Text slides of one MMS in order, one per line, capped at [MAX_MESSAGE_LENGTH]. */ +internal fun joinMmsText(soFar: String, part: String): String { + val joined = if (soFar.isEmpty() || part.isEmpty()) soFar + part else soFar + MMS_TEXT_SEPARATOR + part + return joined.take(MAX_MESSAGE_LENGTH) +} + +private const val MMS_TEXT_SEPARATOR = "\n" + private fun Context.getThreadRecipientIds(threadId: Long): List { val recipientIds = ArrayList() queryCursor( @@ -1160,8 +1167,8 @@ fun Context.updateConversationArchivedStatus(threadId: Long, archived: Boolean) sqliteException.message?.contains("no such column: archived") == true && config.isArchiveAvailable ) { + // The phone's store has no archive flag: keep the chat archived in the app's own list instead. config.isArchiveAvailable = false - return } else { throw sqliteException } diff --git a/app/src/main/kotlin/com/glooboo/umessage/helpers/ConversationListSync.kt b/app/src/main/kotlin/com/glooboo/umessage/helpers/ConversationListSync.kt index 9656a452..99e8c9ca 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/helpers/ConversationListSync.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/helpers/ConversationListSync.kt @@ -206,6 +206,7 @@ class ConversationListSync( val cachedConversations = ArrayList(db.getNonArchived() + db.getAllArchived()) val privateContacts = context.getPrivateContactsIfAvailable() val lookups = ConversationLookups(context, bulk = true) + val archiveKnown = context.config.isArchiveAvailable // Refresh the newest threads first so the top of the list is current right away. The full pass below still // runs: it is what notices deleted threads and keeps the rest of the list, Archived and search up to date. @@ -213,10 +214,10 @@ class ConversationListSync( val newest = context.getConversations(privateContacts = privateContacts, limit = firstPassSize, lookups = lookups) val changed = newest.filter { fresh -> val cached = cachedById[fresh.threadId] - cached == null || !Conversation.areContentsTheSame(old = cached, new = fresh) + cached == null || !sameRow(cached, fresh, archiveKnown) } if (changed.isNotEmpty()) { - changed.forEach { context.insertOrUpdateConversation(keepRead(it), cachedById[it.threadId]) } + changed.forEach { writeIfStillSaved(it, cachedById[it.threadId]) } publish(saved(), true) } @@ -251,11 +252,11 @@ class ConversationListSync( } cachedConversations.forEach { cached -> - val conv = freshById[cached.threadId]?.takeIf { !Conversation.areContentsTheSame(old = cached, new = it) } + val conv = freshById[cached.threadId]?.takeIf { !sameRow(cached, it, archiveKnown) } if (conv != null) { // FIXME: Scheduled message date is being reset here. Conversations with scheduled messages will have // their original date. - context.insertOrUpdateConversation(keepRead(conv)) + writeIfStillSaved(conv, null, wasSaved = true) } } @@ -276,6 +277,22 @@ class ConversationListSync( } } + private fun sameRow(cached: Conversation, fresh: Conversation, archiveKnown: Boolean) = + Conversation.areContentsTheSame(old = cached, new = fresh, compareArchived = archiveKnown) + + /** + * Writes a changed row read earlier, unless a delete that ran meanwhile already took the saved row away: the stale + * read would bring the chat back until the next pass. A row that was never saved is added as before. + */ + private fun writeIfStillSaved(fresh: Conversation, cached: Conversation?, wasSaved: Boolean = cached != null) { + if (wasSaved && context.conversationsDB.getConversationWithThreadId(fresh.threadId) == null) return + if (cached == null) { + context.insertOrUpdateConversation(keepRead(fresh)) + } else { + context.insertOrUpdateConversation(keepRead(fresh), cached) + } + } + /** * A snapshot read from the phone's store before the user opened a chat must not turn the row it was just marked * read in back to unread: when the saved row is read now and the snapshot has nothing newer, the row stays read. diff --git a/app/src/main/kotlin/com/glooboo/umessage/helpers/smartreply/SmartReplyPolicy.kt b/app/src/main/kotlin/com/glooboo/umessage/helpers/smartreply/SmartReplyPolicy.kt index c767d29a..16ea6650 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/helpers/smartreply/SmartReplyPolicy.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/helpers/smartreply/SmartReplyPolicy.kt @@ -47,7 +47,8 @@ object SmartReplyPolicy { private const val CLOCK_SKEW_MILLIS = 60 * 1000L private const val MAX_BODY_CHARS = 160 - private val LONG_NUMBER = Regex("""\d{4}""") + // Four digits or more, except a lone year (19xx, 20xx): "see you in 2025" is fine, "code 1234" is not. + private val LONG_NUMBER = Regex("""(? Unit = {}, onAttachmentHandedOff: (Attachment) -> Unit = {}, +): SendOutcome = sendToDistinctRecipients( + text, distinctRecipients(addresses), subId, attachments, resend, onFailure, onAttachmentHandedOff, +) + +/** Drops a recipient that is the same number as an earlier one written another way ("+4671..." and "071..."). */ +internal fun distinctRecipients(addresses: List): List { + val result = ArrayList(addresses.size) + for (address in addresses) { + if (result.none { it == address || PhoneNumberUtils.compare(it, address) }) result.add(address) + } + return result +} + +private fun Context.sendToDistinctRecipients( + text: String, + addresses: List, + subId: Int?, + attachments: List, + resend: MessageKey?, + onFailure: () -> Unit, + onAttachmentHandedOff: (Attachment) -> Unit, ): SendOutcome { val settings = getSendMessageSettings() activeSendSubscriptionId(subId)?.let { settings.subscriptionId = it } diff --git a/app/src/main/kotlin/com/glooboo/umessage/messaging/ScheduledAttachments.kt b/app/src/main/kotlin/com/glooboo/umessage/messaging/ScheduledAttachments.kt index 8d4a3e81..eb2f6fdd 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/messaging/ScheduledAttachments.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/messaging/ScheduledAttachments.kt @@ -103,8 +103,11 @@ private fun Context.copyInto(uri: Uri, file: File) { } /** Whether every attachment of [message] can still be opened. */ -fun Context.canReadScheduledAttachments(message: Message): Boolean = - message.attachment?.attachments.orEmpty().all { attachment -> +fun Context.canReadScheduledAttachments(message: Message): Boolean = unreadableScheduledAttachments(message).isEmpty() + +/** The attachments of [message] that can no longer be opened. */ +fun Context.unreadableScheduledAttachments(message: Message): List = + message.attachment?.attachments.orEmpty().filterNot { attachment -> try { contentResolver.openInputStream(attachment.getUri())?.use { true } ?: false } catch (_: Exception) { diff --git a/app/src/main/kotlin/com/glooboo/umessage/messaging/SentParts.kt b/app/src/main/kotlin/com/glooboo/umessage/messaging/SentParts.kt index f37c95ea..d962e846 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/messaging/SentParts.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/messaging/SentParts.kt @@ -54,6 +54,9 @@ object SentParts { } } + /** Drops the stored reports of [messageUri]; for a message whose remaining reports were lost. */ + fun forget(context: Context, messageUri: Uri) = start(context, messageUri) + /** Records one part's report for [messageUri] and returns what it means for the message row. */ fun record(context: Context, messageUri: Uri, partSent: Boolean, partCount: Int): Outcome { if (partCount <= 1) { diff --git a/app/src/main/kotlin/com/glooboo/umessage/messaging/StaleOutbox.kt b/app/src/main/kotlin/com/glooboo/umessage/messaging/StaleOutbox.kt index a8f56117..e6d67a66 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/messaging/StaleOutbox.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/messaging/StaleOutbox.kt @@ -1,5 +1,6 @@ package com.glooboo.umessage.messaging +import android.content.ContentUris import android.content.ContentValues import android.content.Context import android.provider.Telephony.Mms @@ -56,6 +57,8 @@ fun Context.failStaleOutboxMessages( if (updated > 0) { marked++ runCatching { messagesDB.updateType(id, isMMS = false, type = Sms.MESSAGE_TYPE_FAILED) } + // Its remaining part reports were lost, so the stored progress would stay forever. + runCatching { SentParts.forget(this, ContentUris.withAppendedId(Sms.CONTENT_URI, id)) } } } catch (_: Exception) { } diff --git a/app/src/main/kotlin/com/glooboo/umessage/models/Conversation.kt b/app/src/main/kotlin/com/glooboo/umessage/models/Conversation.kt index 872f9440..33a079b3 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/models/Conversation.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/models/Conversation.kt @@ -26,8 +26,13 @@ data class Conversation( return old.threadId == new.threadId } - fun areContentsTheSame(old: Conversation, new: Conversation): Boolean { - return old.snippet == new.snippet && + /** + * [compareArchived] is false when the phone's store has no archive flag: its rows then always read "not + * archived" and must not undo an archive the app keeps itself. + */ + fun areContentsTheSame(old: Conversation, new: Conversation, compareArchived: Boolean = false): Boolean { + return (!compareArchived || old.isArchived == new.isArchived) && + old.snippet == new.snippet && old.date == new.date && old.read == new.read && old.title == new.title && diff --git a/app/src/main/kotlin/com/glooboo/umessage/receivers/MmsPushReceiver.kt b/app/src/main/kotlin/com/glooboo/umessage/receivers/MmsPushReceiver.kt index facdee2a..87ab4a0c 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/receivers/MmsPushReceiver.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/receivers/MmsPushReceiver.kt @@ -124,7 +124,7 @@ class MmsPushReceiver : BroadcastReceiver() { private companion object { const val EXTRA_DATA = "data" const val SEEN_TTL_MS = 10 * 60 * 1000L - const val LIBRARY_TASK_TIMEOUT_MS = 20_000L + const val LIBRARY_TASK_TIMEOUT_MS = 8_000L val seen = ConcurrentHashMap() /** PushReceiver's private static PUSH_RECEIVER_EXECUTOR, found by type so field renaming doesn't matter. */ diff --git a/app/src/main/kotlin/com/glooboo/umessage/receivers/MmsReceiver.kt b/app/src/main/kotlin/com/glooboo/umessage/receivers/MmsReceiver.kt index 17eb74d6..5e0cb2df 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/receivers/MmsReceiver.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/receivers/MmsReceiver.kt @@ -16,6 +16,8 @@ import com.glooboo.umessage.extensions.getMMS import com.glooboo.umessage.extensions.getLatestMMS import com.glooboo.umessage.extensions.getNameFromAddress import com.glooboo.umessage.extensions.insertOrUpdateConversation +import com.glooboo.umessage.extensions.isImageMimeType +import com.glooboo.umessage.extensions.isVideoMimeType import com.glooboo.umessage.extensions.shouldUnarchive import com.glooboo.umessage.extensions.showReceivedMessageNotification import com.glooboo.umessage.extensions.updateConversationArchivedStatus @@ -87,6 +89,10 @@ class MmsReceiver : BroadcastReceiver() { * every hook of one download on the same worker thread, so the first [mark] identifies it. */ internal class WorkerThreadTracker { + private companion object { + const val FIRST_HOOK_WAIT_MS = 5_000L + } + private val started = CountDownLatch(1) @Volatile private var worker: Thread? = null @@ -104,7 +110,8 @@ internal class WorkerThreadTracker { /** Waits until the marked thread has ended. False when that did not happen within [timeoutMs]. */ fun await(timeoutMs: Long): Boolean { val deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMs) - if (!started.await(timeoutMs, TimeUnit.MILLISECONDS)) return false + // If mmslib fails before it calls any hook, nothing ever marks a thread: give up sooner than the full wait. + if (!started.await(minOf(timeoutMs, FIRST_HOOK_WAIT_MS), TimeUnit.MILLISECONDS)) return false val thread = worker ?: return false if (thread === Thread.currentThread()) return true val leftMs = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()) @@ -225,10 +232,12 @@ internal class MmsDownloadHandler : MmsReceivedReceiver() { size: Int, address: String ) { - val glideBitmap = try { + // Only a picture or a video has a thumbnail to show; a text-only MMS skips the load. + val imageUri = mms.attachment?.attachments?.firstOrNull { it.mimetype.isPreviewable() }?.getUri() + val glideBitmap = if (imageUri == null) null else try { Glide.with(context) .asBitmap() - .load(mms.attachment!!.attachments.first().getUri()) + .load(imageUri) .centerCrop() .into(size, size) .get(BITMAP_TIMEOUT_MS, TimeUnit.MILLISECONDS) @@ -285,3 +294,5 @@ internal class MmsDownloadHandler : MmsReceivedReceiver() { const val BITMAP_TIMEOUT_MS = 5_000L } } + +private fun String.isPreviewable() = isImageMimeType() || isVideoMimeType() diff --git a/app/src/main/kotlin/com/glooboo/umessage/receivers/ReminderReceiver.kt b/app/src/main/kotlin/com/glooboo/umessage/receivers/ReminderReceiver.kt index 40840987..a18f8323 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/receivers/ReminderReceiver.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/receivers/ReminderReceiver.kt @@ -24,8 +24,11 @@ class ReminderReceiver : BroadcastReceiver() { val reminder = runCatching { runBlocking { context.getMessagesDB().MessageRemindersDao().get(reminderId) } }.getOrNull() ?: return - runCatching { ReminderNotification(context).show(reminder, context.resolveReminderTarget(reminder)) } - // Deleted once it fired, so re-arming after a reboot never fires it a second time. - context.cancelReminder(reminderId) + val shown = runCatching { + ReminderNotification(context).show(reminder, context.resolveReminderTarget(reminder)) + }.isSuccess + // Deleted once it fired, so re-arming after a reboot never fires it a second time. If showing it threw, it is + // kept, so the next re-arm tries again instead of losing the reminder. + if (shown) context.cancelReminder(reminderId) } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/receivers/ScheduledMessageReceiver.kt b/app/src/main/kotlin/com/glooboo/umessage/receivers/ScheduledMessageReceiver.kt index 2d077706..8baed54b 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/receivers/ScheduledMessageReceiver.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/receivers/ScheduledMessageReceiver.kt @@ -24,6 +24,7 @@ import com.glooboo.umessage.helpers.refreshMessages import com.glooboo.umessage.R import com.glooboo.umessage.messaging.bookNextRepeat import com.glooboo.umessage.messaging.canReadScheduledAttachments +import com.glooboo.umessage.messaging.unreadableScheduledAttachments import com.glooboo.umessage.messaging.deleteScheduledRepeat import com.glooboo.umessage.messaging.deleteScheduledAttachments import com.glooboo.umessage.messaging.ScheduledSendClaims @@ -126,7 +127,10 @@ class ScheduledMessageReceiver : BroadcastReceiver() { // Scheduled before the app kept its own copy: the picker's permission expired or the file is gone. // Sending it would go out without the photo, so it is held and the user is told why. hold(context, messageId) - notifyNotSent(context, message, addresses, attachmentMissing = true) + notifyNotSent( + context, message, addresses, attachmentMissing = true, + missingNames = context.unreadableScheduledAttachments(message).map { it.filename }, + ) refreshMessages() return } @@ -157,6 +161,10 @@ class ScheduledMessageReceiver : BroadcastReceiver() { return } + // The message is in the provider now. Hold the row before the cleanup below: if the process dies in + // between, the row is skipped on the next re-arm instead of being sent a second time. + hold(context, messageId) + // A failure already has its "not sent" notification; "sent late" is only for messages that went out. if (!notified) notifyIfLate(context, message, addresses) @@ -223,7 +231,7 @@ class ScheduledMessageReceiver : BroadcastReceiver() { */ private fun notifyNotSent( context: Context, message: Message, addresses: List, attachmentMissing: Boolean = false, - partlySent: Boolean = false, + partlySent: Boolean = false, missingNames: List = emptyList(), ) { val recipientName = message.participants.joinToString { it.name.ifBlank { it.phoneNumbers.firstOrNull()?.normalizedNumber.orEmpty() } @@ -235,7 +243,7 @@ class ScheduledMessageReceiver : BroadcastReceiver() { context.getThreadId(addresses.toSet()).takeIf { it != 0L } ?: message.threadId } val reason = when { - attachmentMissing -> context.getString(R.string.scheduled_attachment_missing, recipientName) + attachmentMissing -> missingAttachmentReason(context, recipientName, missingNames) partlySent -> context.getString(R.string.scheduled_partly_sent, recipientName) else -> null } @@ -249,4 +257,15 @@ class ScheduledMessageReceiver : BroadcastReceiver() { } } } + + /** The "attachment can no longer be opened" text; it names the files (up to three) when their names are known. */ + private fun missingAttachmentReason(context: Context, recipientName: String, names: List): String { + val shown = names.filter { it.isNotBlank() }.take(MAX_NAMED_FILES) + if (shown.isEmpty()) return context.getString(R.string.scheduled_attachment_missing, recipientName) + return context.getString(R.string.scheduled_attachment_missing_named, recipientName, shown.joinToString()) + } + + private companion object { + const val MAX_NAMED_FILES = 3 + } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/services/HeadlessSmsSendService.kt b/app/src/main/kotlin/com/glooboo/umessage/services/HeadlessSmsSendService.kt index 951fcb8d..2c3f0348 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/services/HeadlessSmsSendService.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/services/HeadlessSmsSendService.kt @@ -5,6 +5,7 @@ import android.content.Intent import com.klinker.android.send_message.Settings import org.fossify.commons.helpers.ensureBackgroundThread import com.glooboo.umessage.extensions.config +import com.glooboo.umessage.extensions.subscriptionManagerCompat import com.glooboo.umessage.messaging.notifySendFailedInBackground import com.glooboo.umessage.messaging.sendMessageCompat @@ -39,8 +40,7 @@ class HeadlessSmsSendService : Service() { internal fun send(text: String, addresses: List) { var failed = false try { - val defaultSimId = config.defaultSimId - val subId = if (defaultSimId >= 0) defaultSimId else Settings.DEFAULT_SUBSCRIPTION_ID + val subId = sendSubscriptionId(addresses.first()) sendMessageCompat(text, addresses, subId, emptyList(), onFailure = { failed = true }) } catch (_: Exception) { failed = true @@ -49,6 +49,18 @@ class HeadlessSmsSendService : Service() { runCatching { notifySendFailedInBackground(addresses) } } } + + /** The SIM saved for the first recipient if it is active, else the app default SIM, else the system default. */ + @Suppress("MissingPermission") // a SecurityException is caught by runCatching below + private fun sendSubscriptionId(firstAddress: String): Int { + val defaultSimId = config.defaultSimId + val fallback = if (defaultSimId >= 0) defaultSimId else Settings.DEFAULT_SUBSCRIPTION_ID + val saved = config.getUseSIMIdAtNumberOrNull(firstAddress) ?: return fallback + return runCatching { + val activeIds = subscriptionManagerCompat().activeSubscriptionInfoList.orEmpty().map { it.subscriptionId } + if (saved in activeIds) saved else fallback + }.getOrDefault(fallback) + } } /** Recipients from the scheme-specific part of an sms/smsto/mms/mmsto URI ("+1555,+1666?body=hi"). */ diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/TextNormalizer.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/TextNormalizer.kt index 38a64631..1b17b220 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/TextNormalizer.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/TextNormalizer.kt @@ -91,6 +91,15 @@ object TextNormalizer { * ("2025", "50") or only of letters is left alone, so prices, codes and plain words are not changed. */ fun deobfuscate(text: String): String { + // spam-11: one message is read once per keyword rule; the last text and its result are kept for the next rule. + val last = lastDeobfuscated + if (last != null && (last.first === text || last.first == text)) return last.second + return deobfuscateUncached(text).also { lastDeobfuscated = text to it } + } + + @Volatile private var lastDeobfuscated: Pair? = null + + private fun deobfuscateUncached(text: String): String { val joined = SPACED_OUT.replace(lower(unfancy(text))) { it.value.replace(SPACED_SEPARATOR, "") } return WORD.replace(joined) { match -> val word = match.value diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepository.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepository.kt index 1ac5eb2c..04d79b65 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepository.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepository.kt @@ -244,6 +244,9 @@ class DefaultSpamRepository( receipt.pendingId > 0 && dao.deletePending(receipt.pendingId) > 0 -> true receipt.inboxId > 0 -> runCatching { platform.removeRestored(receipt.inboxId, message.hasStoredMedia) } .getOrDefault(false) + // spam-17: the delivery found the message already in the inbox and wrote no row, so there is nothing to take + // out and the undo can put the blocked row back. + receipt.pendingId <= 0 -> true else -> false } diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/data/ForwardDelivery.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/data/ForwardDelivery.kt index 84e99b43..fe7eb192 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/data/ForwardDelivery.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/data/ForwardDelivery.kt @@ -66,6 +66,7 @@ object SystemForwardSender : ForwardSmsSender { object ForwardDelivery { private const val TAG = "uMessageForward" const val SOURCE = "FORWARD" + private const val MAX_SKIP_LOGS = 3 @Volatile internal var sender: ForwardSmsSender = SystemForwardSender @@ -84,14 +85,18 @@ object ForwardDelivery { } private fun run(context: Context, message: ForwardCandidate, plan: ForwardPlan) { - plan.skipped.forEach { skip -> + // spam-19: at most a few skip entries per message, so many forward rules cannot push BLOCK and ALLOW entries + // out of the shared decision log. + plan.skipped.take(MAX_SKIP_LOGS).forEach { skip -> val to = skip.target?.let { " → $it" }.orEmpty() log(context, message, "FORWARD_SKIPPED", "#${skip.ruleId}$to ${skip.reason.name}") } if (plan.sends.isEmpty()) return // The global "pause all forwarding" switch (Forwarded tab, Settings): rules stay, nothing is sent. if (runCatching { NavPrefs.get(context).forwardPaused }.getOrDefault(false)) { - plan.sends.forEach { log(context, message, "FORWARD_SKIPPED", "#${it.ruleId} → ${it.target} PAUSED") } + plan.sends.take(MAX_SKIP_LOGS).forEach { + log(context, message, "FORWARD_SKIPPED", "#${it.ruleId} → ${it.target} PAUSED") + } return } val reserved = synchronized(ForwardLimits.lock) { reserve(context, message, plan.sends) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamSettingsStore.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamSettingsStore.kt index 6bc3ddb6..e50ec9e5 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamSettingsStore.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/data/SpamSettingsStore.kt @@ -57,6 +57,12 @@ class SpamSettingsStore(context: Context) { return true } + /** Gives back a [claimPurge] whose purge failed, so the next receiver tries again, not after a full interval. */ + @Synchronized + fun releasePurge() { + prefs.edit { remove(KEY_LAST_PURGE) } + } + fun observe(): Flow = callbackFlow { val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key != KEY_LAST_PURGE) trySend(get()) diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/AndroidSpamEnvironment.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/AndroidSpamEnvironment.kt index 7e53b2b8..708961d4 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/AndroidSpamEnvironment.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/AndroidSpamEnvironment.kt @@ -78,9 +78,11 @@ class SystemContactChecker( // The provider notifies mms-sms for every SMS and MMS change, next to the sms or mms row itself. return } - if (uri != null && messageRowId(uri) != null) { + if (uri != null && messageRowId(uri) != null && changedMessages.size < MAX_CHANGED_MESSAGES) { changedMessages.add(uri) } else { + // A change that names no row, or a bulk import that queued too many, drops the cache; the next + // lookup reads everything once instead of one query per changed row. sentCache = null } } @@ -248,6 +250,7 @@ class SystemContactChecker( Telephony.Sms.MESSAGE_TYPE_FAILED, ) const val MAX_SENT_MMS = 200 + const val MAX_CHANGED_MESSAGES = 50 const val PRIVATE_CONTACTS_MAX_AGE_MS = 10 * 60_000L /** The row id a change notification names (content://sms/42, content://sms/inbox/42), or null. */ diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/SpamEngine.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/SpamEngine.kt index fe174351..b9a38edd 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/engine/SpamEngine.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/engine/SpamEngine.kt @@ -287,11 +287,18 @@ object SpamEngine { fun purgeExpired(context: Context, now: Long = System.currentTimeMillis()) { try { val app = context.applicationContext - if (!settingsStore(app).claimPurge(now)) return + val store = settingsStore(app) + if (!store.claimPurge(now)) return // The decision log has its own, shorter retention; it goes first so a failing repository purge // can't keep old sender numbers around. runCatching { UMessage.log(app).purgeExpired() } - runBlocking { repository(app).purgeExpired() } + // spam-14: a purge that failed gives the claim back, so the next message retries it, not 6 hours later. + try { + runBlocking { repository(app).purgeExpired() } + } catch (t: Throwable) { + store.releasePurge() + throw t + } } catch (_: Throwable) { } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/mms/BlockedMmsDownloader.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/mms/BlockedMmsDownloader.kt index 765e8956..8d510b9b 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/mms/BlockedMmsDownloader.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/mms/BlockedMmsDownloader.kt @@ -6,6 +6,7 @@ import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle +import android.telephony.TelephonyManager import com.android.mms.MmsConfig import com.glooboo.umessage.receivers.BlockedMmsDownloadReceiver import com.klinker.android.send_message.SmsManagerFactory @@ -25,8 +26,14 @@ object BlockedMmsDownloader { private const val FILE_PREFIX = "blocked-mms-" private const val HTTP_PARAMS = "httpParams" - /** Starts the download. Throws when the system refused to start it; the caller then marks the content missing. */ + /** + * Starts the download. Throws when the system refused to start it, or when [BlockedMmsPolicy] says not to download + * now (roaming, or too many kept already); the caller then marks the content missing and the placeholder stays. + */ fun start(context: Context, blockedId: Long, contentLocation: String, subscriptionId: Int) { + check(BlockedMmsPolicy.mayDownload(isRoaming(context, subscriptionId), keptFiles(context))) { + "Blocked MMS download skipped by policy" + } val name = "$FILE_PREFIX$blockedId-${UUID.randomUUID()}.dat" val file = File(context.cacheDir, name) val uri = Uri.Builder() @@ -54,6 +61,16 @@ object BlockedMmsDownloader { } } + /** Roaming on the SIM that received the MMS; false when it cannot be told (the download then goes ahead). */ + private fun isRoaming(context: Context, subscriptionId: Int): Boolean = runCatching { + val manager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager + val forSim = if (subscriptionId >= 0) manager.createForSubscriptionId(subscriptionId) else manager + forSim.isNetworkRoaming + }.getOrDefault(false) + + private fun keptFiles(context: Context): Int = + BlockedMmsStore.dir(context).listFiles { file -> file.name.endsWith(".pdu") }?.size ?: 0 + /** The download file named in a result intent, only if it is one of ours in the cache directory. */ fun downloadFile(context: Context, intent: Intent): File? { val path = intent.getStringExtra(EXTRA_FILE) ?: return null diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/mms/BlockedMmsPolicy.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/mms/BlockedMmsPolicy.kt new file mode 100644 index 00000000..751dc8bd --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/mms/BlockedMmsPolicy.kt @@ -0,0 +1,21 @@ +package com.glooboo.umessage.spam.mms + +/** + * spam-10: when a blocked MMS is worth downloading into uMessage's private storage. A blocked MMS that is not + * downloaded stays in Blocked as a placeholder (its row and sender remain; only its pictures are missing), so the + * user can still open it. The limits are deliberately conservative: spam MMS is small and rare, and an unlimited + * download of what a stranger sends is a way to fill the phone or the data plan. Pure JVM. + */ +object BlockedMmsPolicy { + /** Largest announced message size that is downloaded: 1 MiB, above the usual 300 KB to 1 MB carrier limits. */ + const val MAX_MESSAGE_BYTES = 1_048_576L + + /** Most kept downloads at one time; more would fill storage until the purge. */ + const val MAX_KEPT_FILES = 100 + + /** Whether the size announced by the notification allows a download. An unknown size (0 or less) does. */ + fun sizeAllowed(announcedBytes: Long): Boolean = announcedBytes <= MAX_MESSAGE_BYTES + + /** Whether a download may start: never while roaming, and not once [keptFiles] reached [MAX_KEPT_FILES]. */ + fun mayDownload(roaming: Boolean, keptFiles: Int): Boolean = !roaming && keptFiles < MAX_KEPT_FILES +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/mms/MmsPushGate.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/mms/MmsPushGate.kt index 31076acc..e8f16a2d 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/mms/MmsPushGate.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/mms/MmsPushGate.kt @@ -18,6 +18,8 @@ data class MmsPushInfo( val contentLocation: String = "", /** When the carrier deletes the MMS, in ms since the epoch; 0 when unknown. */ val expiresAt: Long = 0, + /** The size the carrier announces (X-Mms-Message-Size) in bytes; 0 when unknown. */ + val messageSize: Long = 0, ) sealed interface MmsPushAction { @@ -73,7 +75,12 @@ object MmsPushGate { } catch (_: Throwable) { 0L } - return MmsPushInfo(cleanAddress(from), transactionId, isNotification = true, location, expiresAt) + val size = try { + pdu.messageSize.coerceAtLeast(0L) + } catch (_: Throwable) { + 0L + } + return MmsPushInfo(cleanAddress(from), transactionId, isNotification = true, location, expiresAt, size) } fun cleanAddress(raw: String): String = raw.substringBefore("/TYPE=").trim() @@ -106,7 +113,11 @@ object MmsPushGate { placeholder = probe.copy(body = MMS_BLOCKED_BODY), decision = decision, transactionId = info.transactionId, - contentLocation = info.contentLocation.takeIf { info.expiresAt == 0L || info.expiresAt > now }.orEmpty(), + // Expired, or announced larger than BlockedMmsPolicy allows: nothing is downloaded, the row stays. + contentLocation = info.contentLocation + .takeIf { info.expiresAt == 0L || info.expiresAt > now } + .takeIf { BlockedMmsPolicy.sizeAllowed(info.messageSize) } + .orEmpty(), ) } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/components/PhoneNumberDisplay.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/components/PhoneNumberDisplay.kt index 124a1aa1..b3e129f5 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/components/PhoneNumberDisplay.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/components/PhoneNumberDisplay.kt @@ -3,11 +3,11 @@ package com.glooboo.umessage.ui.components import android.content.Context import android.telephony.PhoneNumberUtils import android.telephony.TelephonyManager +import android.util.LruCache import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.ui.platform.LocalContext import java.util.Locale -import java.util.concurrent.ConcurrentHashMap /* * CL-10, CL-33, TH-29, VS-38: the one way a phone number, or a sender that is only a number, is shown on screen: the @@ -62,24 +62,36 @@ fun displayNumber(text: String): String { return displayNumber(text, uiLocale()) { PhoneNumberGrouping.format(context, it) } } -/** The platform formatter with the SIM's country (else the phone's region), cached per number. */ +/** Most numbers kept grouped; older ones are formatted again when they come back. */ +private const val GROUPING_CACHE_SIZE = 500 + +/** + * The platform formatter with the SIM's country (else the phone's region), cached per number. The cache is bounded, + * and the country is read again on every miss: when it changed (a SIM swap, a new locale) the cache starts over. + */ private object PhoneNumberGrouping { @Volatile private var country: String? = null - private val cache = ConcurrentHashMap() + private val cache = LruCache(GROUPING_CACHE_SIZE) fun format(context: Context, number: String): String? { - cache[number]?.let { return it } - val iso = countryOf(context).ifBlank { return null } + cache.get(number)?.let { return it } + val iso = refreshCountry(context).ifBlank { return null } val formatted = runCatching { PhoneNumberUtils.formatNumber(number, iso) }.getOrNull() ?: return null - cache[number] = formatted + cache.put(number, formatted) return formatted } - private fun countryOf(context: Context): String = country ?: run { + @Synchronized + private fun refreshCountry(context: Context): String { val sim = runCatching { context.applicationContext.getSystemService(TelephonyManager::class.java)?.simCountryIso }.getOrNull() - (sim?.takeIf { it.isNotBlank() } ?: Locale.getDefault().country).uppercase(Locale.ROOT).also { country = it } + val now = (sim?.takeIf { it.isNotBlank() } ?: Locale.getDefault().country).uppercase(Locale.ROOT) + if (now != country) { + cache.evictAll() + country = now + } + return now } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/components/SettingsRows.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/components/SettingsRows.kt index 3b4aa282..06af3467 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/components/SettingsRows.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/components/SettingsRows.kt @@ -8,6 +8,8 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.toggleable import androidx.compose.material3.RadioButton @@ -152,6 +154,9 @@ private fun RowIconSlot(icon: ImageVector?) { } } +/** A long value is cut with an ellipsis here, so it cannot squeeze the title beside it. */ +private val ValueMaxWidth = 150.dp + /** * Settings row with optional icon, summary and trailing content. With [onClick] the whole row is a 48dp+ * button target; without it the row is read as one static item. @@ -196,8 +201,11 @@ fun SettingsRow( if (value != null) { Text( value, + modifier = Modifier.widthIn(max = ValueMaxWidth), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, ) } trailing?.invoke() diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ContactAvatar.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ContactAvatar.kt index da564a47..228a36bb 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ContactAvatar.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ContactAvatar.kt @@ -3,6 +3,7 @@ package com.glooboo.umessage.ui.conversations import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.Drawable +import android.os.SystemClock import android.util.LruCache import androidx.compose.foundation.Image import androidx.compose.foundation.background @@ -136,6 +137,19 @@ internal fun initialsOf(title: String): String = private object AvatarCache { val bitmaps = object : LruCache(AVATAR_CACHE_SIZE) {} const val AVATAR_CACHE_SIZE = 200 + + /** Photos that failed to load, by when: not retried for a minute, so a broken one is not read again per row. */ + private val failures = object : LruCache(AVATAR_CACHE_SIZE) {} + private const val RETRY_AFTER_MS = 60_000L + + fun failedRecently(uri: String): Boolean { + val at = failures.get(uri) ?: return false + return SystemClock.elapsedRealtime() - at < RETRY_AFTER_MS + } + + fun markFailed(uri: String) { + failures.put(uri, SystemClock.elapsedRealtime()) + } } @Composable @@ -144,11 +158,13 @@ private fun rememberAvatarBitmap(uri: String): ImageBitmap? { val context = LocalContext.current.applicationContext var bitmap by remember(uri) { mutableStateOf(AvatarCache.bitmaps.get(uri)) } LaunchedEffect(uri) { - if (bitmap == null) { + if (bitmap == null && !AvatarCache.failedRecently(uri)) { val loaded = loadAvatar(context, uri) if (loaded != null) { AvatarCache.bitmaps.put(uri, loaded) bitmap = loaded + } else { + AvatarCache.markFailed(uri) } } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsModels.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsModels.kt index fe93e7cf..df957c81 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsModels.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsModels.kt @@ -136,6 +136,7 @@ class ConversationsCallbacks( val onUndoDelete: (Long) -> Unit = {}, val onCommitDelete: (Long) -> Unit = {}, val onUndoArchive: (Long) -> Unit = {}, + val onCommitArchive: (Long) -> Unit = {}, val onNewConversation: () -> Unit = {}, ) { companion object { diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsScreen.kt index 4d3ce1b4..762b6211 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsScreen.kt @@ -176,7 +176,11 @@ private suspend fun showEvent( actionLabel = undoLabel, duration = SnackbarDuration.Short, ) - if (result == SnackbarResult.ActionPerformed) callbacks.onUndoArchive(event.token) + if (result == SnackbarResult.ActionPerformed) { + callbacks.onUndoArchive(event.token) + } else { + callbacks.onCommitArchive(event.token) + } } is ConversationsEvent.MarkedAllRead -> { val result = snackbar.showSnackbar( diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModel.kt index de921032..6980186a 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationsViewModel.kt @@ -29,6 +29,7 @@ import org.fossify.commons.extensions.copyToClipboard import org.fossify.commons.extensions.notificationManager import com.glooboo.umessage.R import com.glooboo.umessage.extensions.config +import com.glooboo.umessage.extensions.conversationsDB import com.glooboo.umessage.extensions.deleteConversation import com.glooboo.umessage.extensions.getAllDrafts import com.glooboo.umessage.extensions.markThreadMessagesRead @@ -210,12 +211,17 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic /** SIM of each thread's newest message (sent or received), so chips show for every conversation. */ @Volatile private var threadSims: Map = emptyMap() + /** The ids of every saved chat, archived ones too, so a deleted chat's SIM entry can be dropped. */ + private fun liveThreadIds(): Set = + (app.conversationsDB.getNonArchived() + app.conversationsDB.getAllArchived()).mapTo(HashSet()) { it.threadId } + /** MC-18: the thread SIMs are read only with two SIMs, and then only messages newer than the last read. */ private fun refreshSims() { viewModelScope.launch { val (freshSims, freshThreadSims) = withContext(Dispatchers.IO) { val loaded = runCatching { SimDirectory.load(app) }.getOrDefault(emptyList()) - loaded to runCatching { ThreadSimCache.get(app).load(app, loaded.size) }.getOrDefault(emptyMap()) + val live = runCatching { liveThreadIds() }.getOrNull() + loaded to runCatching { ThreadSimCache.get(app).load(app, loaded.size, live) }.getOrDefault(emptyMap()) } if (freshSims != sims || freshThreadSims != threadSims) { sims = freshSims @@ -406,6 +412,12 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic } } + /** The Undo window closed without Undo: the saved undo state of the archive is no longer needed. */ + fun commitArchive(token: Long) { + archived.remove(token) + archivedUnread.remove(token) + } + fun undoArchive(token: Long) { val ids = archived.remove(token) ?: return val unread = archivedUnread.remove(token).orEmpty() diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ThreadSimCache.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ThreadSimCache.kt index c3d9b1a4..b6c90742 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ThreadSimCache.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ThreadSimCache.kt @@ -18,9 +18,12 @@ class ThreadSimCache(private val file: File) { private var newestMs = 0L private val sims = HashMap() - /** Thread id to subscription id; empty without a second SIM. Call off the main thread. */ + /** + * Thread id to subscription id; empty without a second SIM. Call off the main thread. [liveThreads], when given + * and not empty, are the threads that still exist: entries of deleted threads are dropped from the kept map. + */ @Synchronized - fun load(context: Context, simCount: Int): Map { + fun load(context: Context, simCount: Int, liveThreads: Set? = null): Map { if (simCount < 2) return emptyMap() if (!loaded) { readFile() @@ -37,17 +40,14 @@ class ThreadSimCache(private val file: File) { arrayOf(newestMs.toString()), "${Sms.DATE} DESC", )?.use { cursor -> - while (cursor.moveToNext()) { - val thread = cursor.getLong(0) - if (!fresh.containsKey(thread)) fresh[thread] = cursor.getInt(1) - newest = maxOf(newest, cursor.getLong(2)) - } + newest = maxOf(newest, collect(cursor, fresh)) } } catch (e: Exception) { Log.w(TAG, "Could not read message SIMs", e) return HashMap(sims) } - val changed = newest != newestMs || fresh.any { (thread, sub) -> sims[thread] != sub } + val pruned = !liveThreads.isNullOrEmpty() && sims.keys.retainAll(liveThreads + fresh.keys) + val changed = pruned || newest != newestMs || fresh.any { (thread, sub) -> sims[thread] != sub } if (changed) { sims.putAll(fresh) newestMs = newest @@ -56,6 +56,17 @@ class ThreadSimCache(private val file: File) { return HashMap(sims) } + /** Fills [fresh] with the first (newest) subscription id per thread; returns the newest message time seen. */ + private fun collect(cursor: android.database.Cursor, fresh: MutableMap): Long { + var newest = 0L + while (cursor.moveToNext()) { + val thread = cursor.getLong(0) + if (!fresh.containsKey(thread)) fresh[thread] = cursor.getInt(1) + newest = maxOf(newest, cursor.getLong(2)) + } + return newest + } + private fun readFile() { try { if (!file.exists()) return diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedModels.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedModels.kt index 0bab351f..6605112a 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedModels.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedModels.kt @@ -95,6 +95,9 @@ sealed interface ForwardedEvent { val ruleOff: Int = 0, val limited: Int = 0, ) : ForwardedEvent + + /** "Open chat" found no chat any more (it was deleted); the snackbar says so. */ + data object ChatMissing : ForwardedEvent } data class DayGroup(val day: LocalDate, val entries: List) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedScreen.kt index 00be9d9c..a4efa732 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedScreen.kt @@ -92,6 +92,10 @@ fun ForwardedRoute( LaunchedEffect(viewModel) { viewModel.events.collect { event -> + if (event is ForwardedEvent.ChatMissing) { + snackbar.currentSnackbarData?.dismiss() + snackbar.showSnackbar(resources.getString(R.string.minor_mt_chat_missing)) + } if (event is ForwardedEvent.Retried) { val locale = resources.configuration.locales[0] val parts = buildList { @@ -116,6 +120,7 @@ fun ForwardedRoute( // Failed forwards count as seen while the tab is open and again when it closes. LifecycleResumeEffect(viewModel) { viewModel.markSeen() + viewModel.refreshNames() onPauseOrDispose { viewModel.markSeen() } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedViewModel.kt index 84813bb4..5c6c0a51 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/forwarded/ForwardedViewModel.kt @@ -31,6 +31,7 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch @@ -64,6 +65,8 @@ class ForwardedViewModel(application: Application) : AndroidViewModel(applicatio // Opening the database the first time reads files: not on the main thread (L5). .flowOn(Dispatchers.IO) .catch { emit(emptyList()) } + // One database collector feeds both the screen state and the name lookup. + .shareIn(viewModelScope, SharingStarted.Eagerly, replay = 1) private val dailyLimitFlow: Flow = W3aPrefs.get(application).dailyForwardLimitFlow.catch { emit(0) } @@ -90,8 +93,9 @@ class ForwardedViewModel(application: Application) : AndroidViewModel(applicatio viewModelScope.launch { entriesFlow.collect { resolveNames(it) } } } - private suspend fun resolveNames(entries: List) { - val wanted = entries.flatMap { listOf(it.sourceAddress, it.target) }.toSet() - ui.value.names.keys + private suspend fun resolveNames(entries: List, force: Boolean = false) { + val all = entries.flatMap { listOf(it.sourceAddress, it.target) }.toSet() + val wanted = if (force) all else all - ui.value.names.keys if (wanted.isEmpty()) return val found = withContext(Dispatchers.IO) { val helper = SimpleContactsHelper(app) @@ -102,6 +106,11 @@ class ForwardedViewModel(application: Application) : AndroidViewModel(applicatio ui.update { it.copy(names = it.names + found) } } + /** Looks the names up again (a contact may have been renamed while the tab was away). */ + fun refreshNames() { + viewModelScope.launch { resolveNames(state.value.entries, force = true) } + } + fun setPaused(paused: Boolean) { prefs.forwardPaused = paused } @@ -139,7 +148,11 @@ class ForwardedViewModel(application: Application) : AndroidViewModel(applicatio fun openThread(entry: ForwardLogEntry, onResult: (threadId: Long, title: String) -> Unit) { viewModelScope.launch { val threadId = withContext(Dispatchers.IO) { app.getThreadId(entry.sourceAddress) } - if (threadId != 0L) onResult(threadId, state.value.nameOf(entry.sourceAddress)) + if (threadId != 0L) { + onResult(threadId, state.value.nameOf(entry.sourceAddress)) + } else { + _events.emit(ForwardedEvent.ChatMissing) + } } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/labels/LabelsState.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/labels/LabelsState.kt index 098ad777..5f1b6eb7 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/labels/LabelsState.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/labels/LabelsState.kt @@ -4,8 +4,8 @@ import androidx.compose.runtime.Immutable import com.glooboo.umessage.models.ConversationLabel import com.glooboo.umessage.models.Label -/** How a label name was judged. */ -enum class LabelResult { Ok, Empty, TooMany, Duplicate } +/** How a label name was judged; [Error] means the database failed and nothing was changed. */ +enum class LabelResult { Ok, Empty, TooMany, Duplicate, Error } /** The colours a label can have. Stored as the ARGB int in [Label.color]. */ enum class LabelColor(val argb: Long) { diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/labels/LabelsViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/labels/LabelsViewModel.kt index b6d35921..71d2ab5c 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/labels/LabelsViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/labels/LabelsViewModel.kt @@ -4,6 +4,7 @@ import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.glooboo.umessage.extensions.labelsDB +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -28,6 +29,10 @@ class LabelsViewModel(application: Application) : AndroidViewModel(application) val dao = app.labelsDB combine(dao.observeLabels(), dao.observeLinks()) { labels, links -> LabelsUiState.of(labels, links) } .collect { _state.value = it } + }.onFailure { + // A database error must not leave the screens waiting for labels forever: show none. + if (it is CancellationException) throw it + _state.value = LabelsUiState(loaded = true) } } } @@ -52,7 +57,7 @@ class LabelsViewModel(application: Application) : AndroidViewModel(application) private fun change(onDone: (LabelResult) -> Unit = {}, block: suspend (LabelsRepository) -> LabelResult) { viewModelScope.launch { val result = withContext(Dispatchers.IO) { - runCatching { block(LabelsRepository(app.labelsDB)) }.getOrDefault(LabelResult.Empty) + runCatching { block(LabelsRepository(app.labelsDB)) }.getOrDefault(LabelResult.Error) } onDone(result) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearch.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearch.kt index f46b8d7a..d43cb93f 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearch.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearch.kt @@ -241,7 +241,11 @@ class MainSearchState { /** The SIM (subscription id) of the filter while [filter] is [InboxFilter.Sim]. */ var simId by mutableIntStateOf(NO_SIM) + /** Set by the view model: stops a search still running when the user leaves search. */ + internal var onClose: (() -> Unit)? = null + fun close() { + onClose?.invoke() active = false query = "" results = emptyList() diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchViewModel.kt index accd3217..2c2d2f70 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/MainSearchViewModel.kt @@ -49,6 +49,7 @@ class MainSearchViewModel(application: Application, handle: SavedStateHandle) : private var searchJob: Job? = null init { + state.onClose = { searchJob?.cancel() } handle.get(KEY_SAVED)?.let { saved -> state.filter = InboxFilter.entries.firstOrNull { it.name == saved.getString(KEY_FILTER) } ?: InboxFilter.All state.labelId = saved.getLong(KEY_LABEL, NO_LABEL) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/newconversation/ContactListLogic.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/newconversation/ContactListLogic.kt index e0ced9b1..972fe6c5 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/newconversation/ContactListLogic.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/newconversation/ContactListLogic.kt @@ -31,7 +31,14 @@ internal fun filterContacts(all: List, query: String): List 0 + contact.phoneNumbers.any { it.normalizedNumber.startsWith(query) || it.value.startsWith(query) } -> 1 + else -> 2 } /** A contact row with a list key that is unique even when two contacts share ids. */ diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/scheduled/ScheduledStateReader.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/scheduled/ScheduledStateReader.kt index 5a0fb58c..6bdddd99 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/scheduled/ScheduledStateReader.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/scheduled/ScheduledStateReader.kt @@ -7,7 +7,9 @@ import com.glooboo.umessage.extensions.getMessagesDB import com.glooboo.umessage.extensions.getThreadTitle import com.glooboo.umessage.extensions.messagesDB import com.glooboo.umessage.helpers.HiddenChats +import com.glooboo.umessage.R import com.glooboo.umessage.messaging.RepeatRule +import com.glooboo.umessage.ui.components.displayTitle import com.glooboo.umessage.models.Message import kotlinx.coroutines.runBlocking @@ -28,7 +30,7 @@ class ScheduledStateReader(private val app: Application) { id = message.id, threadId = message.threadId, title = titleOf(message), - text = message.body, + text = textOf(message), millis = message.millis(), held = message.isHeldScheduled(), repeat = repeats[message.id] ?: RepeatRule.NONE, @@ -38,7 +40,16 @@ class ScheduledStateReader(private val app: Application) { ) } - private fun titleOf(message: Message): String = - runCatching { app.conversationsDB.getConversationWithThreadId(message.threadId)?.title }.getOrNull() + private fun titleOf(message: Message): String { + val title = runCatching { app.conversationsDB.getConversationWithThreadId(message.threadId)?.title }.getOrNull() ?.takeIf { it.isNotBlank() } ?: message.participants.getThreadTitle() + return displayTitle(app, title) + } + + /** The text, or the attachment label when a picture-only message has no text. */ + private fun textOf(message: Message): String { + val hasAttachment = message.attachment?.attachments?.isNotEmpty() == true + if (message.body.isBlank() && hasAttachment) return app.getString(R.string.share_text_attachment) + return message.body + } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/settings/SimNamesDialog.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/settings/SimNamesDialog.kt index ce2b9d78..a78f3461 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/settings/SimNamesDialog.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/settings/SimNamesDialog.kt @@ -14,7 +14,9 @@ import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.SideEffect import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource @@ -24,11 +26,11 @@ import com.glooboo.umessage.R import com.glooboo.umessage.helpers.SimName import com.glooboo.umessage.helpers.SimNames -/** What the user typed for one active SIM, kept while the dialog is open. */ -private class SimEntry(val sim: SimCard, nickname: String, number: String) { - var nickname by mutableStateOf(nickname) - var number by mutableStateOf(number) -} +/** + * What the user typed for one active SIM. The fields keep their text in saved state (a turn of the screen does not + * lose it) and copy it here, where [onSave] reads it. + */ +private class SimEntry(val sim: SimCard, var nickname: String, var number: String) /** * I34: a nickname and a number for each active SIM. Carriers often do not give the number to apps, so it is typed here; @@ -76,6 +78,12 @@ internal fun SimNamesDialog( @Composable private fun SimEntryFields(entry: SimEntry) { + var nickname by rememberSaveable(entry.sim.slot) { mutableStateOf(entry.nickname) } + var number by rememberSaveable(entry.sim.slot) { mutableStateOf(entry.number) } + SideEffect { + entry.nickname = nickname + entry.number = number + } Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { Text( if (entry.sim.carrier.isBlank()) { @@ -86,15 +94,15 @@ private fun SimEntryFields(entry: SimEntry) { style = MaterialTheme.typography.titleSmall, ) OutlinedTextField( - value = entry.nickname, - onValueChange = { entry.nickname = it.take(SimNames.MAX_NICKNAME_LENGTH) }, + value = nickname, + onValueChange = { nickname = it.take(SimNames.MAX_NICKNAME_LENGTH) }, label = { Text(stringResource(R.string.i34_nickname)) }, singleLine = true, modifier = Modifier.fillMaxWidth(), ) OutlinedTextField( - value = entry.number, - onValueChange = { entry.number = it.take(SimNames.MAX_NUMBER_LENGTH) }, + value = number, + onValueChange = { number = it.take(SimNames.MAX_NUMBER_LENGTH) }, label = { Text(stringResource(R.string.i34_number)) }, singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone), diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedHints.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedHints.kt index b829bcb1..31933f8f 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedHints.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedHints.kt @@ -19,6 +19,9 @@ object BlockedHints { "بانک", "حساب", "تراکنش", "مانده", "برداشت", "واریز", ) + // spamui-8: "account locked, call 12345" is a scam's ask, not a notice: a bank text that asks to call is no hint. + private val askWords = listOf("call", "dial", "reply", "contact", "whatsapp", "تماس", "زنگ", "پاسخ") + /** Persian and Arabic-Indic digits to ASCII, so one pattern covers every script. */ fun asciiDigits(text: String): String = buildString(text.length) { for (c in text) { @@ -38,7 +41,7 @@ object BlockedHints { /** * Whether a blocked [body] looks like a verification code, or a bank notice without a link. A code counts even * with a link (owner decision: Smart mode lets those through, so Strict's held ones are flagged too); a bank - * notice with a link is left out: phishing copies exactly those texts. + * notice with a link, or one that asks to call or reply, is left out: phishing copies exactly those texts. */ fun looksImportant(body: String): Boolean { if (body.isBlank()) return false @@ -46,6 +49,7 @@ object BlockedHints { if (OtpDetector.looksLikeOtp(body)) return true if (hasLink(body)) return false val text = asciiDigits(body).lowercase() + if (askWords.any { it in text }) return false return bankWords.any { it in text } && code.containsMatchIn(text) } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedScreen.kt index 177c2c49..073c50e6 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedScreen.kt @@ -288,8 +288,12 @@ fun BlockedScreen( } if (confirmDeleteAll) { val total = state.groups.sumOf { it.messages.size } + // spamui-16: with a chip or a search active only the listed messages go, and the title says so. + val listedOnly = state.filter != BlockedFilter.All || state.query.isNotEmpty() ConfirmDialog( - title = stringResource(R.string.spam_ui_delete_all_title), + title = stringResource( + if (listedOnly) R.string.minor_sui_delete_listed_title else R.string.spam_ui_delete_all_title, + ), message = pluralStringResource(R.plurals.spam_ui_delete_all_message, total, total), confirmLabel = stringResource(R.string.screens_delete), destructive = true, diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedThread.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedThread.kt index 409a1f80..007d09a7 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedThread.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedThread.kt @@ -89,6 +89,9 @@ import com.glooboo.umessage.ui.thread.timeOnlyLabel import java.time.Instant import java.time.LocalDate import java.time.ZoneId +import kotlinx.coroutines.delay + +private const val CLOSE_GRACE_MS = 250L /** One row of the sender thread: a day header or a message bubble. */ sealed interface BlockedThreadItem { @@ -183,7 +186,12 @@ fun BlockedThreadRoute( // restored from another screen), or the user moved or deleted them and kept that. val close by rememberUpdatedState(onBack) LaunchedEffect(settled, closeWhenEmpty, seen) { - if (settled && (closeWhenEmpty || !seen)) close() + if (settled && (closeWhenEmpty || !seen)) { + // spamui-22: a short grace, so a snackbar queued at this very moment (it flips [settled] back and + // restarts this effect) is shown before the screen goes. + delay(CLOSE_GRACE_MS) + close() + } } val actions = remember(viewModel, address, onBack, onOpenRules) { BlockedThreadActions( diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModel.kt index 0e441581..7ea14a58 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModel.kt @@ -478,15 +478,22 @@ class BlockedViewModel( private suspend fun restore(messages: List): Pair, List> { var error = false + val inInbox = setOf(RestoreOutcome.RESTORED, RestoreOutcome.TEXT_ONLY) + // spamui-1: a bigger batch shows its first restored message in the chat list at once, not only at the end. + var firstShown = messages.size <= 1 val receipts = messages.associate { message -> - message.id to runCatching { repository.restore(message.id) }.getOrElse { + val receipt = runCatching { repository.restore(message.id) }.getOrElse { error = true RestoreReceipt(null, RestoreOutcome.FAILED) } + if (!firstShown && receipt.outcome in inInbox) { + firstShown = true + refreshConversations() + } + message.id to receipt } if (error) events.trySend(BlockedEvent.Failed) val now = System.currentTimeMillis() - val inInbox = setOf(RestoreOutcome.RESTORED, RestoreOutcome.TEXT_ONLY) val logged = messages .filter { receipts[it.id]?.outcome in inInbox } .map { RestoredEntry(it.address, it.receivedAt, now) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/CarrierReportUi.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/CarrierReportUi.kt index 0bfa4a1e..4508b947 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/CarrierReportUi.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/CarrierReportUi.kt @@ -51,7 +51,7 @@ internal suspend fun reportToCarrier( val sent = message != null && withContext(Dispatchers.IO) { runCatching { CarrierReport(context).send(message) }.getOrDefault(false) } - val text = context.getString(if (sent) R.string.carrier_report_sent else R.string.carrier_report_failed) + val text = context.getString(if (sent) R.string.minor_sui_report_queued else R.string.carrier_report_failed) snackbar.showSnackbar(text, duration = SnackbarDuration.Short) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/ForwardOwnNumbers.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/ForwardOwnNumbers.kt index f1906e1e..0223ea17 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/ForwardOwnNumbers.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/ForwardOwnNumbers.kt @@ -1,30 +1,45 @@ package com.glooboo.umessage.ui.spam -import android.Manifest import android.annotation.SuppressLint import android.content.Context -import android.content.pm.PackageManager +import android.os.Build +import android.telephony.SubscriptionInfo import android.telephony.SubscriptionManager -import androidx.core.content.ContextCompat +import android.telephony.TelephonyManager /** * The phone numbers of this phone's own SIMs, as far as Android tells us (often it does not). Used to refuse a forward - * target that is the phone itself, which would loop. Empty when permission is missing or the platform returns nothing. + * target that is the phone itself, which would loop. Nothing is asked of the user and no permission is added to the + * manifest (spamui-17): every source is tried and one that Android refuses is skipped, so the list is simply shorter, + * or empty, when the phone keeps its numbers to itself. The default SMS app may read them through READ_SMS. */ object ForwardOwnNumbers { @SuppressLint("MissingPermission") - @Suppress("DEPRECATION") fun load(context: Context): List { - val granted = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == - PackageManager.PERMISSION_GRANTED - if (!granted) return emptyList() - return try { - val manager = context.getSystemService(SubscriptionManager::class.java) ?: return emptyList() - manager.activeSubscriptionInfoList.orEmpty().mapNotNull { info -> info.number?.takeIf { it.isNotBlank() } } - } catch (_: SecurityException) { - emptyList() - } catch (_: RuntimeException) { - emptyList() + val manager = context.getSystemService(SubscriptionManager::class.java) ?: return emptyList() + val subscriptions = guarded { manager.activeSubscriptionInfoList.orEmpty() }.orEmpty() + val numbers = subscriptions.mapNotNull { info -> numberOf(manager, info) } + val line = guarded { context.getSystemService(TelephonyManager::class.java)?.line1Number } + return (numbers + listOfNotNull(line)).filter { it.isNotBlank() }.distinct() + } + + @SuppressLint("MissingPermission") + @Suppress("DEPRECATION") + private fun numberOf(manager: SubscriptionManager, info: SubscriptionInfo): String? { + val modern = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + guarded { manager.getPhoneNumber(info.subscriptionId) } + } else { + null } + return modern?.takeIf { it.isNotBlank() } ?: info.number?.takeIf { it.isNotBlank() } + } + + /** Runs [read]; null when Android refuses (no permission) or fails. */ + private fun guarded(read: () -> T): T? = try { + read() + } catch (_: SecurityException) { + null + } catch (_: RuntimeException) { + null } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/PatternBlock.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/PatternBlock.kt index dd97b523..c700e528 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/PatternBlock.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/PatternBlock.kt @@ -85,7 +85,7 @@ private fun blockLabel(block: PatternBlock): Int = when (block) { } private fun blockSentence(block: PatternBlock): Int = when (block) { - PatternBlock.LINK -> R.string.e_pattern_link_sentence + PatternBlock.LINK -> R.string.minor_sui_pattern_link_sentence PatternBlock.LONG_NUMBER -> R.string.e_pattern_long_number_sentence PatternBlock.STARTS_WITH -> R.string.e_pattern_starts_with_sentence PatternBlock.ANY_OF -> R.string.e_pattern_any_of_sentence diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/theme/UMessageTheme.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/theme/UMessageTheme.kt index 4f52cda7..a592db3d 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/theme/UMessageTheme.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/theme/UMessageTheme.kt @@ -39,7 +39,7 @@ object UMessageColors { val Gold = Color(0xFFA16207) val GoldLight = Color(0xFFFFDDA8) val Background = Color(0xFFF8FAFC) - val Danger = Color(0xFFDC2626) + val Danger = Color(0xFFB91C1C) val Success = Color(0xFF0F9D6B) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadPeopleController.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadPeopleController.kt index f8d64795..a553f978 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadPeopleController.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadPeopleController.kt @@ -61,7 +61,11 @@ class ThreadPeopleController( } } - fun addNumber(number: String) = add(ThreadRecipients.contactForNumber(number)) + /** Adds the typed number; text that is not a phone number (letters) is left in the field and not added. */ + fun addNumber(number: String) { + val valid = ThreadRecipients.typedNumberOrNull(number) ?: return + add(ThreadRecipients.contactForNumber(valid)) + } private fun add(contact: SimpleContact) { vm.peopleQuery.clearText() diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadRecipients.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadRecipients.kt index d12f2468..0d5b6007 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadRecipients.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadRecipients.kt @@ -2,6 +2,7 @@ package com.glooboo.umessage.ui.thread import com.glooboo.umessage.messaging.isShortCodeWithLetters import com.glooboo.umessage.spam.engine.NumberNormalizer +import com.glooboo.umessage.ui.components.isBareNumber import com.google.gson.Gson import com.google.gson.reflect.TypeToken import org.fossify.commons.models.PhoneNumber @@ -125,6 +126,18 @@ class ThreadRecipients(val contacts: List = emptyList()) { return contacts } + /** + * What was typed in the people editor as a phone number in ASCII digits (the app's own digits are accepted), + * or null when it is not a number: "abc" must not become a recipient. + */ + fun typedNumberOrNull(typed: String): String? { + val ascii = typed.trim().map { c -> Character.digit(c, DECIMAL).takeIf { it >= 0 }?.let { '0' + it } ?: c } + .joinToString("") + return ascii.takeIf { isBareNumber(it) } + } + + private const val DECIMAL = 10 + /** A bare contact for [number], keyed by the number's hash as the old code did. */ fun contactForNumber(number: String, name: String = number): SimpleContact = SimpleContact( rawId = number.hashCode(), diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadScreen.kt index 5decd7b4..238b22b4 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadScreen.kt @@ -222,7 +222,8 @@ private fun MessageList(vm: ThreadViewModel, actions: ThreadActions, modifier: M } val index = vm.rows.indexOfFirst { (it as? ThreadRow.Bubble)?.message?.key == command.message } if (index >= 0) { - listState.animateScrollToItem(index) + // Reversed list: a negative offset lifts the target from the bottom edge to about the middle. + listState.animateScrollToItem(index, -(listState.layoutInfo.viewportSize.height / 2)) if (command.flash) vm.flashMessage(command.message) } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadViewModel.kt index c36eb012..a5313236 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadViewModel.kt @@ -141,6 +141,13 @@ class ThreadViewModel(private val saved: SavedStateHandle = SavedStateHandle(emp val isScheduling: Boolean get() = scheduledMillis != null + init { + // A new view model with a saved edit id means the process was killed: the picked attachments (not saved) are + // gone, and saving under the old id would drop the message's attachments and delete their copies. The edit + // becomes a new scheduled message instead; the original stays as it was. + if (scheduledMessageId != null) scheduledMessageId = null + } + fun clearSchedule() { scheduledMillis = null scheduledMessageId = null diff --git a/app/src/main/res/values-fa/strings_minor_core.xml b/app/src/main/res/values-fa/strings_minor_core.xml new file mode 100644 index 00000000..d24a7374 --- /dev/null +++ b/app/src/main/res/values-fa/strings_minor_core.xml @@ -0,0 +1,4 @@ + + + پیام زمان‌بندی‌شدهٔ شما به «%1$s» ارسال نشد: پیوست آن دیگر باز نمی‌شود (%2$s). گفتگو را باز کنید و پیوست را دوباره اضافه کنید. + diff --git a/app/src/main/res/values-fa/strings_minor_mt.xml b/app/src/main/res/values-fa/strings_minor_mt.xml new file mode 100644 index 00000000..f23bb0a2 --- /dev/null +++ b/app/src/main/res/values-fa/strings_minor_mt.xml @@ -0,0 +1,4 @@ + + + این گفتگو دیگر وجود ندارد. + diff --git a/app/src/main/res/values-fa/strings_minor_sui.xml b/app/src/main/res/values-fa/strings_minor_sui.xml new file mode 100644 index 00000000..bb65b2bd --- /dev/null +++ b/app/src/main/res/values-fa/strings_minor_sui.xml @@ -0,0 +1,6 @@ + + + اسپم‌های فهرست‌شده حذف شوند؟ + گزارش برای ارسال به اپراتور در صف قرار گرفت + پیام‌هایی را پیدا می‌کند که لینکی با http، https یا www دارند. + diff --git a/app/src/main/res/values/strings_minor_core.xml b/app/src/main/res/values/strings_minor_core.xml new file mode 100644 index 00000000..6b5faf6a --- /dev/null +++ b/app/src/main/res/values/strings_minor_core.xml @@ -0,0 +1,4 @@ + + + Your scheduled message to \'%1$s\' was not sent: its attachment can no longer be opened (%2$s). Open the chat to add it again. + diff --git a/app/src/main/res/values/strings_minor_mt.xml b/app/src/main/res/values/strings_minor_mt.xml new file mode 100644 index 00000000..421a1078 --- /dev/null +++ b/app/src/main/res/values/strings_minor_mt.xml @@ -0,0 +1,4 @@ + + + This chat no longer exists. + diff --git a/app/src/main/res/values/strings_minor_sui.xml b/app/src/main/res/values/strings_minor_sui.xml new file mode 100644 index 00000000..5eadc85d --- /dev/null +++ b/app/src/main/res/values/strings_minor_sui.xml @@ -0,0 +1,6 @@ + + + Delete the listed spam? + Report queued to your carrier + Matches messages that contain a link starting with http, https or www. + diff --git a/app/src/test/kotlin/com/glooboo/umessage/MinorHmTest.kt b/app/src/test/kotlin/com/glooboo/umessage/MinorHmTest.kt new file mode 100644 index 00000000..a282f857 --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/MinorHmTest.kt @@ -0,0 +1,49 @@ +package com.glooboo.umessage + +import com.glooboo.umessage.extensions.joinMmsText +import com.glooboo.umessage.models.Conversation +import com.glooboo.umessage.ui.newconversation.filterContacts +import com.google.common.truth.Truth.assertThat +import org.fossify.commons.models.PhoneNumber +import org.fossify.commons.models.SimpleContact +import org.junit.Test + +class MinorHmTest { + + private fun contact(id: Int, name: String, number: String) = SimpleContact( + rawId = id, + contactId = id, + name = name, + photoUri = "", + phoneNumbers = arrayListOf(PhoneNumber(number, 0, "", number)), + birthdays = ArrayList(), + anniversaries = ArrayList(), + ) + + private fun conversation(archived: Boolean) = Conversation( + threadId = 1, snippet = "s", date = 1, read = true, title = "t", photoUri = "", + isGroupConversation = false, phoneNumber = "1", isArchived = archived, + ) + + @Test + fun numberPrefixHitsComeBeforeInnerNumberHits() { + val inner = contact(1, "Alpha", "9915550") + val prefix = contact(2, "Beta", "5550199") + assertThat(filterContacts(listOf(inner, prefix), "555")).containsExactly(prefix, inner).inOrder() + } + + @Test + fun mmsTextSlidesAreJoinedInOrder() { + assertThat(joinMmsText("", "one")).isEqualTo("one") + assertThat(joinMmsText("one", "two")).isEqualTo("one\ntwo") + assertThat(joinMmsText("one", "")).isEqualTo("one") + } + + @Test + fun archivedFlagCountsOnlyWhenAsked() { + val a = conversation(archived = true) + val b = conversation(archived = false) + assertThat(Conversation.areContentsTheSame(a, b)).isTrue() + assertThat(Conversation.areContentsTheSame(a, b, compareArchived = true)).isFalse() + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/helpers/smartreply/SmartReplyPolicyTest.kt b/app/src/test/kotlin/com/glooboo/umessage/helpers/smartreply/SmartReplyPolicyTest.kt index 06d70785..079f7b3c 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/helpers/smartreply/SmartReplyPolicyTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/helpers/smartreply/SmartReplyPolicyTest.kt @@ -59,6 +59,8 @@ class SmartReplyPolicyTest { assertThat(SmartReplyPolicy.bodyAllowed("code 1234")).isFalse() assertThat(SmartReplyPolicy.bodyAllowed("code ۱۲۳۴")).isFalse() assertThat(SmartReplyPolicy.bodyAllowed("at 5 pm")).isTrue() + assertThat(SmartReplyPolicy.bodyAllowed("see you in 2025")).isTrue() + assertThat(SmartReplyPolicy.bodyAllowed("code 20245")).isFalse() } @Test diff --git a/app/src/test/kotlin/com/glooboo/umessage/messaging/ScheduledAttachmentsTest.kt b/app/src/test/kotlin/com/glooboo/umessage/messaging/ScheduledAttachmentsTest.kt index 1e3d204f..d9997dd5 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/messaging/ScheduledAttachmentsTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/messaging/ScheduledAttachmentsTest.kt @@ -170,7 +170,8 @@ class ScheduledAttachmentsTest { val held = offMainThread { context.messagesDB.getAllScheduledMessages() }.single() assertThat(held.type).isEqualTo(Telephony.Sms.MESSAGE_TYPE_FAILED) val text = shadowOf(notifications.single()).contentText.toString() - assertThat(text).isEqualTo(context.getString(R.string.scheduled_attachment_missing, "Sara")) + assertThat(text).contains("Sara") + assertThat(text).contains("photo.jpg") } @Test diff --git a/app/src/test/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepositoryTest.kt b/app/src/test/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepositoryTest.kt index 27549162..ab37ee13 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepositoryTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/spam/data/DefaultSpamRepositoryTest.kt @@ -44,6 +44,7 @@ class DefaultSpamRepositoryTest { var mmsDeliveryWorks = true var smsDeliveryWorks = true var removeWorks = true + var alreadyInInbox = false val removed = mutableListOf>() private var nextInboxId = 500L override fun notifyBlocked(message: BlockedMessage) { @@ -53,7 +54,7 @@ class DefaultSpamRepositoryTest { override fun deliverRestored(pending: PendingSmsEntity): Long? { if (!smsDeliveryWorks) return null delivered += pending - return nextInboxId++ + return if (alreadyInInbox) 0L else nextInboxId++ } override fun deliverRestoredMms(message: BlockedMessage): Long? { @@ -300,6 +301,17 @@ class DefaultSpamRepositoryTest { assertEquals(1, dao.getAllBlocked().size) } + /** The inbox already held the message (delivery wrote no row): undo has nothing to remove and still restores. */ + @Test fun undoWhenTheMessageWasAlreadyInTheInboxPutsTheBlockedRowBack() = runTest { + platform.alreadyInInbox = true + val id = repo.storeBlocked(blocked()) + val receipt = repo.restore(id) + assertEquals(0L, receipt.inboxId) + assertTrue(repo.undoRestore(receipt)) + assertTrue(platform.removed.isEmpty()) + assertEquals(1, dao.getAllBlocked().size) + } + /** The inbox copy could not be removed: the message stays restored (never in neither place). */ @Test fun undoThatCannotRemoveTheInboxCopyLeavesTheRestoreDone() = runTest { val id = repo.storeBlocked(blocked()) diff --git a/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamSettingsStoreTest.kt b/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamSettingsStoreTest.kt index ac03f823..d4b0e11c 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamSettingsStoreTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/spam/data/SpamSettingsStoreTest.kt @@ -33,4 +33,11 @@ class SpamSettingsStoreTest { assertThat(store.claimPurge(now = 1_000_001)).isFalse() assertThat(store.claimPurge(now = 1_000_000 + PurgePolicy.INTERVAL_MS)).isTrue() } + + @Test + fun releasedPurgeCanBeClaimedAgain() { + assertThat(store.claimPurge(now = 1_000_000)).isTrue() + store.releasePurge() + assertThat(store.claimPurge(now = 1_000_001)).isTrue() + } } diff --git a/app/src/test/kotlin/com/glooboo/umessage/spam/mms/BlockedMmsPolicyTest.kt b/app/src/test/kotlin/com/glooboo/umessage/spam/mms/BlockedMmsPolicyTest.kt new file mode 100644 index 00000000..0632d004 --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/spam/mms/BlockedMmsPolicyTest.kt @@ -0,0 +1,20 @@ +package com.glooboo.umessage.spam.mms + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class BlockedMmsPolicyTest { + + @Test fun smallOrUnknownSizeIsDownloadedButHugeIsNot() { + assertTrue(BlockedMmsPolicy.sizeAllowed(0)) + assertTrue(BlockedMmsPolicy.sizeAllowed(BlockedMmsPolicy.MAX_MESSAGE_BYTES)) + assertFalse(BlockedMmsPolicy.sizeAllowed(BlockedMmsPolicy.MAX_MESSAGE_BYTES + 1)) + } + + @Test fun roamingOrFullStorageSkipsTheDownload() { + assertTrue(BlockedMmsPolicy.mayDownload(roaming = false, keptFiles = 0)) + assertFalse(BlockedMmsPolicy.mayDownload(roaming = true, keptFiles = 0)) + assertFalse(BlockedMmsPolicy.mayDownload(roaming = false, keptFiles = BlockedMmsPolicy.MAX_KEPT_FILES)) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedHintsTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedHintsTest.kt index 32970a0d..0ec9ee85 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedHintsTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedHintsTest.kt @@ -37,6 +37,12 @@ class BlockedHintsTest { assertThat(BlockedHints.looksImportant("Debit of 120000 from your account http://evil.example")).isFalse() } + @Test + fun bankNoticeThatAsksToCallIsNotImportant() { + assertThat(BlockedHints.looksImportant("Your account is locked, call 12345")).isFalse() + assertThat(BlockedHints.looksImportant("Your verification code is 482913, call us if not you")).isTrue() + } + @Test fun plainPromoIsNotImportant() { assertThat(BlockedHints.looksImportant("Big sale this weekend, 50% off")).isFalse() diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedRound2S1Test.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedRound2S1Test.kt index bfb147e5..b916429e 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedRound2S1Test.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedRound2S1Test.kt @@ -83,11 +83,11 @@ class BlockedRound2S1Test { awaitUntil { events.any { it is BlockedEvent.Restored } } val restored = events.filterIsInstance().single() assertThat(restored.count).isEqualTo(2) - assertThat(vm.state.value.groups.single().messages.map { it.id }).containsExactly(2L) + awaitUntil { vm.state.value.groups.singleOrNull()?.messages?.map { it.id } == listOf(2L) } vm.undoRestore(restored.token) awaitUntil { vm.state.value.groups.singleOrNull()?.messages?.size == 3 } - assertThat(vm.state.value.restored).isEmpty() + awaitUntil { vm.state.value.restored.isEmpty() } } @Test diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModelActionsTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModelActionsTest.kt index 5a861b5e..47059ea4 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModelActionsTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedViewModelActionsTest.kt @@ -194,7 +194,7 @@ class BlockedViewModelActionsTest { awaitUntil { events.isNotEmpty() } val event = events.single() as BlockedEvent.Deleted assertThat(event.count).isEqualTo(1) - assertThat(vm.state.value.groups.single { it.address == NUMBER }.messages.map { it.id }).containsExactly(2L) + awaitUntil { vm.state.value.groups.single { it.address == NUMBER }.messages.map { it.id } == listOf(2L) } vm.undoDelete(event.token) awaitUntil { vm.state.value.groups.single { it.address == NUMBER }.messages.size == 2 } assertThat(blocked()).hasSize(3) diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/thread/ThreadViewModelStateTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/ThreadViewModelStateTest.kt index 2f780f50..4a7461ee 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/thread/ThreadViewModelStateTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/ThreadViewModelStateTest.kt @@ -28,7 +28,8 @@ class ThreadViewModelStateTest { val restored = ThreadViewModel(handle) assertTrue(restored.isScheduling) assertEquals(1_800_000_000_000L, restored.scheduledMillis) - assertEquals(42L, restored.scheduledMessageId) + // The attachments of the edit are not saved, so the edit id is dropped (the message is saved as a new one). + assertNull(restored.scheduledMessageId) } @Test diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/thread/TypedNumberTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/TypedNumberTest.kt new file mode 100644 index 00000000..562e8d34 --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/TypedNumberTest.kt @@ -0,0 +1,27 @@ +package com.glooboo.umessage.ui.thread + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** Thread-22: only phone numbers typed in the people editor become recipients. */ +class TypedNumberTest { + + @Test + fun numbersPass() { + assertEquals("+98 912 345 6789", ThreadRecipients.typedNumberOrNull(" +98 912 345 6789 ")) + assertEquals("5550101", ThreadRecipients.typedNumberOrNull("5550101")) + } + + @Test + fun persianDigitsBecomeAscii() { + assertEquals("0912", ThreadRecipients.typedNumberOrNull("\u06F0\u06F9\u06F1\u06F2")) + } + + @Test + fun lettersAreRejected() { + assertNull(ThreadRecipients.typedNumberOrNull("abc")) + assertNull(ThreadRecipients.typedNumberOrNull("Bank1234")) + assertNull(ThreadRecipients.typedNumberOrNull("")) + } +} From 08c691ecceeb37cf1480ddb1cec9d26a65e11547 Mon Sep 17 00:00:00 2001 From: Sajad <220944007+MyNameIsGlooboo@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:09:30 +0000 Subject: [PATCH 5/5] Translate the new minor-finding strings into 20 languages Co-Authored-By: Claude Sonnet 5.5 --- app/src/main/res/values-ar/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-bn/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-de/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-es/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-fr/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-hi/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-in/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-it/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-ja/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-ko/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-pl/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-pt-rBR/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-ru/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-th/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-tr/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-uk/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-ur/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-vi/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-zh-rCN/strings_minor_i18n.xml | 8 ++++++++ app/src/main/res/values-zh-rTW/strings_minor_i18n.xml | 8 ++++++++ 20 files changed, 160 insertions(+) create mode 100644 app/src/main/res/values-ar/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-bn/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-de/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-es/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-fr/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-hi/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-in/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-it/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-ja/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-ko/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-pl/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-pt-rBR/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-ru/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-th/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-tr/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-uk/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-ur/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-vi/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-zh-rCN/strings_minor_i18n.xml create mode 100644 app/src/main/res/values-zh-rTW/strings_minor_i18n.xml diff --git a/app/src/main/res/values-ar/strings_minor_i18n.xml b/app/src/main/res/values-ar/strings_minor_i18n.xml new file mode 100644 index 00000000..db096000 --- /dev/null +++ b/app/src/main/res/values-ar/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + لم تُرسَل رسالتك المجدولة إلى «%1$s»: تعذّر فتح المرفق (%2$s). افتح المحادثة لإضافته من جديد. + هذه المحادثة لم تعد موجودة. + حذف الرسائل غير المرغوب فيها المعروضة؟ + تم وضع البلاغ في قائمة الإرسال إلى مشغّل الشبكة + تطابق الرسائل التي تحتوي على رابط يبدأ بـ http أو https أو www. + diff --git a/app/src/main/res/values-bn/strings_minor_i18n.xml b/app/src/main/res/values-bn/strings_minor_i18n.xml new file mode 100644 index 00000000..4a1e3100 --- /dev/null +++ b/app/src/main/res/values-bn/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + \'%1$s\'-কে পাঠানো আপনার নির্ধারিত বার্তাটি যায়নি: সংযুক্তিটি আর খোলা যাচ্ছে না (%2$s)। আবার যোগ করতে চ্যাটটি খুলুন। + এই চ্যাটটি আর নেই। + তালিকার স্প্যামগুলো মুছবেন? + রিপোর্ট আপনার মোবাইল অপারেটরকে পাঠানোর অপেক্ষায় আছে + http, https বা www দিয়ে শুরু হওয়া লিংক আছে এমন বার্তার সাথে মেলে। + diff --git a/app/src/main/res/values-de/strings_minor_i18n.xml b/app/src/main/res/values-de/strings_minor_i18n.xml new file mode 100644 index 00000000..b59eb544 --- /dev/null +++ b/app/src/main/res/values-de/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + Deine geplante Nachricht an „%1$s“ wurde nicht gesendet: Der Anhang lässt sich nicht mehr öffnen (%2$s). Öffne den Chat, um ihn erneut hinzuzufügen. + Dieser Chat existiert nicht mehr. + Aufgelisteten Spam löschen? + Meldung an deinen Mobilfunkanbieter vorgemerkt + Trifft auf Nachrichten zu, die einen Link enthalten, der mit http, https oder www beginnt. + diff --git a/app/src/main/res/values-es/strings_minor_i18n.xml b/app/src/main/res/values-es/strings_minor_i18n.xml new file mode 100644 index 00000000..3777de82 --- /dev/null +++ b/app/src/main/res/values-es/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + Tu mensaje programado para «%1$s» no se envió: ya no se puede abrir el archivo adjunto (%2$s). Abre el chat para agregarlo de nuevo. + Este chat ya no existe. + ¿Eliminar el spam de la lista? + Denuncia en cola para tu operador + Coincide con los mensajes que contienen un enlace que empieza por http, https o www. + diff --git a/app/src/main/res/values-fr/strings_minor_i18n.xml b/app/src/main/res/values-fr/strings_minor_i18n.xml new file mode 100644 index 00000000..fc7ba3d0 --- /dev/null +++ b/app/src/main/res/values-fr/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + Votre message programmé pour « %1$s » n\'a pas été envoyé : la pièce jointe ne peut plus être ouverte (%2$s). Ouvrez la discussion pour l\'ajouter à nouveau. + Cette discussion n\'existe plus. + Supprimer les spams listés ? + Signalement en attente d\'envoi à votre opérateur + Correspond aux messages contenant un lien commençant par http, https ou www. + diff --git a/app/src/main/res/values-hi/strings_minor_i18n.xml b/app/src/main/res/values-hi/strings_minor_i18n.xml new file mode 100644 index 00000000..c11138f9 --- /dev/null +++ b/app/src/main/res/values-hi/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + \'%1$s\' को भेजा गया आपका शेड्यूल किया संदेश नहीं गया: अटैचमेंट अब खुल नहीं पा रहा (%2$s)। उसे फिर से जोड़ने के लिए चैट खोलें। + यह चैट अब मौजूद नहीं है। + सूची के स्पैम मिटाएं? + शिकायत आपके मोबाइल ऑपरेटर को भेजने की कतार में है + ऐसे संदेशों से मेल खाता है जिनमें http, https या www से शुरू होने वाला लिंक हो। + diff --git a/app/src/main/res/values-in/strings_minor_i18n.xml b/app/src/main/res/values-in/strings_minor_i18n.xml new file mode 100644 index 00000000..c142b991 --- /dev/null +++ b/app/src/main/res/values-in/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + Pesan terjadwal Anda ke \'%1$s\' tidak terkirim: lampirannya tidak bisa dibuka lagi (%2$s). Buka obrolan untuk menambahkannya lagi. + Obrolan ini sudah tidak ada. + Hapus spam yang tercantum? + Laporan masuk antrean ke operator Anda + Cocok dengan pesan yang berisi tautan diawali http, https, atau www. + diff --git a/app/src/main/res/values-it/strings_minor_i18n.xml b/app/src/main/res/values-it/strings_minor_i18n.xml new file mode 100644 index 00000000..85954dd8 --- /dev/null +++ b/app/src/main/res/values-it/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + Il messaggio programmato per \'%1$s\' non è stato inviato: l\'allegato non si apre più (%2$s). Apri la chat per aggiungerlo di nuovo. + Questa chat non esiste più. + Eliminare lo spam in elenco? + Segnalazione in coda per il tuo operatore + Corrisponde ai messaggi che contengono un link che inizia con http, https o www. + diff --git a/app/src/main/res/values-ja/strings_minor_i18n.xml b/app/src/main/res/values-ja/strings_minor_i18n.xml new file mode 100644 index 00000000..31fb4f45 --- /dev/null +++ b/app/src/main/res/values-ja/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + 「%1$s」宛の予約メッセージは送信されませんでした。添付ファイルを開けなくなっています(%2$s)。チャットを開いて、もう一度添付してください。 + このチャットはもう存在しません。 + 表示中の迷惑メッセージを削除しますか? + 通信事業者への報告を待機中です + http、https、www で始まるリンクを含むメッセージに一致します。 + diff --git a/app/src/main/res/values-ko/strings_minor_i18n.xml b/app/src/main/res/values-ko/strings_minor_i18n.xml new file mode 100644 index 00000000..2d8a9d92 --- /dev/null +++ b/app/src/main/res/values-ko/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + \'%1$s\'에게 예약한 메시지를 보내지 못했어요. 첨부 파일을 더 이상 열 수 없어요(%2$s). 채팅을 열어 다시 첨부해 주세요. + 이 채팅은 더 이상 없어요. + 목록의 스팸을 삭제할까요? + 통신사에 보낼 신고가 대기 중이에요 + http, https 또는 www로 시작하는 링크가 포함된 메시지와 일치해요. + diff --git a/app/src/main/res/values-pl/strings_minor_i18n.xml b/app/src/main/res/values-pl/strings_minor_i18n.xml new file mode 100644 index 00000000..b6bcdd0f --- /dev/null +++ b/app/src/main/res/values-pl/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + Zaplanowana wiadomość do \'%1$s\' nie została wysłana: nie można już otworzyć załącznika (%2$s). Otwórz czat, aby dodać go ponownie. + Ten czat już nie istnieje. + Usunąć spam z listy? + Zgłoszenie czeka na wysłanie do operatora + Pasuje do wiadomości zawierających link zaczynający się od http, https lub www. + diff --git a/app/src/main/res/values-pt-rBR/strings_minor_i18n.xml b/app/src/main/res/values-pt-rBR/strings_minor_i18n.xml new file mode 100644 index 00000000..13a3d5a0 --- /dev/null +++ b/app/src/main/res/values-pt-rBR/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + Sua mensagem agendada para \'%1$s\' não foi enviada: não dá mais para abrir o anexo (%2$s). Abra a conversa para anexá-lo de novo. + Esta conversa não existe mais. + Excluir o spam listado? + Denúncia na fila para sua operadora + Corresponde a mensagens que contêm um link começando com http, https ou www. + diff --git a/app/src/main/res/values-ru/strings_minor_i18n.xml b/app/src/main/res/values-ru/strings_minor_i18n.xml new file mode 100644 index 00000000..90b0468b --- /dev/null +++ b/app/src/main/res/values-ru/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + Запланированное сообщение для «%1$s» не отправлено: вложение больше не открывается (%2$s). Откройте чат, чтобы добавить его снова. + Этого чата больше нет. + Удалить спам из списка? + Жалоба поставлена в очередь для оператора + Совпадает с сообщениями, где есть ссылка, начинающаяся с http, https или www. + diff --git a/app/src/main/res/values-th/strings_minor_i18n.xml b/app/src/main/res/values-th/strings_minor_i18n.xml new file mode 100644 index 00000000..f9143c20 --- /dev/null +++ b/app/src/main/res/values-th/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + ข้อความที่ตั้งเวลาไว้ถึง \'%1$s\' ไม่ได้ส่ง เพราะเปิดไฟล์แนบไม่ได้แล้ว (%2$s) เปิดแชทเพื่อแนบอีกครั้ง + แชทนี้ไม่มีอยู่แล้ว + ลบสแปมในรายการหรือไม่ + รายงานอยู่ในคิวส่งถึงผู้ให้บริการเครือข่ายของคุณ + ตรงกับข้อความที่มีลิงก์ขึ้นต้นด้วย http, https หรือ www + diff --git a/app/src/main/res/values-tr/strings_minor_i18n.xml b/app/src/main/res/values-tr/strings_minor_i18n.xml new file mode 100644 index 00000000..2cfbf18d --- /dev/null +++ b/app/src/main/res/values-tr/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + \'%1$s\' kişisine zamanladığınız mesaj gönderilmedi: ek artık açılamıyor (%2$s). Yeniden eklemek için sohbeti açın. + Bu sohbet artık yok. + Listelenen spam silinsin mi? + Bildirim operatörünüze gönderilmek üzere sıraya alındı + http, https veya www ile başlayan bağlantı içeren mesajlarla eşleşir. + diff --git a/app/src/main/res/values-uk/strings_minor_i18n.xml b/app/src/main/res/values-uk/strings_minor_i18n.xml new file mode 100644 index 00000000..bc719349 --- /dev/null +++ b/app/src/main/res/values-uk/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + Заплановане повідомлення для «%1$s» не надіслано: вкладення більше не відкривається (%2$s). Відкрийте чат, щоб додати його знову. + Цього чату більше немає. + Видалити спам зі списку? + Скаргу поставлено в чергу для оператора + Збігається з повідомленнями, що містять посилання, яке починається з http, https або www. + diff --git a/app/src/main/res/values-ur/strings_minor_i18n.xml b/app/src/main/res/values-ur/strings_minor_i18n.xml new file mode 100644 index 00000000..0f266e16 --- /dev/null +++ b/app/src/main/res/values-ur/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + «%1$s» کو آپ کا طے شدہ پیغام نہیں بھیجا گیا: اٹیچمنٹ اب کھل نہیں رہی (%2$s)۔ اسے دوبارہ شامل کرنے کے لیے چیٹ کھولیں۔ + یہ چیٹ اب موجود نہیں۔ + فہرست کا اسپیم حذف کریں؟ + رپورٹ آپ کے نیٹ ورک فراہم کنندہ کو بھیجنے کے لیے قطار میں ہے + ایسے پیغامات سے میل کھاتا ہے جن میں http، https یا www سے شروع ہونے والا لنک ہو۔ + diff --git a/app/src/main/res/values-vi/strings_minor_i18n.xml b/app/src/main/res/values-vi/strings_minor_i18n.xml new file mode 100644 index 00000000..93d5d9db --- /dev/null +++ b/app/src/main/res/values-vi/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + Tin nhắn đã hẹn giờ gửi tới \'%1$s\' chưa được gửi: không mở được tệp đính kèm nữa (%2$s). Hãy mở cuộc trò chuyện để đính kèm lại. + Cuộc trò chuyện này không còn nữa. + Xóa các tin nhắn rác trong danh sách? + Báo cáo đã được xếp hàng gửi tới nhà mạng của bạn + Khớp với tin nhắn có chứa liên kết bắt đầu bằng http, https hoặc www. + diff --git a/app/src/main/res/values-zh-rCN/strings_minor_i18n.xml b/app/src/main/res/values-zh-rCN/strings_minor_i18n.xml new file mode 100644 index 00000000..4e8efeca --- /dev/null +++ b/app/src/main/res/values-zh-rCN/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + 您定时发送给“%1$s”的短信未能发出:附件已无法打开(%2$s)。请打开会话重新添加。 + 此会话已不存在。 + 要删除列出的垃圾短信吗? + 举报已排队,等待发送给您的运营商 + 匹配包含以 http、https 或 www 开头的链接的短信。 + diff --git a/app/src/main/res/values-zh-rTW/strings_minor_i18n.xml b/app/src/main/res/values-zh-rTW/strings_minor_i18n.xml new file mode 100644 index 00000000..b5f50a14 --- /dev/null +++ b/app/src/main/res/values-zh-rTW/strings_minor_i18n.xml @@ -0,0 +1,8 @@ + + + 您排程傳送給「%1$s」的簡訊未能送出:附件已無法開啟(%2$s)。請開啟對話重新新增。 + 此對話已不存在。 + 要刪除列出的垃圾簡訊嗎? + 檢舉已排入佇列,等待傳送給您的電信業者 + 符合包含以 http、https 或 www 開頭連結的簡訊。 +