From 84194c169d953969b268bbd15b2ed92d7cb84ca2 Mon Sep 17 00:00:00 2001 From: Sajad <220944007+MyNameIsGlooboo@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:10:15 +0000 Subject: [PATCH] Review fixes and forwarding in every build Applies the 11 Nov code review: bug, performance and privacy fixes across the thread, conversation list, search, Blocked, rules, settings, backup, export, notifications and the spam engine. Adds partial-MMS Retry (ResendLedger), carrier send time (date_sent, database version 7), delete confirmation for whole chats, tappable phone numbers in bubbles, multi-select in a blocked thread, a rule test preview, Undo for read-code cleanup, a PIN length hint and timed cleanup of exports. Forwarding is available in every build, Google Play included. New strings are translated into 19 languages. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 4 + .../7.json | 468 +++ .../main/kotlin/com/glooboo/umessage/App.kt | 2 + .../umessage/activities/LinkOpenActivity.kt | 4 + .../glooboo/umessage/activities/MainRoutes.kt | 2 + .../activities/NewConversationActivity.kt | 9 +- .../umessage/activities/ThreadActivity.kt | 3374 +++++++++-------- .../glooboo/umessage/backup/SettingsBackup.kt | 12 +- .../umessage/backup/SettingsBackupFormat.kt | 33 +- .../glooboo/umessage/dialogs/AppLockDialog.kt | 6 +- .../umessage/dialogs/MessageDetailsDialog.kt | 8 +- .../export/ConversationExportFactory.kt | 186 +- .../umessage/export/ConversationExportJob.kt | 190 +- .../glooboo/umessage/extensions/Context.kt | 20 +- .../glooboo/umessage/helpers/CacheCleanup.kt | 52 + .../umessage/helpers/MessageCategories.kt | 218 +- .../umessage/helpers/ReminderNotification.kt | 178 +- .../umessage/helpers/RetentionRunner.kt | 249 +- .../glooboo/umessage/helpers/SavedTexts.kt | 9 +- .../umessage/interfaces/ConversationsDao.kt | 4 + .../umessage/interfaces/MessagesDao.kt | 678 ++-- .../glooboo/umessage/messaging/Messaging.kt | 418 +- .../glooboo/umessage/messaging/PartialSend.kt | 71 + .../receivers/ScheduledMessageReceiver.kt | 485 +-- .../glooboo/umessage/receivers/SmsReceiver.kt | 2 + .../receivers/SmsStatusSentReceiver.kt | 323 +- .../glooboo/umessage/spam/TextNormalizer.kt | 21 +- .../umessage/spam/data/DigestNotifier.kt | 2 +- .../glooboo/umessage/spam/data/PendingSms.kt | 5 + .../glooboo/umessage/spam/data/SmsDelivery.kt | 8 +- .../com/glooboo/umessage/spam/data/SpamDao.kt | 3 + .../umessage/spam/data/SpamDatabase.kt | 17 +- .../umessage/ui/components/TimeFormat.kt | 22 +- .../ui/conversations/ConversationRowCache.kt | 55 + .../ui/conversations/ConversationsModels.kt | 6 + .../ui/conversations/ConversationsScreen.kt | 1252 +++--- .../conversations/ConversationsViewModel.kt | 160 +- .../ui/details/ConversationMediaScreen.kt | 5 +- .../umessage/ui/details/ConversationSearch.kt | 11 +- .../umessage/ui/details/MediaActions.kt | 28 +- .../umessage/ui/labels/LabelEditDialog.kt | 18 +- .../glooboo/umessage/ui/lock/LockScreen.kt | 7 + .../umessage/ui/log/DecisionLogActivity.kt | 12 +- .../glooboo/umessage/ui/log/DecisionLogCsv.kt | 155 +- .../glooboo/umessage/ui/main/MainSearch.kt | 11 +- .../umessage/ui/main/MainSearchPage.kt | 2 +- .../umessage/ui/main/MainSearchViewModel.kt | 56 +- .../ui/main/NotificationsOffBanner.kt | 30 +- .../glooboo/umessage/ui/main/ShortcutHits.kt | 4 +- .../umessage/ui/settings/RestoreSummary.kt | 7 +- .../umessage/ui/settings/SettingsScreen.kt | 24 +- .../ui/settings/StorageCleanupRows.kt | 476 +-- .../umessage/ui/spam/BlockedActions.kt | 2 + .../ui/spam/BlockedNumbersViewModel.kt | 17 +- .../umessage/ui/spam/BlockedRestored.kt | 251 +- .../umessage/ui/spam/BlockedRestoredSheet.kt | 14 +- .../glooboo/umessage/ui/spam/BlockedScreen.kt | 22 +- .../umessage/ui/spam/BlockedSenderRow.kt | 8 +- .../glooboo/umessage/ui/spam/BlockedThread.kt | 62 +- .../ui/spam/BlockedThreadSelection.kt | 53 + .../umessage/ui/spam/BlockedViewModel.kt | 55 +- .../glooboo/umessage/ui/spam/CarrierReport.kt | 148 +- .../glooboo/umessage/ui/spam/RuleDryRun.kt | 139 + .../umessage/ui/spam/RuleRecentTest.kt | 94 + .../glooboo/umessage/ui/spam/RulesScreen.kt | 146 +- .../umessage/ui/spam/RulesViewModel.kt | 85 +- .../umessage/ui/spam/SenderBlocking.kt | 18 +- .../umessage/ui/spam/SettingsScreen.kt | 804 ++-- .../umessage/ui/spam/SettingsViewModel.kt | 130 +- .../umessage/ui/theme/UMessageTheme.kt | 8 +- .../glooboo/umessage/ui/thread/PhoneMatch.kt | 92 + .../glooboo/umessage/ui/thread/Tapbacks.kt | 30 +- .../ui/thread/ThreadAttachmentController.kt | 9 + .../umessage/ui/thread/ThreadBubbleStyle.kt | 323 +- .../ui/thread/ThreadExportController.kt | 241 +- .../glooboo/umessage/ui/thread/ThreadLinks.kt | 310 +- .../umessage/ui/thread/ThreadLookupCache.kt | 86 + .../umessage/ui/thread/ThreadMediaSizes.kt | 189 +- .../umessage/ui/thread/ThreadScheduleUi.kt | 423 ++- .../umessage/ui/thread/ThreadScreen.kt | 41 +- .../umessage/ui/thread/ThreadSearch.kt | 18 + .../umessage/ui/thread/ThreadSearchBar.kt | 15 +- .../ui/thread/ThreadSelectionActions.kt | 11 +- .../ui/thread/ThreadSendController.kt | 30 +- .../umessage/ui/thread/ThreadViewModel.kt | 75 +- .../umessage/ui/vcard/VCardViewerScreen.kt | 53 +- .../res/values-ar/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 21 + .../res/values-ar/strings_review_nov11.xml | 83 + .../res/values-bn/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 13 + .../res/values-bn/strings_review_nov11.xml | 63 + .../res/values-de/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 13 + .../res/values-de/strings_review_nov11.xml | 63 + .../res/values-es/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 13 + .../res/values-es/strings_review_nov11.xml | 63 + app/src/main/res/values-fa/strings.xml | 2 + .../res/values-fa/strings_auto_delete.xml | 6 + .../res/values-fa/strings_carrier_report.xml | 2 +- .../res/values-fa/strings_conversations.xml | 9 + app/src/main/res/values-fa/strings_labels.xml | 8 + .../res/values-fa/strings_media_links.xml | 1 + app/src/main/res/values-fa/strings_notify.xml | 1 + .../strings_review2_blocked_rules.xml | 14 + .../main/res/values-fa/strings_round2x.xml | 9 + .../res/values-fa/strings_rule_preview.xml | 12 + .../res/values-fa/strings_saved_texts.xml | 1 + .../main/res/values-fa/strings_screens.xml | 3 + .../main/res/values-fa/strings_settings_f.xml | 2 + .../res/values-fa/strings_thread_composer.xml | 1 + .../res/values-fa/strings_thread_phone.xml | 6 + .../res/values-fa/strings_thread_round2.xml | 10 + .../res/values-fr/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 13 + .../res/values-fr/strings_review_nov11.xml | 63 + .../res/values-hi/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 13 + .../res/values-hi/strings_review_nov11.xml | 63 + .../res/values-in/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 11 + .../res/values-in/strings_review_nov11.xml | 58 + .../res/values-it/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 13 + .../res/values-it/strings_review_nov11.xml | 63 + .../res/values-ja/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 11 + .../res/values-ja/strings_review_nov11.xml | 58 + .../res/values-ko/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 11 + .../res/values-ko/strings_review_nov11.xml | 58 + .../res/values-pl/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 17 + .../res/values-pl/strings_review_nov11.xml | 73 + .../values-pt-rBR/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 13 + .../values-pt-rBR/strings_review_nov11.xml | 63 + .../res/values-ru/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 17 + .../res/values-ru/strings_review_nov11.xml | 73 + .../res/values-th/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 11 + .../res/values-th/strings_review_nov11.xml | 58 + .../res/values-tr/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 13 + .../res/values-tr/strings_review_nov11.xml | 63 + .../res/values-uk/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 17 + .../res/values-uk/strings_review_nov11.xml | 73 + .../res/values-vi/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 11 + .../res/values-vi/strings_review_nov11.xml | 58 + .../values-zh-rCN/strings_carrier_report.xml | 2 +- .../strings_review2_blocked_rules.xml | 11 + .../values-zh-rCN/strings_review_nov11.xml | 58 + app/src/main/res/values/strings.xml | 2 + .../main/res/values/strings_auto_delete.xml | 6 + .../res/values/strings_carrier_report.xml | 32 +- .../main/res/values/strings_conversations.xml | 9 + app/src/main/res/values/strings_labels.xml | 8 + .../main/res/values/strings_media_links.xml | 1 + app/src/main/res/values/strings_notify.xml | 1 + .../values/strings_review2_blocked_rules.xml | 14 + app/src/main/res/values/strings_round2x.xml | 9 + .../main/res/values/strings_rule_preview.xml | 12 + .../main/res/values/strings_saved_texts.xml | 35 +- app/src/main/res/values/strings_screens.xml | 3 + .../main/res/values/strings_settings_f.xml | 2 + .../res/values/strings_thread_composer.xml | 1 + .../main/res/values/strings_thread_phone.xml | 7 + .../main/res/values/strings_thread_round2.xml | 12 + .../umessage/backup/BackupRuleCountsTest.kt | 39 + .../umessage/dialogs/AppLockLogicTest.kt | 6 + .../umessage/export/ExportFileTitleTest.kt | 22 + .../umessage/helpers/CacheCleanupTest.kt | 43 + .../umessage/helpers/SavedTextsTest.kt | 8 + .../umessage/messaging/PartialSendTest.kt | 74 + .../umessage/receivers/SmsReceiverTest.kt | 13 + .../spam/TextNormalizerObfuscationTest.kt | 29 + .../data/PendingSmsDateSentMigrationTest.kt | 73 + .../spam/data/SpamDatabaseMigrationTest.kt | 2 +- .../spam/engine/OtpGroupedCodeTest.kt | 31 + .../ConversationsViewModelTest.kt | 24 +- .../umessage/ui/conversations/RowCacheTest.kt | 36 + .../umessage/ui/lock/LockScreenTest.kt | 1 + .../umessage/ui/main/MainSearchTest.kt | 2 + .../umessage/ui/main/SearchNumberHitsTest.kt | 13 + .../umessage/ui/spam/BlockedRound2S1Test.kt | 234 ++ .../umessage/ui/spam/CarrierReportTest.kt | 223 +- .../umessage/ui/spam/RuleDryRunTest.kt | 91 + .../umessage/ui/thread/MediaSizesTest.kt | 11 + .../umessage/ui/thread/PhoneLinksTest.kt | 81 + .../umessage/ui/thread/SecureUrlTest.kt | 22 + .../umessage/ui/thread/ThreadRound2Test.kt | 93 + .../ui/thread/ThreadSendControllerTest.kt | 23 +- docs/PLAY_STORE.md | 2 +- 197 files changed, 10660 insertions(+), 5613 deletions(-) create mode 100644 app/schemas/com.glooboo.umessage.spam.data.SpamDatabase/7.json create mode 100644 app/src/main/kotlin/com/glooboo/umessage/helpers/CacheCleanup.kt create mode 100644 app/src/main/kotlin/com/glooboo/umessage/messaging/PartialSend.kt create mode 100644 app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationRowCache.kt create mode 100644 app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedThreadSelection.kt create mode 100644 app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleDryRun.kt create mode 100644 app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleRecentTest.kt create mode 100644 app/src/main/kotlin/com/glooboo/umessage/ui/thread/PhoneMatch.kt create mode 100644 app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadLookupCache.kt create mode 100644 app/src/main/res/values-ar/strings_review_nov11.xml create mode 100644 app/src/main/res/values-bn/strings_review_nov11.xml create mode 100644 app/src/main/res/values-de/strings_review_nov11.xml create mode 100644 app/src/main/res/values-es/strings_review_nov11.xml create mode 100644 app/src/main/res/values-fa/strings_round2x.xml create mode 100644 app/src/main/res/values-fa/strings_rule_preview.xml create mode 100644 app/src/main/res/values-fa/strings_thread_phone.xml create mode 100644 app/src/main/res/values-fa/strings_thread_round2.xml create mode 100644 app/src/main/res/values-fr/strings_review_nov11.xml create mode 100644 app/src/main/res/values-hi/strings_review_nov11.xml create mode 100644 app/src/main/res/values-in/strings_review_nov11.xml create mode 100644 app/src/main/res/values-it/strings_review_nov11.xml create mode 100644 app/src/main/res/values-ja/strings_review_nov11.xml create mode 100644 app/src/main/res/values-ko/strings_review_nov11.xml create mode 100644 app/src/main/res/values-pl/strings_review_nov11.xml create mode 100644 app/src/main/res/values-pt-rBR/strings_review_nov11.xml create mode 100644 app/src/main/res/values-ru/strings_review_nov11.xml create mode 100644 app/src/main/res/values-th/strings_review_nov11.xml create mode 100644 app/src/main/res/values-tr/strings_review_nov11.xml create mode 100644 app/src/main/res/values-uk/strings_review_nov11.xml create mode 100644 app/src/main/res/values-vi/strings_review_nov11.xml create mode 100644 app/src/main/res/values-zh-rCN/strings_review_nov11.xml create mode 100644 app/src/main/res/values/strings_round2x.xml create mode 100644 app/src/main/res/values/strings_rule_preview.xml create mode 100644 app/src/main/res/values/strings_thread_phone.xml create mode 100644 app/src/main/res/values/strings_thread_round2.xml create mode 100644 app/src/test/kotlin/com/glooboo/umessage/backup/BackupRuleCountsTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/export/ExportFileTitleTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/helpers/CacheCleanupTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/messaging/PartialSendTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/spam/TextNormalizerObfuscationTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/spam/data/PendingSmsDateSentMigrationTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/spam/engine/OtpGroupedCodeTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/ui/conversations/RowCacheTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedRound2S1Test.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/ui/spam/RuleDryRunTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/ui/thread/PhoneLinksTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/ui/thread/SecureUrlTest.kt create mode 100644 app/src/test/kotlin/com/glooboo/umessage/ui/thread/ThreadRound2Test.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 1924f215..2d52e77d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] +### Changed +- Automatic forwarding is now available in every build, including Google Play + ## [0.4.5] - 2026-11-09 ### Added - Tap a notification that holds only a verification code to copy the code (the notification closes; the Open button opens the chat). Turn it off in Settings > Notifications ("Copy the code when I tap the notification") diff --git a/app/schemas/com.glooboo.umessage.spam.data.SpamDatabase/7.json b/app/schemas/com.glooboo.umessage.spam.data.SpamDatabase/7.json new file mode 100644 index 00000000..e16bd9dd --- /dev/null +++ b/app/schemas/com.glooboo.umessage.spam.data.SpamDatabase/7.json @@ -0,0 +1,468 @@ +{ + "formatVersion": 1, + "database": { + "version": 7, + "identityHash": "b54fa4938247e6d625c6ad79a12069a4", + "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)", + "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 + } + ], + "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)", + "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" + } + ], + "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, 'b54fa4938247e6d625c6ad79a12069a4')" + ] + } +} \ No newline at end of file diff --git a/app/src/main/kotlin/com/glooboo/umessage/App.kt b/app/src/main/kotlin/com/glooboo/umessage/App.kt index ccc33e3d..f97df7e3 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/App.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/App.kt @@ -24,6 +24,7 @@ import org.fossify.commons.helpers.ensureBackgroundThread import com.glooboo.umessage.activities.CopyCodeActivity import com.glooboo.umessage.activities.SplashActivity import com.glooboo.umessage.extensions.rescheduleAllScheduledMessages +import com.glooboo.umessage.helpers.CacheCleanup import com.glooboo.umessage.helpers.DailyChecks import com.glooboo.umessage.helpers.HiddenChatsSession import com.glooboo.umessage.helpers.MessagingCache @@ -61,6 +62,7 @@ class App : FossifyApp() { ensureBackgroundThread { PendingSmsQueue.replay(this) + CacheCleanup.run(this) tidyScheduledAttachments() rescheduleAllScheduledMessages() rearmReminders() diff --git a/app/src/main/kotlin/com/glooboo/umessage/activities/LinkOpenActivity.kt b/app/src/main/kotlin/com/glooboo/umessage/activities/LinkOpenActivity.kt index 37e5b648..9dc85cb6 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/LinkOpenActivity.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/LinkOpenActivity.kt @@ -10,6 +10,7 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import org.fossify.commons.extensions.copyToClipboard import com.glooboo.umessage.R +import com.glooboo.umessage.helpers.threadPrefs import com.glooboo.umessage.ui.theme.UMessageTheme import com.glooboo.umessage.ui.thread.LinkSheet import com.glooboo.umessage.ui.thread.linkCopyText @@ -49,6 +50,9 @@ class LinkOpenActivity : ComponentActivity() { finish() }, onDismiss = ::finish, + // The action exists for saved contacts only (NotificationHelper), so the link is trusted; + // the "lock risky links" setting still applies. + lockRisky = threadPrefs.riskyLinksLocked, ) } } 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 8d6d2f40..997c0281 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/MainRoutes.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/MainRoutes.kt @@ -63,6 +63,8 @@ class MainRoutes(private val activity: BaseSimpleActivity) { onDeleteSelected = viewModel::deleteSelected, onArchiveOne = viewModel::archiveOne, onDeleteOne = viewModel::deleteOne, + onConfirmDelete = viewModel::confirmDelete, + onCancelDelete = viewModel::cancelDelete, onBlockSelected = viewModel::blockSelected, onBlockOne = viewModel::blockOne, onReportSpamSelected = viewModel::reportSpamSelected, 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 f96f0813..afd83416 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/NewConversationActivity.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/NewConversationActivity.kt @@ -171,8 +171,13 @@ class NewConversationActivity : ComposeSimpleActivity() { getSuggestedContacts(privateContacts).filter { it.phoneNumbers.isNotEmpty() } }.getOrDefault(emptyList()) val phoneContacts = if (canReadContacts) loadPhoneContacts(this@NewConversationActivity) else emptyList() - val all = (phoneContacts + privateContacts.filter { it.phoneNumbers.isNotEmpty() }) - .distinctBy { it.phoneNumbers.first().normalizedNumber } + // Whole contacts, not first numbers: people sharing a landline stay separate. A private contact is + // only dropped when a phone contact has the same name and the same set of numbers. + fun identity(c: SimpleContact) = c.name to c.phoneNumbers.map { it.normalizedNumber }.toSet() + val phoneIdentities = phoneContacts.mapTo(HashSet(), ::identity) + val all = phoneContacts + privateContacts + .filter { it.phoneNumbers.isNotEmpty() && identity(it) !in phoneIdentities } + .distinctBy { it.contactId } LoadedContacts(all, suggested) } suggestions = loadedContacts.suggestions 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 821328c2..6f647719 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/activities/ThreadActivity.kt @@ -1,1631 +1,1743 @@ -package com.glooboo.umessage.activities - -import android.annotation.SuppressLint -import android.app.Activity -import android.content.ActivityNotFoundException -import android.content.Intent -import android.net.Uri -import android.os.Build -import android.os.Bundle -import android.os.Looper -import android.provider.MediaStore -import android.provider.Telephony -import android.util.Log -import android.view.WindowManager -import android.widget.Toast -import androidx.activity.result.ActivityResultLauncher -import androidx.activity.result.PickVisualMediaRequest -import androidx.activity.result.contract.ActivityResultContracts -import androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia -import androidx.activity.viewModels -import androidx.annotation.StringRes -import androidx.compose.foundation.text.input.clearText -import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd -import androidx.compose.material3.SnackbarDuration -import androidx.compose.runtime.snapshotFlow -import androidx.core.content.pm.ShortcutManagerCompat -import androidx.core.net.toUri -import androidx.lifecycle.lifecycleScope -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.launch -import org.fossify.commons.extensions.appLockManager -import org.fossify.commons.extensions.getMyContactsCursor -import org.fossify.commons.extensions.hideKeyboard -import org.fossify.commons.extensions.normalizeString -import org.fossify.commons.extensions.notificationManager -import org.fossify.commons.extensions.showErrorToast -import org.fossify.commons.extensions.toast -import org.fossify.commons.helpers.MyContactsContentProvider -import org.fossify.commons.helpers.PERMISSION_READ_PHONE_STATE -import org.fossify.commons.helpers.ensureBackgroundThread -import com.glooboo.umessage.ui.components.ChoiceItem -import com.glooboo.umessage.ui.components.showChoiceDialog -import org.fossify.commons.models.SimpleContact -import com.glooboo.umessage.R -import com.glooboo.umessage.dialogs.GroupMessageSendDialog -import com.glooboo.umessage.dialogs.InvalidNumberDialog -import com.glooboo.umessage.extensions.config -import com.glooboo.umessage.extensions.conversationsDB -import com.glooboo.umessage.extensions.deleteSmsDraft -import com.glooboo.umessage.extensions.getContactFromAddress -import com.glooboo.umessage.extensions.getSmsDraft -import com.glooboo.umessage.extensions.getThreadId -import com.glooboo.umessage.extensions.getThreadParticipants -import com.glooboo.umessage.extensions.isSavedContactNumber -import com.glooboo.umessage.extensions.getThreadTitle -import com.glooboo.umessage.extensions.launchConversationDetails -import com.glooboo.umessage.extensions.launchViewIntent -import com.glooboo.umessage.extensions.markMessageRead -import com.glooboo.umessage.extensions.markThreadMessagesRead -import com.glooboo.umessage.extensions.messagesDB -import com.glooboo.umessage.extensions.removeDiacriticsIfNeeded -import com.glooboo.umessage.extensions.saveSmsDraft -import com.glooboo.umessage.extensions.shouldUnarchive -import com.glooboo.umessage.extensions.startContactDetailsIntent -import com.glooboo.umessage.extensions.subscriptionManagerCompat -import com.glooboo.umessage.extensions.toArrayList -import com.glooboo.umessage.extensions.toSortedMessages -import com.glooboo.umessage.extensions.updateConversationArchivedStatus -import com.glooboo.umessage.extensions.updateScheduledMessagesThreadId -import com.glooboo.umessage.helpers.AudioPlayerManager -import com.glooboo.umessage.helpers.EXTRA_VCARD_URI -import com.glooboo.umessage.helpers.IS_LAUNCHED_FROM_SHORTCUT -import com.glooboo.umessage.helpers.IS_RECYCLE_BIN -import com.glooboo.umessage.helpers.SEARCHED_MESSAGE_ID -import com.glooboo.umessage.helpers.messageNotes -import com.glooboo.umessage.helpers.SEARCHED_MESSAGE_IS_MMS -import com.glooboo.umessage.helpers.THREAD_ATTACHMENT_URI -import com.glooboo.umessage.helpers.THREAD_ATTACHMENT_URIS -import com.glooboo.umessage.helpers.THREAD_ID -import com.glooboo.umessage.helpers.THREAD_NUMBER -import com.glooboo.umessage.helpers.w3cPrefs -import com.glooboo.umessage.helpers.THREAD_TEXT -import com.glooboo.umessage.helpers.THREAD_TITLE -import com.glooboo.umessage.helpers.ChatArrival -import com.glooboo.umessage.helpers.ChatSounds -import com.glooboo.umessage.helpers.LocationSharer -import com.glooboo.umessage.helpers.cancelFailedSendNotification -import com.glooboo.umessage.helpers.composerPrefs -import com.glooboo.umessage.helpers.generateRandomId -import com.glooboo.umessage.helpers.refreshConversations -import com.glooboo.umessage.helpers.refreshMessages -import com.glooboo.umessage.messaging.ScheduledSendClaims -import com.glooboo.umessage.messaging.MmsRetryResult -import com.glooboo.umessage.messaging.downloadMms -import com.glooboo.umessage.messaging.undownloadedMms -import com.glooboo.umessage.messaging.isLongMmsMessage -import com.glooboo.umessage.messaging.scheduledAttachmentTracker -import com.glooboo.umessage.models.Attachment -import com.glooboo.umessage.models.Conversation -import com.glooboo.umessage.models.Events -import com.glooboo.umessage.models.Message -import com.glooboo.umessage.models.MessageKey -import com.glooboo.umessage.models.ThreadItem -import com.glooboo.umessage.ui.thread.IncomingShareGuard -import com.glooboo.umessage.ui.thread.MessageNoteStore -import com.glooboo.umessage.ui.thread.AttachKind -import com.glooboo.umessage.ui.thread.MediaSizes -import com.glooboo.umessage.ui.thread.ThreadExportController -import com.glooboo.umessage.ui.thread.DraftText -import com.glooboo.umessage.ui.thread.SendGuard -import com.glooboo.umessage.ui.thread.SendSteps -import com.glooboo.umessage.ui.thread.adoptScheduledMessages -import com.glooboo.umessage.ui.thread.refreshRepeatRules -import com.glooboo.umessage.ui.thread.simHeaderLabels -import com.glooboo.umessage.ui.thread.SmsSegments -import com.glooboo.umessage.ui.thread.ThreadActions -import com.glooboo.umessage.ui.thread.ThreadLaunchHints -import com.glooboo.umessage.ui.thread.ThreadMenuAction -import com.glooboo.umessage.ui.thread.SenderStatus -import com.glooboo.umessage.ui.log.DecisionLogActivity -import com.glooboo.umessage.spam.ForwardingAvailability -import com.glooboo.umessage.ui.spam.ForwardingActivity -import com.glooboo.umessage.ui.thread.UnknownCardController -import com.glooboo.umessage.ui.thread.ContextThreadMessageSource -import com.glooboo.umessage.ui.thread.ThreadMessagesRepository -import com.glooboo.umessage.ui.thread.draftToSave -import com.glooboo.umessage.ui.thread.mergeRefreshedMessages -import com.glooboo.umessage.ui.thread.saveFileName -import com.glooboo.umessage.ui.thread.ThreadScreen -import com.glooboo.umessage.ui.thread.ThreadViewModel -import com.glooboo.umessage.ui.thread.removeThreadMessages -import com.glooboo.umessage.ui.thread.ThreadScheduleUi -import com.glooboo.umessage.ui.thread.ThreadSimController -import com.glooboo.umessage.ui.thread.ThreadConversationActions -import com.glooboo.umessage.ui.thread.ThreadPeopleController -import com.glooboo.umessage.ui.thread.ThreadSelectionActions -import com.glooboo.umessage.ui.thread.ThreadSenderActions -import com.glooboo.umessage.ui.thread.ThreadAttachmentController -import com.glooboo.umessage.ui.thread.MessageSignature -import com.glooboo.umessage.ui.thread.ThreadLocationController -import com.glooboo.umessage.ui.thread.isNumericShortCode -import com.glooboo.umessage.ui.thread.RecentPhotosAccess -import com.glooboo.umessage.ui.thread.ContextMessageSender -import com.glooboo.umessage.ui.thread.OutgoingMessage -import com.glooboo.umessage.ui.thread.ResendTracker -import com.glooboo.umessage.messaging.RepeatRule -import com.glooboo.umessage.ui.thread.ThreadScheduleController -import com.glooboo.umessage.ui.thread.ThreadSendController -import com.glooboo.umessage.ui.thread.buildScheduledMessage -import com.glooboo.umessage.ui.thread.isSchedulableTime -import com.glooboo.umessage.ui.thread.ThreadMenuInput -import com.glooboo.umessage.ui.thread.ThreadPrivacyActions -import com.glooboo.umessage.ui.lock.HiddenChatGate -import com.glooboo.umessage.ui.lock.LockScope -import com.glooboo.umessage.ui.thread.ThreadRecipients -import com.glooboo.umessage.ui.thread.TapbackReaction -import com.glooboo.umessage.ui.thread.buildThreadItems -import com.glooboo.umessage.ui.thread.firstUnreadMessageId -import com.glooboo.umessage.ui.thread.buildThreadMenu -import com.glooboo.umessage.ui.thread.sendsAsMms -import org.greenrobot.eventbus.EventBus -import org.greenrobot.eventbus.Subscribe -import org.greenrobot.eventbus.ThreadMode -import java.io.File - -/** - * The chat screen's host. The layout is Compose ([ThreadScreen]) over [ThreadViewModel]; the work is done by the - * classes in ui/thread: [ThreadMessagesRepository] (loading, paging, refreshing), [ThreadSendController] and - * [ThreadScheduleController] (sending and scheduling to every [ThreadRecipients] address), - * [ThreadAttachmentController], [ThreadSimController], [ThreadScheduleUi], [ThreadSenderActions], - * [ThreadConversationActions], [ThreadSelectionActions] and [ThreadPeopleController]. This class owns the lifecycle, - * the intent, the activity result launchers and the order in which a conversation is loaded. - */ -open class ThreadActivity : ComposeSimpleActivity() { - private val vm: ThreadViewModel by viewModels() - - private var threadId = 0L - - /** B06: a hidden chat asks for the app lock before it shows. */ - private val hiddenGate = HiddenChatGate(this) { threadId } - @Volatile - private var isActivityVisible = false - - @Volatile - private var hasWindowFocusNow = false - private var refreshedSinceSent = false - private var threadItems: List = emptyList() - private var bus: EventBus? = null - private var conversation: Conversation? = null - private var recipients = ThreadRecipients() - private var privateContacts = ArrayList() - /** The loaded messages: loading, paging, refreshing and every single change go through it. */ - private val repository by lazy { ThreadMessagesRepository(ContextThreadMessageSource(applicationContext)) } - private val messages: List get() = repository.current - private val sim by lazy { ThreadSimController(this, vm) } - private val scheduleUi by lazy { - ThreadScheduleUi( - activity = this, - vm = vm, - cancel = ::cancelScheduledMessageAndRefresh, - sendNow = ::sendScheduledMessageNow, - loadIntoComposer = { message -> - clearCurrentMessage() - vm.text.setTextAndPlaceCursorAtEnd(message.body) - message.attachment?.attachments?.forEach { attachmentController.add(it.getUri()) } - }, - ) - } - private var isJumpingToMessage = false - private var isRecycleBin = false - private var isLaunchedFromShortcut = false - - /** The reactions found by the last [getThreadItems] (I30). */ - @Volatile - private var latestReactions: Map> = emptyMap() - - /** True once the provider's messages are loaded: only they know what is really unread (I26). */ - @Volatile - private var providerLoaded = false - - /** - * True once the user really had this chat in front of them (see [isSeenByUser]). A quick open and Back can end - * before the provider load finishes; the load then still marks the chat read for this reason. - */ - @Volatile - private var shownToUser = false - - /** The stored draft is put back once each time a chat is opened; see [DraftText.restore]. */ - private var draftRestored = false - - private var isGroupMessageConfirmationVisible = false - /** One send from the composer at a time: a second tap while it runs is ignored (MS5). */ - private val composerSend = SendGuard() - - /** The failed message "Retry" put into the composer, resent in its place by the next Send. */ - private val resend = ResendTracker() - - private val sendController by lazy { - ThreadSendController(ContextMessageSender(this)) { error -> - if (error is Exception) { - showErrorToast(error) - } else { - showErrorToast(error.localizedMessage ?: getString(org.fossify.commons.R.string.unknown_error_occurred)) - } - } - } - private val scheduleController by lazy { ThreadScheduleController(applicationContext) } - - private val attachmentController by lazy { ThreadAttachmentController(this, vm) { updateMessageType() } } - - /** True once the composer's text listener runs; [loadConversation] runs again for a new intent. */ - private var composerListening = false - - // Activity Result API launchers. They are registered up front so results are delivered even when the process was - // killed while the other app (camera, picker) was open. - private val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { saved -> - val uri = vm.capturedImageUri - vm.capturedImageUri = null - if (saved && uri != null) { - resend.clear() - attachmentController.add(uri) - } - } - - /** The system Photo Picker: no storage permission needed, several items at once. */ - private val pickMedia = registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia()) { uris -> - if (uris.isNotEmpty()) resend.clear() - uris.forEach { attachmentController.add(it) } - } - - private val pickDocument = registerForActivityResult(ActivityResultContracts.GetContent()) { uri -> - if (uri != null) { - resend.clear() - attachmentController.add(uri) - } - } - - private val pickContact = registerForActivityResult(ActivityResultContracts.PickContact()) { uri -> - if (uri != null) { - resend.clear() - attachmentController.addContact(uri) - } - } - - /** Video and audio recorders return the recording's uri in the result data. */ - private val recordMedia = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - val uri = result.data?.data - if (result.resultCode == Activity.RESULT_OK && uri != null) { - resend.clear() - attachmentController.add(uri) - } - } - - /** I52: the system prompt for the location; the user may allow the approximate position only. */ - private val locationPermission: ActivityResultLauncher> = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { - location.onPermissionResult() - } - - /** I69: the media prompt of the recent photos row; the sheet reads the answer from the permission itself. */ - private val photoPermission: ActivityResultLauncher> = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { - vm.photoAccessVersion++ - } - - /** I65: sounds for sent and received messages, when switched on. */ - private val chatSounds by lazy { ChatSounds.create(this) } - - private val location: ThreadLocationController = ThreadLocationController( - activity = this, - requestPermission = { launchForResult(locationPermission, LocationSharer.LOCATION_PERMISSIONS) }, - insert = { insertLocationLink(it) }, - ) - - /** "Save" on an MMS attachment: a document (one attachment) or a folder (several). */ - private val saveAttachmentsTarget = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> - val data = result.data - val destination = data?.data - if (result.resultCode == Activity.RESULT_OK && destination != null) { - val toSave = vm.attachmentsToSave - vm.attachmentsToSave = null - attachmentController.save(toSave, destination) - } else { - vm.attachmentsToSave = null - } - } - - private val actions = ThreadActions( - onBack = { finish() }, - onMenuAction = { handleMenuAction(it) }, - onSelectionAction = { selectionActions.handle(it) }, - onBubbleClick = { message -> if (message.isScheduled) scheduleUi.showOptions(message) }, - onSenderClick = { openSenderContact(it) }, - onRetry = { message, text -> retryFailedMessage(message, text) }, - onLoadOlder = { if (!isJumpingToMessage) loadMoreMessages() }, - onSend = { sendMessage() }, - onSendLongPress = { if (!vm.isScheduling) scheduleUi.pickTime() }, - onAttach = { handleAttach(it) }, - onEditSchedule = { scheduleUi.pickTime(vm.scheduledMillis) }, - onDiscardSchedule = { scheduleUi.discard() }, - onSelectSim = { selectSim(it) }, - onRemoveAttachment = { attachmentController.remove(it) }, - onOpenFile = { uri, mimeType, filename -> launchViewIntent(uri, mimeType, filename) }, - onOpenVCard = { uri -> - startActivity(Intent(this, VCardViewerActivity::class.java).putExtra(EXTRA_VCARD_URI, uri)) - }, - onReplyInfo = { - InvalidNumberDialog(activity = this, text = getString(R.string.invalid_short_code_desc)) - }, - onPickContact = { people.pickContact(it) }, - onAddTypedNumber = { people.addNumber(it) }, - onRemovePerson = { people.remove(it) }, - onConfirmPeople = { people.confirm() }, - onAddPhoto = { - resend.clear() - attachmentController.add(it) - }, - onRequestPhotos = { - launchForResult(photoPermission, RecentPhotosAccess.permissions(Build.VERSION.SDK_INT)) - }, - onDownloadMms = { id -> ensureBackgroundThread { downloadMmsFromChat(id) } }, - ) - - /** Q40: "Tap to download". A message that is gone from the provider (downloaded meanwhile) just refreshes. */ - private fun downloadMmsFromChat(id: Long) { - if (downloadMms(id) == MmsRetryResult.NotPending) refreshMessages() - } - - /** - * singleTop: a notification or shortcut for a conversation reuses this screen. The same conversation keeps its - * draft and attachments and only applies what the intent adds; another conversation is loaded in place (the - * current draft was already saved in onPause). - */ - override fun onNewIntent(intent: Intent) { - super.onNewIntent(intent) - if (intent.extras == null) return - val newThreadId = intent.getLongExtra(THREAD_ID, 0L) - setIntent(intent) - if (newThreadId != 0L && newThreadId == threadId) { - // Shared text into the chat that is open: added after what is typed, never dropped (B9). - intent.getStringExtra(THREAD_TEXT)?.let { shared -> - vm.text.setTextAndPlaceCursorAtEnd(DraftText.appendShared(vm.text.text.toString(), shared)) - } - addAttachmentsFromIntent() - takeSearchedMessage()?.let { jumpToMessage(it) } - takeOpenSearch() - applyLaunchHints() - return - } - - resetForNewConversation() - draftRestored = false - readIntentExtras() - // onResume does not run again for a chat that is already in front: the hidden-chat cover is decided here. - hiddenGate.check() - loadConversation(isFreshLaunch = true) - markReadIfSeen() - } - - private fun readIntentExtras() { - threadId = intent.getLongExtra(THREAD_ID, 0L) - intent.getStringExtra(THREAD_TITLE)?.let { vm.title = it } - isRecycleBin = intent.getBooleanExtra(IS_RECYCLE_BIN, false) - isLaunchedFromShortcut = intent.getBooleanExtra(IS_LAUNCHED_FROM_SHORTCUT, false) - vm.isRecycleBin = isRecycleBin - takeOpenSearch() - } - - /** [EXTRA_OPEN_SEARCH] (Conversation details' "Search in conversation"): opens the search bar, once. */ - private fun takeOpenSearch() { - if (intent.getBooleanExtra(EXTRA_OPEN_SEARCH, false)) { - intent.removeExtra(EXTRA_OPEN_SEARCH) - if (!isRecycleBin) vm.openSearch() - } - } - - /** - * The focus and notice extras (opened from a blocked chat after Not spam): once the first load is - * done, the message field takes focus and the keyboard comes up, and the note shows. Taken off the intent, so a - * rotation does not do it again. - */ - private fun applyLaunchHints() { - val hints = ThreadLaunchHints.take(intent) - hints.notice?.let { note -> - lifecycleScope.launch { - vm.snackbar.showSnackbar(note, withDismissAction = true, duration = SnackbarDuration.Short) - } - } - if (hints.focusComposer && !isRecycleBin && !isSpecialNumber()) { - window.setSoftInputMode( - WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE or - WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE, - ) - vm.focusInput++ - } - } - - /** Clears everything that belongs to the previous conversation before another one is loaded in place. */ - private fun resetForNewConversation() { - AudioPlayerManager.release() - conversation = null - recipients = ThreadRecipients() - privateContacts = ArrayList() - repository.reset() - threadItems = emptyList() - refreshedSinceSent = false - isJumpingToMessage = false - isGroupMessageConfirmationVisible = false - resend.clear() - vm.clearSchedule() - vm.clearSelection() - vm.clearAttachments() - vm.text.clearText() - vm.publishItems(emptyList()) - vm.reactions = emptyMap() - latestReactions = emptyMap() - vm.firstUnreadId = null - vm.unreadResolved = false - vm.unreadScrolled = false - providerLoaded = false - shownToUser = false - vm.loaded = false - vm.title = "" - vm.subtitle = null - vm.avatarPhotoUri = "" - vm.showPeople = false - vm.showAttachSheet = false - vm.showEmojiPanel = false - vm.closeSearch() - vm.people = emptyList() - refreshMenuItems() - } - - override fun onCreate(savedInstanceState: Bundle?) { - // Same window theme as every other Compose screen (the manifest entry has none). - setTheme(R.style.Theme_UMessage_Screen) - super.onCreate(savedInstanceState) - - val extras = intent.extras - if (extras == null) { - toast(org.fossify.commons.R.string.unknown_error_occurred) - finish() - return - } - - readIntentExtras() - - setUMessageContent { ThreadScreen(vm, actions) } - // After the process was killed the time survives in saved state but the label does not. - vm.scheduledMillis?.let { scheduleUi.show(it) } - - bus = EventBus.getDefault() - bus!!.register(this) - - refreshMenuItems() - senderActions.observeRules() - vm.stars.attach(this, lifecycleScope) - vm.notes.attach(MessageNoteStore(messageNotes), lifecycleScope) - loadConversation(isFreshLaunch = savedInstanceState == null) - } - - override fun onResume() { - super.onResume() - hiddenGate.check() - - isActivityVisible = true - - scheduleUi.onResume() - - ensureBackgroundThread { - val newConv = conversationsDB.getConversationWithThreadId(threadId) - if (newConv != null) { - conversation = newConv - runOnUiThread { - setupThreadTitle() - // "Conversation details" and the other entries that need the saved conversation. - refreshMenuItems() - } - } - - val smsDraft = getSmsDraft(threadId) - if (smsDraft.isNotEmpty()) { - runOnUiThread { - // Once per open, and merged with what is already in the composer (B8): a shared text, or text - // typed before this read finished, is kept; coming back from the camera never rewinds it. - if (!draftRestored) { - draftRestored = true - vm.text.setTextAndPlaceCursorAtEnd(DraftText.restore(vm.text.text.toString(), smsDraft)) - } - } - } - } - markReadIfSeen() - } - - override fun onWindowFocusChanged(hasFocus: Boolean) { - super.onWindowFocusChanged(hasFocus) - hasWindowFocusNow = hasFocus - if (hasFocus) markReadIfSeen() - } - - /** - * TU-11: messages count as read only while the user can actually see this chat: the screen is in front, its - * window has focus (not under the lock screen, the notification shade or a dialog) and the app lock is not up. - * Texts that arrive while the chat sits open in the background stay unread until the user comes back to it. - */ - private fun isSeenByUser(): Boolean = - isActivityVisible && hasWindowFocusNow && !hiddenGate.blocking && !LockScope.isLockedNow(this) - - private fun markReadIfSeen() { - if (!isSeenByUser()) return - shownToUser = true - markThreadReadInBackground(threadId) - } - - private fun markThreadReadInBackground(thread: Long) { - notificationManager.cancel(thread.hashCode()) - // The chat is open: its "Message not sent" notification has done its job, the failed row has Retry (MS3). - cancelFailedSendNotification(thread) - ensureBackgroundThread { - // I26: the unread messages are noted first; the build that does it marks them read itself. - if (!providerLoaded && !isRecycleBin) return@ensureBackgroundThread - // A refused provider write must not skip the saved flags or the list refresh. - runCatching { markThreadMessagesRead(thread) } - repository.markAllRead(thread) - bus?.post(Events.RefreshConversations(thread)) - // A notification posted while the chat was being read would otherwise stay. - notificationManager.cancel(thread.hashCode()) - } - } - - override fun onPause() { - super.onPause() - saveDraftMessage() - bus?.post(Events.RefreshConversations()) - isActivityVisible = false - } - - override fun onStop() { - super.onStop() - AudioPlayerManager.release() - if (selectionActionsDelegate.isInitialized()) selectionActions.release() - saveDraftMessage() - } - - override fun onDestroy() { - super.onDestroy() - chatSounds.release() - bus?.unregister(this) - } - - private fun saveDraftMessage() { - if (!vm.loaded && vm.text.text.isEmpty()) return - val draftMessage = draftToSave(vm.text.text.toString()) - val draftThreadId = threadId - ensureBackgroundThread { - if (draftMessage != null) { - saveSmsDraft(draftMessage, draftThreadId) - } else { - deleteSmsDraft(draftThreadId) - } - } - } - - /** Whether the only participant's number is already a saved contact; checked off the main thread. */ - @Volatile - private var firstNumberIsSaved = false - - /** I04: whether the only person is a stranger (not a contact, never written to); checked off the main thread. */ - @Volatile - private var senderIsStranger = false - private val unknownCard by lazy { UnknownCardController(this, vm) } - - private val selectionActionsDelegate = lazy { - ThreadSelectionActions( - activity = this, - vm = vm, - isRecycleBin = { isRecycleBin }, - saveAttachments = ::saveMMS, - deleteMessages = ::deleteMessages, - ) - } - private val selectionActions by selectionActionsDelegate - - private val exportController by lazy { - ThreadExportController( - activity = this, - threadId = { threadId }, - title = { vm.title }, - numbers = { recipients.addresses.distinct() }, - showMessage = { text -> lifecycleScope.launch { vm.snackbar.showSnackbar(text) } }, - ) - } - - private val conversationActions by lazy { - ThreadConversationActions( - activity = this, - threadId = { threadId }, - isRecycleBin = { isRecycleBin }, - recipients = { recipients }, - conversation = { conversation }, - title = { vm.title }, - showMessage = { text -> lifecycleScope.launch { vm.snackbar.showSnackbar(text) } }, - onRenamed = { renamed -> - conversation = renamed - setupThreadTitle() - }, - ) - } - - private val people by lazy { - ThreadPeopleController( - activity = this, - vm = vm, - recipients = { recipients }, - setRecipients = { recipients = it }, - privateContacts = { privateContacts }, - threadId = { threadId }, - onPeopleChanged = { updateMessageType() }, - ) - } - - /** N05, B06: Mute and Hide entries of the menu. */ - private val privacy by lazy { - ThreadPrivacyActions(this, { threadId }, onChange = { refreshMenuItems() }, onHidden = { finish() }) - } - - /** Block, unblock and report spam; it also tells the menu whether the sender is already blocked. */ - private val senderActions by lazy { - ThreadSenderActions( - activity = this, - scope = lifecycleScope, - snackbar = vm.snackbar, - recipients = { recipients }, - senderName = { vm.title }, - lastReceivedSubscriptionId = { messages.lastOrNull { it.isReceivedMessage() }?.subscriptionId ?: -1 }, - onStatusChanged = { refreshMenuItems() }, - ) - } - - private fun refreshMenuItems() { - vm.threadId = threadId - senderActions.refreshIfPeopleChanged() - vm.linksTrusted = recipients.size == 1 && firstNumberIsSaved - unknownCard.refresh( - senderIsStranger, recipients, messages.lastOrNull { it.isReceivedMessage() }, threadId, - hasRule = senderActions.allowedSender != null || senderActions.blockedSender != null, - ) - vm.menu = buildThreadMenu( - ThreadMenuInput( - recipients = recipients, - hasItems = threadItems.isNotEmpty(), - hasConversation = conversation != null, - isArchived = conversation?.isArchived, - isRecycleBin = isRecycleBin, - archiveAvailable = config.isArchiveAvailable, - singleNumberIsSaved = firstNumberIsSaved, - reportedSender = senderActions.reportedSender, - blockedSender = senderActions.blockedSender, - allowedSender = senderActions.allowedSender, - pinShortcutSupported = ShortcutManagerCompat.isRequestPinShortcutSupported(this), - forwardingAvailable = ForwardingAvailability.isAvailable(this), - muted = privacy.isMuted(), - hiddenChat = privacy.isHiddenChat(), - ) - ) - vm.senderStatus = when { - senderActions.blockedSender != null -> SenderStatus.Blocked - senderActions.allowedSender != null -> SenderStatus.Allowed - else -> SenderStatus.None - } - } - - private fun handleMenuAction(action: ThreadMenuAction) { - if (recipients.isEmpty()) return - when (action) { - ThreadMenuAction.Block -> senderActions.askBlock() - ThreadMenuAction.Unblock -> senderActions.unblock() - ThreadMenuAction.ReportSpam -> senderActions.askReportSpam() - ThreadMenuAction.AllowSender -> senderActions.allowSender() - ThreadMenuAction.WhyDecided -> startActivity(Intent(this, DecisionLogActivity::class.java)) - ThreadMenuAction.Search -> vm.openSearch() - ThreadMenuAction.AlwaysForward -> openForwardRuleForSender() - ThreadMenuAction.Delete -> conversationActions.askDelete() - ThreadMenuAction.Restore -> conversationActions.askRestoreAll() - ThreadMenuAction.Archive -> conversationActions.setArchived(true) - ThreadMenuAction.Unarchive -> conversationActions.setArchived(false) - ThreadMenuAction.Rename -> conversationActions.rename() - ThreadMenuAction.Details -> launchConversationDetails(threadId) - ThreadMenuAction.AddToContact -> conversationActions.addNumberToContacts() - ThreadMenuAction.CopyNumber -> conversationActions.copyNumber() - ThreadMenuAction.Dial -> conversationActions.dial() - ThreadMenuAction.ManagePeople -> people.toggle() - ThreadMenuAction.MarkUnread -> conversationActions.markUnread() - ThreadMenuAction.ShareAsText -> conversationActions.shareAsText() - ThreadMenuAction.ExportConversation -> exportController.start() - ThreadMenuAction.AddToHomeScreen -> conversationActions.addToHomeScreen() - ThreadMenuAction.Labels -> vm.labelsFor = threadId - ThreadMenuAction.Mute -> privacy.askMute() - ThreadMenuAction.Unmute -> privacy.unmute() - ThreadMenuAction.Hide -> privacy.hide() - ThreadMenuAction.Unhide -> privacy.unhide() - } - } - - /** - * TH-11, TH-20: "Always forward from this sender" opens the forwarding screen with the rule editor already - * filled in for this sender; saving it goes through the editor's usual checks (and the app lock). - */ - private fun openForwardRuleForSender() { - if (!ForwardingAvailability.isAvailable(this)) return - val address = recipients.reportableAddress ?: return - startActivity(ForwardingActivity.intent(this, address)) - } - - private fun setupCachedMessages(callback: () -> Unit) { - ensureBackgroundThread { - repository.loadCached(threadId, isRecycleBin) - - setupParticipants() - setupAdapter() - - runOnUiThread { - if (messages.isEmpty() && !isSpecialNumber()) { - window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) - vm.focusInput++ - } - - setupThreadTitle() - setupSIMSelector() - updateMessageType() - callback() - } - } - } - - private fun setupThread(callback: () -> Unit) { - if (conversation == null && isLaunchedFromShortcut) { - if (isTaskRoot) { - Intent(this, MainActivity::class.java).apply { - addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) - startActivity(this) - } - } - finish() - return - } - val privateCursor = getMyContactsCursor(favoritesOnly = false, withPhoneNumbersOnly = true) - ensureBackgroundThread { - privateContacts = MyContactsContentProvider.getSimpleContacts(this, privateCursor) - - val cachedMessagesCode = messages.hashCode() - if (!isRecycleBin) repository.loadNewest(threadId) - providerLoaded = true - // The first mark-read attempt may have come before the messages were loaded. When the user already - // saw the chat but left before this point, nobody would ask again: mark it now. - val loadedThread = threadId - if (shownToUser) markThreadReadInBackground(loadedThread) else runOnUiThread { markReadIfSeen() } - - val providerParticipantsChanged = reconcileProviderParticipants() - val hasParticipantWithoutName = recipients.contacts.any { contact -> - contact.phoneNumbers.map { it.normalizedNumber }.contains(contact.name) - } - - try { - if (canReuseLoadedThread(providerParticipantsChanged, cachedMessagesCode, hasParticipantWithoutName)) { - adoptWaitingScheduledMessages() - setupAdapter() - runOnUiThread { callback() } - return@ensureBackgroundThread - } - } catch (ignored: Exception) { - } - - setupParticipants() - - // check if no participant came from a privately stored contact in Simple Contacts - if (privateContacts.isNotEmpty()) { - val senderNumbersToReplace = HashMap() - recipients.contacts.filter { it.doesHavePhoneNumber(it.name) }.forEach { participant -> - privateContacts.firstOrNull { it.doesHavePhoneNumber(participant.phoneNumbers.first().normalizedNumber) } - ?.apply { - senderNumbersToReplace[participant.phoneNumbers.first().normalizedNumber] = - name - participant.name = name - participant.photoUri = photoUri - } - } - - messages.forEach { message -> - if (senderNumbersToReplace.keys.contains(message.senderName)) { - message.senderName = senderNumbersToReplace[message.senderName]!! - } - } - } - - if (recipients.isEmpty()) { - val name = intent.getStringExtra(THREAD_TITLE) ?: "" - val numbers = getPhoneNumbersFromIntent() - if (numbers.isEmpty()) { - // No messages, no participants known to the phone and no number in the intent: nothing to write to. - Log.w("ThreadActivity", "Chat opened without a conversation, participants or number") - toast(R.string.new_conversation_invalid_number, length = Toast.LENGTH_LONG) - finish() - return@ensureBackgroundThread - } - recipients = ThreadRecipients.fromNumbers(numbers, name) - } - - adoptWaitingScheduledMessages() - - if (!isRecycleBin) { - messages.chunked(30).forEach { currentMessages -> - messagesDB.insertMessages(*currentMessages.toTypedArray()) - } - } - - setupAdapter() - runOnUiThread { - setupThreadTitle() - setupSIMSelector() - callback() - } - } - } - - /** - * Brings in messages scheduled for these people while they had no conversation yet, which waited in a temporary - * thread of their own: without this the real conversation said "No messages yet". Runs in the background. - */ - private fun adoptWaitingScheduledMessages() { - if (isRecycleBin || recipients.isEmpty()) return - val adopted = adoptScheduledMessages(threadId, recipients.addresses) - if (adopted.isEmpty()) return - repository.addAll(adopted) - bus?.post(Events.RefreshConversations()) - } - - private fun canReuseLoadedThread( - providerParticipantsChanged: Boolean, - cachedMessagesCode: Int, - hasParticipantWithoutName: Boolean, - ): Boolean { - if (providerParticipantsChanged || recipients.isEmpty() || hasParticipantWithoutName) { - return false - } - - return messages.hashCode() == cachedMessagesCode - } - - /** Rebuilds the thread items from [messages] and hands them to the Compose list. */ - private fun setupAdapter() { - val latestThreadItems = getThreadItems() - // Saved picture sizes are read before the rows are shown, so photo bubbles start at their size (TU-25). - if (Looper.myLooper() != Looper.getMainLooper()) MediaSizes.warm(this, messages) - val number = recipients.singleNumber - firstNumberIsSaved = number != null && isSavedContactNumber(number) - senderIsStranger = unknownCard.isStranger(number, firstNumberIsSaved, recipients.isGroup) - - runOnUiThread { - publishItems(latestThreadItems) - refreshMenuItems() - if (vm.firstUnreadId != null && !vm.unreadScrolled) { - vm.unreadScrolled = true - vm.scrollToUnread() - } - } - } - - private fun publishItems(items: List) { - threadItems = items - vm.reactions = latestReactions - vm.isGroup = recipients.isGroup - vm.approximateScheduledIds = config.inexactScheduledMessages.mapNotNullTo(HashSet()) { it.toLongOrNull() } - vm.refreshRepeatRules(this, items) - vm.publishItems(items) - vm.loaded = true - } - - private fun retryFailedMessage(failedKey: MessageKey, text: String) { - // Matched by id and type: SMS 57 and MMS 57 are different messages (MessageKey). - // A held scheduled message (RM-25) is sent now as it is; on success its scheduled row, and so the failed - // mark, is removed. It never goes through the composer, so the user's draft stays. - messages.firstOrNull { it.key == failedKey && it.isHeldScheduled() }?.let { - sendScheduledMessageNow(it) - return - } - val failed = messages.firstOrNull { it.key == failedKey && it.type == Telephony.Sms.MESSAGE_TYPE_FAILED } - if (failed != null) { - // Tapping "Not sent. Tap to retry." sends the failed message again right away, as it was (text, pictures - // and files, SIM), in the failed row's place. It used to only copy the text into the composer, so on - // a tap nothing visibly happened, and it replaced whatever the user was typing. The draft stays untouched. - sendNormalMessage( - text = failed.body.ifEmpty { text }, - subscriptionId = failed.subscriptionId.takeIf { it >= 0 } ?: sim.subscriptionId, - attachments = failed.attachment?.attachments.orEmpty(), - resendId = failedKey, - fromComposer = false, - ) { handedOff -> if (!handedOff) toast(R.string.message_not_sent_short) } - return - } - // The failed message is not loaded any more: fall back to putting its text into the composer. - resend.prepare(failedKey, text) - vm.text.setTextAndPlaceCursorAtEnd(text) - } - - private fun openSenderContact(message: Message) { - val number = message.getSender()?.phoneNumbers?.firstOrNull()?.normalizedNumber ?: return - getContactFromAddress(number) { - if (it != null) { - startContactDetailsIntent(it) - } - } - } - - private fun deleteMessages( - messagesToRemove: List, - toRecycleBin: Boolean, - fromRecycleBin: Boolean, - ) { - repository.remove(messagesToRemove) - val latestThreadItems = getThreadItems() - val hasMessages = messages.isNotEmpty() - - runOnUiThread { - messagesToRemove.forEach { message -> - message.attachment?.attachments?.forEach { AudioPlayerManager.release(it.getUri()) } - } - if (!hasMessages) { - finish() - } else { - publishItems(latestThreadItems) - vm.clearSelection() - } - } - - // Only scheduled messages left: they move to a temporary thread until one is sent. - removeThreadMessages( - messagesToRemove, toRecycleBin, fromRecycleBin, threadId, messages.toSortedMessages(), conversation, scheduleController, - )?.let { threadId = it } - } - - /** The message a search result opened this chat at, read once from the intent and then cleared. */ - private fun takeSearchedMessage(): MessageKey? { - val id = intent.getLongExtra(SEARCHED_MESSAGE_ID, -1L) - val isMMS = intent.getBooleanExtra(SEARCHED_MESSAGE_IS_MMS, false) - intent.removeExtra(SEARCHED_MESSAGE_ID) - intent.removeExtra(SEARCHED_MESSAGE_IS_MMS) - return if (id == -1L) null else MessageKey(id, isMMS) - } - - /** Scrolls to [target], paging in older history until it is loaded. Matched by id and type (MessageKey). */ - private fun jumpToMessage(target: MessageKey) { - if (messages.any { it.key == target }) { - vm.scrollToMessage(target, flash = true) - return - } - - ensureBackgroundThread { - if (repository.loadingOlder) return@ensureBackgroundThread - repository.loadingOlder = true - isJumpingToMessage = true - - var cutoff = repository.oldestDate() ?: Int.MAX_VALUE - var found = false - var loops = 0 - - // not the best solution, but this will do for now. - runCatching { - while (!found && !repository.allFetched) { - if (repository.fetchOlder(threadId, cutoff).isEmpty() || loops >= 1000) break - val messageSnapshot = messages.toSortedMessages() - cutoff = messageSnapshot.first().date - found = messageSnapshot.any { it.key == target } - loops++ - } - } - - val latestThreadItems = getThreadItems() - runOnUiThread { - publishItems(latestThreadItems) - repository.loadingOlder = false - vm.scrollToMessage(target, flash = true) - isJumpingToMessage = false - } - } - } - - private fun loadMoreMessages() { - val cutoff = repository.oldestDate() ?: return - if (repository.allFetched || repository.loadingOlder) return - repository.loadingOlder = true - val thread = threadId - ensureBackgroundThread { - // A failure must not leave loadingOlder set: that stopped paging until the chat was reopened. - val loaded = runCatching { repository.fetchOlder(thread, cutoff) }.isSuccess - val latestThreadItems = if (loaded) getThreadItems() else null - runOnUiThread { - latestThreadItems?.let { publishItems(it) } - repository.loadingOlder = false - } - } - } - - 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() - } - } - } else { - finish() - } - } - } - - private fun setupConversation() { - ensureBackgroundThread { - conversation = conversationsDB.getConversationWithThreadId(threadId) - // The menu may have been built before the conversation was read (no "Conversation details" then). - runOnUiThread { refreshMenuItems() } - } - } - - private fun setupComposer(isFreshLaunch: Boolean) { - vm.showCounter = config.showCharacterCounter - vm.sendOnEnter = config.sendOnEnter - vm.voiceButton = composerPrefs.voiceButton - - if (!composerListening) { - composerListening = true - lifecycleScope.launch { - snapshotFlow { vm.text.text.toString() }.collect { onMessageTextChanged(it) } - } - } - - // The view model keeps text and attachments across recreation, so the intent only seeds a fresh launch. - if (isFreshLaunch) { - intent.getStringExtra(THREAD_TEXT)?.let { vm.text.setTextAndPlaceCursorAtEnd(it) } - addAttachmentsFromIntent() - } - } - - private fun addAttachmentsFromIntent() { - if (intent.extras?.containsKey(THREAD_ATTACHMENT_URI) == true) { - val uri = intent.getStringExtra(THREAD_ATTACHMENT_URI)?.toUri() - if (uri != null && IncomingShareGuard.isAllowed(uri, packageName)) attachmentController.add(uri) - } else if (intent.extras?.containsKey(THREAD_ATTACHMENT_URIS) == true) { - @Suppress("DEPRECATION", "UNCHECKED_CAST") - (intent.getSerializableExtra(THREAD_ATTACHMENT_URIS) as? ArrayList)?.forEach { - if (IncomingShareGuard.isAllowed(it, packageName)) attachmentController.add(it) - } - } - } - - private fun onMessageTextChanged(text: String) { - resend.onTextChanged(text) - - updateMessageType() - val signed = withSignature(text) - val messageString = if (config.useSimpleCharacters) signed.normalizeString() else signed - val segments = if (messageString.isEmpty()) null else SmsSegments.of(messageString) - vm.segments = segments - noteLongTextAsMmsOnce(messageString) - } - - /** Says once that a long text goes as MMS; it does not block the send. */ - private fun noteLongTextAsMmsOnce(messageString: String) { - // RM-46: a long text turning into MMS used to happen without a word; say so once. - if (!vm.longMmsNoted && vm.attachments.isEmpty() && messageString.isNotBlank() && isLongMmsMessage(messageString)) { - vm.longMmsNoted = true - lifecycleScope.launch { vm.snackbar.showSnackbar(getString(R.string.thread_long_text_as_mms)) } - } - } - - private fun hasOnlyScheduledMessages(): Boolean = repository.hasOnlyScheduled() - - private fun getProviderThreadParticipants(): ThreadRecipients? { - if (isRecycleBin || threadId <= 0L || hasOnlyScheduledMessages()) { - return null - } - - return getThreadParticipants(threadId, null).takeIf { it.isNotEmpty() }?.let { ThreadRecipients(it) } - } - - private fun reconcileProviderParticipants(): Boolean { - val providerParticipants = getProviderThreadParticipants() ?: return false - val participantsChanged = !recipients.sameAddressesAs(providerParticipants) - recipients = providerParticipants - - if (participantsChanged) { - runOnUiThread { - maybeDisableShortCodeReply() - } - } - - return participantsChanged - } - - private fun setupParticipants() { - if (recipients.isEmpty()) { - recipients = if (messages.isEmpty()) { - val intentNumbers = getPhoneNumbersFromIntent() - ThreadRecipients(ThreadRecipients.withIntentNumbers(getThreadParticipants(threadId, null), intentNumbers)) - } else { - getProviderThreadParticipants() ?: ThreadRecipients(messages.first().participants) - } - runOnUiThread { - maybeDisableShortCodeReply() - } - } - } - - private fun isSpecialNumber(): Boolean = recipients.hasShortCodeWithLetters - - /** Codes and service messages: no sounds for them. */ - private fun isCodeSender(): Boolean = isSpecialNumber() || recipients.addresses.any { isNumericShortCode(it) } - - private fun maybeDisableShortCodeReply() { - if (isSpecialNumber() && !isRecycleBin) { - currentFocus?.clearFocus() - hideKeyboard() - vm.text.clearText() - vm.replyDisabled = true - } - } - - private fun setupThreadTitle() { - val title = conversation?.title - vm.title = if (!title.isNullOrEmpty()) { - title - } else { - recipients.toArrayList().getThreadTitle() - } - // The people may have changed: a group shows how its messages go out. - updateMessageType() - // Same avatar as the conversation list: the conversation's photo, else the contact's, else initials or icon. - vm.avatarPhotoUri = if (recipients.size == 1) { - conversation?.photoUri?.takeIf { it.isNotEmpty() } ?: recipients.contacts.first().photoUri - } else { - "" - } - updateSubtitle() - } - - /** Second line of the top bar: the number, or the group size. The SIM lives in the message field instead. */ - private fun updateSubtitle() { - val parts = ArrayList() - if (recipients.size == 1) { - val number = recipients.contacts.first().phoneNumbers.firstOrNull()?.normalizedNumber - if (!number.isNullOrEmpty() && number != vm.title) parts.add(number) - } else if (recipients.isGroup) { - parts.add(resources.getQuantityString(R.plurals.thread_people, recipients.size, recipients.size)) - } - vm.subtitle = parts.takeIf { it.isNotEmpty() }?.joinToString(getString(R.string.ui_separator)) - } - - private fun setupSIMSelector() { - if (sim.load(recipients, messages.lastOrNull())) updateSubtitle() - } - - private fun selectSim(index: Int) { - if (sim.select(index, recipients)) updateSubtitle() - } - - @SuppressLint("MissingPermission") - private fun getThreadItems(): List { - if (isFinishing) { - return emptyList() - } - - val simLabels = simHeaderLabels(subscriptionManagerCompat().activeSubscriptionInfoList, 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. - if (providerLoaded && !vm.unreadResolved) { - vm.firstUnreadId = if (isRecycleBin) null else firstUnreadMessageId(messages) - vm.unreadResolved = true - } - val result = buildThreadItems( - messages, simLabels, seen = isSeenByUser(), deliveryReportsOn = config.enableDeliveryReports, - firstUnreadId = vm.firstUnreadId, showTapbacks = w3cPrefs.showTapbacks, - undownloadedMms = undownloadedMms(messages), - ) - latestReactions = result.reactions - if (!isCodeSender()) { - chatSounds.received(result.newlyRead.map { ChatArrival(it.id, it.isMMS, it.date * 1000L) }) - } - if (result.newlyRead.isNotEmpty()) { - result.newlyRead.forEach { markMessageRead(it.id, it.isMMS) } - conversationsDB.markRead(threadId) - bus?.post(Events.RefreshConversations()) - } - return result.items - } - - private fun launchForResult( - launcher: ActivityResultLauncher, - input: I, - @StringRes error: Int = org.fossify.commons.R.string.no_app_found, - ) { - hideKeyboard() - try { - // The picker or camera the user opened here is not leaving the app: coming back does not lock it again. - appLockManager.allowOwnTrip() - launcher.launch(input) - } catch (e: ActivityNotFoundException) { - showErrorToast(getString(error)) - } catch (e: Exception) { - showErrorToast(e) - } - } - - private fun handleAttach(kind: AttachKind) { - when (kind) { - AttachKind.Photo -> launchForResult(pickMedia, PickVisualMediaRequest(PickVisualMedia.ImageAndVideo)) - AttachKind.Camera -> askCameraKind() - AttachKind.TakePhoto -> launchCapturePhotoIntent() - AttachKind.RecordVideo -> launchCaptureVideoIntent() - AttachKind.RecordAudio -> launchCaptureAudioIntent() - AttachKind.File -> launchForResult(pickDocument, "*/*") - AttachKind.Contact -> launchForResult(pickContact, null) - AttachKind.Location -> location.start() - AttachKind.SavedText -> vm.showSavedTexts = true - AttachKind.Schedule -> - scheduleUi.pickTime(vm.scheduledMillis) - } - } - - /** TH-22: the one Camera entry of the attach sheet asks whether to take a photo or record a video. */ - private fun askCameraKind() { - showChoiceDialog( - items = listOf( - ChoiceItem(getString(R.string.thread_attach_take_photo), AttachKind.TakePhoto), - ChoiceItem(getString(R.string.thread_attach_record_video), AttachKind.RecordVideo), - ), - title = getString(R.string.thread_review_attach_camera), - ) { handleAttach(it) } - } - - private fun launchCapturePhotoIntent() { - val uri = attachmentController.newCaptureUri() - // Kept in saved state: the camera often outlives this process on low-memory phones. - vm.capturedImageUri = uri - launchForResult(takePicture, uri) - } - - private fun launchCaptureVideoIntent() { - launchForResult(recordMedia, Intent(MediaStore.ACTION_VIDEO_CAPTURE)) - } - - /** The link goes in at the cursor, on its own line; the user reads it and presses Send. */ - private fun insertLocationLink(link: String) { - val before = vm.text.text.subSequence(0, vm.text.selection.min) - vm.insertAtCursor(LocationSharer.placedAfter(before, link)) - } - - private fun launchCaptureAudioIntent() { - launchForResult(recordMedia, Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION)) - } - - /** Send: asks for the SIM and the group MMS choice when needed (each once, TU-03), then sends or schedules. */ - private fun sendMessage() { - // Blank text, or a photo still being shrunk, cannot be sent (TU-04, TU-05). - if (!vm.canSend) return - SendSteps( - needsSim = { sim.mustAsk() }, - askSim = { onChosen -> - showChoiceDialog( - items = sim.choices.mapIndexed { index, card -> ChoiceItem(card.label, index) }, - title = getString(R.string.thread_change_sim), - selected = sim.selectedIndex, - ) { index -> - selectSim(index) - onChosen() - } - }, - needsGroupChoice = ::needsGroupMessageChoice, - askGroupChoice = ::askGroupMessageChoice, - send = ::sendComposedMessage, - ).run() - } - - private fun sendComposedMessage() { - // The composer may have changed while a question was open. - if (!vm.canSend) return - var text = withSignature(vm.text.text.toString().trim()) - vm.firstUnreadId = null - vm.scrollToBottom() - - text = removeDiacriticsIfNeeded(text) - - val subscriptionId = sim.subscriptionId - - if (vm.isScheduling) { - sendScheduledMessage(text, subscriptionId) - } else { - sendNormalMessage(text, subscriptionId) - } - } - - private fun needsGroupMessageChoice(): Boolean = - !config.isGroupMessageMmsPreferenceResolved && recipients.distinctAddresses.size >= 2 - - private fun askGroupMessageChoice(onChosen: () -> Unit) { - if (isGroupMessageConfirmationVisible) return - isGroupMessageConfirmationVisible = true - GroupMessageSendDialog( - activity = this, - callback = { sendAsGroupMms -> - config.sendGroupMessageMMS = sendAsGroupMms - updateMessageType() - onChosen() - }, - onDismiss = { isGroupMessageConfirmationVisible = false } - ) - } - - private fun sendScheduledMessage(text: String, subscriptionId: Int) { - val scheduledMillis = vm.scheduledMillis ?: return - if (!isSchedulableTime(scheduledMillis, System.currentTimeMillis())) { - toast(R.string.must_pick_time_in_the_future) - scheduleUi.pickTime(scheduledMillis) - return - } - - refreshedSinceSent = false - val messageId = vm.scheduledMessageId ?: generateRandomId() - val repeat = RepeatRule.fromName(vm.scheduledRepeat) - // Built here on the main thread: it reads the composer's attachments. - val pickedMessage = buildScheduledMessage( - text = text, - recipients = recipients, - subscriptionId = subscriptionId, - messageId = messageId, - millis = scheduledMillis, - threadId = threadId, - threadHasMessages = messages.isNotEmpty(), - isMms = isMmsMessage(text), - attachments = attachmentController.asMessageAttachments(messageId), - ) - ensureBackgroundThread { - try { - // A thread without messages gets a temporary thread until a real message is sent. - val startsTemporaryThread = messages.isEmpty() - val message = scheduleController.save(pickedMessage, startsTemporaryThread, conversation, repeat) - if (startsTemporaryThread) threadId = message.threadId - insertOrUpdateMessage(message) - - runOnUiThread { - clearCurrentMessage() - vm.clearSchedule() - } - } catch (e: Exception) { - // The composer keeps the text, attachments and time so the user can try again. - showErrorToast( - e.localizedMessage ?: getString(org.fossify.commons.R.string.unknown_error_occurred) - ) - } - } - } - - /** - * Sends [text] with [attachments] now, on a worker thread: the provider writes, the thread lookups of a group and - * an MMS attachment's bytes never run on the main thread (MS5). The composer is cleared only when [fromComposer] - * and the message was handed to the system: after a failure the user's text and photos stay so they can try - * again. While a send from the composer runs, a second tap on Send does nothing. [onDone] gets whether the message - * was handed off, on the worker thread. - */ - private fun sendNormalMessage( - text: String, - subscriptionId: Int, - attachments: List = attachmentController.asMessageAttachments(), - resendId: MessageKey? = resend.target, - fromComposer: Boolean = true, - onDone: (Boolean) -> Unit = {}, - ) { - if (fromComposer && !composerSend.tryStart()) return - refreshedSinceSent = false - var outgoing = OutgoingMessage(text, recipients.addresses, subscriptionId, attachments, resendId) - if (fromComposer) { - // MS6: each photo goes out as its own MMS. One that was queued leaves the composer at once, so when a - // later one fails and the user taps Send again, only what did not go out is sent, not every photo twice. - outgoing = outgoing.copy(onAttachmentHandedOff = { sent -> - runOnUiThread { vm.removeAttachment(sent.uriString) } - }) - } - val composerAtSend = vm.text.text.toString() - ensureBackgroundThread { - try { - onDone(sendOutgoing(outgoing, fromComposer, composerAtSend)) - } finally { - if (fromComposer) composerSend.finish() - } - } - } - - /** The blocking part of [sendNormalMessage]; runs on a worker thread. True when the message was handed off. */ - private fun sendOutgoing(outgoing: OutgoingMessage, fromComposer: Boolean, composerAtSend: String): Boolean { - val result = sendController.send(outgoing, fromComposer) - if (result.completed) { - // A failed send that left a row in the provider still shows up below, with its Retry button. - val thread = threadId - repository.newProviderRows(thread, limit = maxOf(1, outgoing.attachments.size)) - .forEach { insertOrUpdateMessage(it) } - } - runOnUiThread { - // Not when the user already typed something else meanwhile. - if (result.clearComposer && vm.text.text.toString() == composerAtSend) clearCurrentMessage() - if (fromComposer && result.handedOff) chatSounds.sent() - } - return result.handedOff - } - - private fun clearCurrentMessage() { - vm.text.clearText() - attachmentController.clear() - updateMessageType() - } - - private fun insertOrUpdateMessage(message: Message) { - repository.upsert(message) - - val newItems = getThreadItems() - runOnUiThread { - publishItems(newItems) - vm.scrollToBottom() - if (!refreshedSinceSent) { - refreshMessages() - } - } - messagesDB.insertOrUpdate(message) - if (shouldUnarchive()) { - updateConversationArchivedStatus(message.threadId, false) - refreshConversations() - } - } - - /** The numbers the intent opened this chat for: one, or several for a group. */ - private fun getPhoneNumbersFromIntent(): List = ThreadRecipients.numbersFromExtra(intent.getStringExtra(THREAD_NUMBER)) - - private fun saveMMS(attachments: List) { - vm.attachmentsToSave = attachments - if (attachments.size == 1) { - val attachment = attachments.first() - Intent(Intent.ACTION_CREATE_DOCUMENT).apply { - type = attachment.mimetype - addCategory(Intent.CATEGORY_OPENABLE) - // The part's file name ("IMG_2041.jpg"), not the last piece of its content uri ("1234"). - putExtra(Intent.EXTRA_TITLE, saveFileName(attachment)) - launchForResult(saveAttachmentsTarget, this, error = org.fossify.commons.R.string.system_service_disabled) - } - } else { - Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply { - addCategory(Intent.CATEGORY_DEFAULT) - launchForResult(saveAttachmentsTarget, this, error = org.fossify.commons.R.string.system_service_disabled) - } - } - } - - @Subscribe(threadMode = ThreadMode.ASYNC) - fun refreshMessages(@Suppress("unused") event: Events.RefreshMessages) { - if (isRecycleBin) { - return - } - - refreshedSinceSent = true - repository.allFetched = false - - // The notification stays while the chat is open but not seen (TU-11). - if (isSeenByUser()) { - notificationManager.cancel(threadId.hashCode()) - } - - // Still loading: no recipients yet, so there is nothing to look up (an empty list would blank the thread, B13). - if (recipients.isEmpty()) return - - val messageSnapshot = messages.toSortedMessages() - val lastMaxId = messageSnapshot.filterNot { it.isScheduled }.maxByOrNull { it.id }?.id ?: 0L - val providerParticipantsChanged = reconcileProviderParticipants() - // The provider is asked for the thread only while this chat has none of its own yet (scheduled messages in a - // temporary thread, or no messages): asking every time created an empty provider thread (B13). - val newThreadId = providerThreadIdFor(messageSnapshot) - val newMessages = repository.newestFromProvider(newThreadId) - if (messageSnapshot.isNotEmpty() && messageSnapshot.all { it.isScheduled } && newMessages.isNotEmpty()) { - // update scheduled messages with real thread id - threadId = newThreadId - updateScheduledMessagesThreadId( - messages = messageSnapshot.filter { it.threadId != threadId }, - newThreadId = threadId - ) - } - - // A full page means older messages exist; the ones already paged in are kept (see mergeRefreshedMessages). - repository.refresh(threadId, newMessages) - - messages.filter { !it.isScheduled && !it.isReceivedMessage() && it.id > lastMaxId } - .forEach { latestMessage -> - messagesDB.insertOrIgnore(latestMessage) - } - - // A new conversation (a group just started here) is saved with its first text; the menu needs it. - if (conversation == null) conversation = conversationsDB.getConversationWithThreadId(threadId) - setupAdapter() - runOnUiThread { - if (providerParticipantsChanged) { - setupThreadTitle() - } - setupSIMSelector() - } - } - - private fun providerThreadIdFor(messageSnapshot: List): Long = - if (threadId > 0L && messageSnapshot.any { !it.isScheduled }) { - threadId - } else { - getThreadId(recipients.addresses.toSet()) - } - - /** I60: the signature goes under what is typed, but not under a failed message that is being sent again. */ - private fun withSignature(text: String): String = - if (resend.target != null) text else MessageSignature.applyTo(text, composerPrefs.signature) - - private fun isMmsMessage(text: String): Boolean = sendsAsMms( - hasAttachments = vm.attachments.isNotEmpty(), - recipientCount = recipients.size, - sendGroupAsMms = config.sendGroupMessageMMS, - isLongText = isLongMmsMessage(text), - ) - - private fun updateMessageType() { - vm.isMms = isMmsMessage(withSignature(vm.text.text.toString())) - vm.groupSendMode = if (recipients.distinctAddresses.size >= 2 && config.isGroupMessageMmsPreferenceResolved) { - config.sendGroupMessageMMS - } else { - null - } - } - - /** - * "Send now" on a scheduled bubble: sends that message as it is, straight from its own text and attachments. - * It used to go through the composer, which threw away whatever the user was typing. The scheduled copy is - * removed only once the message was handed off. - */ - private fun sendScheduledMessageNow(message: Message) { - val outgoing = OutgoingMessage( - text = message.body, - addresses = recipients.addresses, - subscriptionId = message.subscriptionId, - attachments = message.attachment?.attachments.orEmpty(), - resendOf = null, - onAttachmentHandedOff = scheduledAttachmentTracker(message), - ) - refreshedSinceSent = false - ensureBackgroundThread { - // F3: the alarm may be sending this very message; whoever claims it first sends it, the other does nothing. - if (!ScheduledSendClaims.claim(this, message.id, allowHeld = true)) return@ensureBackgroundThread - try { - if (sendOutgoing(outgoing, fromComposer = false, composerAtSend = "")) { - runOnUiThread { cancelScheduledMessageAndRefresh(message.id) } - } else { - // Not sent: held again, so Retry stays and no alarm sends it by itself. - runCatching { messagesDB.updateScheduledType(message.id, Telephony.Sms.MESSAGE_TYPE_FAILED) } - } - } finally { - ScheduledSendClaims.release(message.id) - } - } - } - - /** - * [keepAttachmentFiles] when the composer still shows the message's attachments (the user left schedule mode - * while editing it); those private copies are then deleted on the next app start. - */ - private fun cancelScheduledMessageAndRefresh(messageId: Long, keepAttachmentFiles: Boolean = false) { - messages.firstOrNull { it.id == messageId && it.isScheduled }?.attachment?.attachments?.forEach { - AudioPlayerManager.release(it.getUri()) - } - ensureBackgroundThread { - scheduleController.cancel(messageId, keepAttachmentFiles) - refreshMessages() - } - } - - companion object { - /** 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" - } -} +package com.glooboo.umessage.activities + +import android.annotation.SuppressLint +import android.app.Activity +import android.content.ActivityNotFoundException +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.os.Looper +import android.provider.MediaStore +import android.provider.Telephony +import android.util.Log +import android.view.WindowManager +import android.widget.Toast +import androidx.activity.result.ActivityResultLauncher +import androidx.activity.result.PickVisualMediaRequest +import androidx.activity.result.contract.ActivityResultContracts +import androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia +import androidx.activity.viewModels +import androidx.annotation.StringRes +import androidx.compose.foundation.text.input.clearText +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd +import androidx.compose.material3.SnackbarDuration +import androidx.compose.runtime.snapshotFlow +import androidx.core.content.pm.ShortcutManagerCompat +import androidx.core.net.toUri +import androidx.lifecycle.lifecycleScope +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import org.fossify.commons.extensions.appLockManager +import org.fossify.commons.extensions.getMyContactsCursor +import org.fossify.commons.extensions.hideKeyboard +import org.fossify.commons.extensions.normalizeString +import org.fossify.commons.extensions.notificationManager +import org.fossify.commons.extensions.showErrorToast +import org.fossify.commons.extensions.toast +import org.fossify.commons.helpers.MyContactsContentProvider +import org.fossify.commons.helpers.PERMISSION_READ_PHONE_STATE +import org.fossify.commons.helpers.ensureBackgroundThread +import com.glooboo.umessage.ui.components.ChoiceItem +import com.glooboo.umessage.ui.components.showChoiceDialog +import org.fossify.commons.models.SimpleContact +import com.glooboo.umessage.R +import com.glooboo.umessage.dialogs.GroupMessageSendDialog +import com.glooboo.umessage.dialogs.InvalidNumberDialog +import com.glooboo.umessage.extensions.config +import com.glooboo.umessage.extensions.conversationsDB +import com.glooboo.umessage.extensions.deleteSmsDraft +import com.glooboo.umessage.extensions.getContactFromAddress +import com.glooboo.umessage.extensions.getSmsDraft +import com.glooboo.umessage.extensions.getThreadId +import com.glooboo.umessage.extensions.getThreadParticipants +import com.glooboo.umessage.extensions.isSavedContactNumber +import com.glooboo.umessage.extensions.restoreMessageFromRecycleBin +import com.glooboo.umessage.extensions.updateLastConversationMessage +import com.glooboo.umessage.extensions.getThreadTitle +import com.glooboo.umessage.extensions.launchConversationDetails +import com.glooboo.umessage.extensions.launchViewIntent +import com.glooboo.umessage.extensions.markMessageRead +import com.glooboo.umessage.extensions.markThreadMessagesRead +import com.glooboo.umessage.extensions.messagesDB +import com.glooboo.umessage.extensions.removeDiacriticsIfNeeded +import com.glooboo.umessage.extensions.saveSmsDraft +import com.glooboo.umessage.extensions.shouldUnarchive +import com.glooboo.umessage.extensions.startContactDetailsIntent +import com.glooboo.umessage.extensions.subscriptionManagerCompat +import com.glooboo.umessage.extensions.toArrayList +import com.glooboo.umessage.extensions.toSortedMessages +import com.glooboo.umessage.extensions.updateConversationArchivedStatus +import com.glooboo.umessage.extensions.updateScheduledMessagesThreadId +import com.glooboo.umessage.helpers.AudioPlayerManager +import com.glooboo.umessage.helpers.EXTRA_VCARD_URI +import com.glooboo.umessage.helpers.IS_LAUNCHED_FROM_SHORTCUT +import com.glooboo.umessage.helpers.IS_RECYCLE_BIN +import com.glooboo.umessage.helpers.SEARCHED_MESSAGE_ID +import com.glooboo.umessage.helpers.messageNotes +import com.glooboo.umessage.helpers.SEARCHED_MESSAGE_IS_MMS +import com.glooboo.umessage.helpers.THREAD_ATTACHMENT_URI +import com.glooboo.umessage.helpers.THREAD_ATTACHMENT_URIS +import com.glooboo.umessage.helpers.THREAD_ID +import com.glooboo.umessage.helpers.THREAD_NUMBER +import com.glooboo.umessage.helpers.w3cPrefs +import com.glooboo.umessage.helpers.THREAD_TEXT +import com.glooboo.umessage.helpers.THREAD_TITLE +import com.glooboo.umessage.helpers.ChatArrival +import com.glooboo.umessage.helpers.ChatSounds +import com.glooboo.umessage.helpers.LocationSharer +import com.glooboo.umessage.helpers.cancelFailedSendNotification +import com.glooboo.umessage.helpers.composerPrefs +import com.glooboo.umessage.helpers.generateRandomId +import com.glooboo.umessage.helpers.refreshConversations +import com.glooboo.umessage.helpers.refreshMessages +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.undownloadedMms +import com.glooboo.umessage.messaging.isLongMmsMessage +import com.glooboo.umessage.messaging.scheduledAttachmentTracker +import com.glooboo.umessage.messaging.withUnsentOnly +import com.glooboo.umessage.models.Attachment +import com.glooboo.umessage.models.Conversation +import com.glooboo.umessage.models.Events +import com.glooboo.umessage.models.Message +import com.glooboo.umessage.models.MessageKey +import com.glooboo.umessage.models.ThreadItem +import com.glooboo.umessage.ui.thread.IncomingShareGuard +import com.glooboo.umessage.ui.thread.MessageNoteStore +import com.glooboo.umessage.ui.thread.AttachKind +import com.glooboo.umessage.ui.thread.MediaSizes +import com.glooboo.umessage.ui.thread.SearchHit +import com.glooboo.umessage.ui.thread.ThreadLookupCache +import com.glooboo.umessage.ui.thread.matchesSearch +import com.glooboo.umessage.ui.thread.messagesToCache +import com.glooboo.umessage.ui.thread.ThreadExportController +import com.glooboo.umessage.ui.thread.DraftText +import com.glooboo.umessage.ui.thread.SendGuard +import com.glooboo.umessage.ui.thread.SendSteps +import com.glooboo.umessage.ui.thread.adoptScheduledMessages +import com.glooboo.umessage.ui.thread.refreshRepeatRules +import com.glooboo.umessage.ui.thread.simHeaderLabels +import com.glooboo.umessage.ui.thread.SmsSegments +import com.glooboo.umessage.ui.thread.ThreadActions +import com.glooboo.umessage.ui.thread.ThreadLaunchHints +import com.glooboo.umessage.ui.thread.ThreadMenuAction +import com.glooboo.umessage.ui.thread.SenderStatus +import com.glooboo.umessage.ui.log.DecisionLogActivity +import com.glooboo.umessage.spam.ForwardingAvailability +import com.glooboo.umessage.ui.spam.ForwardingActivity +import com.glooboo.umessage.ui.thread.UnknownCardController +import com.glooboo.umessage.ui.thread.ContextThreadMessageSource +import com.glooboo.umessage.ui.thread.ThreadMessagesRepository +import com.glooboo.umessage.ui.thread.draftToSave +import com.glooboo.umessage.ui.thread.mergeRefreshedMessages +import com.glooboo.umessage.ui.thread.saveFileName +import com.glooboo.umessage.ui.thread.ThreadScreen +import com.glooboo.umessage.ui.thread.ThreadViewModel +import com.glooboo.umessage.ui.thread.removeThreadMessages +import com.glooboo.umessage.ui.thread.ThreadScheduleUi +import com.glooboo.umessage.ui.thread.ThreadSimController +import com.glooboo.umessage.ui.thread.ThreadConversationActions +import com.glooboo.umessage.ui.thread.ThreadPeopleController +import com.glooboo.umessage.ui.thread.ThreadSelectionActions +import com.glooboo.umessage.ui.thread.ThreadSenderActions +import com.glooboo.umessage.ui.thread.ThreadAttachmentController +import com.glooboo.umessage.ui.thread.MessageSignature +import com.glooboo.umessage.ui.thread.ThreadLocationController +import com.glooboo.umessage.ui.thread.isNumericShortCode +import com.glooboo.umessage.ui.thread.RecentPhotosAccess +import com.glooboo.umessage.ui.thread.ContextMessageSender +import com.glooboo.umessage.ui.thread.OutgoingMessage +import com.glooboo.umessage.ui.thread.ResendTracker +import com.glooboo.umessage.messaging.RepeatRule +import com.glooboo.umessage.ui.thread.ThreadScheduleController +import com.glooboo.umessage.ui.thread.ThreadSendController +import com.glooboo.umessage.ui.thread.buildScheduledMessage +import com.glooboo.umessage.ui.thread.isSchedulableTime +import com.glooboo.umessage.ui.thread.ThreadMenuInput +import com.glooboo.umessage.ui.thread.ThreadPrivacyActions +import com.glooboo.umessage.ui.lock.HiddenChatGate +import com.glooboo.umessage.ui.lock.LockScope +import com.glooboo.umessage.ui.thread.ThreadRecipients +import com.glooboo.umessage.ui.thread.TapbackReaction +import com.glooboo.umessage.ui.thread.buildThreadItems +import com.glooboo.umessage.ui.thread.firstUnreadMessageId +import com.glooboo.umessage.ui.thread.buildThreadMenu +import com.glooboo.umessage.ui.thread.sendsAsMms +import org.greenrobot.eventbus.EventBus +import org.greenrobot.eventbus.Subscribe +import org.greenrobot.eventbus.ThreadMode +import java.io.File + +/** + * The chat screen's host. The layout is Compose ([ThreadScreen]) over [ThreadViewModel]; the work is done by the + * classes in ui/thread: [ThreadMessagesRepository] (loading, paging, refreshing), [ThreadSendController] and + * [ThreadScheduleController] (sending and scheduling to every [ThreadRecipients] address), + * [ThreadAttachmentController], [ThreadSimController], [ThreadScheduleUi], [ThreadSenderActions], + * [ThreadConversationActions], [ThreadSelectionActions] and [ThreadPeopleController]. This class owns the lifecycle, + * the intent, the activity result launchers and the order in which a conversation is loaded. + */ +open class ThreadActivity : ComposeSimpleActivity() { + private val vm: ThreadViewModel by viewModels() + + private var threadId = 0L + + /** B06: a hidden chat asks for the app lock before it shows. */ + private val hiddenGate = HiddenChatGate(this) { threadId } + @Volatile + private var isActivityVisible = false + + @Volatile + private var hasWindowFocusNow = false + private var refreshedSinceSent = false + private var threadItems: List = emptyList() + private var bus: EventBus? = null + private var conversation: Conversation? = null + private var recipients = ThreadRecipients() + private var privateContacts = ArrayList() + /** The loaded messages: loading, paging, refreshing and every single change go through it. */ + private val repository by lazy { ThreadMessagesRepository(ContextThreadMessageSource(applicationContext)) } + private val messages: List get() = repository.current + private val sim by lazy { ThreadSimController(this, vm) } + private val scheduleUi by lazy { + ThreadScheduleUi( + activity = this, + vm = vm, + cancel = ::cancelScheduledMessageAndRefresh, + sendNow = ::sendScheduledMessageNow, + loadIntoComposer = { message -> + clearCurrentMessage() + vm.text.setTextAndPlaceCursorAtEnd(message.body) + message.attachment?.attachments?.forEach { attachmentController.add(it.getUri()) } + }, + ) + } + private var isJumpingToMessage = false + + /** Contact, stranger and SIM lookups that stay the same from one refresh to the next (thread-19). */ + private val lookups = ThreadLookupCache() + private val contactsObserver = object : android.database.ContentObserver(android.os.Handler(Looper.getMainLooper())) { + override fun onChange(selfChange: Boolean) { + lookups.invalidateContacts() + } + } + private var isRecycleBin = false + private var isLaunchedFromShortcut = false + + /** The reactions found by the last [getThreadItems] (I30). */ + @Volatile + private var latestReactions: Map> = emptyMap() + + /** True once the provider's messages are loaded: only they know what is really unread (I26). */ + @Volatile + private var providerLoaded = false + + /** + * True once the user really had this chat in front of them (see [isSeenByUser]). A quick open and Back can end + * before the provider load finishes; the load then still marks the chat read for this reason. + */ + @Volatile + private var shownToUser = false + + /** The stored draft is put back once each time a chat is opened; see [DraftText.restore]. */ + private var draftRestored = false + + private var isGroupMessageConfirmationVisible = false + /** One send from the composer at a time: a second tap while it runs is ignored (MS5). */ + private val composerSend = SendGuard() + + /** The failed message "Retry" put into the composer, resent in its place by the next Send. */ + private val resend = ResendTracker() + + private val sendController by lazy { + ThreadSendController(ContextMessageSender(this)) { error -> + if (error is Exception) { + showErrorToast(error) + } else { + showErrorToast(error.localizedMessage ?: getString(org.fossify.commons.R.string.unknown_error_occurred)) + } + } + } + private val scheduleController by lazy { ThreadScheduleController(applicationContext) } + + private val attachmentController by lazy { ThreadAttachmentController(this, vm) { updateMessageType() } } + + /** True once the composer's text listener runs; [loadConversation] runs again for a new intent. */ + private var composerListening = false + + // Activity Result API launchers. They are registered up front so results are delivered even when the process was + // killed while the other app (camera, picker) was open. + private val takePicture = registerForActivityResult(ActivityResultContracts.TakePicture()) { saved -> + val uri = vm.capturedImageUri + vm.capturedImageUri = null + if (saved && uri != null) { + resend.clear() + attachmentController.add(uri) + } + } + + /** The system Photo Picker: no storage permission needed, several items at once. */ + private val pickMedia = registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia()) { uris -> + if (uris.isNotEmpty()) resend.clear() + uris.forEach { attachmentController.add(it) } + } + + private val pickDocument = registerForActivityResult(ActivityResultContracts.GetContent()) { uri -> + if (uri != null) { + resend.clear() + attachmentController.add(uri) + } + } + + private val pickContact = registerForActivityResult(ActivityResultContracts.PickContact()) { uri -> + if (uri != null) { + resend.clear() + attachmentController.addContact(uri) + } + } + + /** Video and audio recorders return the recording's uri in the result data. */ + private val recordMedia = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + val uri = result.data?.data + if (result.resultCode == Activity.RESULT_OK && uri != null) { + resend.clear() + attachmentController.add(uri) + } + } + + /** I52: the system prompt for the location; the user may allow the approximate position only. */ + private val locationPermission: ActivityResultLauncher> = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { + location.onPermissionResult() + } + + /** I69: the media prompt of the recent photos row; the sheet reads the answer from the permission itself. */ + private val photoPermission: ActivityResultLauncher> = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { + vm.photoAccessVersion++ + } + + /** I65: sounds for sent and received messages, when switched on. */ + private val chatSounds by lazy { ChatSounds.create(this) } + + private val location: ThreadLocationController = ThreadLocationController( + activity = this, + requestPermission = { launchForResult(locationPermission, LocationSharer.LOCATION_PERMISSIONS) }, + insert = { insertLocationLink(it) }, + ) + + /** "Save" on an MMS attachment: a document (one attachment) or a folder (several). */ + private val saveAttachmentsTarget = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> + val data = result.data + val destination = data?.data + if (result.resultCode == Activity.RESULT_OK && destination != null) { + val toSave = vm.attachmentsToSave + vm.attachmentsToSave = null + attachmentController.save(toSave, destination) + } else { + vm.attachmentsToSave = null + } + } + + private val actions = ThreadActions( + onBack = { finish() }, + onMenuAction = { handleMenuAction(it) }, + onSelectionAction = { selectionActions.handle(it) }, + onBubbleClick = { message -> if (message.isScheduled) scheduleUi.showOptions(message) }, + onSenderClick = { openSenderContact(it) }, + onRetry = { message, text -> retryFailedMessage(message, text) }, + onLoadOlder = { if (!isJumpingToMessage) loadMoreMessages() }, + onSend = { sendMessage() }, + onSendLongPress = { if (!vm.isScheduling) scheduleUi.pickTime() }, + onAttach = { handleAttach(it) }, + onEditSchedule = { scheduleUi.pickTime(vm.scheduledMillis) }, + onDiscardSchedule = { scheduleUi.discard() }, + onSelectSim = { selectSim(it) }, + onRemoveAttachment = { attachmentController.remove(it) }, + onOpenFile = { uri, mimeType, filename -> launchViewIntent(uri, mimeType, filename) }, + onOpenVCard = { uri -> + startActivity(Intent(this, VCardViewerActivity::class.java).putExtra(EXTRA_VCARD_URI, uri)) + }, + onReplyInfo = { + InvalidNumberDialog(activity = this, text = getString(R.string.invalid_short_code_desc)) + }, + onPickContact = { people.pickContact(it) }, + onAddTypedNumber = { people.addNumber(it) }, + onRemovePerson = { people.remove(it) }, + onConfirmPeople = { people.confirm() }, + onAddPhoto = { + resend.clear() + attachmentController.add(it) + }, + onRequestPhotos = { + launchForResult(photoPermission, RecentPhotosAccess.permissions(Build.VERSION.SDK_INT)) + }, + onDownloadMms = { id -> ensureBackgroundThread { downloadMmsFromChat(id) } }, + ) + + /** Q40: "Tap to download". A message that is gone from the provider (downloaded meanwhile) just refreshes. */ + private fun downloadMmsFromChat(id: Long) { + if (downloadMms(id) == MmsRetryResult.NotPending) refreshMessages() + } + + /** + * singleTop: a notification or shortcut for a conversation reuses this screen. The same conversation keeps its + * draft and attachments and only applies what the intent adds; another conversation is loaded in place (the + * current draft was already saved in onPause). + */ + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + if (intent.extras == null) return + val newThreadId = intent.getLongExtra(THREAD_ID, 0L) + setIntent(intent) + if (newThreadId != 0L && newThreadId == threadId) { + // Shared text into the chat that is open: added after what is typed, never dropped (B9). + intent.getStringExtra(THREAD_TEXT)?.let { shared -> + vm.text.setTextAndPlaceCursorAtEnd(DraftText.appendShared(vm.text.text.toString(), shared)) + } + addAttachmentsFromIntent() + takeSearchedMessage()?.let { jumpToMessage(it) } + takeOpenSearch() + applyLaunchHints() + return + } + + resetForNewConversation() + draftRestored = false + readIntentExtras() + // onResume does not run again for a chat that is already in front: the hidden-chat cover is decided here. + hiddenGate.check() + loadConversation(isFreshLaunch = true) + markReadIfSeen() + } + + private fun readIntentExtras() { + threadId = intent.getLongExtra(THREAD_ID, 0L) + intent.getStringExtra(THREAD_TITLE)?.let { vm.title = it } + isRecycleBin = intent.getBooleanExtra(IS_RECYCLE_BIN, false) + isLaunchedFromShortcut = intent.getBooleanExtra(IS_LAUNCHED_FROM_SHORTCUT, false) + vm.isRecycleBin = isRecycleBin + takeOpenSearch() + } + + /** [EXTRA_OPEN_SEARCH] (Conversation details' "Search in conversation"): opens the search bar, once. */ + private fun takeOpenSearch() { + if (intent.getBooleanExtra(EXTRA_OPEN_SEARCH, false)) { + intent.removeExtra(EXTRA_OPEN_SEARCH) + if (!isRecycleBin) vm.openSearch() + } + } + + /** + * The focus and notice extras (opened from a blocked chat after Not spam): once the first load is + * done, the message field takes focus and the keyboard comes up, and the note shows. Taken off the intent, so a + * rotation does not do it again. + */ + private fun applyLaunchHints() { + val hints = ThreadLaunchHints.take(intent) + hints.notice?.let { note -> + lifecycleScope.launch { + vm.snackbar.showSnackbar(note, withDismissAction = true, duration = SnackbarDuration.Short) + } + } + if (hints.focusComposer && !isRecycleBin && !isSpecialNumber()) { + window.setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE or + WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE, + ) + vm.focusInput++ + } + } + + /** Clears everything that belongs to the previous conversation before another one is loaded in place. */ + private fun resetForNewConversation() { + AudioPlayerManager.release() + conversation = null + recipients = ThreadRecipients() + privateContacts = ArrayList() + repository.reset() + lookups.clear() + threadItems = emptyList() + refreshedSinceSent = false + isJumpingToMessage = false + isGroupMessageConfirmationVisible = false + resend.clear() + vm.clearSchedule() + vm.clearSelection() + vm.clearAttachments() + vm.text.clearText() + vm.publishItems(emptyList()) + vm.reactions = emptyMap() + latestReactions = emptyMap() + vm.firstUnreadId = null + vm.unreadResolved = false + vm.unreadScrolled = false + providerLoaded = false + shownToUser = false + vm.loaded = false + vm.title = "" + vm.subtitle = null + vm.avatarPhotoUri = "" + vm.showPeople = false + vm.showAttachSheet = false + vm.showEmojiPanel = false + vm.closeSearch() + vm.people = emptyList() + refreshMenuItems() + } + + override fun onCreate(savedInstanceState: Bundle?) { + // Same window theme as every other Compose screen (the manifest entry has none). + setTheme(R.style.Theme_UMessage_Screen) + super.onCreate(savedInstanceState) + + val extras = intent.extras + if (extras == null) { + toast(org.fossify.commons.R.string.unknown_error_occurred) + finish() + return + } + + readIntentExtras() + + setUMessageContent { ThreadScreen(vm, actions) } + // After the process was killed the time survives in saved state but the label does not. + vm.scheduledMillis?.let { scheduleUi.show(it) } + + bus = EventBus.getDefault() + bus!!.register(this) + + // Search in conversation also looks at the messages that are not loaded yet. + vm.olderSearch = { thread, query -> + messagesDB.searchThreadMessages(thread, query) + .filter { matchesSearch(it.body, query) } + .map { SearchHit(it.key, it.date) } + } + vm.loadAndScrollTo = ::jumpToMessage + runCatching { + contentResolver.registerContentObserver( + android.provider.ContactsContract.Contacts.CONTENT_URI, true, contactsObserver + ) + } + + refreshMenuItems() + senderActions.observeRules() + vm.stars.attach(this, lifecycleScope) + vm.notes.attach(MessageNoteStore(messageNotes), lifecycleScope) + loadConversation(isFreshLaunch = savedInstanceState == null) + } + + override fun onResume() { + super.onResume() + hiddenGate.check() + + isActivityVisible = true + // The SIM cards may have changed while the chat was in the background. + lookups.invalidateSims() + + scheduleUi.onResume() + + ensureBackgroundThread { + val newConv = conversationsDB.getConversationWithThreadId(threadId) + if (newConv != null) { + conversation = newConv + runOnUiThread { + setupThreadTitle() + // "Conversation details" and the other entries that need the saved conversation. + refreshMenuItems() + } + } + + val smsDraft = getSmsDraft(threadId) + if (smsDraft.isNotEmpty()) { + runOnUiThread { + // Once per open, and merged with what is already in the composer (B8): a shared text, or text + // typed before this read finished, is kept; coming back from the camera never rewinds it. + if (!draftRestored) { + draftRestored = true + vm.text.setTextAndPlaceCursorAtEnd(DraftText.restore(vm.text.text.toString(), smsDraft)) + } + } + } + } + markReadIfSeen() + } + + override fun onWindowFocusChanged(hasFocus: Boolean) { + super.onWindowFocusChanged(hasFocus) + hasWindowFocusNow = hasFocus + if (hasFocus) markReadIfSeen() + } + + /** + * TU-11: messages count as read only while the user can actually see this chat: the screen is in front, its + * window has focus (not under the lock screen, the notification shade or a dialog) and the app lock is not up. + * Texts that arrive while the chat sits open in the background stay unread until the user comes back to it. + */ + private fun isSeenByUser(): Boolean = + isActivityVisible && hasWindowFocusNow && !hiddenGate.blocking && !LockScope.isLockedNow(this) + + private fun markReadIfSeen() { + if (!isSeenByUser()) return + shownToUser = true + markThreadReadInBackground(threadId) + } + + private fun markThreadReadInBackground(thread: Long) { + notificationManager.cancel(thread.hashCode()) + // The chat is open: its "Message not sent" notification has done its job, the failed row has Retry (MS3). + cancelFailedSendNotification(thread) + ensureBackgroundThread { + // I26: the unread messages are noted first; the build that does it marks them read itself. + if (!providerLoaded && !isRecycleBin) return@ensureBackgroundThread + // A refused provider write must not skip the saved flags or the list refresh. + runCatching { markThreadMessagesRead(thread) } + repository.markAllRead(thread) + bus?.post(Events.RefreshConversations(thread)) + // A notification posted while the chat was being read would otherwise stay. + notificationManager.cancel(thread.hashCode()) + } + } + + override fun onPause() { + super.onPause() + saveDraftMessage() + bus?.post(Events.RefreshConversations()) + isActivityVisible = false + } + + override fun onStop() { + super.onStop() + AudioPlayerManager.release() + if (selectionActionsDelegate.isInitialized()) selectionActions.release() + saveDraftMessage() + } + + override fun onDestroy() { + super.onDestroy() + chatSounds.release() + bus?.unregister(this) + vm.olderSearch = null + vm.loadAndScrollTo = null + runCatching { contentResolver.unregisterContentObserver(contactsObserver) } + } + + private fun saveDraftMessage() { + if (!vm.loaded && vm.text.text.isEmpty()) return + val draftMessage = draftToSave(vm.text.text.toString()) + val draftThreadId = threadId + ensureBackgroundThread { + if (draftMessage != null) { + saveSmsDraft(draftMessage, draftThreadId) + } else { + deleteSmsDraft(draftThreadId) + } + } + } + + /** Whether the only participant's number is already a saved contact; checked off the main thread. */ + @Volatile + private var firstNumberIsSaved = false + + /** I04: whether the only person is a stranger (not a contact, never written to); checked off the main thread. */ + @Volatile + private var senderIsStranger = false + private val unknownCard by lazy { UnknownCardController(this, vm) } + + private val selectionActionsDelegate = lazy { + ThreadSelectionActions( + activity = this, + vm = vm, + isRecycleBin = { isRecycleBin }, + saveAttachments = ::saveMMS, + deleteMessages = ::deleteMessages, + ) + } + private val selectionActions by selectionActionsDelegate + + private val exportController by lazy { + ThreadExportController( + activity = this, + threadId = { threadId }, + title = { vm.title }, + numbers = { recipients.addresses.distinct() }, + showMessage = { text -> lifecycleScope.launch { vm.snackbar.showSnackbar(text) } }, + ) + } + + private val conversationActions by lazy { + ThreadConversationActions( + activity = this, + threadId = { threadId }, + isRecycleBin = { isRecycleBin }, + recipients = { recipients }, + conversation = { conversation }, + title = { vm.title }, + showMessage = { text -> lifecycleScope.launch { vm.snackbar.showSnackbar(text) } }, + onRenamed = { renamed -> + conversation = renamed + setupThreadTitle() + }, + ) + } + + private val people by lazy { + ThreadPeopleController( + activity = this, + vm = vm, + recipients = { recipients }, + setRecipients = { recipients = it }, + privateContacts = { privateContacts }, + threadId = { threadId }, + onPeopleChanged = { updateMessageType() }, + ) + } + + /** N05, B06: Mute and Hide entries of the menu. */ + private val privacy by lazy { + ThreadPrivacyActions(this, { threadId }, onChange = { refreshMenuItems() }, onHidden = { finish() }) + } + + /** Block, unblock and report spam; it also tells the menu whether the sender is already blocked. */ + private val senderActions by lazy { + ThreadSenderActions( + activity = this, + scope = lifecycleScope, + snackbar = vm.snackbar, + recipients = { recipients }, + senderName = { vm.title }, + lastReceivedSubscriptionId = { messages.lastOrNull { it.isReceivedMessage() }?.subscriptionId ?: -1 }, + onStatusChanged = { refreshMenuItems() }, + ) + } + + private fun refreshMenuItems() { + vm.threadId = threadId + senderActions.refreshIfPeopleChanged() + vm.linksTrusted = recipients.size == 1 && firstNumberIsSaved + unknownCard.refresh( + senderIsStranger, recipients, messages.lastOrNull { it.isReceivedMessage() }, threadId, + hasRule = senderActions.allowedSender != null || senderActions.blockedSender != null, + ) + vm.menu = buildThreadMenu( + ThreadMenuInput( + recipients = recipients, + hasItems = threadItems.isNotEmpty(), + hasConversation = conversation != null, + isArchived = conversation?.isArchived, + isRecycleBin = isRecycleBin, + archiveAvailable = config.isArchiveAvailable, + singleNumberIsSaved = firstNumberIsSaved, + reportedSender = senderActions.reportedSender, + blockedSender = senderActions.blockedSender, + allowedSender = senderActions.allowedSender, + pinShortcutSupported = ShortcutManagerCompat.isRequestPinShortcutSupported(this), + forwardingAvailable = ForwardingAvailability.isAvailable(this), + muted = privacy.isMuted(), + hiddenChat = privacy.isHiddenChat(), + ) + ) + vm.senderStatus = when { + senderActions.blockedSender != null -> SenderStatus.Blocked + senderActions.allowedSender != null -> SenderStatus.Allowed + else -> SenderStatus.None + } + } + + private fun handleMenuAction(action: ThreadMenuAction) { + if (recipients.isEmpty()) return + when (action) { + ThreadMenuAction.Block -> senderActions.askBlock() + ThreadMenuAction.Unblock -> senderActions.unblock() + ThreadMenuAction.ReportSpam -> senderActions.askReportSpam() + ThreadMenuAction.AllowSender -> senderActions.allowSender() + ThreadMenuAction.WhyDecided -> startActivity(Intent(this, DecisionLogActivity::class.java)) + ThreadMenuAction.Search -> vm.openSearch() + ThreadMenuAction.AlwaysForward -> openForwardRuleForSender() + ThreadMenuAction.Delete -> conversationActions.askDelete() + ThreadMenuAction.Restore -> conversationActions.askRestoreAll() + ThreadMenuAction.Archive -> conversationActions.setArchived(true) + ThreadMenuAction.Unarchive -> conversationActions.setArchived(false) + ThreadMenuAction.Rename -> conversationActions.rename() + ThreadMenuAction.Details -> launchConversationDetails(threadId) + ThreadMenuAction.AddToContact -> conversationActions.addNumberToContacts() + ThreadMenuAction.CopyNumber -> conversationActions.copyNumber() + ThreadMenuAction.Dial -> conversationActions.dial() + ThreadMenuAction.ManagePeople -> people.toggle() + ThreadMenuAction.MarkUnread -> conversationActions.markUnread() + ThreadMenuAction.ShareAsText -> conversationActions.shareAsText() + ThreadMenuAction.ExportConversation -> exportController.start() + ThreadMenuAction.AddToHomeScreen -> conversationActions.addToHomeScreen() + ThreadMenuAction.Labels -> vm.labelsFor = threadId + ThreadMenuAction.Mute -> privacy.askMute() + ThreadMenuAction.Unmute -> privacy.unmute() + ThreadMenuAction.Hide -> privacy.hide() + ThreadMenuAction.Unhide -> privacy.unhide() + } + } + + /** + * TH-11, TH-20: "Always forward from this sender" opens the forwarding screen with the rule editor already + * filled in for this sender; saving it goes through the editor's usual checks (and the app lock). + */ + private fun openForwardRuleForSender() { + if (!ForwardingAvailability.isAvailable(this)) return + val address = recipients.reportableAddress ?: return + startActivity(ForwardingActivity.intent(this, address)) + } + + private fun setupCachedMessages(callback: () -> Unit) { + ensureBackgroundThread { + repository.loadCached(threadId, isRecycleBin) + + setupParticipants() + setupAdapter() + + runOnUiThread { + if (messages.isEmpty() && !isSpecialNumber()) { + window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) + vm.focusInput++ + } + + setupThreadTitle() + setupSIMSelector() + updateMessageType() + callback() + } + } + } + + private fun setupThread(callback: () -> Unit) { + if (conversation == null && isLaunchedFromShortcut) { + if (isTaskRoot) { + Intent(this, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) + startActivity(this) + } + } + finish() + return + } + val privateCursor = getMyContactsCursor(favoritesOnly = false, withPhoneNumbersOnly = true) + ensureBackgroundThread { + privateContacts = MyContactsContentProvider.getSimpleContacts(this, privateCursor) + + val cachedMessagesCode = messages.hashCode() + val cachedBefore = messages + if (!isRecycleBin) repository.loadNewest(threadId) + providerLoaded = true + // The first mark-read attempt may have come before the messages were loaded. When the user already + // saw the chat but left before this point, nobody would ask again: mark it now. + val loadedThread = threadId + if (shownToUser) markThreadReadInBackground(loadedThread) else runOnUiThread { markReadIfSeen() } + + val providerParticipantsChanged = reconcileProviderParticipants() + val hasParticipantWithoutName = recipients.contacts.any { contact -> + contact.phoneNumbers.map { it.normalizedNumber }.contains(contact.name) + } + + try { + if (canReuseLoadedThread(providerParticipantsChanged, cachedMessagesCode, hasParticipantWithoutName)) { + adoptWaitingScheduledMessages() + setupAdapter() + runOnUiThread { callback() } + return@ensureBackgroundThread + } + } catch (ignored: Exception) { + } + + setupParticipants() + + // check if no participant came from a privately stored contact in Simple Contacts + if (privateContacts.isNotEmpty()) { + val senderNumbersToReplace = HashMap() + recipients.contacts.filter { it.doesHavePhoneNumber(it.name) }.forEach { participant -> + privateContacts.firstOrNull { it.doesHavePhoneNumber(participant.phoneNumbers.first().normalizedNumber) } + ?.apply { + senderNumbersToReplace[participant.phoneNumbers.first().normalizedNumber] = + name + participant.name = name + participant.photoUri = photoUri + } + } + + messages.forEach { message -> + if (senderNumbersToReplace.keys.contains(message.senderName)) { + message.senderName = senderNumbersToReplace[message.senderName]!! + } + } + } + + if (recipients.isEmpty()) { + val name = intent.getStringExtra(THREAD_TITLE) ?: "" + val numbers = getPhoneNumbersFromIntent() + if (numbers.isEmpty()) { + // No messages, no participants known to the phone and no number in the intent: nothing to write to. + Log.w("ThreadActivity", "Chat opened without a conversation, participants or number") + toast(R.string.new_conversation_invalid_number, length = Toast.LENGTH_LONG) + finish() + return@ensureBackgroundThread + } + recipients = ThreadRecipients.fromNumbers(numbers, name) + } + + adoptWaitingScheduledMessages() + + if (!isRecycleBin) { + // Only what is new or changed since the cached copy: the whole page used to be rewritten on every open. + messagesToCache(messages, cachedBefore).chunked(30).forEach { currentMessages -> + messagesDB.insertMessages(*currentMessages.toTypedArray()) + } + } + + setupAdapter() + runOnUiThread { + setupThreadTitle() + setupSIMSelector() + callback() + } + } + } + + /** + * Brings in messages scheduled for these people while they had no conversation yet, which waited in a temporary + * thread of their own: without this the real conversation said "No messages yet". Runs in the background. + */ + private fun adoptWaitingScheduledMessages() { + if (isRecycleBin || recipients.isEmpty()) return + val adopted = adoptScheduledMessages(threadId, recipients.addresses) + if (adopted.isEmpty()) return + repository.addAll(adopted) + bus?.post(Events.RefreshConversations()) + } + + private fun canReuseLoadedThread( + providerParticipantsChanged: Boolean, + cachedMessagesCode: Int, + hasParticipantWithoutName: Boolean, + ): Boolean { + if (providerParticipantsChanged || recipients.isEmpty() || hasParticipantWithoutName) { + return false + } + + return messages.hashCode() == cachedMessagesCode + } + + /** Rebuilds the thread items from [messages] and hands them to the Compose list. */ + private fun setupAdapter() { + val latestThreadItems = getThreadItems() + // Saved picture sizes are read before the rows are shown, so photo bubbles start at their size (TU-25). + if (Looper.myLooper() != Looper.getMainLooper()) MediaSizes.warm(this, messages) + val number = recipients.singleNumber + // Looked up once per opening and again only when the contacts change or the user writes to this person. + firstNumberIsSaved = number != null && lookups.isSaved(number) { isSavedContactNumber(number) } + val hasSent = messages.any { !it.isReceivedMessage() && !it.isScheduled } + senderIsStranger = lookups.isStranger(number, firstNumberIsSaved, hasSent) { + unknownCard.isStranger(number, firstNumberIsSaved, recipients.isGroup) + } + + runOnUiThread { + publishItems(latestThreadItems) + refreshMenuItems() + if (vm.firstUnreadId != null && !vm.unreadScrolled) { + vm.unreadScrolled = true + vm.scrollToUnread() + } + } + } + + private fun publishItems(items: List) { + threadItems = items + vm.reactions = latestReactions + vm.isGroup = recipients.isGroup + vm.approximateScheduledIds = config.inexactScheduledMessages.mapNotNullTo(HashSet()) { it.toLongOrNull() } + vm.refreshRepeatRules(this, items) + vm.publishItems(items) + vm.loaded = true + } + + private fun retryFailedMessage(failedKey: MessageKey, text: String) { + // Matched by id and type: SMS 57 and MMS 57 are different messages (MessageKey). + // A held scheduled message (RM-25) is sent now as it is; on success its scheduled row, and so the failed + // mark, is removed. It never goes through the composer, so the user's draft stays. + messages.firstOrNull { it.key == failedKey && it.isHeldScheduled() }?.let { + sendScheduledMessageNow(it) + return + } + val failed = messages.firstOrNull { it.key == failedKey && it.type == Telephony.Sms.MESSAGE_TYPE_FAILED } + if (failed != null) { + // Tapping "Not sent. Tap to retry." sends the failed message again right away, as it was (text, pictures + // and files, SIM), in the failed row's place. It used to only copy the text into the composer, so on + // a tap nothing visibly happened, and it replaced whatever the user was typing. The draft stays untouched. + sendNormalMessage( + text = failed.body.ifEmpty { text }, + subscriptionId = failed.subscriptionId.takeIf { it >= 0 } ?: sim.subscriptionId, + attachments = failed.attachment?.attachments.orEmpty(), + resendId = failedKey, + fromComposer = false, + ) { handedOff -> if (!handedOff) toast(R.string.message_not_sent_short) } + return + } + // The failed message is not loaded any more: fall back to putting its text into the composer. + resend.prepare(failedKey, text) + vm.text.setTextAndPlaceCursorAtEnd(text) + } + + private fun openSenderContact(message: Message) { + val number = message.getSender()?.phoneNumbers?.firstOrNull()?.normalizedNumber ?: return + getContactFromAddress(number) { + if (it != null) { + startContactDetailsIntent(it) + } + } + } + + private fun deleteMessages( + messagesToRemove: List, + toRecycleBin: Boolean, + fromRecycleBin: Boolean, + ) { + repository.remove(messagesToRemove) + val latestThreadItems = getThreadItems() + val hasMessages = messages.isNotEmpty() + + runOnUiThread { + messagesToRemove.forEach { message -> + message.attachment?.attachments?.forEach { AudioPlayerManager.release(it.getUri()) } + } + if (!hasMessages) { + finish() + } else { + publishItems(latestThreadItems) + vm.clearSelection() + } + } + + // Only scheduled messages left: they move to a temporary thread until one is sent. + val movedToTemporaryThread = removeThreadMessages( + messagesToRemove, toRecycleBin, fromRecycleBin, threadId, messages.toSortedMessages(), conversation, scheduleController, + )?.also { threadId = it } != null + // Messages that went to the recycle bin can come straight back (scheduled ones were cancelled, not recycled). + val recycled = messagesToRemove.filterNot { it.isScheduled } + val undoable = toRecycleBin && !movedToTemporaryThread + if (undoable && hasMessages && recycled.isNotEmpty()) offerUndoDelete(recycled) + } + + /** A snackbar after messages went to the recycle bin: Undo puts them back. */ + private fun offerUndoDelete(recycled: List) { + runOnUiThread { + lifecycleScope.launch { + val result = vm.snackbar.showSnackbar( + message = getString(R.string.thread_messages_deleted), + actionLabel = getString(R.string.thread_messages_deleted_undo), + duration = androidx.compose.material3.SnackbarDuration.Long, + ) + if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) undoDelete(recycled) + } + } + } + + /** Takes [restored] out of the recycle bin again and shows them in the chat. */ + private fun undoDelete(restored: List) { + val thread = threadId + ensureBackgroundThread { + restored.forEach { restoreMessageFromRecycleBin(it.id, it.isMMS) } + updateLastConversationMessage(thread) + repository.addAll(restored) + val latestThreadItems = getThreadItems() + runOnUiThread { publishItems(latestThreadItems) } + refreshConversations() + } + } + + /** The message a search result opened this chat at, read once from the intent and then cleared. */ + private fun takeSearchedMessage(): MessageKey? { + val id = intent.getLongExtra(SEARCHED_MESSAGE_ID, -1L) + val isMMS = intent.getBooleanExtra(SEARCHED_MESSAGE_IS_MMS, false) + intent.removeExtra(SEARCHED_MESSAGE_ID) + intent.removeExtra(SEARCHED_MESSAGE_IS_MMS) + return if (id == -1L) null else MessageKey(id, isMMS) + } + + /** Scrolls to [target], paging in older history until it is loaded. Matched by id and type (MessageKey). */ + private fun jumpToMessage(target: MessageKey) { + if (messages.any { it.key == target }) { + vm.scrollToMessage(target, flash = true) + return + } + + ensureBackgroundThread { + if (repository.loadingOlder) return@ensureBackgroundThread + repository.loadingOlder = true + isJumpingToMessage = true + + var cutoff = repository.oldestDate() ?: Int.MAX_VALUE + var found = false + var loops = 0 + + // not the best solution, but this will do for now. + runCatching { + while (!found && !repository.allFetched) { + if (repository.fetchOlder(threadId, cutoff).isEmpty() || loops >= 1000) break + val messageSnapshot = messages.toSortedMessages() + cutoff = messageSnapshot.first().date + found = messageSnapshot.any { it.key == target } + loops++ + } + } + + val latestThreadItems = getThreadItems() + runOnUiThread { + publishItems(latestThreadItems) + repository.loadingOlder = false + vm.scrollToMessage(target, flash = true) + isJumpingToMessage = false + } + } + } + + private fun loadMoreMessages() { + val cutoff = repository.oldestDate() ?: return + if (repository.allFetched || repository.loadingOlder) return + repository.loadingOlder = true + val thread = threadId + ensureBackgroundThread { + // A failure must not leave loadingOlder set: that stopped paging until the chat was reopened. + val loaded = runCatching { repository.fetchOlder(thread, cutoff) }.isSuccess + val latestThreadItems = if (loaded) getThreadItems() else null + runOnUiThread { + latestThreadItems?.let { publishItems(it) } + repository.loadingOlder = false + } + } + } + + 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() + } + } + } else { + finish() + } + } + } + + private fun setupConversation() { + ensureBackgroundThread { + conversation = conversationsDB.getConversationWithThreadId(threadId) + // The menu may have been built before the conversation was read (no "Conversation details" then). + runOnUiThread { refreshMenuItems() } + } + } + + private fun setupComposer(isFreshLaunch: Boolean) { + vm.showCounter = config.showCharacterCounter + vm.sendOnEnter = config.sendOnEnter + vm.voiceButton = composerPrefs.voiceButton + + if (!composerListening) { + composerListening = true + lifecycleScope.launch { + snapshotFlow { vm.text.text.toString() }.collect { onMessageTextChanged(it) } + } + } + + // The view model keeps text and attachments across recreation, so the intent only seeds a fresh launch. + if (isFreshLaunch) { + intent.getStringExtra(THREAD_TEXT)?.let { vm.text.setTextAndPlaceCursorAtEnd(it) } + addAttachmentsFromIntent() + } + } + + private fun addAttachmentsFromIntent() { + if (intent.extras?.containsKey(THREAD_ATTACHMENT_URI) == true) { + val uri = intent.getStringExtra(THREAD_ATTACHMENT_URI)?.toUri() + if (uri != null && IncomingShareGuard.isAllowed(uri, packageName)) attachmentController.add(uri) + } else if (intent.extras?.containsKey(THREAD_ATTACHMENT_URIS) == true) { + @Suppress("DEPRECATION", "UNCHECKED_CAST") + (intent.getSerializableExtra(THREAD_ATTACHMENT_URIS) as? ArrayList)?.forEach { + if (IncomingShareGuard.isAllowed(it, packageName)) attachmentController.add(it) + } + } + } + + private fun onMessageTextChanged(text: String) { + resend.onTextChanged(text) + + updateMessageType() + val signed = withSignature(text) + val messageString = if (config.useSimpleCharacters) signed.normalizeString() else signed + val segments = if (messageString.isEmpty()) null else SmsSegments.of(messageString) + vm.segments = segments + noteLongTextAsMmsOnce(messageString) + } + + /** Says once that a long text goes as MMS; it does not block the send. */ + private fun noteLongTextAsMmsOnce(messageString: String) { + // RM-46: a long text turning into MMS used to happen without a word; say so once. + if (!vm.longMmsNoted && vm.attachments.isEmpty() && messageString.isNotBlank() && isLongMmsMessage(messageString)) { + vm.longMmsNoted = true + lifecycleScope.launch { vm.snackbar.showSnackbar(getString(R.string.thread_long_text_as_mms)) } + } + } + + private fun hasOnlyScheduledMessages(): Boolean = repository.hasOnlyScheduled() + + private fun getProviderThreadParticipants(): ThreadRecipients? { + if (isRecycleBin || threadId <= 0L || hasOnlyScheduledMessages()) { + return null + } + + return getThreadParticipants(threadId, null).takeIf { it.isNotEmpty() }?.let { ThreadRecipients(it) } + } + + private fun reconcileProviderParticipants(): Boolean { + val providerParticipants = getProviderThreadParticipants() ?: return false + val participantsChanged = !recipients.sameAddressesAs(providerParticipants) + recipients = providerParticipants + + if (participantsChanged) { + runOnUiThread { + maybeDisableShortCodeReply() + } + } + + return participantsChanged + } + + private fun setupParticipants() { + if (recipients.isEmpty()) { + recipients = if (messages.isEmpty()) { + val intentNumbers = getPhoneNumbersFromIntent() + ThreadRecipients(ThreadRecipients.withIntentNumbers(getThreadParticipants(threadId, null), intentNumbers)) + } else { + getProviderThreadParticipants() ?: ThreadRecipients(messages.first().participants) + } + runOnUiThread { + maybeDisableShortCodeReply() + } + } + } + + private fun isSpecialNumber(): Boolean = recipients.hasShortCodeWithLetters + + /** Codes and service messages: no sounds for them. */ + private fun isCodeSender(): Boolean = isSpecialNumber() || recipients.addresses.any { isNumericShortCode(it) } + + private fun maybeDisableShortCodeReply() { + if (isSpecialNumber() && !isRecycleBin) { + currentFocus?.clearFocus() + hideKeyboard() + vm.text.clearText() + vm.replyDisabled = true + } + } + + private fun setupThreadTitle() { + val title = conversation?.title + vm.title = if (!title.isNullOrEmpty()) { + title + } else { + recipients.toArrayList().getThreadTitle() + } + // The people may have changed: a group shows how its messages go out. + updateMessageType() + // Same avatar as the conversation list: the conversation's photo, else the contact's, else initials or icon. + vm.avatarPhotoUri = if (recipients.size == 1) { + conversation?.photoUri?.takeIf { it.isNotEmpty() } ?: recipients.contacts.first().photoUri + } else { + "" + } + updateSubtitle() + } + + /** Second line of the top bar: the number, or the group size. The SIM lives in the message field instead. */ + private fun updateSubtitle() { + val parts = ArrayList() + if (recipients.size == 1) { + val number = recipients.contacts.first().phoneNumbers.firstOrNull()?.normalizedNumber + if (!number.isNullOrEmpty() && number != vm.title) parts.add(number) + } else if (recipients.isGroup) { + parts.add(resources.getQuantityString(R.plurals.thread_people, recipients.size, recipients.size)) + } + vm.subtitle = parts.takeIf { it.isNotEmpty() }?.joinToString(getString(R.string.ui_separator)) + } + + private fun setupSIMSelector() { + if (sim.load(recipients, messages.lastOrNull())) updateSubtitle() + } + + private fun selectSim(index: Int) { + if (sim.select(index, recipients)) updateSubtitle() + } + + @SuppressLint("MissingPermission") + private fun getThreadItems(): List { + if (isFinishing) { + return emptyList() + } + + val simLabels = lookups.sims { + simHeaderLabels(subscriptionManagerCompat().activeSubscriptionInfoList, 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. + if (providerLoaded && !vm.unreadResolved) { + vm.firstUnreadId = if (isRecycleBin) null else firstUnreadMessageId(messages) + vm.unreadResolved = true + } + val result = buildThreadItems( + messages, simLabels, seen = isSeenByUser(), deliveryReportsOn = config.enableDeliveryReports, + firstUnreadId = vm.firstUnreadId, showTapbacks = w3cPrefs.showTapbacks, + undownloadedMms = undownloadedMms(messages), + ) + latestReactions = result.reactions + if (!isCodeSender()) { + chatSounds.received(result.newlyRead.map { ChatArrival(it.id, it.isMMS, it.date * 1000L) }) + } + if (result.newlyRead.isNotEmpty()) { + result.newlyRead.forEach { markMessageRead(it.id, it.isMMS) } + conversationsDB.markRead(threadId) + bus?.post(Events.RefreshConversations()) + } + return result.items + } + + private fun launchForResult( + launcher: ActivityResultLauncher, + input: I, + @StringRes error: Int = org.fossify.commons.R.string.no_app_found, + ) { + hideKeyboard() + try { + // The picker or camera the user opened here is not leaving the app: coming back does not lock it again. + appLockManager.allowOwnTrip() + launcher.launch(input) + } catch (e: ActivityNotFoundException) { + showErrorToast(getString(error)) + } catch (e: Exception) { + showErrorToast(e) + } + } + + private fun handleAttach(kind: AttachKind) { + when (kind) { + AttachKind.Photo -> launchForResult(pickMedia, PickVisualMediaRequest(PickVisualMedia.ImageAndVideo)) + AttachKind.Camera -> askCameraKind() + AttachKind.TakePhoto -> launchCapturePhotoIntent() + AttachKind.RecordVideo -> launchCaptureVideoIntent() + AttachKind.RecordAudio -> launchCaptureAudioIntent() + AttachKind.File -> launchForResult(pickDocument, "*/*") + AttachKind.Contact -> launchForResult(pickContact, null) + AttachKind.Location -> location.start() + AttachKind.SavedText -> vm.showSavedTexts = true + AttachKind.Schedule -> + scheduleUi.pickTime(vm.scheduledMillis) + } + } + + /** TH-22: the one Camera entry of the attach sheet asks whether to take a photo or record a video. */ + private fun askCameraKind() { + showChoiceDialog( + items = listOf( + ChoiceItem(getString(R.string.thread_attach_take_photo), AttachKind.TakePhoto), + ChoiceItem(getString(R.string.thread_attach_record_video), AttachKind.RecordVideo), + ), + title = getString(R.string.thread_review_attach_camera), + ) { handleAttach(it) } + } + + private fun launchCapturePhotoIntent() { + val uri = attachmentController.newCaptureUri() + // Kept in saved state: the camera often outlives this process on low-memory phones. + vm.capturedImageUri = uri + launchForResult(takePicture, uri) + } + + private fun launchCaptureVideoIntent() { + launchForResult(recordMedia, Intent(MediaStore.ACTION_VIDEO_CAPTURE)) + } + + /** The link goes in at the cursor, on its own line; the user reads it and presses Send. */ + private fun insertLocationLink(link: String) { + val before = vm.text.text.subSequence(0, vm.text.selection.min) + vm.insertAtCursor(LocationSharer.placedAfter(before, link)) + } + + private fun launchCaptureAudioIntent() { + launchForResult(recordMedia, Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION)) + } + + /** Send: asks for the SIM and the group MMS choice when needed (each once, TU-03), then sends or schedules. */ + private fun sendMessage() { + // Blank text, or a photo still being shrunk, cannot be sent (TU-04, TU-05). + if (!vm.canSend) return + SendSteps( + needsSim = { sim.mustAsk() }, + askSim = { onChosen -> + showChoiceDialog( + items = sim.choices.mapIndexed { index, card -> ChoiceItem(card.label, index) }, + title = getString(R.string.thread_change_sim), + selected = sim.selectedIndex, + ) { index -> + selectSim(index) + onChosen() + } + }, + needsGroupChoice = ::needsGroupMessageChoice, + askGroupChoice = ::askGroupMessageChoice, + send = ::sendComposedMessage, + ).run() + } + + private fun sendComposedMessage() { + // The composer may have changed while a question was open. + if (!vm.canSend) return + var text = withSignature(vm.text.text.toString().trim()) + vm.firstUnreadId = null + vm.scrollToBottom() + + text = removeDiacriticsIfNeeded(text) + + val subscriptionId = sim.subscriptionId + + if (vm.isScheduling) { + sendScheduledMessage(text, subscriptionId) + } else { + sendNormalMessage(text, subscriptionId) + } + } + + private fun needsGroupMessageChoice(): Boolean = + !config.isGroupMessageMmsPreferenceResolved && recipients.distinctAddresses.size >= 2 + + private fun askGroupMessageChoice(onChosen: () -> Unit) { + if (isGroupMessageConfirmationVisible) return + isGroupMessageConfirmationVisible = true + GroupMessageSendDialog( + activity = this, + callback = { sendAsGroupMms -> + config.sendGroupMessageMMS = sendAsGroupMms + updateMessageType() + onChosen() + }, + onDismiss = { isGroupMessageConfirmationVisible = false } + ) + } + + private fun sendScheduledMessage(text: String, subscriptionId: Int) { + val scheduledMillis = vm.scheduledMillis ?: return + if (!isSchedulableTime(scheduledMillis, System.currentTimeMillis())) { + toast(R.string.must_pick_time_in_the_future) + scheduleUi.pickTime(scheduledMillis) + return + } + + refreshedSinceSent = false + val messageId = vm.scheduledMessageId ?: generateRandomId() + val repeat = RepeatRule.fromName(vm.scheduledRepeat) + // Built here on the main thread: it reads the composer's attachments. + val pickedMessage = buildScheduledMessage( + text = text, + recipients = recipients, + subscriptionId = subscriptionId, + messageId = messageId, + millis = scheduledMillis, + threadId = threadId, + threadHasMessages = messages.isNotEmpty(), + isMms = isMmsMessage(text), + attachments = attachmentController.asMessageAttachments(messageId), + ) + ensureBackgroundThread { + try { + // A thread without messages gets a temporary thread until a real message is sent. + val startsTemporaryThread = messages.isEmpty() + val message = scheduleController.save(pickedMessage, startsTemporaryThread, conversation, repeat) + if (startsTemporaryThread) threadId = message.threadId + insertOrUpdateMessage(message) + + runOnUiThread { + clearCurrentMessage() + vm.clearSchedule() + } + } catch (e: Exception) { + // The composer keeps the text, attachments and time so the user can try again. + showErrorToast( + e.localizedMessage ?: getString(org.fossify.commons.R.string.unknown_error_occurred) + ) + } + } + } + + /** + * Sends [text] with [attachments] now, on a worker thread: the provider writes, the thread lookups of a group and + * an MMS attachment's bytes never run on the main thread (MS5). The composer is cleared only when [fromComposer] + * and the message was handed to the system: after a failure the user's text and photos stay so they can try + * again. While a send from the composer runs, a second tap on Send does nothing. [onDone] gets whether the message + * was handed off, on the worker thread. + */ + private fun sendNormalMessage( + text: String, + subscriptionId: Int, + attachments: List = attachmentController.asMessageAttachments(), + resendId: MessageKey? = resend.target, + fromComposer: Boolean = true, + onPartial: (SendOutcome) -> Unit = {}, + onDone: (Boolean) -> Unit = {}, + ) { + if (fromComposer && !composerSend.tryStart()) return + refreshedSinceSent = false + var outgoing = OutgoingMessage(text, recipients.addresses, subscriptionId, attachments, resendId) + if (fromComposer) { + // MS6: each photo goes out as its own MMS. One that was queued leaves the composer at once, so when a + // later one fails and the user taps Send again, only what did not go out is sent, not every photo twice. + outgoing = outgoing.copy(onAttachmentHandedOff = { sent -> + runOnUiThread { vm.removeAttachment(sent.uriString) } + }) + } + val composerAtSend = vm.text.text.toString() + ensureBackgroundThread { + try { + onDone(sendOutgoing(outgoing, fromComposer, composerAtSend, onPartial)) + } finally { + if (fromComposer) composerSend.finish() + } + } + } + + /** The blocking part of [sendNormalMessage]; runs on a worker thread. True when the message was handed off. */ + private fun sendOutgoing( + outgoing: OutgoingMessage, + fromComposer: Boolean, + composerAtSend: String, + onPartial: (SendOutcome) -> Unit = {}, + ): Boolean { + val result = sendController.send(outgoing, fromComposer) + result.partial?.let { partial -> + handlePartialSend(partial, fromComposer, composerAtSend) + onPartial(partial) + } + if (result.completed) { + // A failed send that left a row in the provider still shows up below, with its Retry button. + val thread = threadId + repository.newProviderRows(thread, limit = maxOf(1, outgoing.attachments.size)) + .forEach { insertOrUpdateMessage(it) } + } + runOnUiThread { + // Not when the user already typed something else meanwhile. + if (result.clearComposer && vm.text.text.toString() == composerAtSend) clearCurrentMessage() + if (fromComposer && result.handedOff) chatSounds.sent() + } + return result.handedOff + } + + /** Some pictures went out and some did not: say so, and make sure another try sends only the rest. */ + private fun handlePartialSend(partial: SendOutcome, fromComposer: Boolean, composerAtSend: String) { + toast(R.string.message_partly_sent, android.widget.Toast.LENGTH_LONG) + if (!fromComposer) return + runOnUiThread { + attachmentController.keepOnly(partial.remainingAttachments) + // The text went with the last picture; not when the user already typed something else meanwhile. + if (partial.textSent && vm.text.text.toString() == composerAtSend) vm.text.clearText() + resend.clear() + updateMessageType() + } + } + + private fun clearCurrentMessage() { + vm.text.clearText() + attachmentController.clear() + updateMessageType() + } + + private fun insertOrUpdateMessage(message: Message) { + repository.upsert(message) + + val newItems = getThreadItems() + runOnUiThread { + publishItems(newItems) + vm.scrollToBottom() + if (!refreshedSinceSent) { + refreshMessages() + } + } + messagesDB.insertOrUpdate(message) + if (shouldUnarchive()) { + updateConversationArchivedStatus(message.threadId, false) + refreshConversations() + } + } + + /** The numbers the intent opened this chat for: one, or several for a group. */ + private fun getPhoneNumbersFromIntent(): List = ThreadRecipients.numbersFromExtra(intent.getStringExtra(THREAD_NUMBER)) + + private fun saveMMS(attachments: List) { + vm.attachmentsToSave = attachments + if (attachments.size == 1) { + val attachment = attachments.first() + Intent(Intent.ACTION_CREATE_DOCUMENT).apply { + type = attachment.mimetype + addCategory(Intent.CATEGORY_OPENABLE) + // The part's file name ("IMG_2041.jpg"), not the last piece of its content uri ("1234"). + putExtra(Intent.EXTRA_TITLE, saveFileName(attachment)) + launchForResult(saveAttachmentsTarget, this, error = org.fossify.commons.R.string.system_service_disabled) + } + } else { + Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply { + addCategory(Intent.CATEGORY_DEFAULT) + launchForResult(saveAttachmentsTarget, this, error = org.fossify.commons.R.string.system_service_disabled) + } + } + } + + @Subscribe(threadMode = ThreadMode.ASYNC) + fun refreshMessages(@Suppress("unused") event: Events.RefreshMessages) { + if (isRecycleBin) { + return + } + + refreshedSinceSent = true + repository.allFetched = false + + // The notification stays while the chat is open but not seen (TU-11). + if (isSeenByUser()) { + notificationManager.cancel(threadId.hashCode()) + } + + // Still loading: no recipients yet, so there is nothing to look up (an empty list would blank the thread, B13). + if (recipients.isEmpty()) return + + val messageSnapshot = messages.toSortedMessages() + val lastMaxId = messageSnapshot.filterNot { it.isScheduled }.maxByOrNull { it.id }?.id ?: 0L + val providerParticipantsChanged = reconcileProviderParticipants() + // The provider is asked for the thread only while this chat has none of its own yet (scheduled messages in a + // temporary thread, or no messages): asking every time created an empty provider thread (B13). + val newThreadId = providerThreadIdFor(messageSnapshot) + val newMessages = repository.newestFromProvider(newThreadId) + if (messageSnapshot.isNotEmpty() && messageSnapshot.all { it.isScheduled } && newMessages.isNotEmpty()) { + // update scheduled messages with real thread id + threadId = newThreadId + updateScheduledMessagesThreadId( + messages = messageSnapshot.filter { it.threadId != threadId }, + newThreadId = threadId + ) + } + + // A full page means older messages exist; the ones already paged in are kept (see mergeRefreshedMessages). + repository.refresh(threadId, newMessages) + + messages.filter { !it.isScheduled && !it.isReceivedMessage() && it.id > lastMaxId } + .forEach { latestMessage -> + messagesDB.insertOrIgnore(latestMessage) + } + + // A new conversation (a group just started here) is saved with its first text; the menu needs it. + if (conversation == null) conversation = conversationsDB.getConversationWithThreadId(threadId) + setupAdapter() + runOnUiThread { + if (providerParticipantsChanged) { + setupThreadTitle() + } + setupSIMSelector() + } + } + + private fun providerThreadIdFor(messageSnapshot: List): Long = + if (threadId > 0L && messageSnapshot.any { !it.isScheduled }) { + threadId + } else { + getThreadId(recipients.addresses.toSet()) + } + + /** I60: the signature goes under what is typed, but not under a failed message that is being sent again. */ + private fun withSignature(text: String): String = + if (resend.target != null) text else MessageSignature.applyTo(text, composerPrefs.signature) + + private fun isMmsMessage(text: String): Boolean = sendsAsMms( + hasAttachments = vm.attachments.isNotEmpty(), + recipientCount = recipients.size, + sendGroupAsMms = config.sendGroupMessageMMS, + isLongText = isLongMmsMessage(text), + ) + + private fun updateMessageType() { + vm.isMms = isMmsMessage(withSignature(vm.text.text.toString())) + vm.groupSendMode = if (recipients.distinctAddresses.size >= 2 && config.isGroupMessageMmsPreferenceResolved) { + config.sendGroupMessageMMS + } else { + null + } + } + + /** + * "Send now" on a scheduled bubble: sends that message as it is, straight from its own text and attachments. + * It used to go through the composer, which threw away whatever the user was typing. The scheduled copy is + * removed only once the message was handed off. + */ + private fun sendScheduledMessageNow(message: Message) { + val outgoing = OutgoingMessage( + text = message.body, + addresses = recipients.addresses, + subscriptionId = message.subscriptionId, + attachments = message.attachment?.attachments.orEmpty(), + resendOf = null, + onAttachmentHandedOff = scheduledAttachmentTracker(message), + ) + refreshedSinceSent = false + ensureBackgroundThread { + // F3: the alarm may be sending this very message; whoever claims it first sends it, the other does nothing. + if (!ScheduledSendClaims.claim(this, message.id, allowHeld = true)) return@ensureBackgroundThread + try { + val sent = sendOutgoing(outgoing, fromComposer = false, composerAtSend = "") { partial -> + keepUnsentOfScheduled(message, partial) + } + if (sent) { + runOnUiThread { cancelScheduledMessageAndRefresh(message.id) } + } else { + // Not sent: held again, so Retry stays and no alarm sends it by itself. + runCatching { messagesDB.updateScheduledType(message.id, Telephony.Sms.MESSAGE_TYPE_FAILED) } + } + } finally { + ScheduledSendClaims.release(message.id) + } + } + } + + /** + * A scheduled message that went out in part stays held, but with only what was not sent (and no text when that + * went), so the next Retry does not send the same pictures again. + */ + private fun keepUnsentOfScheduled(message: Message, partial: SendOutcome) { + // Runs on the send's worker thread, before the caller holds the row; + // stays held (failed) so no alarm resends it. + val unsent = message.withUnsentOnly(partial).copy(type = Telephony.Sms.MESSAGE_TYPE_FAILED) + runCatching { messagesDB.insertOrUpdate(unsent) } + refreshMessages() + } + + /** + * [keepAttachmentFiles] when the composer still shows the message's attachments (the user left schedule mode + * while editing it); those private copies are then deleted on the next app start. + */ + private fun cancelScheduledMessageAndRefresh(messageId: Long, keepAttachmentFiles: Boolean = false) { + messages.firstOrNull { it.id == messageId && it.isScheduled }?.attachment?.attachments?.forEach { + AudioPlayerManager.release(it.getUri()) + } + ensureBackgroundThread { + scheduleController.cancel(messageId, keepAttachmentFiles) + refreshMessages() + } + } + + companion object { + /** 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/backup/SettingsBackup.kt b/app/src/main/kotlin/com/glooboo/umessage/backup/SettingsBackup.kt index 97281452..23c341af 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/backup/SettingsBackup.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/backup/SettingsBackup.kt @@ -13,6 +13,7 @@ import com.glooboo.umessage.helpers.W3aPrefs import com.glooboo.umessage.helpers.W3cPrefs import com.glooboo.umessage.spam.ForwardingAvailability import com.glooboo.umessage.spam.ListKind +import com.glooboo.umessage.spam.SpamRule import com.glooboo.umessage.spam.SpamSettings import com.glooboo.umessage.spam.UMessage import com.glooboo.umessage.spam.engine.SpamEngine @@ -62,9 +63,13 @@ object SettingsBackup { val content: BackupContent, val forwards: ForwardImport, val changedSettings: List, + /** The rules of the file that are not on the phone yet; the summary counts these. */ + val newRules: List = content.rules, + /** Rules of the file already on the phone (or repeated in the file). */ + val rulesPresent: Int = 0, ) { - val allowRules: Int get() = content.rules.count { it.kind == ListKind.ALLOW } - val blockRules: Int get() = content.rules.size - allowRules + val allowRules: Int get() = newRules.count { it.kind == ListKind.ALLOW } + val blockRules: Int get() = newRules.size - allowRules } /** @@ -129,7 +134,8 @@ object SettingsBackup { ) val current = collectSettings(app, repo.settings.first()) val changed = SettingsBackupFormat.changedSettings(current, content.settings) - Preview(content, forwards, changed) to null + val (fresh, present) = SettingsBackupFormat.newRules(content.rules, repo.rules.first()) + Preview(content, forwards, changed, fresh, present) to null } catch (_: IOException) { null to Failure.UNREADABLE } catch (_: SQLException) { 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 46207fb9..8692de46 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/backup/SettingsBackupFormat.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/backup/SettingsBackupFormat.kt @@ -196,6 +196,9 @@ data class BackupContent( val settings: BackupSettings, /** Version of the app that wrote the file; information only, never applied. Null in files from before N09. */ val appVersion: String? = null, + /** 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, ) /** @@ -252,16 +255,38 @@ object SettingsBackupFormat { val isBackup = root != null && root.str("app") == APP && root.str("kind") == KIND && (root.int("version") ?: 0) >= 1 if (root == null || !isBackup) throw BackupFormatException("Not a uMessage settings backup") + val rules = root.array("rules").orEmpty().mapNotNull(BackupJson::readRule) + val forwards = root.array("forwardRules").orEmpty().mapNotNull(BackupJson::readForward) return BackupContent( - rules = root.array("rules").orEmpty().asSequence().mapNotNull(BackupJson::readRule) - .take(MAX_RULES).toList(), - forwardRules = root.array("forwardRules").orEmpty().asSequence().mapNotNull(BackupJson::readForward) - .take(MAX_FORWARD_RULES).toList(), + rules = rules.take(MAX_RULES), + forwardRules = forwards.take(MAX_FORWARD_RULES), settings = BackupSettingsJson.readSettings(root["settings"] as? JsonObject), appVersion = root.str("appVersion")?.take(MAX_VERSION), + droppedRules = (rules.size - MAX_RULES).coerceAtLeast(0), + droppedForwardRules = (forwards.size - MAX_FORWARD_RULES).coerceAtLeast(0), ) } + /** + * 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 + * prefixes without case). Also counts a rule repeated inside the file once. + */ + fun newRules(incoming: List, existing: List): Pair, Int> { + val known = existing.map(::ruleKey).toMutableSet() + val fresh = incoming.filter { known.add(ruleKey(it)) } + return fresh to incoming.size - fresh.size + } + + private fun ruleKey(rule: SpamRule): String { + val pattern = when (rule.type) { + RuleType.NUMBER -> ForwardTargets.key(rule.pattern).ifEmpty { rule.pattern.trim() } + RuleType.SENDER_ID, RuleType.PREFIX -> rule.pattern.trim().lowercase() + else -> rule.pattern.trim() + } + return "${rule.kind.name}|${rule.type.name}|$pattern" + } + /** * Two forward rules with the same conditions (time window and codes included), sending SIM and targets are the * same rule, so importing twice adds nothing (L3). Targets compare by their last digits: 0555… matches +1555…. diff --git a/app/src/main/kotlin/com/glooboo/umessage/dialogs/AppLockDialog.kt b/app/src/main/kotlin/com/glooboo/umessage/dialogs/AppLockDialog.kt index f46ffb20..426b66d4 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/dialogs/AppLockDialog.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/dialogs/AppLockDialog.kt @@ -338,7 +338,11 @@ private fun PinTab(requiredHash: String, onSuccess: (hash: String) -> Unit) { ) if (requiredHash.isEmpty() && !repeating) { Text( - stringResource(R.string.dialogs_lock_pin_suggestion, AppLockLogic.SUGGESTED_PIN_LENGTH), + stringResource( + R.string.lock_pin_length_hint, AppLockLogic.MIN_PIN_LENGTH, AppLockLogic.MAX_PIN_LENGTH + ) + + "\n" + + stringResource(R.string.dialogs_lock_pin_suggestion, AppLockLogic.SUGGESTED_PIN_LENGTH), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center, diff --git a/app/src/main/kotlin/com/glooboo/umessage/dialogs/MessageDetailsDialog.kt b/app/src/main/kotlin/com/glooboo/umessage/dialogs/MessageDetailsDialog.kt index b63aa576..9149a7e2 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/dialogs/MessageDetailsDialog.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/dialogs/MessageDetailsDialog.kt @@ -111,7 +111,9 @@ class MessageDetailsDialog(val activity: BaseSimpleActivity, val message: Messag private fun buildProperties(): List { @SuppressLint("MissingPermission") - val availableSIMs = activity.subscriptionManagerCompat().activeSubscriptionInfoList.orEmpty() + val availableSIMs = runCatching { + activity.subscriptionManagerCompat().activeSubscriptionInfoList.orEmpty() + }.getOrDefault(emptyList()) return buildList { add(senderProperty()) if (availableSIMs.count() > 1) { @@ -197,7 +199,9 @@ class MessageDetailsDialog(val activity: BaseSimpleActivity, val message: Messag formatContactInfo(senderName, senderPhoneNumber) { displayNumber(activity, it) } } else { participants.joinToString(listSeparator(activity.uiLocale)) { - formatContactInfo(it.name, it.phoneNumbers.first().value) { number -> displayNumber(activity, number) } + formatContactInfo(it.name, it.phoneNumbers.firstOrNull()?.value ?: it.name) { number -> + displayNumber(activity, number) + } } } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/export/ConversationExportFactory.kt b/app/src/main/kotlin/com/glooboo/umessage/export/ConversationExportFactory.kt index 7e1d9b25..6041bd33 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/export/ConversationExportFactory.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/export/ConversationExportFactory.kt @@ -1,93 +1,93 @@ -package com.glooboo.umessage.export - -import android.content.Context -import android.text.format.DateFormat -import com.glooboo.umessage.R -import com.glooboo.umessage.helpers.DateStyle -import com.glooboo.umessage.helpers.MessageNoteKey -import com.glooboo.umessage.helpers.w3cPrefs -import com.glooboo.umessage.models.Message -import com.glooboo.umessage.models.MessageNote -import com.glooboo.umessage.ui.thread.MessageNoteLines -import com.glooboo.umessage.ui.thread.fullDateLabel -import com.glooboo.umessage.ui.thread.messageDetailsTime -import java.time.Instant -import java.time.ZoneId -import java.util.Locale - -/** The title and the lines under it that open an export, in the user's language. */ -class ExportHeader(val title: String, val lines: List) - -/** - * Builds exports with the app's words and the user's date style. Dates are written in both calendars as soon as the - * date style is not plain Gregorian, so a reader of the file never has to convert one into the other. - */ -class ConversationExportFactory(private val context: Context, private val zone: ZoneId = ZoneId.systemDefault()) { - private val locale: Locale = context.resources.configuration.locales[0] ?: Locale.getDefault() - private val jalali = context.w3cPrefs.dateStyle != DateStyle.GREGORIAN - private val use24Hour = DateFormat.is24HourFormat(context) - - fun builder() = ConversationExportBuilder(labels(), ::timeOf, ::rangeOf) - - fun timeText(epochMillis: Long): String = - messageDetailsTime(epochMillis, zone, use24Hour, locale, jalali = jalali, both = jalali) - - private fun timeOf(message: Message) = timeText(message.millis()) - - private fun rangeOf(first: Message, last: Message): String { - fun day(message: Message) = fullDateLabel( - Instant.ofEpochMilli(message.millis()).atZone(zone).toLocalDate(), locale, jalali = jalali, both = jalali, - ) - val from = day(first) - val to = day(last) - return if (from == to) from else context.getString(R.string.share_text_range, from, to) - } - - private fun labels() = ExportLabels( - me = context.getString(R.string.me), - attachmentTag = context.getString(R.string.export_conv_attachment_label), - status = ExportStatusLabels( - received = context.getString(R.string.export_status_received), - sent = context.getString(R.string.export_status_sent), - delivered = context.getString(R.string.export_status_delivered), - failed = context.getString(R.string.export_status_failed), - sending = context.getString(R.string.export_status_sending), - draft = context.getString(R.string.export_status_draft), - ), - unnamedAttachment = context.getString(R.string.export_pdf_attachment_unnamed), - attachmentLine = { name, type -> context.getString(R.string.export_pdf_attachment, name, type) }, - ) - - /** [firstMillis] and [lastMillis] are the first and last message times: the zone line lists their offsets. */ - fun header( - export: ConversationExport, exportedAtMillis: Long, firstMillis: Long = exportedAtMillis, - lastMillis: Long = exportedAtMillis, - ): ExportHeader { - val lines = buildList { - add(context.getString(R.string.export_pdf_with, export.title)) - if (export.numbers.isNotEmpty() && export.numbers != listOf(export.title)) { - add(context.getString(R.string.export_pdf_numbers, export.numbers.joinToString(", "))) - } - export.rangeText?.let { add(context.getString(R.string.export_pdf_range, it)) } - add(context.resources.getQuantityString(R.plurals.export_pdf_count, export.count, export.count)) - add(context.getString(R.string.export_pdf_zone, zoneText(firstMillis, lastMillis))) - add(exportedLine(exportedAtMillis)) - } - return ExportHeader(context.getString(R.string.export_pdf_title), lines) - } - - fun exportedLine(exportedAtMillis: Long): String = - context.getString(R.string.export_pdf_exported, timeText(exportedAtMillis)) - - fun hashLine(export: ConversationExport): String = context.getString(R.string.export_pdf_hash, export.sha256) - - fun notCertifiedLine(): String = context.getString(R.string.export_pdf_not_certified) - - /** "Europe/London (UTC+00:00)", with every offset the messages between the two times can carry (D14). */ - private fun zoneText(firstMillis: Long, lastMillis: Long): String = - "${zone.id} (${ZoneOffsets.text(ZoneOffsets.between(zone, firstMillis, lastMillis))})" -} - -/** The notes of a chat (by note key, see MessageNotes.notesForThread) as the lines under the messages. */ -fun noteLines(context: Context, notes: Map) = - MessageNoteLines(context.getString(R.string.note)) { notes[MessageNoteKey.of(it)]?.text } +package com.glooboo.umessage.export + +import android.content.Context +import android.text.format.DateFormat +import com.glooboo.umessage.R +import com.glooboo.umessage.helpers.DateStyle +import com.glooboo.umessage.helpers.MessageNoteKey +import com.glooboo.umessage.helpers.w3cPrefs +import com.glooboo.umessage.models.Message +import com.glooboo.umessage.models.MessageNote +import com.glooboo.umessage.ui.thread.MessageNoteLines +import com.glooboo.umessage.ui.thread.fullDateLabel +import com.glooboo.umessage.ui.thread.messageDetailsTime +import java.time.Instant +import java.time.ZoneId +import java.util.Locale + +/** The title and the lines under it that open an export, in the user's language. */ +class ExportHeader(val title: String, val lines: List) + +/** + * Builds exports with the app's words and the user's date style. Dates are written in both calendars as soon as the + * date style is not plain Gregorian, so a reader of the file never has to convert one into the other. + */ +class ConversationExportFactory(private val context: Context, private val zone: ZoneId = ZoneId.systemDefault()) { + private val locale: Locale = context.resources.configuration.locales[0] ?: Locale.getDefault() + private val jalali = context.w3cPrefs.dateStyle != DateStyle.GREGORIAN + private val use24Hour = DateFormat.is24HourFormat(context) + + fun builder() = ConversationExportBuilder(labels(), ::timeOf, ::rangeOf) + + fun timeText(epochMillis: Long): String = + messageDetailsTime(epochMillis, zone, use24Hour, locale, jalali = jalali, both = jalali) + + private fun timeOf(message: Message) = timeText(message.millis()) + + private fun rangeOf(first: Message, last: Message): String { + fun day(message: Message) = fullDateLabel( + Instant.ofEpochMilli(message.millis()).atZone(zone).toLocalDate(), locale, jalali = jalali, both = jalali, + ) + val from = day(first) + val to = day(last) + return if (from == to) from else context.getString(R.string.share_text_range, from, to) + } + + private fun labels() = ExportLabels( + me = context.getString(R.string.me), + attachmentTag = context.getString(R.string.export_conv_attachment_label), + status = ExportStatusLabels( + received = context.getString(R.string.export_status_received), + sent = context.getString(R.string.export_status_sent), + delivered = context.getString(R.string.export_status_delivered), + failed = context.getString(R.string.export_status_failed), + sending = context.getString(R.string.export_status_sending), + draft = context.getString(R.string.export_status_draft), + ), + unnamedAttachment = context.getString(R.string.export_pdf_attachment_unnamed), + attachmentLine = { name, type -> context.getString(R.string.export_pdf_attachment, name, type) }, + ) + + /** [firstMillis] and [lastMillis] are the first and last message times: the zone line lists their offsets. */ + fun header( + export: ConversationExport, exportedAtMillis: Long, firstMillis: Long = exportedAtMillis, + lastMillis: Long = exportedAtMillis, + ): ExportHeader { + val lines = buildList { + add(context.getString(R.string.export_pdf_with, export.title)) + if (export.numbers.isNotEmpty() && export.numbers != listOf(export.title)) { + add(context.getString(R.string.export_pdf_numbers, export.numbers.joinToString(", "))) + } + export.rangeText?.let { add(context.getString(R.string.export_pdf_range, it)) } + add(context.resources.getQuantityString(R.plurals.export_pdf_count, export.count, export.count)) + add(context.getString(R.string.export_pdf_zone, zoneText(firstMillis, lastMillis))) + add(exportedLine(exportedAtMillis)) + } + return ExportHeader(context.getString(R.string.export_pdf_title), lines) + } + + fun exportedLine(exportedAtMillis: Long): String = + context.getString(R.string.export_pdf_exported, timeText(exportedAtMillis)) + + fun hashLine(export: ConversationExport): String = context.getString(R.string.export_pdf_hash, export.sha256) + + fun notCertifiedLine(): String = context.getString(R.string.export_pdf_not_certified) + + /** "Europe/London (UTC+00:00)", with every offset the messages between the two times can carry (D14). */ + private fun zoneText(firstMillis: Long, lastMillis: Long): String = + "${zone.id} (${ZoneOffsets.text(ZoneOffsets.between(zone, firstMillis, lastMillis))})" +} + +/** The notes of a chat (by note key, see MessageNotes.notesForThread) as the lines under the messages. */ +fun noteLines(context: Context, notes: Map) = + MessageNoteLines(context.getString(R.string.note)) { notes[MessageNoteKey.of(it)]?.text } diff --git a/app/src/main/kotlin/com/glooboo/umessage/export/ConversationExportJob.kt b/app/src/main/kotlin/com/glooboo/umessage/export/ConversationExportJob.kt index 3ea6d5f4..95fad0a9 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/export/ConversationExportJob.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/export/ConversationExportJob.kt @@ -1,91 +1,99 @@ -package com.glooboo.umessage.export - -import android.content.Context -import com.glooboo.umessage.R -import com.glooboo.umessage.helpers.messageNotes -import com.glooboo.umessage.ui.thread.readWholeThread -import kotlinx.coroutines.runBlocking -import java.io.File -import java.time.ZoneId - -enum class ConversationFileFormat(val extension: String, val mimeType: String) { - PDF("pdf", "application/pdf"), - TEXT("txt", "text/plain"), -} - -/** - * Reads one conversation, builds the export and writes the file in the app cache, ready to be shared. Meant for a - * background thread. Files of earlier exports are deleted after a day, so old conversations do not pile up there. - */ -class ConversationExportJob(private val context: Context) { - - sealed interface Result { - class Done(val file: File, val export: ConversationExport, val mimeType: String) : Result - data object Empty : Result - data object Cancelled : Result - } - - fun run( - threadId: Long, - title: String, - numbers: List, - format: ConversationFileFormat, - range: ExportRange, - isCancelled: () -> Boolean, - ): Result { - val now = System.currentTimeMillis() - val factory = ConversationExportFactory(context) - val messages = range.filter(readWholeThread(context, threadId), now, ZoneId.systemDefault()) - val notes = runCatching { runBlocking { context.messageNotes.notesForThread(threadId) } } - .getOrDefault(emptyMap()) - val export = factory.builder().build(messages, title, numbers, noteLines(context, notes)) - if (export.count == 0) return Result.Empty - if (isCancelled()) return Result.Cancelled - val file = newFile(title, format, now) - val header = factory.header( - export, now, firstMillis = messages.minOfOrNull { it.millis() } ?: now, - lastMillis = messages.maxOfOrNull { it.millis() } ?: now, - ) - val finished = when (format) { - ConversationFileFormat.PDF -> file.outputStream().buffered().use { out -> - ConversationPdfWriter(context).write(export, pdfTexts(factory, export, header, now), out, isCancelled) - } - - ConversationFileFormat.TEXT -> { - val footer = listOf(factory.hashLine(export), factory.notCertifiedLine()) - file.writeText(ConversationTextWriter.render(export, listOf(header.title) + header.lines, footer)) - true - } - } - if (!finished) { - file.delete() - return Result.Cancelled - } - return Result.Done(file, export, format.mimeType) - } - - private fun pdfTexts( - factory: ConversationExportFactory, export: ConversationExport, header: ExportHeader, now: Long, - ) = PdfTexts( - header = header, - notCertified = factory.notCertifiedLine(), - verification = factory.hashLine(export) + " | " + factory.exportedLine(now), - page = { number, total -> context.getString(R.string.export_pdf_page, number, total) }, - from = { context.getString(R.string.export_pdf_from, it) }, - to = { context.getString(R.string.export_pdf_to, it) }, - ) - - private fun newFile(title: String, format: ConversationFileFormat, now: Long): File { - val dir = File(context.cacheDir, SHARED_DIR).apply { mkdirs() } - ExportFileName.deleteOld(dir, now, KEEP_MS) - return ExportFileName.unique(dir, title, format.extension, now) - } - - companion object { - /** The cache folder the FileProvider already shares (see provider_paths.xml). */ - const val SHARED_DIR = "shared_logs" - - /** Earlier export files are removed after this long, not at the next export (D15). */ - const val KEEP_MS = 24L * 60 * 60 * 1000 - } -} +package com.glooboo.umessage.export + +import android.content.Context +import com.glooboo.umessage.R +import com.glooboo.umessage.helpers.messageNotes +import com.glooboo.umessage.ui.thread.readWholeThread +import kotlinx.coroutines.runBlocking +import java.io.File +import java.time.ZoneId + +enum class ConversationFileFormat(val extension: String, val mimeType: String) { + PDF("pdf", "application/pdf"), + TEXT("txt", "text/plain"), +} + +private const val MAX_TITLE_CHARS = 30 + +/** [title] reduced to letters and digits joined by "-", at most 30 characters; empty when nothing is left. */ +internal fun exportFileTitle(title: String): String = + title.map { if (it.isLetterOrDigit()) it else ' ' }.joinToString("") + .trim().split(Regex("\\s+")).filter { it.isNotEmpty() }.joinToString("-") + .take(MAX_TITLE_CHARS).trim('-') + +/** + * Reads one conversation, builds the export and writes the file in the app cache, ready to be shared. Meant for a + * background thread. Files of earlier exports are deleted after a day, so old conversations do not pile up there. + */ +class ConversationExportJob(private val context: Context) { + + sealed interface Result { + class Done(val file: File, val export: ConversationExport, val mimeType: String) : Result + data object Empty : Result + data object Cancelled : Result + } + + fun run( + threadId: Long, + title: String, + numbers: List, + format: ConversationFileFormat, + range: ExportRange, + isCancelled: () -> Boolean, + ): Result { + val now = System.currentTimeMillis() + val factory = ConversationExportFactory(context) + val messages = range.filter(readWholeThread(context, threadId), now, ZoneId.systemDefault()) + val notes = runCatching { runBlocking { context.messageNotes.notesForThread(threadId) } } + .getOrDefault(emptyMap()) + val export = factory.builder().build(messages, title, numbers, noteLines(context, notes)) + if (export.count == 0) return Result.Empty + if (isCancelled()) return Result.Cancelled + val file = newFile(title, format, now) + val header = factory.header( + export, now, firstMillis = messages.minOfOrNull { it.millis() } ?: now, + lastMillis = messages.maxOfOrNull { it.millis() } ?: now, + ) + val finished = when (format) { + ConversationFileFormat.PDF -> file.outputStream().buffered().use { out -> + ConversationPdfWriter(context).write(export, pdfTexts(factory, export, header, now), out, isCancelled) + } + + ConversationFileFormat.TEXT -> { + val footer = listOf(factory.hashLine(export), factory.notCertifiedLine()) + file.writeText(ConversationTextWriter.render(export, listOf(header.title) + header.lines, footer)) + true + } + } + if (!finished) { + file.delete() + return Result.Cancelled + } + return Result.Done(file, export, format.mimeType) + } + + private fun pdfTexts( + factory: ConversationExportFactory, export: ConversationExport, header: ExportHeader, now: Long, + ) = PdfTexts( + header = header, + notCertified = factory.notCertifiedLine(), + verification = factory.hashLine(export) + " | " + factory.exportedLine(now), + page = { number, total -> context.getString(R.string.export_pdf_page, number, total) }, + from = { context.getString(R.string.export_pdf_from, it) }, + to = { context.getString(R.string.export_pdf_to, it) }, + ) + + private fun newFile(title: String, format: ConversationFileFormat, now: Long): File { + val dir = File(context.cacheDir, SHARED_DIR).apply { mkdirs() } + ExportFileName.deleteOld(dir, now, KEEP_MS) + return ExportFileName.unique(dir, title, format.extension, now) + } + + companion object { + /** The cache folder the FileProvider already shares (see provider_paths.xml). */ + const val SHARED_DIR = "shared_logs" + + /** Earlier export files are removed after this long, not at the next export (D15). */ + const val KEEP_MS = 24L * 60 * 60 * 1000 + } +} 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 2346fc17..fdb73de8 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/extensions/Context.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/extensions/Context.kt @@ -859,13 +859,17 @@ fun Context.getSuggestedContacts( val normalizer = NumberNormalizer { region } val uri = Sms.CONTENT_URI val projection = arrayOf( - Sms.ADDRESS + Sms.ADDRESS, + Sms.THREAD_ID ) val sortOrder = "${Sms.DATE} DESC LIMIT 50" val blockedNumbers = getBlockedNumbers() + // People from chats hidden behind the app lock must not show up here while it is locked. + val hiddenThreadIds = com.glooboo.umessage.helpers.HiddenChats.get(this).hiddenIds() queryCursor(uri, projection, null, null, sortOrder, showErrors = true) { cursor -> + if (cursor.getLongValue(Sms.THREAD_ID) in hiddenThreadIds) return@queryCursor val senderNumber = cursor.getStringValue(Sms.ADDRESS) ?: return@queryCursor val namePhoto = getNameAndPhotoFromPhoneNumber(senderNumber) var senderName = namePhoto.name @@ -958,6 +962,7 @@ fun Context.insertNewSMS( threadId: Long, type: Int, subscriptionId: Int, + dateSent: Long = 0L, ): Long { val uri = Sms.CONTENT_URI val contentValues = ContentValues().apply { @@ -965,12 +970,13 @@ fun Context.insertNewSMS( put(Sms.SUBJECT, subject) put(Sms.BODY, body) put(Sms.DATE, date) + // The carrier's send time: the caller's [dateSent] (0 = unknown), else the receiver's own (I16). With neither, + // the provider keeps its own default. + (dateSent.takeIf { it > 0L } ?: IncomingDateSent.current())?.let { put(Sms.DATE_SENT, it) } put(Sms.READ, read) put(Sms.THREAD_ID, threadId) put(Sms.TYPE, type) put(Sms.SUBSCRIPTION_ID, subscriptionId) - // The carrier's own send time, when the receiver knows it (I16). - IncomingDateSent.current()?.let { put(Sms.DATE_SENT, it) } } return try { @@ -1441,9 +1447,11 @@ fun Context.updateLastConversationMessage(threadIds: Iterable) { try { contentResolver.delete(uri, selection, null) for (threadId in threadIds) { - // An empty thread, or one of a blocked number, has none: the other threads still refresh (B12). - val newConversation = getConversations(threadId).firstOrNull() ?: continue - insertOrUpdateConversation(newConversation) + // One thread without a row (an empty thread, or one of a blocked number) must not stop the others from + // being refreshed (B12). + runCatching { + getConversations(threadId).firstOrNull()?.let { insertOrUpdateConversation(it) } + } } } catch (_: Exception) { } diff --git a/app/src/main/kotlin/com/glooboo/umessage/helpers/CacheCleanup.kt b/app/src/main/kotlin/com/glooboo/umessage/helpers/CacheCleanup.kt new file mode 100644 index 00000000..af145640 --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/helpers/CacheCleanup.kt @@ -0,0 +1,52 @@ +package com.glooboo.umessage.helpers + +import android.content.Context +import android.os.Handler +import android.os.Looper +import java.io.File + +/** + * Sent-photo copies, camera shots, vCards and shared conversation text are written to the cache for the share or send + * and nothing deletes them afterwards. They are removed at app start once old enough that no send or draft can still + * use them, so a hidden or locked chat's pictures and text do not stay in the cache unencrypted. + */ +object CacheCleanup { + private const val DAY_MS = 24L * 60 * 60 * 1000 + private const val MINUTE_MS = 60L * 1000 + + /** How long an exported file stays in the cache after the share sheet opened: long enough for a slow upload. */ + const val SHARE_COPY_LIFETIME_MS = 15 * MINUTE_MS + + /** Cache folder to its age limit. */ + private val folders = listOf( + "attachments" to DAY_MS, "compressed" to DAY_MS, "shared_logs" to SHARE_COPY_LIFETIME_MS + ) + + /** Call off the main thread. */ + fun run(context: Context, now: Long = System.currentTimeMillis()) { + folders.forEach { (name, maxAge) -> deleteOlderThan(File(context.cacheDir, name), maxAge, now) } + } + + /** + * Deletes the exported [file] after [SHARE_COPY_LIFETIME_MS], so a shared chat or decision log does not stay in the + * cache unencrypted. If the app is closed before then, [run] removes it at the next start. + */ + fun deleteAfterShare(file: File, delayMs: Long = SHARE_COPY_LIFETIME_MS) { + Handler(Looper.getMainLooper()).postDelayed({ Thread { deleteQuietly(file) }.start() }, delayMs) + } + + /** Deletes [file] when it exists; true when it is gone afterwards. */ + internal fun deleteQuietly(file: File): Boolean = + runCatching { !file.exists() || file.delete() }.getOrDefault(false) + + /** Deletes the files directly in [dir] last changed more than [maxAgeMs] before [now]; returns how many. */ + internal fun deleteOlderThan(dir: File, maxAgeMs: Long, now: Long): Int { + var deleted = 0 + runCatching { + dir.listFiles()?.forEach { file -> + if (file.isFile && now - file.lastModified() > maxAgeMs && file.delete()) deleted++ + } + } + return deleted + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/helpers/MessageCategories.kt b/app/src/main/kotlin/com/glooboo/umessage/helpers/MessageCategories.kt index f92573fc..eb827e74 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/helpers/MessageCategories.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/helpers/MessageCategories.kt @@ -1,109 +1,109 @@ -package com.glooboo.umessage.helpers - -import com.glooboo.umessage.spam.TextNormalizer -import com.google.i18n.phonenumbers.PhoneNumberUtil -import java.util.Locale - -/** The kind of a conversation, for the Transactions and Offers filters. Anything unsure is [Other]. */ -enum class MessageCategory { Personal, Transactions, Offers, Other } - -/** - * A small on-device guess of what a text is, from its sender and words alone; nothing leaves the phone. Pure JVM. - * - * It is deliberately cautious: a text in the wrong category is worse than one left in [MessageCategory.Other], which - * only shows under "all". So a category needs several signs at once, and the sender must look like a service (a name - * or a short line), never a person's mobile number or a saved contact: - * - Transactions: an amount with a currency (or after "مبلغ", "balance"...) and a money word (واریز, برداشت, مانده...). - * - Offers: a promotion word and a link, and no amount. - * - A one-time code ([OtpCodes], the one rule of the app), or a text with both signs, is [MessageCategory.Other]. - * The word lists are in [CategoryKeywords]. Wave 2 (bank cards) and the weekly digest reuse this class. - */ -object MessageCategories { - - /** - * The category of one text. [isContact] is true for a saved contact or a group; [userSent] is true when the user - * has written in the thread. Either one makes it [MessageCategory.Personal] whatever the words say. - */ - fun classify(address: String, body: String, isContact: Boolean, userSent: Boolean = false): MessageCategory { - if (isContact || userSent) return MessageCategory.Personal - if (!isServiceSender(address)) return MessageCategory.Other - val text = TextNormalizer.fold(body) - if (text.isBlank() || OtpCodes.looksLikeCode(text)) return MessageCategory.Other - val amount = hasAmount(text) - val promo = PROMO.containsMatchIn(text) - return when { - promo && !amount && LINK.containsMatchIn(text) -> MessageCategory.Offers - !promo && amount && TRANSACTION.containsMatchIn(text) -> MessageCategory.Transactions - else -> MessageCategory.Other - } - } - - /** True when [text] (already folded) holds a sum of money. */ - internal fun hasAmount(text: String): Boolean = AMOUNT.containsMatchIn(text) - - /** - * A sender that is a business or a bank, not a person: a name with letters ("BankName"), or a short line without - * a plus sign and not a mobile number. Mobile numbers, landlines and international numbers read as people. - */ - internal fun isServiceSender(address: String): Boolean { - val trimmed = address.trim() - if (trimmed.isEmpty()) return false - val folded = TextNormalizer.fold(trimmed) - return folded.any { it.isLetter() } || isShortLine(folded) - } - - /** - * A number that reads as a service line: digits only, and not a real mobile or landline number of any country - * (libphonenumber decides, read in the phone's own country, so no country is special). A short code, also one - * written with a country code ("+98 5000123"), is a service line; a number with a leading 0 is a person. - */ - private fun isShortLine(folded: String): Boolean { - if (!folded.all { it.isDigit() || it in NUMBER_SYMBOLS }) return false - val digits = folded.filter { it.isDigit() } - val international = folded.trimStart().startsWith("+") || digits.startsWith("00") - if (!international && digits.startsWith("0")) return false - val region = Locale.getDefault().country.uppercase().ifBlank { null } - val util = PhoneNumberUtil.getInstance() - val number = runCatching { - util.parse(if (international) "+" + digits.removePrefix("00") else digits, region) - }.getOrNull() - if (number != null && util.isValidNumber(number)) return false - val national = number?.let { util.getNationalSignificantNumber(it) } ?: digits - return national.length in MIN_LINE_DIGITS..MAX_LINE_DIGITS - } - - private const val MIN_LINE_DIGITS = 3 - private const val MAX_LINE_DIGITS = 12 - private const val NUMBER_SYMBOLS = "+- ()" - - private val PROMO = words(CategoryKeywords.PROMO) - private val TRANSACTION = words(CategoryKeywords.TRANSACTION) - - private val LINK = Regex( - "(https?://|www\\.)\\S+|\\b[a-z0-9][a-z0-9-]*\\.(ir|com|net|org|shop|store|link|me|app|co|info)\\b", - RegexOption.IGNORE_CASE, - ) - - private const val NUMBER = "\\d[\\d,.\u066C\u066B]*" - private val AMOUNT = Regex( - "$NUMBER\\s*(${alternatives(CategoryKeywords.CURRENCY)})(?![a-z])|" + - "[\$\u20AC\u00A3]\\s*\\d|" + - "(${alternatives(CategoryKeywords.AMOUNT_LABEL)})\\s*[:\uFF1A]?\\s*[+-]?\\s*\\d", - RegexOption.IGNORE_CASE, - ) - - private fun alternatives(list: List): String = - list.joinToString("|") { Regex.escape(TextNormalizer.fold(it)) } - - /** Latin words need a word edge on both sides; Persian words are found anywhere. */ - private fun words(list: List): Regex = Regex( - list.joinToString("|") { word -> - val folded = TextNormalizer.fold(word) - val escaped = Regex.escape(folded) - val latinStart = folded.first() in 'a'..'z' || folded.first() in 'A'..'Z' - val latinEnd = folded.last() in 'a'..'z' || folded.last() in 'A'..'Z' - (if (latinStart) "(? MessageCategory.Offers + !promo && amount && TRANSACTION.containsMatchIn(text) -> MessageCategory.Transactions + else -> MessageCategory.Other + } + } + + /** True when [text] (already folded) holds a sum of money. */ + internal fun hasAmount(text: String): Boolean = AMOUNT.containsMatchIn(text) + + /** + * A sender that is a business or a bank, not a person: a name with letters ("BankName"), or a short line without + * a plus sign and not a mobile number. Mobile numbers, landlines and international numbers read as people. + */ + internal fun isServiceSender(address: String): Boolean { + val trimmed = address.trim() + if (trimmed.isEmpty()) return false + val folded = TextNormalizer.fold(trimmed) + return folded.any { it.isLetter() } || isShortLine(folded) + } + + /** + * A number that reads as a service line: digits only, and not a real mobile or landline number of any country + * (libphonenumber decides, read in the phone's own country, so no country is special). A short code, also one + * written with a country code ("+98 5000123"), is a service line; a number with a leading 0 is a person. + */ + private fun isShortLine(folded: String): Boolean { + if (!folded.all { it.isDigit() || it in NUMBER_SYMBOLS }) return false + val digits = folded.filter { it.isDigit() } + val international = folded.trimStart().startsWith("+") || digits.startsWith("00") + if (!international && digits.startsWith("0")) return false + val region = Locale.getDefault().country.uppercase().ifBlank { null } + val util = PhoneNumberUtil.getInstance() + val number = runCatching { + util.parse(if (international) "+" + digits.removePrefix("00") else digits, region) + }.getOrNull() + if (number != null && util.isValidNumber(number)) return false + val national = number?.let { util.getNationalSignificantNumber(it) } ?: digits + return national.length in MIN_LINE_DIGITS..MAX_LINE_DIGITS + } + + private const val MIN_LINE_DIGITS = 3 + private const val MAX_LINE_DIGITS = 12 + private const val NUMBER_SYMBOLS = "+- ()" + + private val PROMO = words(CategoryKeywords.PROMO) + private val TRANSACTION = words(CategoryKeywords.TRANSACTION) + + private val LINK = Regex( + "(https?://|www\\.)\\S+|\\b[a-z0-9][a-z0-9-]*\\.(ir|com|net|org|shop|store|link|me|app|co|info)\\b", + RegexOption.IGNORE_CASE, + ) + + private const val NUMBER = "\\d[\\d,.\u066C\u066B]*" + private val AMOUNT = Regex( + "$NUMBER\\s*(${alternatives(CategoryKeywords.CURRENCY)})(?![a-z])|" + + "[\$\u20AC\u00A3]\\s*\\d|" + + "(${alternatives(CategoryKeywords.AMOUNT_LABEL)})\\s*[:\uFF1A]?\\s*[+-]?\\s*\\d", + RegexOption.IGNORE_CASE, + ) + + private fun alternatives(list: List): String = + list.joinToString("|") { Regex.escape(TextNormalizer.fold(it)) } + + /** Latin words need a word edge on both sides; Persian words are found anywhere. */ + private fun words(list: List): Regex = Regex( + list.joinToString("|") { word -> + val folded = TextNormalizer.fold(word) + val escaped = Regex.escape(folded) + val latinStart = folded.first() in 'a'..'z' || folded.first() in 'A'..'Z' + val latinEnd = folded.last() in 'a'..'z' || folded.last() in 'A'..'Z' + (if (latinStart) "(? 0) pickCodes(codeDays, now) else emptyList() - val old = if (oldDays > 0) pickOld(oldDays, now, MessageRetention.BATCH) else emptyList() - val batch = (codes + old).distinctBy { it.key }.take(MessageRetention.BATCH) - batch.forEach { app.moveMessageToRecycleBin(it.id, it.isMMS, it) } - if (batch.isNotEmpty()) { - app.updateLastConversationMessage(batch.map { it.threadId }.toSet()) - refreshConversations() - refreshMessages() - } - return batch.size - } - - private fun isStarred(message: Message) = app.starredDB.isStarred(message.id, message.isMMS) - - /** F6: the messages that carry a private note or a reminder, looked up once per scan. */ - private fun keptLookup(): (Message) -> Boolean { - val noteKeys = runCatching { runBlocking { app.messageNotesDB.getAllKeys() } }.getOrDefault(emptyList()).toSet() - val reminded = runCatching { runBlocking { app.getMessagesDB().MessageRemindersDao().getAll() } } - .getOrDefault(emptyList()).map { it.key }.toSet() - return { m -> MessageNoteKey.of(m) in noteKeys || MessageKey(m.id, m.isMMS) in reminded } - } - - private fun pickCodes(days: Int, now: Long): List { - val cutoff = MessageRetention.cutoffSeconds(now, days) - val kept = keptLookup() - return scan(cutoff, MessageRetention.BATCH) { - MessageRetention.selectCodes(it, cutoff, kept) { m -> isStarred(m) } - } - } - - private fun pickOld(days: Int, now: Long, limit: Int): List { - val cutoff = MessageRetention.cutoffSeconds(now, days) - val pinned = app.config.pinnedConversations.mapNotNull { it.toLongOrNull() }.toSet() - val kept = keptLookup() - return scan(cutoff, limit) { MessageRetention.selectOld(it, cutoff, pinned, kept) { m -> isStarred(m) } } - } - - /** - * Pages through the old messages and keeps what [pick] chooses until [limit] are found or [MAX_SCANNED] were read. - * Nothing is moved while reading, so the pages do not shift under the offset. - */ - private fun scan(cutoff: Int, limit: Int, pick: (List) -> List): List { - val found = ArrayList() - var offset = 0 - while (found.size < limit && offset < MAX_SCANNED) { - val page = app.messagesDB.getRetentionCandidates(cutoff, PAGE, offset) - found += pick(page) - if (page.size < PAGE) break - offset += PAGE - } - return found.take(limit) - } - - private companion object { - const val PAGE = 1000 - const val MAX_SCANNED = 20_000 - const val MAX_ROUNDS = 40 - const val PREVIEW_LIMIT = 5000 - } -} +package com.glooboo.umessage.helpers + +import android.content.Context +import com.glooboo.umessage.extensions.config +import com.glooboo.umessage.extensions.getMessagesDB +import com.glooboo.umessage.extensions.messagesDB +import com.glooboo.umessage.extensions.moveMessageToRecycleBin +import com.glooboo.umessage.extensions.restoreMessageFromRecycleBin +import com.glooboo.umessage.extensions.updateLastConversationMessage +import com.glooboo.umessage.models.Message +import com.glooboo.umessage.models.MessageKey +import kotlinx.coroutines.runBlocking + +/** + * I02 and I45: moves old read verification codes ([CleanupPrefs.codeDays]) and old messages + * ([CleanupPrefs.oldMessageDays]) to the recycle bin. It never deletes for good: with the bin off it does nothing. + * Which messages qualify is decided by [MessageRetention]; this class reads the cache in pages, moves a batch of at + * most [MessageRetention.BATCH] and tells the lists. Blocking: call it on a background thread. + */ +@Suppress("TooManyFunctions") // One small step per cleanup rule; the entry points read top to bottom. +class RetentionRunner(context: Context) { + + private val app = context.applicationContext + private val prefs = app.cleanupPrefs + + /** The daily and receive-time check: does one batch, at most once per [CleanupPrefs.CLEANUP_INTERVAL_MS]. */ + fun runIfDue(now: Long) { + if (prefs.codeDays == 0 && prefs.oldMessageDays == 0) return + if (!app.config.useRecycleBin || !prefs.claimCleanup(now)) return + moveBatch(now) + } + + /** After the user chose an age and confirmed: moves everything due now, batch after batch. Returns the count. */ + fun runNow(now: Long): Int { + if (!app.config.useRecycleBin) return 0 + var moved = 0 + repeat(MAX_ROUNDS) { + val count = moveBatch(now) + moved += count + if (count < MessageRetention.BATCH) return moved + } + return moved + } + + /** + * After the user confirmed the read-codes cleanup: moves the read codes older than [days], batch after batch, and + * returns their keys so the caller can offer Undo through [restore]. Only codes move here, never other messages. + */ + fun moveCodesNow(days: Int, now: Long): List { + if (!app.config.useRecycleBin || days <= 0) return emptyList() + val moved = ArrayList() + repeat(MAX_ROUNDS) { + val batch = pickCodes(days, now) + moveToBin(batch) + moved += batch.map { it.key } + if (batch.size < MessageRetention.BATCH) return moved + } + return moved + } + + /** Undo of [moveCodesNow]: takes [keys] back out of the recycle bin and tells the lists. */ + fun restore(keys: List) { + if (keys.isEmpty()) return + keys.forEach { app.restoreMessageFromRecycleBin(it.id, it.isMMS) } + val threads = keys.mapNotNull { app.messagesDB.getMessage(it.id, it.isMMS)?.threadId }.toSet() + app.updateLastConversationMessage(threads) + refreshConversations() + refreshMessages() + } + + /** How many messages [days] of keep-time would move to the bin now (counted up to [PREVIEW_LIMIT]). */ + fun countOld(days: Int, now: Long): Int = pickOld(days, now, PREVIEW_LIMIT).size + + /** How many read code messages [days] of keep-time would move to the bin now (counted up to [PREVIEW_LIMIT]). */ + fun countCodes(days: Int, now: Long): Int = pickCodes(days, now, PREVIEW_LIMIT).size + + private fun moveBatch(now: Long): Int { + val codeDays = prefs.codeDays + val oldDays = prefs.oldMessageDays + val codes = if (codeDays > 0) pickCodes(codeDays, now) else emptyList() + val old = if (oldDays > 0) pickOld(oldDays, now, MessageRetention.BATCH) else emptyList() + val batch = (codes + old).distinctBy { it.key }.take(MessageRetention.BATCH) + moveToBin(batch) + return batch.size + } + + private fun moveToBin(batch: List) { + batch.forEach { app.moveMessageToRecycleBin(it.id, it.isMMS, it) } + if (batch.isNotEmpty()) { + app.updateLastConversationMessage(batch.map { it.threadId }.toSet()) + refreshConversations() + refreshMessages() + } + } + + private fun isStarred(message: Message) = app.starredDB.isStarred(message.id, message.isMMS) + + /** F6: the messages that carry a private note or a reminder, looked up once per scan. */ + private fun keptLookup(): (Message) -> Boolean { + val noteKeys = runCatching { runBlocking { app.messageNotesDB.getAllKeys() } }.getOrDefault(emptyList()).toSet() + val reminded = runCatching { runBlocking { app.getMessagesDB().MessageRemindersDao().getAll() } } + .getOrDefault(emptyList()).map { it.key }.toSet() + return { m -> MessageNoteKey.of(m) in noteKeys || MessageKey(m.id, m.isMMS) in reminded } + } + + private fun pickCodes(days: Int, now: Long, limit: Int = MessageRetention.BATCH): List { + val cutoff = MessageRetention.cutoffSeconds(now, days) + val kept = keptLookup() + return scan(cutoff, limit) { MessageRetention.selectCodes(it, cutoff, kept) { m -> isStarred(m) } } + } + + private fun pickOld(days: Int, now: Long, limit: Int): List { + val cutoff = MessageRetention.cutoffSeconds(now, days) + val pinned = app.config.pinnedConversations.mapNotNull { it.toLongOrNull() }.toSet() + val kept = keptLookup() + return scan(cutoff, limit) { MessageRetention.selectOld(it, cutoff, pinned, kept) { m -> isStarred(m) } } + } + + /** + * Pages through the old messages and keeps what [pick] chooses until [limit] are found or [MAX_SCANNED] were read. + * Nothing is moved while reading, so the pages do not shift under the offset. + */ + private fun scan(cutoff: Int, limit: Int, pick: (List) -> List): List { + val found = ArrayList() + var offset = 0 + while (found.size < limit && offset < MAX_SCANNED) { + val page = app.messagesDB.getRetentionCandidates(cutoff, PAGE, offset) + found += pick(page) + if (page.size < PAGE) break + offset += PAGE + } + return found.take(limit) + } + + private companion object { + const val PAGE = 1000 + const val MAX_SCANNED = 20_000 + const val MAX_ROUNDS = 40 + const val PREVIEW_LIMIT = 5000 + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/helpers/SavedTexts.kt b/app/src/main/kotlin/com/glooboo/umessage/helpers/SavedTexts.kt index 75b7e1ff..50d4d3d6 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/helpers/SavedTexts.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/helpers/SavedTexts.kt @@ -24,7 +24,7 @@ class SavedTexts(private val prefs: ComposerPrefs) { * number never shows up there. */ fun quickReplies(): List = all() - .filter { it.text.length < QUICK_REPLY_MAX_LENGTH && !LONG_NUMBER.containsMatchIn(it.text) } + .filter { it.text.length < QUICK_REPLY_MAX_LENGTH && !hasLongNumber(it.text) } .take(QUICK_REPLY_MAX_COUNT) fun add(title: String, text: String): SavedTextAdd { @@ -63,6 +63,13 @@ class SavedTexts(private val prefs: ComposerPrefs) { const val QUICK_REPLY_MAX_LENGTH = 40 const val QUICK_REPLY_MAX_COUNT = 5 private val LONG_NUMBER = Regex("""\p{Nd}{6,}""") + private val DIGIT_GROUPING = Regex("""[\s\-.]""") + private const val QUICK_REPLY_MAX_DIGITS = 8 + + /** True for a run of 6+ digits, or 8+ digits in total once spaces, dashes and dots are ignored. */ + internal fun hasLongNumber(text: String): Boolean = + LONG_NUMBER.containsMatchIn(text) || + text.replace(DIGIT_GROUPING, "").count { Character.isDigit(it) } >= QUICK_REPLY_MAX_DIGITS private const val KEY_ID = "id" private const val KEY_TITLE = "title" private const val KEY_TEXT = "text" diff --git a/app/src/main/kotlin/com/glooboo/umessage/interfaces/ConversationsDao.kt b/app/src/main/kotlin/com/glooboo/umessage/interfaces/ConversationsDao.kt index 1b141e59..d278512c 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/interfaces/ConversationsDao.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/interfaces/ConversationsDao.kt @@ -67,6 +67,10 @@ interface ConversationsDao { @Query("SELECT * FROM conversations WHERE thread_id = :threadId") fun getConversationWithThreadId(threadId: Long): Conversation? + /** Every chat row as stored, without the newest-message preview subquery; for matching phone numbers in search. */ + @Query("SELECT * FROM conversations") + fun getAllForNumberSearch(): List + @Query("SELECT * FROM conversations WHERE read = 0") fun getUnreadConversations(): List diff --git a/app/src/main/kotlin/com/glooboo/umessage/interfaces/MessagesDao.kt b/app/src/main/kotlin/com/glooboo/umessage/interfaces/MessagesDao.kt index 2f694175..2526c472 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/interfaces/MessagesDao.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/interfaces/MessagesDao.kt @@ -1,328 +1,350 @@ -@file:Suppress("MaxLineLength") -package com.glooboo.umessage.interfaces - -import androidx.room.ColumnInfo -import androidx.room.Dao -import androidx.room.Insert -import androidx.room.OnConflictStrategy -import androidx.room.Query -import androidx.room.RawQuery -import androidx.room.Transaction -import androidx.sqlite.db.SimpleSQLiteQuery -import androidx.sqlite.db.SupportSQLiteQuery -import com.glooboo.umessage.helpers.MessageFoldBackfill -import com.glooboo.umessage.models.Message -import com.glooboo.umessage.models.MessageAttachment -import com.glooboo.umessage.models.RecycleBinMessage -import com.glooboo.umessage.spam.TextNormalizer - -/** Search shows at most this many messages (and this many conversations), newest first (MC-17). */ -const val SEARCH_RESULTS_LIMIT = 100 - -private const val SEARCH_ORDER = "ORDER BY date DESC, id DESC LIMIT $SEARCH_RESULTS_LIMIT" - -/* I28, I56: the shortcut queries only prefilter in SQL; the caller keeps the rows that really hold a picture or link. */ -/** F5: what search and the shortcuts may show: sent or received messages that are not in the recycle bin. */ -private const val SHOWN_ONLY = "is_scheduled = 0 AND NOT EXISTS " + - "(SELECT 1 FROM recycle_bin_messages r WHERE r.id = messages.id AND r.is_mms = messages.is_mms)" -private const val SHORTCUT_BASE = "SELECT * FROM messages WHERE $SHOWN_ONLY" -private const val IMAGE_PREFILTER = "attachment LIKE '%image/%'" -private const val LINK_PREFILTER = "(body LIKE '%http%' OR body LIKE '%www.%')" -private const val SHORTCUT_ORDER = "ORDER BY date DESC, id DESC LIMIT :limit" - -/** A message whose folded body is still to be written: its row number and body (the backfill). */ -data class UnfoldedBody( - @ColumnInfo(name = "rid") val rowid: Long, - @ColumnInfo(name = "body") val body: String, -) - -/** Newest non-scheduled message time per thread, in seconds. */ -data class ThreadLastDate( - @ColumnInfo(name = "thread_id") val threadId: Long, - @ColumnInfo(name = "date") val date: Int, -) - -/** - * Rows in `messages` and `recycle_bin_messages` are keyed by (id, is_mms), see [com.glooboo.umessage.models.MessageKey]: - * every query that targets one message takes both. The `*Scheduled*` helpers are the exception: scheduled ids are - * unique among scheduled rows, and those helpers only ever match `is_scheduled = 1`. - */ -@Dao -interface MessagesDao { - @Insert(onConflict = OnConflictStrategy.REPLACE) - fun insertOrUpdate(message: Message) - - @Insert(onConflict = OnConflictStrategy.REPLACE) - fun insertRecycleBinEntry(recycleBinMessage: RecycleBinMessage) - - @Insert(onConflict = OnConflictStrategy.IGNORE) - fun insertOrIgnore(message: Message): Long - - @Insert(onConflict = OnConflictStrategy.REPLACE) - fun insertMessages(vararg message: Message) - - /** Caches [messages] in one transaction, keeping any row already cached under the same (id, is_mms). */ - @Insert(onConflict = OnConflictStrategy.IGNORE) - fun insertOrIgnoreAll(messages: List) - - @Query("SELECT * FROM messages") - fun getAll(): List - - @Query("SELECT * FROM messages WHERE id = :id AND is_mms = :isMMS") - fun getMessage(id: Long, isMMS: Boolean): Message? - - @Query("SELECT * FROM recycle_bin_messages") - fun getAllRecycleBinEntries(): List - - @Query("SELECT messages.* FROM messages LEFT OUTER JOIN recycle_bin_messages ON messages.id = recycle_bin_messages.id AND messages.is_mms = recycle_bin_messages.is_mms WHERE recycle_bin_messages.id IS NOT NULL") - fun getAllRecycleBinMessages(): List - - @Query("SELECT messages.* FROM messages LEFT OUTER JOIN recycle_bin_messages ON messages.id = recycle_bin_messages.id AND messages.is_mms = recycle_bin_messages.is_mms WHERE recycle_bin_messages.id IS NULL AND is_scheduled = 1") - fun getAllScheduledMessages(): List - - /** - * DL-13: recycle-bin entries deleted before [timestamp], read from the bin itself. Reading them through their - * cached copies missed every entry whose copy was never cached, so those stayed forever. - */ - @Query("SELECT * FROM recycle_bin_messages WHERE deleted_ts < :timestamp") - fun getOldRecycleBinEntries(timestamp: Long): List - - /** - * I02, I45: read, received or sent messages dated before [before] (seconds) that are not in the recycle bin, - * oldest first, [limit] rows from [offset]. The automatic cleanup pages through them and picks in memory. - */ - @Query("SELECT * FROM messages WHERE is_scheduled = 0 AND read = 1 AND date < :before AND type IN (1, 2) AND NOT EXISTS (SELECT 1 FROM recycle_bin_messages r WHERE r.id = messages.id AND r.is_mms = messages.is_mms) ORDER BY date ASC, id ASC LIMIT :limit OFFSET :offset") - fun getRetentionCandidates(before: Int, limit: Int, offset: Int): List - - @Query("SELECT * FROM messages WHERE thread_id = :threadId") - fun getThreadMessages(threadId: Long): List - - /** PF1: the newest [limit] cached messages of the thread (what opening a chat shows), not the whole thread. */ - @Query("SELECT * FROM messages WHERE thread_id = :threadId ORDER BY date DESC, id DESC LIMIT :limit") - fun getNewestThreadMessages(threadId: Long, limit: Int): List - - /** PF1: like [getNewestThreadMessages], without the messages in the recycle bin. */ - @Query( - "SELECT * FROM messages WHERE thread_id = :threadId AND NOT EXISTS " + - "(SELECT 1 FROM recycle_bin_messages r WHERE r.id = messages.id AND r.is_mms = messages.is_mms) " + - "ORDER BY date DESC, id DESC LIMIT :limit" - ) - fun getNewestNonRecycledThreadMessages(threadId: Long, limit: Int): List - - /** PF1: like [getNewestThreadMessages], only the messages in the recycle bin. */ - @Query( - "SELECT * FROM messages WHERE thread_id = :threadId AND EXISTS " + - "(SELECT 1 FROM recycle_bin_messages r WHERE r.id = messages.id AND r.is_mms = messages.is_mms) " + - "ORDER BY date DESC, id DESC LIMIT :limit" - ) - fun getNewestRecycleBinThreadMessages(threadId: Long, limit: Int): List - - /** DL-12: any one message of the thread, for its participants, without loading the whole chat. */ - @Query("SELECT * FROM messages WHERE thread_id = :threadId LIMIT 1") - fun getAnyThreadMessage(threadId: Long): Message? - - /** Per thread, the date of the newest cached message that was sent or received and is not in the recycle bin. */ - @Query( - "SELECT thread_id, MAX(date) AS date FROM messages WHERE is_scheduled = 0 AND NOT EXISTS " + - "(SELECT 1 FROM recycle_bin_messages r WHERE r.id = messages.id AND r.is_mms = messages.is_mms) " + - "GROUP BY thread_id" - ) - fun getLastMessageDates(): List - - /** The threads with a message sent or received on the SIM [subscriptionId] (the SIM tile of the search page). */ - @Query("SELECT DISTINCT thread_id FROM messages WHERE subscription_id = :subscriptionId AND is_scheduled = 0") - fun getThreadIdsOnSim(subscriptionId: Int): List - - /** DL-08: the message a chat's preview shows: its newest sent or received one outside the recycle bin. */ - @Query( - "SELECT * FROM messages WHERE thread_id = :threadId AND is_scheduled = 0 AND NOT EXISTS " + - "(SELECT 1 FROM recycle_bin_messages r WHERE r.id = messages.id AND r.is_mms = messages.is_mms) " + - "ORDER BY date DESC, id DESC LIMIT 1" - ) - fun getNewestShownMessage(threadId: Long): Message? - - @Query("SELECT messages.* FROM messages LEFT OUTER JOIN recycle_bin_messages ON messages.id = recycle_bin_messages.id AND messages.is_mms = recycle_bin_messages.is_mms WHERE recycle_bin_messages.id IS NULL AND thread_id = :threadId") - fun getNonRecycledThreadMessages(threadId: Long): List - - @Query("SELECT messages.* FROM messages LEFT OUTER JOIN recycle_bin_messages ON messages.id = recycle_bin_messages.id AND messages.is_mms = recycle_bin_messages.is_mms WHERE recycle_bin_messages.id IS NOT NULL AND thread_id = :threadId") - fun getThreadMessagesFromRecycleBin(threadId: Long): List - - @Query("SELECT messages.* FROM messages LEFT OUTER JOIN recycle_bin_messages ON messages.id = recycle_bin_messages.id AND messages.is_mms = recycle_bin_messages.is_mms WHERE recycle_bin_messages.id IS NULL AND thread_id = :threadId AND is_scheduled = 1") - fun getScheduledThreadMessages(threadId: Long): List - - @Query("SELECT * FROM messages WHERE thread_id = :threadId AND id = :messageId AND is_scheduled = 1") - fun getScheduledMessageWithId(threadId: Long, messageId: Long): Message - - @Query("SELECT COUNT(*) FROM recycle_bin_messages") - fun getArchivedCount(): Int - - /** Messages of [threadId] that are in the recycle bin. */ - @Query( - "SELECT COUNT(*) FROM messages JOIN recycle_bin_messages r " + - "ON r.id = messages.id AND r.is_mms = messages.is_mms WHERE messages.thread_id = :threadId" - ) - fun getRecycleBinMessageCountForThread(threadId: Long): Int - - /** Recycle-bin messages the bin can show and delete: those with a cached copy. */ - @Query( - "SELECT COUNT(*) FROM messages JOIN recycle_bin_messages r " + - "ON r.id = messages.id AND r.is_mms = messages.is_mms" - ) - fun getRecycleBinMessageCount(): Int - - /** [pattern] is a [TextNormalizer.likeContains] pattern. Newest first, at most [SEARCH_RESULTS_LIMIT]. */ - @Query("SELECT * FROM messages WHERE $SHOWN_ONLY AND body LIKE :pattern ESCAPE '\\' $SEARCH_ORDER") - fun getMessagesWithText(pattern: String): List - - @RawQuery - fun getMessagesRaw(query: SupportSQLiteQuery): List - - /** PF2: [pattern] is a [TextNormalizer.likeContains] pattern of an already folded text, matched on `body_folded`. */ - @Query("SELECT * FROM messages WHERE $SHOWN_ONLY AND body_folded LIKE :pattern ESCAPE '\\' $SEARCH_ORDER") - fun getMessagesWithFoldedText(pattern: String): List - - /** Up to [limit] messages after row [afterRowid] whose folded body has not been written yet (the backfill). */ - @Query( - "SELECT rowid AS rid, body FROM messages WHERE rowid > :afterRowid AND body_folded = '' AND body <> '' " + - "ORDER BY rowid LIMIT :limit" - ) - fun getUnfoldedBodies(afterRowid: Long, limit: Int): List - - /** Writes [folded] to row [rowid]; does nothing when the body changed (or the row was replaced) meanwhile. */ - @Query("UPDATE messages SET body_folded = :folded WHERE rowid = :rowid AND body = :body") - fun updateBodyFolded(rowid: Long, body: String, folded: String): Int - - /** Writes a whole batch of the backfill in one transaction. */ - @Transaction - fun updateBodiesFolded(batch: List) { - for (row in batch) updateBodyFolded(row.rowid, row.body, TextNormalizer.fold(row.body)) - } - - /** - * Messages whose body contains [text], read through [TextNormalizer.fold] on both sides, so "علي" finds "علی", - * "123" finds "۱۲۳" and a zero-width non-joiner does not break a match. `%` and `_` are matched as typed (MC-14). - * - * PF2: the query is folded once here and compared with the saved `body_folded` column. Until - * [com.glooboo.umessage.helpers.MessageFoldBackfill] has filled the column of every old row, the rows still - * empty (`body_folded = ''` with a body) are searched the old way, with the SQL fold chain, and merged in; the - * chain then runs over those rows only, and not at all once the backfill is complete. - * - * MC-17: newest first by date (kept in seconds for SMS and MMS alike; ids of the two are separate counters and - * say nothing about age), at most [SEARCH_RESULTS_LIMIT]. - */ - fun searchMessages(text: String): List { - if (!TextNormalizer.needsFold(text)) return getMessagesWithText(TextNormalizer.likeContains(text)) - val pattern = TextNormalizer.likeContains(TextNormalizer.fold(text)) - val fast = getMessagesWithFoldedText(pattern) - if (MessageFoldBackfill.isComplete) return fast - // rowid, not id: SMS 57 and MMS 57 share an id (see MessageKey), but every row has its own rowid. - val unfolded = SHOWN_ONLY + " AND body_folded = '' AND body <> ''" - val sql = TextNormalizer.sqlFoldedLike("messages", "rowid", "body", unfolded) + " $SEARCH_ORDER" - val old = getMessagesRaw(SimpleSQLiteQuery(sql, arrayOf(pattern))) - if (old.isEmpty()) return fast - return (fast + old).distinctBy { it.key } - .sortedWith(compareByDescending { it.date }.thenByDescending { it.id }) - .take(SEARCH_RESULTS_LIMIT) - } - - @Query("UPDATE messages SET read = 1 WHERE id = :id AND is_mms = :isMMS") - fun markRead(id: Long, isMMS: Boolean) - - @Query("UPDATE messages SET read = 1 WHERE thread_id = :threadId") - fun markThreadRead(threadId: Long) - - @Query("UPDATE messages SET type = :type WHERE id = :id AND is_mms = :isMMS") - fun updateType(id: Long, isMMS: Boolean, type: Int): Int - - @Query("UPDATE messages SET status = :status WHERE id = :id AND is_mms = :isMMS") - fun updateStatus(id: Long, isMMS: Boolean, status: Int): Int - - /** Sets the type of the scheduled message [id] (never a provider message that happens to share the id). */ - @Query("UPDATE messages SET type = :type WHERE id = :id AND is_scheduled = 1") - fun updateScheduledType(id: Long, type: Int): Int - - /** - * F3: claims the scheduled message [id] for sending: flips it from queued (6) to outbox (4) in one statement, so of - * any number of racing senders (alarm, app-start re-arm, "send now") exactly one gets 1 back and sends it. - */ - @Query("UPDATE messages SET type = 4 WHERE id = :id AND is_scheduled = 1 AND type = 6") - fun claimScheduledForSend(id: Long): Int - - /** Like [claimScheduledForSend], and also takes a message held as failed (5): the user's Retry or "Send now". */ - @Query("UPDATE messages SET type = 4 WHERE id = :id AND is_scheduled = 1 AND type IN (5, 6)") - fun claimScheduledOrHeldForSend(id: Long): Int - - /** Keeps only the attachments of the scheduled message [id] that have not been handed off yet (MS6). */ - @Query("UPDATE messages SET attachment = :attachment WHERE id = :id AND is_scheduled = 1") - fun updateScheduledAttachment(id: Long, attachment: MessageAttachment?): Int - - @Transaction - fun delete(id: Long, isMMS: Boolean) { - deleteFromMessages(id, isMMS) - deleteFromRecycleBin(id, isMMS) - } - - @Query("DELETE FROM messages WHERE id = :id AND is_mms = :isMMS") - fun deleteFromMessages(id: Long, isMMS: Boolean) - - @Query("DELETE FROM recycle_bin_messages WHERE id = :id AND is_mms = :isMMS") - fun deleteFromRecycleBin(id: Long, isMMS: Boolean) - - /** - * Moves the scheduled message [id] to [threadId]. An update, not an insert: a message cancelled or sent in the - * meantime (its row deleted by another thread) stays gone instead of coming back. - */ - @Query("UPDATE messages SET thread_id = :threadId WHERE id = :id AND is_scheduled = 1") - fun moveScheduledMessage(id: Long, threadId: Long) - - /** Deletes the scheduled message [id] (never a provider message that happens to share the id). */ - @Query("DELETE FROM messages WHERE id = :id AND is_scheduled = 1") - fun deleteScheduledMessage(id: Long) - - @Transaction - fun deleteThreadMessages(threadId: Long) { - deleteThreadMessagesFromRecycleBin(threadId) - deleteAllThreadMessages(threadId) - } - - @Query("DELETE FROM messages WHERE thread_id = :threadId") - fun deleteAllThreadMessages(threadId: Long) - - @Query( - "DELETE FROM recycle_bin_messages WHERE EXISTS (SELECT 1 FROM messages WHERE messages.thread_id = :threadId " + - "AND messages.id = recycle_bin_messages.id AND messages.is_mms = recycle_bin_messages.is_mms)" - ) - fun deleteThreadMessagesFromRecycleBin(threadId: Long) - - /** - * Drops the cached copies of provider messages. Scheduled messages and recycle-bin entries are kept: this table - * is their only copy. - */ - @Query( - "DELETE FROM messages WHERE is_scheduled = 0 AND NOT EXISTS (SELECT 1 FROM recycle_bin_messages " + - "WHERE recycle_bin_messages.id = messages.id AND recycle_bin_messages.is_mms = messages.is_mms)" - ) - fun deleteCachedMessages() - - /** Newest messages that may hold a picture (their attachment text names an image type), at most [limit]. */ - @Query("$SHORTCUT_BASE AND $IMAGE_PREFILTER $SHORTCUT_ORDER") - fun getImageCandidates(limit: Int): List - - @Query("$SHORTCUT_BASE AND thread_id = :threadId AND $IMAGE_PREFILTER $SHORTCUT_ORDER") - fun getThreadImageCandidates(threadId: Long, limit: Int): List - - /** Newest messages whose text may hold a web link, at most [limit]. */ - @Query("$SHORTCUT_BASE AND $LINK_PREFILTER $SHORTCUT_ORDER") - fun getLinkCandidates(limit: Int): List - - @Query("$SHORTCUT_BASE AND thread_id = :threadId AND $LINK_PREFILTER $SHORTCUT_ORDER") - fun getThreadLinkCandidates(threadId: Long, limit: Int): List - - /** I13: the messages sent or received at [date] (seconds), to find a starred message again under a new id. */ - @Query("SELECT * FROM messages WHERE date = :date AND is_scheduled = 0") - fun getMessagesAtDate(date: Int): List - - /** DA3: changes whenever the cache gets a new row; O(1), so it can say "nothing new since the last look". */ - @Query("SELECT COALESCE(MAX(rowid), 0) FROM messages") - fun cacheStamp(): Long -} +@file:Suppress("MaxLineLength") +package com.glooboo.umessage.interfaces + +import androidx.room.ColumnInfo +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import androidx.room.RawQuery +import androidx.room.Transaction +import androidx.sqlite.db.SimpleSQLiteQuery +import androidx.sqlite.db.SupportSQLiteQuery +import com.glooboo.umessage.helpers.MessageFoldBackfill +import com.glooboo.umessage.models.Message +import com.glooboo.umessage.models.MessageAttachment +import com.glooboo.umessage.models.RecycleBinMessage +import com.glooboo.umessage.spam.TextNormalizer + +/** Search shows at most this many messages (and this many conversations), newest first (MC-17). */ +const val SEARCH_RESULTS_LIMIT = 100 + +/** Search in one conversation reads at most this many matches. */ +const val THREAD_SEARCH_LIMIT = 1000 + +private const val SEARCH_ORDER = "ORDER BY date DESC, id DESC LIMIT $SEARCH_RESULTS_LIMIT" + +/* I28, I56: the shortcut queries only prefilter in SQL; the caller keeps the rows that really hold a picture or link. */ +/** F5: what search and the shortcuts may show: sent or received messages that are not in the recycle bin. */ +private const val SHOWN_ONLY = "is_scheduled = 0 AND NOT EXISTS " + + "(SELECT 1 FROM recycle_bin_messages r WHERE r.id = messages.id AND r.is_mms = messages.is_mms)" +private const val SHORTCUT_BASE = "SELECT * FROM messages WHERE $SHOWN_ONLY" +private const val IMAGE_PREFILTER = "attachment LIKE '%image/%'" +private const val LINK_PREFILTER = "(body LIKE '%http%' OR body LIKE '%www.%')" +private const val SHORTCUT_ORDER = "ORDER BY date DESC, id DESC LIMIT :limit" + +/** A message whose folded body is still to be written: its row number and body (the backfill). */ +data class UnfoldedBody( + @ColumnInfo(name = "rid") val rowid: Long, + @ColumnInfo(name = "body") val body: String, +) + +/** Newest non-scheduled message time per thread, in seconds. */ +data class ThreadLastDate( + @ColumnInfo(name = "thread_id") val threadId: Long, + @ColumnInfo(name = "date") val date: Int, +) + +/** + * Rows in `messages` and `recycle_bin_messages` are keyed by (id, is_mms), see [com.glooboo.umessage.models.MessageKey]: + * every query that targets one message takes both. The `*Scheduled*` helpers are the exception: scheduled ids are + * unique among scheduled rows, and those helpers only ever match `is_scheduled = 1`. + */ +@Dao +interface MessagesDao { + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun insertOrUpdate(message: Message) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun insertRecycleBinEntry(recycleBinMessage: RecycleBinMessage) + + @Insert(onConflict = OnConflictStrategy.IGNORE) + fun insertOrIgnore(message: Message): Long + + @Insert(onConflict = OnConflictStrategy.REPLACE) + fun insertMessages(vararg message: Message) + + /** Caches [messages] in one transaction, keeping any row already cached under the same (id, is_mms). */ + @Insert(onConflict = OnConflictStrategy.IGNORE) + fun insertOrIgnoreAll(messages: List) + + @Query("SELECT * FROM messages") + fun getAll(): List + + @Query("SELECT * FROM messages WHERE id = :id AND is_mms = :isMMS") + fun getMessage(id: Long, isMMS: Boolean): Message? + + @Query("SELECT * FROM recycle_bin_messages") + fun getAllRecycleBinEntries(): List + + @Query("SELECT messages.* FROM messages LEFT OUTER JOIN recycle_bin_messages ON messages.id = recycle_bin_messages.id AND messages.is_mms = recycle_bin_messages.is_mms WHERE recycle_bin_messages.id IS NOT NULL") + fun getAllRecycleBinMessages(): List + + @Query("SELECT messages.* FROM messages LEFT OUTER JOIN recycle_bin_messages ON messages.id = recycle_bin_messages.id AND messages.is_mms = recycle_bin_messages.is_mms WHERE recycle_bin_messages.id IS NULL AND is_scheduled = 1") + fun getAllScheduledMessages(): List + + /** + * DL-13: recycle-bin entries deleted before [timestamp], read from the bin itself. Reading them through their + * cached copies missed every entry whose copy was never cached, so those stayed forever. + */ + @Query("SELECT * FROM recycle_bin_messages WHERE deleted_ts < :timestamp") + fun getOldRecycleBinEntries(timestamp: Long): List + + /** + * I02, I45: read, received or sent messages dated before [before] (seconds) that are not in the recycle bin, + * oldest first, [limit] rows from [offset]. The automatic cleanup pages through them and picks in memory. + */ + @Query("SELECT * FROM messages WHERE is_scheduled = 0 AND read = 1 AND date < :before AND type IN (1, 2) AND NOT EXISTS (SELECT 1 FROM recycle_bin_messages r WHERE r.id = messages.id AND r.is_mms = messages.is_mms) ORDER BY date ASC, id ASC LIMIT :limit OFFSET :offset") + fun getRetentionCandidates(before: Int, limit: Int, offset: Int): List + + @Query("SELECT * FROM messages WHERE thread_id = :threadId") + fun getThreadMessages(threadId: Long): List + + /** PF1: the newest [limit] cached messages of the thread (what opening a chat shows), not the whole thread. */ + @Query("SELECT * FROM messages WHERE thread_id = :threadId ORDER BY date DESC, id DESC LIMIT :limit") + fun getNewestThreadMessages(threadId: Long, limit: Int): List + + /** PF1: like [getNewestThreadMessages], without the messages in the recycle bin. */ + @Query( + "SELECT * FROM messages WHERE thread_id = :threadId AND NOT EXISTS " + + "(SELECT 1 FROM recycle_bin_messages r WHERE r.id = messages.id AND r.is_mms = messages.is_mms) " + + "ORDER BY date DESC, id DESC LIMIT :limit" + ) + fun getNewestNonRecycledThreadMessages(threadId: Long, limit: Int): List + + /** PF1: like [getNewestThreadMessages], only the messages in the recycle bin. */ + @Query( + "SELECT * FROM messages WHERE thread_id = :threadId AND EXISTS " + + "(SELECT 1 FROM recycle_bin_messages r WHERE r.id = messages.id AND r.is_mms = messages.is_mms) " + + "ORDER BY date DESC, id DESC LIMIT :limit" + ) + fun getNewestRecycleBinThreadMessages(threadId: Long, limit: Int): List + + /** DL-12: any one message of the thread, for its participants, without loading the whole chat. */ + @Query("SELECT * FROM messages WHERE thread_id = :threadId LIMIT 1") + fun getAnyThreadMessage(threadId: Long): Message? + + /** Per thread, the date of the newest cached message that was sent or received and is not in the recycle bin. */ + @Query( + "SELECT thread_id, MAX(date) AS date FROM messages WHERE is_scheduled = 0 AND NOT EXISTS " + + "(SELECT 1 FROM recycle_bin_messages r WHERE r.id = messages.id AND r.is_mms = messages.is_mms) " + + "GROUP BY thread_id" + ) + fun getLastMessageDates(): List + + /** The threads with a message sent or received on the SIM [subscriptionId] (the SIM tile of the search page). */ + @Query("SELECT DISTINCT thread_id FROM messages WHERE subscription_id = :subscriptionId AND is_scheduled = 0") + fun getThreadIdsOnSim(subscriptionId: Int): List + + /** DL-08: the message a chat's preview shows: its newest sent or received one outside the recycle bin. */ + @Query( + "SELECT * FROM messages WHERE thread_id = :threadId AND is_scheduled = 0 AND NOT EXISTS " + + "(SELECT 1 FROM recycle_bin_messages r WHERE r.id = messages.id AND r.is_mms = messages.is_mms) " + + "ORDER BY date DESC, id DESC LIMIT 1" + ) + fun getNewestShownMessage(threadId: Long): Message? + + @Query("SELECT messages.* FROM messages LEFT OUTER JOIN recycle_bin_messages ON messages.id = recycle_bin_messages.id AND messages.is_mms = recycle_bin_messages.is_mms WHERE recycle_bin_messages.id IS NULL AND thread_id = :threadId") + fun getNonRecycledThreadMessages(threadId: Long): List + + @Query("SELECT messages.* FROM messages LEFT OUTER JOIN recycle_bin_messages ON messages.id = recycle_bin_messages.id AND messages.is_mms = recycle_bin_messages.is_mms WHERE recycle_bin_messages.id IS NOT NULL AND thread_id = :threadId") + fun getThreadMessagesFromRecycleBin(threadId: Long): List + + @Query("SELECT messages.* FROM messages LEFT OUTER JOIN recycle_bin_messages ON messages.id = recycle_bin_messages.id AND messages.is_mms = recycle_bin_messages.is_mms WHERE recycle_bin_messages.id IS NULL AND thread_id = :threadId AND is_scheduled = 1") + fun getScheduledThreadMessages(threadId: Long): List + + /** One scheduled message by id, without loading every scheduled message. */ + @Query("SELECT * FROM messages WHERE id = :messageId AND is_scheduled = 1 LIMIT 1") + fun getScheduledMessageById(messageId: Long): Message? + + @Query("SELECT * FROM messages WHERE thread_id = :threadId AND id = :messageId AND is_scheduled = 1") + fun getScheduledMessageWithId(threadId: Long, messageId: Long): Message + + @Query("SELECT COUNT(*) FROM recycle_bin_messages") + fun getArchivedCount(): Int + + /** Messages of [threadId] that are in the recycle bin. */ + @Query( + "SELECT COUNT(*) FROM messages JOIN recycle_bin_messages r " + + "ON r.id = messages.id AND r.is_mms = messages.is_mms WHERE messages.thread_id = :threadId" + ) + fun getRecycleBinMessageCountForThread(threadId: Long): Int + + /** Recycle-bin messages the bin can show and delete: those with a cached copy. */ + @Query( + "SELECT COUNT(*) FROM messages JOIN recycle_bin_messages r " + + "ON r.id = messages.id AND r.is_mms = messages.is_mms" + ) + fun getRecycleBinMessageCount(): Int + + /** [pattern] is a [TextNormalizer.likeContains] pattern. Newest first, at most [SEARCH_RESULTS_LIMIT]. */ + @Query("SELECT * FROM messages WHERE $SHOWN_ONLY AND body LIKE :pattern ESCAPE '\\' $SEARCH_ORDER") + fun getMessagesWithText(pattern: String): List + + /** [pattern] is a [TextNormalizer.likeContains] pattern. One thread, newest first, at most [THREAD_SEARCH_LIMIT]. */ + @Query( + "SELECT * FROM messages WHERE thread_id = :threadId AND body LIKE :pattern ESCAPE '\\' AND $SHOWN_ONLY " + + "ORDER BY date DESC, id DESC LIMIT $THREAD_SEARCH_LIMIT" + ) + fun getThreadMessagesWithText(threadId: Long, pattern: String): List + + /** Like [searchMessages], within the one conversation [threadId] (search in conversation, TH-20). */ + fun searchThreadMessages(threadId: Long, text: String): List { + if (!TextNormalizer.needsFold(text)) return getThreadMessagesWithText(threadId, TextNormalizer.likeContains(text)) + val sql = TextNormalizer.sqlFoldedLike("messages", "rowid", "body", "thread_id = $threadId AND $SHOWN_ONLY") + + " ORDER BY date DESC, id DESC LIMIT $THREAD_SEARCH_LIMIT" + return getMessagesRaw(SimpleSQLiteQuery(sql, arrayOf(TextNormalizer.likeContains(TextNormalizer.fold(text))))) + } + + @RawQuery + fun getMessagesRaw(query: SupportSQLiteQuery): List + + /** PF2: [pattern] is a [TextNormalizer.likeContains] pattern of an already folded text, matched on `body_folded`. */ + @Query("SELECT * FROM messages WHERE $SHOWN_ONLY AND body_folded LIKE :pattern ESCAPE '\\' $SEARCH_ORDER") + fun getMessagesWithFoldedText(pattern: String): List + + /** Up to [limit] messages after row [afterRowid] whose folded body has not been written yet (the backfill). */ + @Query( + "SELECT rowid AS rid, body FROM messages WHERE rowid > :afterRowid AND body_folded = '' AND body <> '' " + + "ORDER BY rowid LIMIT :limit" + ) + fun getUnfoldedBodies(afterRowid: Long, limit: Int): List + + /** Writes [folded] to row [rowid]; does nothing when the body changed (or the row was replaced) meanwhile. */ + @Query("UPDATE messages SET body_folded = :folded WHERE rowid = :rowid AND body = :body") + fun updateBodyFolded(rowid: Long, body: String, folded: String): Int + + /** Writes a whole batch of the backfill in one transaction. */ + @Transaction + fun updateBodiesFolded(batch: List) { + for (row in batch) updateBodyFolded(row.rowid, row.body, TextNormalizer.fold(row.body)) + } + + /** + * Messages whose body contains [text], read through [TextNormalizer.fold] on both sides, so "علي" finds "علی", + * "123" finds "۱۲۳" and a zero-width non-joiner does not break a match. `%` and `_` are matched as typed (MC-14). + * + * PF2: the query is folded once here and compared with the saved `body_folded` column. Until + * [com.glooboo.umessage.helpers.MessageFoldBackfill] has filled the column of every old row, the rows still + * empty (`body_folded = ''` with a body) are searched the old way, with the SQL fold chain, and merged in; the + * chain then runs over those rows only, and not at all once the backfill is complete. + * + * MC-17: newest first by date (kept in seconds for SMS and MMS alike; ids of the two are separate counters and + * say nothing about age), at most [SEARCH_RESULTS_LIMIT]. + */ + fun searchMessages(text: String): List { + if (!TextNormalizer.needsFold(text)) return getMessagesWithText(TextNormalizer.likeContains(text)) + val pattern = TextNormalizer.likeContains(TextNormalizer.fold(text)) + val fast = getMessagesWithFoldedText(pattern) + if (MessageFoldBackfill.isComplete) return fast + // rowid, not id: SMS 57 and MMS 57 share an id (see MessageKey), but every row has its own rowid. + val unfolded = SHOWN_ONLY + " AND body_folded = '' AND body <> ''" + val sql = TextNormalizer.sqlFoldedLike("messages", "rowid", "body", unfolded) + " $SEARCH_ORDER" + val old = getMessagesRaw(SimpleSQLiteQuery(sql, arrayOf(pattern))) + if (old.isEmpty()) return fast + return (fast + old).distinctBy { it.key } + .sortedWith(compareByDescending { it.date }.thenByDescending { it.id }) + .take(SEARCH_RESULTS_LIMIT) + } + + @Query("UPDATE messages SET read = 1 WHERE id = :id AND is_mms = :isMMS") + fun markRead(id: Long, isMMS: Boolean) + + @Query("UPDATE messages SET read = 1 WHERE thread_id = :threadId") + fun markThreadRead(threadId: Long) + + @Query("UPDATE messages SET type = :type WHERE id = :id AND is_mms = :isMMS") + fun updateType(id: Long, isMMS: Boolean, type: Int): Int + + @Query("UPDATE messages SET status = :status WHERE id = :id AND is_mms = :isMMS") + fun updateStatus(id: Long, isMMS: Boolean, status: Int): Int + + /** Sets the type of the scheduled message [id] (never a provider message that happens to share the id). */ + @Query("UPDATE messages SET type = :type WHERE id = :id AND is_scheduled = 1") + fun updateScheduledType(id: Long, type: Int): Int + + /** + * F3: claims the scheduled message [id] for sending: flips it from queued (6) to outbox (4) in one statement, so of + * any number of racing senders (alarm, app-start re-arm, "send now") exactly one gets 1 back and sends it. + */ + @Query("UPDATE messages SET type = 4 WHERE id = :id AND is_scheduled = 1 AND type = 6") + fun claimScheduledForSend(id: Long): Int + + /** Like [claimScheduledForSend], and also takes a message held as failed (5): the user's Retry or "Send now". */ + @Query("UPDATE messages SET type = 4 WHERE id = :id AND is_scheduled = 1 AND type IN (5, 6)") + fun claimScheduledOrHeldForSend(id: Long): Int + + /** Keeps only the attachments of the scheduled message [id] that have not been handed off yet (MS6). */ + @Query("UPDATE messages SET attachment = :attachment WHERE id = :id AND is_scheduled = 1") + fun updateScheduledAttachment(id: Long, attachment: MessageAttachment?): Int + + @Transaction + fun delete(id: Long, isMMS: Boolean) { + deleteFromMessages(id, isMMS) + deleteFromRecycleBin(id, isMMS) + } + + @Query("DELETE FROM messages WHERE id = :id AND is_mms = :isMMS") + fun deleteFromMessages(id: Long, isMMS: Boolean) + + @Query("DELETE FROM recycle_bin_messages WHERE id = :id AND is_mms = :isMMS") + fun deleteFromRecycleBin(id: Long, isMMS: Boolean) + + /** + * Moves the scheduled message [id] to [threadId]. An update, not an insert: a message cancelled or sent in the + * meantime (its row deleted by another thread) stays gone instead of coming back. + */ + @Query("UPDATE messages SET thread_id = :threadId WHERE id = :id AND is_scheduled = 1") + fun moveScheduledMessage(id: Long, threadId: Long) + + /** Deletes the scheduled message [id] (never a provider message that happens to share the id). */ + @Query("DELETE FROM messages WHERE id = :id AND is_scheduled = 1") + fun deleteScheduledMessage(id: Long) + + @Transaction + fun deleteThreadMessages(threadId: Long) { + deleteThreadMessagesFromRecycleBin(threadId) + deleteAllThreadMessages(threadId) + } + + @Query("DELETE FROM messages WHERE thread_id = :threadId") + fun deleteAllThreadMessages(threadId: Long) + + @Query( + "DELETE FROM recycle_bin_messages WHERE EXISTS (SELECT 1 FROM messages WHERE messages.thread_id = :threadId " + + "AND messages.id = recycle_bin_messages.id AND messages.is_mms = recycle_bin_messages.is_mms)" + ) + fun deleteThreadMessagesFromRecycleBin(threadId: Long) + + /** + * Drops the cached copies of provider messages. Scheduled messages and recycle-bin entries are kept: this table + * is their only copy. + */ + @Query( + "DELETE FROM messages WHERE is_scheduled = 0 AND NOT EXISTS (SELECT 1 FROM recycle_bin_messages " + + "WHERE recycle_bin_messages.id = messages.id AND recycle_bin_messages.is_mms = messages.is_mms)" + ) + fun deleteCachedMessages() + + /** Newest messages that may hold a picture (their attachment text names an image type), at most [limit]. */ + @Query("$SHORTCUT_BASE AND $IMAGE_PREFILTER $SHORTCUT_ORDER") + fun getImageCandidates(limit: Int): List + + @Query("$SHORTCUT_BASE AND thread_id = :threadId AND $IMAGE_PREFILTER $SHORTCUT_ORDER") + fun getThreadImageCandidates(threadId: Long, limit: Int): List + + /** Newest messages whose text may hold a web link, at most [limit]. */ + @Query("$SHORTCUT_BASE AND $LINK_PREFILTER $SHORTCUT_ORDER") + fun getLinkCandidates(limit: Int): List + + @Query("$SHORTCUT_BASE AND thread_id = :threadId AND $LINK_PREFILTER $SHORTCUT_ORDER") + fun getThreadLinkCandidates(threadId: Long, limit: Int): List + + /** I13: the messages sent or received at [date] (seconds), to find a starred message again under a new id. */ + @Query("SELECT * FROM messages WHERE date = :date AND is_scheduled = 0") + fun getMessagesAtDate(date: Int): List + + /** DA3: changes whenever the cache gets a new row; O(1), so it can say "nothing new since the last look". */ + @Query("SELECT COALESCE(MAX(rowid), 0) FROM messages") + fun cacheStamp(): Long +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/messaging/Messaging.kt b/app/src/main/kotlin/com/glooboo/umessage/messaging/Messaging.kt index ece20251..fa9e2817 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/messaging/Messaging.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/messaging/Messaging.kt @@ -1,158 +1,260 @@ -package com.glooboo.umessage.messaging - -import android.content.Context -import android.util.Log -import android.util.Patterns -import android.widget.Toast.LENGTH_LONG -import com.klinker.android.send_message.Settings -import org.fossify.commons.extensions.toast -import org.fossify.commons.helpers.ensureBackgroundThread -import com.glooboo.umessage.R -import com.glooboo.umessage.extensions.config -import com.glooboo.umessage.extensions.getThreadId -import com.glooboo.umessage.extensions.messagingUtils -import com.glooboo.umessage.extensions.shortcutHelper -import com.glooboo.umessage.messaging.SmsException.Companion.EMPTY_DESTINATION_ADDRESS -import com.glooboo.umessage.messaging.SmsException.Companion.ERROR_PERSISTING_MESSAGE -import com.glooboo.umessage.messaging.SmsException.Companion.ERROR_SENDING_MESSAGE -import com.glooboo.umessage.models.Attachment -import com.glooboo.umessage.models.MessageKey - -@Deprecated("TODO: Move/rewrite messaging config code into the app.") -fun Context.getSendMessageSettings(): Settings { - val settings = Settings() - settings.useSystemSending = true - settings.deliveryReports = config.enableDeliveryReports - val after = config.sendLongAsMmsAfterParts - settings.sendLongAsMms = after != LongTextMms.NEVER - // The library sends as MMS above this many parts; the setting says "from this many parts". - settings.sendLongAsMmsAfter = (after - 1).coerceAtLeast(1) - settings.group = config.sendGroupMessageMMS - return settings -} - -/** Q9: true only when the user chose a number of parts in Settings and [text] has at least that many. */ -fun Context.isLongMmsMessage(text: String, settings: Settings = getSendMessageSettings()): Boolean { - if (!settings.sendLongAsMms) return false - return LongTextMms.shouldSendAsMms(LongTextMms.smsParts(text), settings.sendLongAsMmsAfter + 1) -} - -/** - * Sends the message using the in-app SmsManager API wrappers if it's an SMS or using android-smsmms for MMS. - * Errors are shown as toasts. Returns false when the message never reached the provider (nothing was saved, so - * nothing can be retried from the thread), true otherwise, including sends that were saved and then failed. - * [onFailure] runs, after the toast, whenever this call already knows the send failed, whatever it returns; callers - * running in the background use it to tell the user, since a toast there is never seen. Failures reported later by - * the radio go through the sent receivers instead. [onAttachmentHandedOff] is told about each attachment that was queued - * (MS6), so a caller that holds the whole message can drop it and never send it twice on a later Retry. - */ -fun Context.sendMessageCompat( - text: String, - addresses: List, - subId: Int?, - attachments: List, - resend: MessageKey? = null, - onFailure: () -> Unit = {}, - onAttachmentHandedOff: (Attachment) -> Unit = {}, -): Boolean { - val settings = getSendMessageSettings() - activeSendSubscriptionId(subId)?.let { settings.subscriptionId = it } - - val messagingUtils = messagingUtils - var handedOff = true - var failed = false - val isMms = attachments.isNotEmpty() || isLongMmsMessage(text, settings) - || addresses.size > 1 && settings.group - // The failed message being resent is replaced only by a resend of the same type: SMS and MMS ids are separate - // sequences, so handing an SMS id to the MMS path (or the other way round) would touch an unrelated message. - val messageId = resend?.takeIf { it.isMMS == isMms }?.id - if (isMms) { - // we send all MMS attachments separately to reduces the chances of hitting provider MMS limit. - if (attachments.isNotEmpty()) { - val lastIndex = attachments.lastIndex - if (attachments.size > 1) { - for (i in 0 until lastIndex) { - val attachment = attachments[i] - if (messagingUtils.sendMmsMessage("", addresses, attachment, settings, messageId)) { - onAttachmentHandedOff(attachment) - } else { - handedOff = false - failed = true - } - } - } - - val lastAttachment = attachments[lastIndex] - if (messagingUtils.sendMmsMessage(text, addresses, lastAttachment, settings, messageId)) { - onAttachmentHandedOff(lastAttachment) - } else { - handedOff = false - failed = true - } - } else { - handedOff = messagingUtils.sendMmsMessage(text, addresses, null, settings, messageId) - failed = !handedOff - } - } else { - try { - messagingUtils.sendSmsMessage( - text = text, - addresses = addresses.toSet(), - subId = settings.subscriptionId, - requireDeliveryReport = settings.deliveryReports, - messageId = messageId - ) - } catch (e: SmsException) { - // A sending error leaves a failed row in the provider; the other errors leave nothing. - handedOff = e.errorCode == ERROR_SENDING_MESSAGE - failed = true - when (e.errorCode) { - EMPTY_DESTINATION_ADDRESS -> toast( - id = R.string.empty_destination_address, - length = LENGTH_LONG - ) - - ERROR_PERSISTING_MESSAGE -> toast( - id = R.string.unable_to_save_message, - length = LENGTH_LONG - ) - - ERROR_SENDING_MESSAGE -> toast( - msg = getString( - R.string.sms_preparation_error_details, - getString(R.string.message_not_sent_short), - e.errorCode - ), - length = LENGTH_LONG - ) - } - } catch (e: Exception) { - handedOff = false - failed = true - Log.e("Messaging", "Sending an SMS failed", e) - toast(id = R.string.message_send_retry_later, length = LENGTH_LONG) - } - } - if (failed) { - onFailure() - } - ensureBackgroundThread { - val threadId = getThreadId(addresses.toSet()) - shortcutHelper.reportSendMessageUsage(threadId) - } - return handedOff -} - -/** - * Check if a given "address" is a short code. - * There's not much info available on these special numbers, even the wikipedia page (https://en.wikipedia.org/wiki/Short_code) - * contains outdated information regarding max number of digits. The exact parameters for short codes can vary by country and by carrier. - */ -fun isShortCodeWithLetters(address: String): Boolean { - if (Patterns.EMAIL_ADDRESS.matcher(address).matches()) { - // emails are not short codes: https://github.com/FossifyOrg/Messages/issues/115 - return false - } - - return address.any { it.isLetter() } -} +package com.glooboo.umessage.messaging + +import android.content.Context +import android.util.Log +import android.util.Patterns +import android.widget.Toast.LENGTH_LONG +import com.klinker.android.send_message.Settings +import org.fossify.commons.extensions.toast +import org.fossify.commons.helpers.ensureBackgroundThread +import com.glooboo.umessage.R +import com.glooboo.umessage.extensions.config +import com.glooboo.umessage.extensions.deleteMessage +import com.glooboo.umessage.extensions.getThreadId +import com.glooboo.umessage.extensions.messagingUtils +import com.glooboo.umessage.extensions.shortcutHelper +import com.glooboo.umessage.messaging.SmsException.Companion.EMPTY_DESTINATION_ADDRESS +import com.glooboo.umessage.messaging.SmsException.Companion.ERROR_PERSISTING_MESSAGE +import com.glooboo.umessage.messaging.SmsException.Companion.ERROR_SENDING_MESSAGE +import com.glooboo.umessage.models.Attachment +import com.glooboo.umessage.models.MessageKey + +@Deprecated("TODO: Move/rewrite messaging config code into the app.") +fun Context.getSendMessageSettings(): Settings { + val settings = Settings() + settings.useSystemSending = true + settings.deliveryReports = config.enableDeliveryReports + val after = config.sendLongAsMmsAfterParts + settings.sendLongAsMms = after != LongTextMms.NEVER + // The library sends as MMS above this many parts; the setting says "from this many parts". + settings.sendLongAsMmsAfter = (after - 1).coerceAtLeast(1) + settings.group = config.sendGroupMessageMMS + return settings +} + +/** Q9: true only when the user chose a number of parts in Settings and [text] has at least that many. */ +fun Context.isLongMmsMessage(text: String, settings: Settings = getSendMessageSettings()): Boolean { + if (!settings.sendLongAsMms) return false + return LongTextMms.shouldSendAsMms(LongTextMms.smsParts(text), settings.sendLongAsMmsAfter + 1) +} + +/** + * What a send handed to the system. [handedOff] is true when every part reached the provider (an SMS that was saved + * and then failed counts, as before). A message with several attachments goes out as one MMS per attachment, so it + * can go out in part: [remainingAttachments] are the ones not handed off, [sentCount] how many were, and [textSent] + * whether the text went with the last one. A retry sends only [remainingAttachments], and the text only when it was + * not [textSent], so nothing the recipient already has is sent twice. + */ +data class SendOutcome( + val handedOff: Boolean, + val remainingAttachments: List = emptyList(), + val sentCount: Int = 0, + val textSent: Boolean = false, +) { + /** Some attachments went out and some did not. */ + val partlySent: Boolean get() = !handedOff && sentCount > 0 +} + +/** Same as [sendMessageDetailed], for callers that only need to know whether everything was handed off. */ +fun Context.sendMessageCompat( + text: String, + addresses: List, + subId: Int?, + attachments: List, + resend: MessageKey? = null, + onFailure: () -> Unit = {}, + onAttachmentHandedOff: (Attachment) -> Unit = {}, +): Boolean = + sendMessageDetailed(text, addresses, subId, attachments, resend, onFailure, onAttachmentHandedOff).handedOff + +/** + * Sends the message using the in-app SmsManager API wrappers if it's an SMS or using android-smsmms for MMS. + * Errors are shown as toasts. [SendOutcome.handedOff] is false when the message never reached the provider (nothing + * was saved, so nothing can be retried from the thread), true otherwise, including sends that were saved and then + * failed; for several attachments see [SendOutcome]. + * [onFailure] runs, after the toast, whenever this call already knows the send failed, whatever it returns; callers + * running in the background use it to tell the user, since a toast there is never seen. Failures reported later by + * the radio go through the sent receivers instead. [onAttachmentHandedOff] is told about each attachment that was queued + * (MS6), so a caller that holds the whole message can drop it and never send it twice on a later Retry. + */ +fun Context.sendMessageDetailed( + text: String, + addresses: List, + subId: Int?, + attachments: List, + resend: MessageKey? = null, + onFailure: () -> Unit = {}, + onAttachmentHandedOff: (Attachment) -> Unit = {}, +): SendOutcome { + val settings = getSendMessageSettings() + activeSendSubscriptionId(subId)?.let { settings.subscriptionId = it } + + val messagingUtils = messagingUtils + val progress = SendProgress() + val isMms = attachments.isNotEmpty() || isLongMmsMessage(text, settings) + || addresses.size > 1 && settings.group + // The failed message being resent is replaced only by a resend of the same type: SMS and MMS ids are separate + // sequences, so handing an SMS id to the MMS path (or the other way round) would touch an unrelated message. + val messageId = resend?.takeIf { it.isMMS == isMms }?.id + if (isMms && messageId != null && attachments.size > 1) { + return resendBundledMms( + MessageKey(messageId, true), text, addresses, attachments, settings, onFailure, onAttachmentHandedOff, + ) + } + if (isMms) { + sendMmsParts(messagingUtils, text, addresses, attachments, settings, messageId, progress, onAttachmentHandedOff) + } else { + sendSmsPart(messagingUtils, text, addresses, settings, messageId, progress) + } + if (progress.failed) { + onFailure() + } + ensureBackgroundThread { + val threadId = getThreadId(addresses.toSet()) + shortcutHelper.reportSendMessageUsage(threadId) + } + return SendOutcome(progress.handedOff, progress.remaining, progress.sentCount, progress.textSent) +} + +/** What one [sendMessageDetailed] call has done so far. */ +private class SendProgress { + var handedOff = true + var failed = false + var sentCount = 0 + var textSent = false + val remaining = ArrayList() + val sentUris = ArrayList() +} + +/** + * Retry of a failed MMS row that holds several attachments (one bundled MMS from another app, or from before each + * picture went out on its own). Each part goes out as its own MMS, so the row cannot stand for all of them: the + * status receivers would delete it when the first part reports, losing the parts that failed. So the parts are sent + * without the row's id, the row is deleted here only when every part was handed off, and the parts that did go out + * are remembered ([ResendLedgers]) so another Retry of the row sends only the rest. + */ +private fun Context.resendBundledMms( + row: MessageKey, + text: String, + addresses: List, + attachments: List, + settings: Settings, + onFailure: () -> Unit, + onAttachmentHandedOff: (Attachment) -> Unit, +): SendOutcome { + val ledger = ResendLedgers.get(this, row) + val todo = ledger.undelivered(attachments) + val progress = SendProgress() + if (todo.isEmpty() && ledger.textSent) { + deleteMessage(row.id, true) + ResendLedgers.forget(this, row) + return SendOutcome(handedOff = true, sentCount = attachments.size, textSent = true) + } + val toSend = ledger.textToSend(text) + sendMmsParts(messagingUtils, toSend, addresses, todo, settings, null, progress, onAttachmentHandedOff) + if (progress.handedOff) { + deleteMessage(row.id, true) + ResendLedgers.forget(this, row) + } else { + ResendLedgers.save(this, row, ledger.plus(progress.sentUris, progress.textSent)) + onFailure() + } + return SendOutcome(progress.handedOff, progress.remaining, progress.sentCount, progress.textSent) +} + +private fun sendMmsParts( + messagingUtils: MessagingUtils, + text: String, + addresses: List, + attachments: List, + settings: Settings, + messageId: Long?, + progress: SendProgress, + onAttachmentHandedOff: (Attachment) -> Unit = {}, +) { + // we send all MMS attachments separately to reduces the chances of hitting provider MMS limit. + if (attachments.isEmpty()) { + progress.handedOff = messagingUtils.sendMmsMessage(text, addresses, null, settings, messageId) + progress.failed = !progress.handedOff + return + } + val lastIndex = attachments.lastIndex + for (i in 0 until lastIndex) { + val attachment = attachments[i] + if (messagingUtils.sendMmsMessage("", addresses, attachment, settings, messageId)) { + progress.sentCount++ + progress.sentUris += attachment.uriString + onAttachmentHandedOff(attachment) + } else { + progress.remaining += attachment + progress.handedOff = false + progress.failed = true + } + } + + val lastAttachment = attachments[lastIndex] + if (messagingUtils.sendMmsMessage(text, addresses, lastAttachment, settings, messageId)) { + progress.sentCount++ + progress.sentUris += lastAttachment.uriString + onAttachmentHandedOff(lastAttachment) + progress.textSent = true + } else { + progress.remaining += lastAttachment + progress.handedOff = false + progress.failed = true + } +} + +private fun Context.sendSmsPart( + messagingUtils: MessagingUtils, + text: String, + addresses: List, + settings: Settings, + messageId: Long?, + progress: SendProgress, +) { + try { + messagingUtils.sendSmsMessage( + text = text, + addresses = addresses.toSet(), + subId = settings.subscriptionId, + requireDeliveryReport = settings.deliveryReports, + messageId = messageId + ) + } catch (e: SmsException) { + // A sending error leaves a failed row in the provider; the other errors leave nothing. + progress.handedOff = e.errorCode == ERROR_SENDING_MESSAGE + progress.failed = true + when (e.errorCode) { + EMPTY_DESTINATION_ADDRESS -> toast(id = R.string.empty_destination_address, length = LENGTH_LONG) + ERROR_PERSISTING_MESSAGE -> toast(id = R.string.unable_to_save_message, length = LENGTH_LONG) + ERROR_SENDING_MESSAGE -> toast( + msg = getString( + R.string.sms_preparation_error_details, + getString(R.string.message_not_sent_short), + e.errorCode + ), + length = LENGTH_LONG + ) + } + } catch (e: Exception) { + progress.handedOff = false + progress.failed = true + Log.e("Messaging", "Sending an SMS failed", e) + toast(id = R.string.message_send_retry_later, length = LENGTH_LONG) + } +} + +/** + * Check if a given "address" is a short code. + * There's not much info available on these special numbers, even the wikipedia page (https://en.wikipedia.org/wiki/Short_code) + * contains outdated information regarding max number of digits. The exact parameters for short codes can vary by country and by carrier. + */ +fun isShortCodeWithLetters(address: String): Boolean { + if (Patterns.EMAIL_ADDRESS.matcher(address).matches()) { + // emails are not short codes: https://github.com/FossifyOrg/Messages/issues/115 + return false + } + + return address.any { it.isLetter() } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/messaging/PartialSend.kt b/app/src/main/kotlin/com/glooboo/umessage/messaging/PartialSend.kt new file mode 100644 index 00000000..fa79b8d8 --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/messaging/PartialSend.kt @@ -0,0 +1,71 @@ +package com.glooboo.umessage.messaging + +import android.content.Context +import androidx.core.content.edit +import com.glooboo.umessage.models.Attachment +import com.glooboo.umessage.models.Message +import com.glooboo.umessage.models.MessageKey + +/** + * This scheduled message as it stands after [outcome] went out in part: only the attachments that were not handed off + * are left, and the text is gone when it already went with the last attachment. Saved back to the held row, so a retry + * sends only what the recipient does not have yet. + */ +fun Message.withUnsentOnly(outcome: SendOutcome): Message = copy( + body = if (outcome.textSent) "" else body, + attachment = attachment?.copy(attachments = ArrayList(outcome.remainingAttachments)), +) + +/** + * What an earlier Retry of one failed row (several attachments) already handed off. The row itself cannot say: its + * parts all stay in it until it is deleted, and it is deleted only once everything went out, so a second Retry after + * a partial one would send the delivered pictures again. [attachmentUris] are the delivered attachments, [textSent] + * whether the text went with the last one. + */ +data class ResendLedger(val attachmentUris: Set = emptySet(), val textSent: Boolean = false) { + + /** The attachments in [all] this ledger has not delivered yet. */ + fun undelivered(all: List): List = all.filter { it.uriString !in attachmentUris } + + /** [text] to send now: nothing when it already went. */ + fun textToSend(text: String): String = if (textSent) "" else text + + /** This ledger plus what [outcome] delivered ([sentUris] are the attachments that were handed off). */ + fun plus(sentUris: List, textNowSent: Boolean) = + ResendLedger(attachmentUris + sentUris, textSent || textNowSent) + + fun encode(): String = (listOf(if (textSent) TEXT_SENT else TEXT_NOT_SENT) + attachmentUris).joinToString("\n") + + companion object { + private const val TEXT_SENT = "1" + private const val TEXT_NOT_SENT = "0" + + fun decode(value: String?): ResendLedger { + val lines = value?.split('\n').orEmpty() + if (lines.isEmpty()) return ResendLedger() + return ResendLedger(lines.drop(1).filter { it.isNotEmpty() }.toSet(), lines[0] == TEXT_SENT) + } + } +} + +/** Keeps a [ResendLedger] per failed provider row, between Retry taps. */ +object ResendLedgers { + private const val PREFS = "mms_resend_ledgers" + private val lock = Any() + + private fun key(row: MessageKey) = "${if (row.isMMS) "mms" else "sms"}:${row.id}" + + private fun prefs(context: Context) = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + + fun get(context: Context, row: MessageKey): ResendLedger = synchronized(lock) { + ResendLedger.decode(prefs(context).getString(key(row), null)) + } + + fun save(context: Context, row: MessageKey, ledger: ResendLedger) = synchronized(lock) { + prefs(context).edit(commit = true) { putString(key(row), ledger.encode()) } + } + + fun forget(context: Context, row: MessageKey) = synchronized(lock) { + prefs(context).edit(commit = true) { remove(key(row)) } + } +} 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 1ff35923..2d077706 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/receivers/ScheduledMessageReceiver.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/receivers/ScheduledMessageReceiver.kt @@ -1,233 +1,252 @@ -package com.glooboo.umessage.receivers - -import android.app.AlarmManager -import android.content.BroadcastReceiver -import android.content.Context -import android.content.Intent -import android.os.Handler -import android.os.Looper -import android.os.PowerManager -import android.provider.Telephony -import androidx.annotation.VisibleForTesting -import androidx.core.app.AlarmManagerCompat -import org.fossify.commons.extensions.showErrorToast -import org.fossify.commons.helpers.ensureBackgroundThread -import com.glooboo.umessage.extensions.conversationsDB -import com.glooboo.umessage.extensions.deleteScheduledMessage -import com.glooboo.umessage.extensions.getAddresses -import com.glooboo.umessage.extensions.getThreadId -import com.glooboo.umessage.extensions.messagesDB -import com.glooboo.umessage.extensions.notificationHelper -import com.glooboo.umessage.helpers.SCHEDULED_MESSAGE_ID -import com.glooboo.umessage.helpers.refreshConversations -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.deleteScheduledRepeat -import com.glooboo.umessage.messaging.deleteScheduledAttachments -import com.glooboo.umessage.messaging.ScheduledSendClaims -import com.glooboo.umessage.messaging.scheduledAttachmentTracker -import com.glooboo.umessage.messaging.sendMessageCompat -import com.glooboo.umessage.models.Message -import kotlin.time.Duration.Companion.minutes - -/** How a late send is counted: more than this after the scheduled time. Inexact alarms are often a few minutes off. */ -internal const val SCHEDULED_LATE_AFTER_MILLIS = 5 * 60_000L - -/** Whole minutes [nowMillis] is past [scheduledMillis], or null when it is not late enough to mention. */ -internal fun lateMinutes(scheduledMillis: Long, nowMillis: Long): Long? { - val late = nowMillis - scheduledMillis - return if (late > SCHEDULED_LATE_AFTER_MILLIS) late / 60_000L else null -} - -class ScheduledMessageReceiver : BroadcastReceiver() { - - override fun onReceive(context: Context, intent: Intent) { - val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager - val wakelock = powerManager.newWakeLock( - PowerManager.PARTIAL_WAKE_LOCK, - "simple.messenger:scheduled.message.receiver" - ) - wakelock.acquire(1.minutes.inWholeMilliseconds) - - val pendingResult = goAsync() - ensureBackgroundThread { - try { - handleIntent(context, intent) - } finally { - try { - if (wakelock.isHeld) wakelock.release() - } catch (_: Exception) { - } - - pendingResult.finish() - } - } - } - - private fun notifyIfLate(context: Context, message: Message, addresses: List) { - lateMinutes(message.millis(), System.currentTimeMillis())?.let { late -> - notifySentLate(context, message, addresses, late) - } - } - - @VisibleForTesting - internal fun handleIntent(context: Context, intent: Intent) { - val messageId = intent.getLongExtra(SCHEDULED_MESSAGE_ID, 0L) - // Looked up by id alone: alarms set by older builds also carry a thread id, which is stale once the message - // moved to a temporary thread. An alarm for a message that was deleted, or one already held after a failed - // send, does nothing: a held message goes out only on the user's Retry. - val message = try { - context.messagesDB.getAllScheduledMessages().firstOrNull { it.id == messageId } - } catch (e: Exception) { - e.printStackTrace() - return - } - if (message == null || message.isHeldScheduled()) return - - // F3: only one sender per message. The alarm, the re-arm on app start or boot and "Send now" can all reach it - // together; the one that claims the row sends, the others find it taken and stop. - val claimed = try { - ScheduledSendClaims.claim(context, messageId) - } catch (e: Exception) { - e.printStackTrace() - return - } - if (!claimed) return - try { - sendClaimed(context, message) - } finally { - ScheduledSendClaims.release(messageId) - } - } - - private fun sendClaimed(context: Context, message: Message) { - val messageId = message.id - val addresses = message.participants.getAddresses() - val attachments = message.attachment?.attachments ?: emptyList() - - var notified = false - fun notifyOnce() { - if (!notified) { - notified = true - notifyNotSent(context, message, addresses) - } - } - - if (!context.canReadScheduledAttachments(message)) { - // 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) - refreshMessages() - return - } - - try { - // Send right here on the worker, inside the goAsync window and wakelock. The scheduled row is the only - // copy of the message, so it is deleted only once the message is in the telephony provider. - val handedOff = context.sendMessageCompat( - message.body, addresses, message.subscriptionId, attachments, onFailure = ::notifyOnce, - onAttachmentHandedOff = context.scheduledAttachmentTracker(message), - ) - if (!handedOff) { - // The scheduled row stays, so the message is not lost, but held: it goes out only on the user's - // Retry, never again by itself. - hold(context, messageId) - refreshMessages() - return - } - - // A failure already has its "not sent" notification; "sent late" is only for messages that went out. - if (!notified) notifyIfLate(context, message, addresses) - - // A repeating message books its next copy only now that this one went out; the copy gets its own - // attachment files, so this runs before they are deleted. A message that failed on the radio is kept as - // failed in its thread, and its repeat pauses with it. - if (!notified) runCatching { context.bookNextRepeat(message) } - context.deleteScheduledRepeat(messageId) - - // delete temporary conversation and message as it's already persisted to the telephony db now - context.deleteScheduledMessage(messageId) - // The attachments were read into the outgoing message, so the private copies are no longer needed. - context.deleteScheduledAttachments(messageId) - context.conversationsDB.deleteThreadId(messageId) - refreshMessages() - refreshConversations() - } catch (e: Exception) { - hold(context, messageId) // no-op if the row was already handed off and deleted - notifyOnce() - context.showErrorToast(e) - } catch (e: Error) { - hold(context, messageId) - notifyOnce() - context.showErrorToast( - e.localizedMessage ?: context.getString(org.fossify.commons.R.string.unknown_error_occurred) - ) - } - } - - /** - * Marks a scheduled message that could not be sent as failed. rescheduleAllScheduledMessages skips failed ones, - * so it is never sent again on app start, boot or a time change, only when the user retries it. - */ - private fun hold(context: Context, messageId: Long) { - runCatching { context.messagesDB.updateScheduledType(messageId, Telephony.Sms.MESSAGE_TYPE_FAILED) } - } - - /** - * RM-27: a message that went out well after its time (no exact alarm access, or the phone was off or dozing) says - * so, and why, instead of leaving the user to wonder. - */ - private fun notifySentLate(context: Context, message: Message, addresses: List, lateMinutes: Long) { - val recipientName = message.participants.joinToString { - it.name.ifBlank { it.phoneNumbers.firstOrNull()?.normalizedNumber.orEmpty() } - } - val threadId = context.getThreadId(addresses.toSet()).takeIf { it != 0L } ?: message.threadId - val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager - val exactAllowed = runCatching { AlarmManagerCompat.canScheduleExactAlarms(alarmManager) }.getOrDefault(true) - runCatching { - Handler(Looper.getMainLooper()).post { - runCatching { - context.notificationHelper.showScheduledSentLateNotification( - recipientName, threadId, lateMinutes, exactAllowed - ) - } - } - } - } - - /** - * A scheduled message fires from an alarm, usually while the app is closed, where a toast is never seen. So a - * failed one always gets a "not sent" notification. It opens the real conversation with [addresses]: a message - * scheduled in a new conversation lives in a temporary thread that is gone once it was handed off. - */ - private fun notifyNotSent( - context: Context, message: Message, addresses: List, attachmentMissing: Boolean = false - ) { - val recipientName = message.participants.joinToString { - it.name.ifBlank { it.phoneNumbers.firstOrNull()?.normalizedNumber.orEmpty() } - } - // A held message stays in its own thread (a temporary one for a new conversation), where Retry is. - val threadId = if (attachmentMissing) { - message.threadId - } else { - context.getThreadId(addresses.toSet()).takeIf { it != 0L } ?: message.threadId - } - val reason = if (attachmentMissing) { - context.getString(R.string.scheduled_attachment_missing, recipientName) - } else { - null - } - runCatching { - Handler(Looper.getMainLooper()).post { - runCatching { - context.notificationHelper.showSendingFailedNotification( - recipientName, threadId, reason, automatic = true - ) - } - } - } - } -} +package com.glooboo.umessage.receivers + +import android.app.AlarmManager +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.os.Handler +import android.os.Looper +import android.os.PowerManager +import android.provider.Telephony +import androidx.annotation.VisibleForTesting +import androidx.core.app.AlarmManagerCompat +import org.fossify.commons.extensions.showErrorToast +import org.fossify.commons.helpers.ensureBackgroundThread +import com.glooboo.umessage.extensions.conversationsDB +import com.glooboo.umessage.extensions.deleteScheduledMessage +import com.glooboo.umessage.extensions.getAddresses +import com.glooboo.umessage.extensions.getThreadId +import com.glooboo.umessage.extensions.messagesDB +import com.glooboo.umessage.extensions.notificationHelper +import com.glooboo.umessage.helpers.SCHEDULED_MESSAGE_ID +import com.glooboo.umessage.helpers.refreshConversations +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.deleteScheduledRepeat +import com.glooboo.umessage.messaging.deleteScheduledAttachments +import com.glooboo.umessage.messaging.ScheduledSendClaims +import com.glooboo.umessage.messaging.scheduledAttachmentTracker +import com.glooboo.umessage.messaging.sendMessageDetailed +import com.glooboo.umessage.messaging.withUnsentOnly +import com.glooboo.umessage.models.Message +import kotlin.time.Duration.Companion.minutes + +/** How a late send is counted: more than this after the scheduled time. Inexact alarms are often a few minutes off. */ +internal const val SCHEDULED_LATE_AFTER_MILLIS = 5 * 60_000L + +/** Whole minutes [nowMillis] is past [scheduledMillis], or null when it is not late enough to mention. */ +internal fun lateMinutes(scheduledMillis: Long, nowMillis: Long): Long? { + val late = nowMillis - scheduledMillis + return if (late > SCHEDULED_LATE_AFTER_MILLIS) late / 60_000L else null +} + +class ScheduledMessageReceiver : BroadcastReceiver() { + + override fun onReceive(context: Context, intent: Intent) { + val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager + val wakelock = powerManager.newWakeLock( + PowerManager.PARTIAL_WAKE_LOCK, + "simple.messenger:scheduled.message.receiver" + ) + wakelock.acquire(1.minutes.inWholeMilliseconds) + + val pendingResult = goAsync() + ensureBackgroundThread { + try { + handleIntent(context, intent) + } finally { + try { + if (wakelock.isHeld) wakelock.release() + } catch (_: Exception) { + } + + pendingResult.finish() + } + } + } + + private fun notifyIfLate(context: Context, message: Message, addresses: List) { + lateMinutes(message.millis(), System.currentTimeMillis())?.let { late -> + notifySentLate(context, message, addresses, late) + } + } + + /** + * Looked up by id alone: alarms set by older builds also carry a thread id, which is stale once the message + * moved to a temporary thread. An alarm for a message that was deleted, or one already held after a failed + * send, does nothing (null): a held message goes out only on the user's Retry. + */ + private fun dueMessage(context: Context, messageId: Long): Message? { + val message = try { + context.messagesDB.getScheduledMessageById(messageId) + } catch (e: Exception) { + e.printStackTrace() + return null + } + return message?.takeUnless { it.isHeldScheduled() } + } + + @VisibleForTesting + internal fun handleIntent(context: Context, intent: Intent) { + val messageId = intent.getLongExtra(SCHEDULED_MESSAGE_ID, 0L) + val message = dueMessage(context, messageId) ?: return + + // F3: only one sender per message. The alarm, the re-arm on app start or boot and "Send now" can all reach it + // together; the one that claims the row sends, the others find it taken and stop. + val claimed = try { + ScheduledSendClaims.claim(context, messageId) + } catch (e: Exception) { + e.printStackTrace() + return + } + if (!claimed) return + try { + sendClaimed(context, message) + } finally { + ScheduledSendClaims.release(messageId) + } + } + + private fun sendClaimed(context: Context, message: Message) { + val messageId = message.id + val addresses = message.participants.getAddresses() + val attachments = message.attachment?.attachments ?: emptyList() + + var notified = false + fun notifyOnce() { + if (!notified) { + notified = true + notifyNotSent(context, message, addresses) + } + } + + if (!context.canReadScheduledAttachments(message)) { + // 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) + refreshMessages() + return + } + + try { + // Send right here on the worker, inside the goAsync window and wakelock. The scheduled row is the only + // copy of the message, so it is deleted only once the message is in the telephony provider. + var failureKnown = false + val outcome = context.sendMessageDetailed( + message.body, addresses, message.subscriptionId, attachments, onFailure = { failureKnown = true }, + onAttachmentHandedOff = context.scheduledAttachmentTracker(message), + ) + val handedOff = outcome.handedOff + if (outcome.partlySent) { + // Some pictures went out and some did not. The held row keeps only what was not sent, so the + // user's Retry does not send the same pictures twice; the notification says so. + runCatching { context.messagesDB.insertOrUpdate(message.withUnsentOnly(outcome)) } + notified = true + notifyNotSent(context, message, addresses, partlySent = true) + } else if (failureKnown) { + notifyOnce() + } + if (!handedOff) { + // The scheduled row stays, so the message is not lost, but held: it goes out only on the user's + // Retry, never again by itself. + hold(context, messageId) + refreshMessages() + return + } + + // A failure already has its "not sent" notification; "sent late" is only for messages that went out. + if (!notified) notifyIfLate(context, message, addresses) + + // A repeating message books its next copy only now that this one went out; the copy gets its own + // attachment files, so this runs before they are deleted. A message that failed on the radio is kept as + // failed in its thread, and its repeat pauses with it. + if (!notified) runCatching { context.bookNextRepeat(message) } + context.deleteScheduledRepeat(messageId) + + // delete temporary conversation and message as it's already persisted to the telephony db now + context.deleteScheduledMessage(messageId) + // The attachments were read into the outgoing message, so the private copies are no longer needed. + context.deleteScheduledAttachments(messageId) + context.conversationsDB.deleteThreadId(messageId) + refreshMessages() + refreshConversations() + } catch (e: Exception) { + hold(context, messageId) // no-op if the row was already handed off and deleted + notifyOnce() + context.showErrorToast(e) + } catch (e: Error) { + hold(context, messageId) + notifyOnce() + context.showErrorToast( + e.localizedMessage ?: context.getString(org.fossify.commons.R.string.unknown_error_occurred) + ) + } + } + + /** + * Marks a scheduled message that could not be sent as failed. rescheduleAllScheduledMessages skips failed ones, + * so it is never sent again on app start, boot or a time change, only when the user retries it. + */ + private fun hold(context: Context, messageId: Long) { + runCatching { context.messagesDB.updateScheduledType(messageId, Telephony.Sms.MESSAGE_TYPE_FAILED) } + } + + /** + * RM-27: a message that went out well after its time (no exact alarm access, or the phone was off or dozing) says + * so, and why, instead of leaving the user to wonder. + */ + private fun notifySentLate(context: Context, message: Message, addresses: List, lateMinutes: Long) { + val recipientName = message.participants.joinToString { + it.name.ifBlank { it.phoneNumbers.firstOrNull()?.normalizedNumber.orEmpty() } + } + val threadId = context.getThreadId(addresses.toSet()).takeIf { it != 0L } ?: message.threadId + val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager + val exactAllowed = runCatching { AlarmManagerCompat.canScheduleExactAlarms(alarmManager) }.getOrDefault(true) + runCatching { + Handler(Looper.getMainLooper()).post { + runCatching { + context.notificationHelper.showScheduledSentLateNotification( + recipientName, threadId, lateMinutes, exactAllowed + ) + } + } + } + } + + /** + * A scheduled message fires from an alarm, usually while the app is closed, where a toast is never seen. So a + * failed one always gets a "not sent" notification. It opens the real conversation with [addresses]: a message + * scheduled in a new conversation lives in a temporary thread that is gone once it was handed off. + */ + private fun notifyNotSent( + context: Context, message: Message, addresses: List, attachmentMissing: Boolean = false, + partlySent: Boolean = false, + ) { + val recipientName = message.participants.joinToString { + it.name.ifBlank { it.phoneNumbers.firstOrNull()?.normalizedNumber.orEmpty() } + } + // A held message stays in its own thread (a temporary one for a new conversation), where Retry is. + val threadId = if (attachmentMissing) { + message.threadId + } else { + context.getThreadId(addresses.toSet()).takeIf { it != 0L } ?: message.threadId + } + val reason = when { + attachmentMissing -> context.getString(R.string.scheduled_attachment_missing, recipientName) + partlySent -> context.getString(R.string.scheduled_partly_sent, recipientName) + else -> null + } + runCatching { + Handler(Looper.getMainLooper()).post { + runCatching { + context.notificationHelper.showSendingFailedNotification( + recipientName, threadId, reason, automatic = true + ) + } + } + } + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/receivers/SmsReceiver.kt b/app/src/main/kotlin/com/glooboo/umessage/receivers/SmsReceiver.kt index 7a0377d6..ba4cea93 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/receivers/SmsReceiver.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/receivers/SmsReceiver.kt @@ -127,6 +127,8 @@ class SmsReceiver : BroadcastReceiver() { subscriptionId = subscriptionId, status = runCatching { last.status }.getOrDefault(0), createdAt = now, + // The carrier's send time; without a usable one (0 or a time in the future) date_sent stays unset. + dateSent = runCatching { last.timestampMillis }.getOrDefault(0L).takeIf { it in 1..now } ?: 0L, ) } 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 4e751bb3..31efe23f 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/receivers/SmsStatusSentReceiver.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/receivers/SmsStatusSentReceiver.kt @@ -1,160 +1,163 @@ -package com.glooboo.umessage.receivers - -import android.app.Activity -import android.content.Context -import android.content.Intent -import android.net.Uri -import android.os.Handler -import android.os.Looper -import android.provider.Telephony.Sms -import androidx.core.net.toUri -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.ProcessLifecycleOwner -import org.fossify.commons.extensions.getMyContactsCursor -import com.glooboo.umessage.extensions.conversationsDB -import com.glooboo.umessage.extensions.getMessageRecipientAddress -import com.glooboo.umessage.extensions.getNameFromAddress -import com.glooboo.umessage.extensions.getThreadId -import com.glooboo.umessage.extensions.messagesDB -import com.glooboo.umessage.extensions.messagingUtils -import com.glooboo.umessage.extensions.notificationHelper -import com.glooboo.umessage.helpers.cancelFailedSendNotification -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.spam.data.ForwardDelivery - -/** Handles updating databases and states when a SMS message is sent. */ -class SmsStatusSentReceiver : SendStatusReceiver() { - - /** What this part's report means for the message row; worked out once, used by both updates. */ - private var outcome: SentParts.Outcome? = null - - override fun updateAndroidDatabase(context: Context, intent: Intent, receiverResultCode: Int) { - val messageUri: Uri? = intent.data - val messagingUtils = context.messagingUtils - - val partSent = receiverResultCode == Activity.RESULT_OK - val partCount = intent.getIntExtra(EXTRA_PART_COUNT, 1) - val outcome = if (messageUri != null) { - SentParts.record(context, messageUri, partSent, partCount) - } else if (partSent) { - SentParts.Outcome.SENT - } else { - SentParts.Outcome.FAILED_FIRST - } - this.outcome = outcome - - when (outcome) { - SentParts.Outcome.SENT -> messagingUtils.updateSmsMessageSendingStatus(messageUri, Sms.MESSAGE_TYPE_SENT) - SentParts.Outcome.FAILED_FIRST, SentParts.Outcome.FAILED_AGAIN -> - messagingUtils.updateSmsMessageSendingStatus(messageUri, Sms.MESSAGE_TYPE_FAILED) - - SentParts.Outcome.STILL_SENDING -> Unit - } - // A copy of a group text failed: the group's summary row stops saying "Sent" (MS1). - if (outcome.isFailure()) { - groupRowUri(intent)?.let { messagingUtils.updateSmsMessageSendingStatus(it, Sms.MESSAGE_TYPE_FAILED) } - } - if (outcome == SentParts.Outcome.FAILED_FIRST) { - messagingUtils.maybeShowErrorToast( - resultCode = receiverResultCode, - errorCode = intent.getIntExtra(EXTRA_ERROR_CODE, NO_ERROR_CODE), - noDefault = intent.getBooleanExtra(EXTRA_NO_DEFAULT, false) - ) - } - } - - override fun updateAppDatabase(context: Context, intent: Intent, receiverResultCode: Int) { - val messageId = messageIdOf(intent.data) ?: return - // Already on the worker thread, inside the goAsync window. - val type = when (outcome) { - SentParts.Outcome.SENT -> Sms.MESSAGE_TYPE_SENT - SentParts.Outcome.FAILED_FIRST, SentParts.Outcome.FAILED_AGAIN -> Sms.MESSAGE_TYPE_FAILED - SentParts.Outcome.STILL_SENDING, null -> return - } - - context.messagesDB.updateType(messageId, isMMS = false, type = type) - val groupUri = groupRowUri(intent) - if (outcome.isFailure()) { - groupUri?.let { messageIdOf(it) }?.let { context.messagesDB.updateType(it, isMMS = false, type = type) } - } - refreshMessages() - refreshConversations() - // Once per message, however many of its parts failed. - if (outcome == SentParts.Outcome.FAILED_FIRST) { - runCatching { logFailedForward(context, intent) } - showSendingFailedNotification(context, messageId, groupUri) - } else if (outcome == SentParts.Outcome.SENT) { - // A retry that went out: the old "Message not sent" notification has done its job (MS3). - runCatching { cancelFailedNotification(context, messageId, groupUri) } - } - } - - private fun SentParts.Outcome?.isFailure() = - this == SentParts.Outcome.FAILED_FIRST || this == SentParts.Outcome.FAILED_AGAIN - - private fun groupRowUri(intent: Intent): Uri? = intent.getStringExtra(EXTRA_GROUP_ROW_URI)?.toUri() - - /** The chat the notification is about: a group text's own chat, else the chat of the recipient's copy. */ - private fun threadOf(context: Context, messageId: Long, groupUri: Uri?): Long? { - if (groupUri == null) return context.getThreadId(context.getMessageRecipientAddress(messageId)) - return context.contentResolver.query(groupUri, arrayOf(Sms.THREAD_ID), null, null, null)?.use { - if (it.moveToFirst()) it.getLong(0) else null - } - } - - private fun cancelFailedNotification(context: Context, messageId: Long, groupUri: Uri?) { - if (!context.hasFailedSendNotification()) return - threadOf(context, messageId, groupUri)?.takeIf { it > 0 }?.let { context.cancelFailedSendNotification(it) } - } - - /** - * A failed forward is marked failed in the forward log, found by the log row id the sent report carries (never by - * its number), and goes in the decision log too (with its target, never its text). - */ - private fun logFailedForward(context: Context, intent: Intent) { - val uri = intent.data ?: return - val logId = intent.getLongExtra(EXTRA_FORWARD_LOG_ID, NO_LOG_ID).takeIf { it > 0 } - context.contentResolver.query(uri, arrayOf(Sms.ADDRESS, Sms.BODY), null, null, null)?.use { cursor -> - if (!cursor.moveToFirst()) return - ForwardDelivery.onRadioFailure( - context, - address = cursor.getString(0).orEmpty(), - body = cursor.getString(1), - subscriptionId = intent.getIntExtra(EXTRA_SUB_ID, -1), - logId = logId, - ) - } - } - - private fun showSendingFailedNotification(context: Context, messageId: Long, groupUri: Uri?) { - // Reading the current state is fine off the main thread; only changing it is not. - if (ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) { - return - } - // A group text: one notice for the group's chat (not one per person, each opening that person's own chat). - val threadId = threadOf(context, messageId, groupUri) ?: return - val recipientName = if (groupUri != null) { - runCatching { context.conversationsDB.getConversationWithThreadId(threadId)?.title }.getOrNull().orEmpty() - } else { - val address = context.getMessageRecipientAddress(messageId) - context.getMyContactsCursor(favoritesOnly = false, withPhoneNumbersOnly = true).use { - context.getNameFromAddress(address, it) - } - } - Handler(Looper.getMainLooper()).post { - context.notificationHelper.showSendingFailedNotification(recipientName, threadId) - } - } - - companion object { - /** Long extra of the sent report: the forward-log row of a forward (H2). */ - const val EXTRA_FORWARD_LOG_ID = "com.glooboo.spamless.extra.FORWARD_LOG_ID" - - /** String extra of the sent report: the summary row of a group text sent as separate copies (MS1). */ - const val EXTRA_GROUP_ROW_URI = "com.glooboo.spamless.extra.GROUP_ROW_URI" - private const val NO_LOG_ID = -1L - } -} +package com.glooboo.umessage.receivers + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Handler +import android.os.Looper +import android.provider.Telephony.Sms +import androidx.core.net.toUri +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.ProcessLifecycleOwner +import org.fossify.commons.extensions.getMyContactsCursor +import com.glooboo.umessage.extensions.conversationsDB +import com.glooboo.umessage.extensions.getMessageRecipientAddress +import com.glooboo.umessage.extensions.getNameFromAddress +import com.glooboo.umessage.extensions.getThreadId +import com.glooboo.umessage.extensions.messagesDB +import com.glooboo.umessage.extensions.messagingUtils +import com.glooboo.umessage.extensions.notificationHelper +import com.glooboo.umessage.helpers.cancelFailedSendNotification +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.spam.data.ForwardDelivery + +/** Handles updating databases and states when a SMS message is sent. */ +class SmsStatusSentReceiver : SendStatusReceiver() { + + /** What this part's report means for the message row; worked out once, used by both updates. */ + private var outcome: SentParts.Outcome? = null + + override fun updateAndroidDatabase(context: Context, intent: Intent, receiverResultCode: Int) { + val messageUri: Uri? = intent.data + val messagingUtils = context.messagingUtils + + val partSent = receiverResultCode == Activity.RESULT_OK + val partCount = intent.getIntExtra(EXTRA_PART_COUNT, 1) + val outcome = if (messageUri != null) { + SentParts.record(context, messageUri, partSent, partCount) + } else if (partSent) { + SentParts.Outcome.SENT + } else { + SentParts.Outcome.FAILED_FIRST + } + this.outcome = outcome + + when (outcome) { + SentParts.Outcome.SENT -> messagingUtils.updateSmsMessageSendingStatus(messageUri, Sms.MESSAGE_TYPE_SENT) + SentParts.Outcome.FAILED_FIRST, SentParts.Outcome.FAILED_AGAIN -> + messagingUtils.updateSmsMessageSendingStatus(messageUri, Sms.MESSAGE_TYPE_FAILED) + + SentParts.Outcome.STILL_SENDING -> Unit + } + // A copy of a group text failed: the group's summary row stops saying "Sent" (MS1). + if (outcome.isFailure()) { + groupRowUri(intent)?.let { messagingUtils.updateSmsMessageSendingStatus(it, Sms.MESSAGE_TYPE_FAILED) } + } + if (outcome == SentParts.Outcome.FAILED_FIRST) { + messagingUtils.maybeShowErrorToast( + resultCode = receiverResultCode, + errorCode = intent.getIntExtra(EXTRA_ERROR_CODE, NO_ERROR_CODE), + noDefault = intent.getBooleanExtra(EXTRA_NO_DEFAULT, false) + ) + } + } + + override fun updateAppDatabase(context: Context, intent: Intent, receiverResultCode: Int) { + val messageId = messageIdOf(intent.data) ?: return + // Already on the worker thread, inside the goAsync window. + val type = when (outcome) { + SentParts.Outcome.SENT -> Sms.MESSAGE_TYPE_SENT + SentParts.Outcome.FAILED_FIRST, SentParts.Outcome.FAILED_AGAIN -> Sms.MESSAGE_TYPE_FAILED + SentParts.Outcome.STILL_SENDING, null -> return + } + + context.messagesDB.updateType(messageId, isMMS = false, type = type) + val groupUri = groupRowUri(intent) + if (outcome.isFailure()) { + groupUri?.let { messageIdOf(it) }?.let { context.messagesDB.updateType(it, isMMS = false, type = type) } + } + refreshMessages() + refreshConversations() + // Once per message, however many of its parts failed. + if (outcome == SentParts.Outcome.FAILED_FIRST) { + runCatching { logFailedForward(context, intent) } + showSendingFailedNotification(context, messageId, groupUri) + } else if (outcome == SentParts.Outcome.SENT) { + // A retry that went out: the old "Message not sent" notification has done its job (MS3). + runCatching { cancelFailedNotification(context, messageId, groupUri) } + } + } + + private fun SentParts.Outcome?.isFailure() = + this == SentParts.Outcome.FAILED_FIRST || this == SentParts.Outcome.FAILED_AGAIN + + private fun groupRowUri(intent: Intent): Uri? = intent.getStringExtra(EXTRA_GROUP_ROW_URI)?.toUri() + + /** The chat the notification is about: a group text's own chat, else the chat of the recipient's copy. */ + private fun threadOf(context: Context, messageId: Long, groupUri: Uri?): Long? { + if (groupUri == null) return context.getThreadId(context.getMessageRecipientAddress(messageId)) + return context.contentResolver.query(groupUri, arrayOf(Sms.THREAD_ID), null, null, null)?.use { + if (it.moveToFirst()) it.getLong(0) else null + } + } + + private fun cancelFailedNotification(context: Context, messageId: Long, groupUri: Uri?) { + if (!context.hasFailedSendNotification()) return + threadOf(context, messageId, groupUri)?.takeIf { it > 0 }?.let { context.cancelFailedSendNotification(it) } + } + + /** + * A failed forward is marked failed in the forward log, found by the log row id the sent report carries (never by + * its number), and goes in the decision log too (with its target, never its text). + */ + private fun logFailedForward(context: Context, intent: Intent) { + val uri = intent.data ?: return + val logId = intent.getLongExtra(EXTRA_FORWARD_LOG_ID, NO_LOG_ID).takeIf { it > 0 } + context.contentResolver.query(uri, arrayOf(Sms.ADDRESS, Sms.BODY), null, null, null)?.use { cursor -> + if (!cursor.moveToFirst()) return + ForwardDelivery.onRadioFailure( + context, + address = cursor.getString(0).orEmpty(), + body = cursor.getString(1), + subscriptionId = intent.getIntExtra(EXTRA_SUB_ID, -1), + logId = logId, + ) + } + } + + private fun showSendingFailedNotification(context: Context, messageId: Long, groupUri: Uri?) { + // Reading the current state is fine off the main thread; only changing it is not. + if (ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) { + return + } + // A group text: one notice for the group's chat (not one per person, each opening that person's own chat). + val threadId = threadOf(context, messageId, groupUri) ?: return + val recipientName = if (groupUri != null) { + runCatching { context.conversationsDB.getConversationWithThreadId(threadId)?.title }.getOrNull().orEmpty() + } else { + val address = context.getMessageRecipientAddress(messageId) + // Without contacts permission the lookup can throw: the notification still goes out, with the plain number. + runCatching { + context.getMyContactsCursor(favoritesOnly = false, withPhoneNumbersOnly = true).use { + context.getNameFromAddress(address, it) + } + }.getOrDefault(address) + } + Handler(Looper.getMainLooper()).post { + context.notificationHelper.showSendingFailedNotification(recipientName, threadId) + } + } + + companion object { + /** Long extra of the sent report: the forward-log row of a forward (H2). */ + const val EXTRA_FORWARD_LOG_ID = "com.glooboo.spamless.extra.FORWARD_LOG_ID" + + /** String extra of the sent report: the summary row of a group text sent as separate copies (MS1). */ + const val EXTRA_GROUP_ROW_URI = "com.glooboo.spamless.extra.GROUP_ROW_URI" + private const val NO_LOG_ID = -1L + } +} 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 678efa64..38a64631 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/TextNormalizer.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/TextNormalizer.kt @@ -91,7 +91,7 @@ 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 { - val joined = SPACED_OUT.replace(lower(text)) { it.value.replace(SPACED_SEPARATOR, "") } + val joined = SPACED_OUT.replace(lower(unfancy(text))) { it.value.replace(SPACED_SEPARATOR, "") } return WORD.replace(joined) { match -> val word = match.value val hasLetter = word.any { it.isLetter() } @@ -106,6 +106,25 @@ object TextNormalizer { } } + /** + * Combining and invisible marks that spam puts between letters (kept out of [fold], which search turns into + * SQL): diacritics, strike-through and underline overlays. + */ + private val COMBINING_MARKS = Regex( + "[\\u0300-\\u036F\\u20D0-\\u20FF\\u200E\\u200F\\u202A-\\u202E\\u2061-\\u2064" + + "\\u2066-\\u2069\\uFE00-\\uFE0F]" + ) + + /** + * "Fancy text" read as plain text, for [deobfuscate] only: compatibility normalization (fullwidth letters, + * mathematical bold or script letters and digits become ASCII), then the combining marks above are dropped. + */ + private fun unfancy(text: String): String { + if (text.all { it.code < 0x80 }) return text + val normalized = java.text.Normalizer.normalize(text, java.text.Normalizer.Form.NFKC) + return COMBINING_MARKS.replace(normalized, "") + } + /** Whether [text] contains [keyword] once both are folded, ignoring case in every script. */ fun containsFolded(text: String, keyword: String): Boolean { val wanted = fold(keyword) diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/data/DigestNotifier.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/data/DigestNotifier.kt index fdc08a5d..8fcf8b9c 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/data/DigestNotifier.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/data/DigestNotifier.kt @@ -24,7 +24,7 @@ object DigestNotifier { fun postIfDue(context: Context, now: Long): Boolean { val prefs = context.cleanupPrefs if (!prefs.digestOn || !prefs.claimDigest(now)) return false - val blocked = SpamDatabase.getInstance(context).spamDao().getAllBlocked() + val blocked = SpamDatabase.getInstance(context).spamDao().getBlockedBetween(now - WeeklyDigest.WEEK_MS, now) val digest = WeeklyDigest.compute(blocked, now) if (digest.held == 0) return false show(context, digest) 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 3980ac3e..65cc5ec8 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 @@ -2,6 +2,7 @@ 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 @@ -29,6 +30,8 @@ data class PendingSmsEntity( 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 { @@ -120,6 +123,7 @@ object IncomingSmsProcessor { subscriptionId = message.subscriptionId, status = message.status, notify = notify, + dateSent = message.dateSent, ) } catch (first: Throwable) { insertRaw(context, message, first) @@ -140,6 +144,7 @@ object IncomingSmsProcessor { 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) diff --git a/app/src/main/kotlin/com/glooboo/umessage/spam/data/SmsDelivery.kt b/app/src/main/kotlin/com/glooboo/umessage/spam/data/SmsDelivery.kt index c1a33fcf..7661da21 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/spam/data/SmsDelivery.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/spam/data/SmsDelivery.kt @@ -41,6 +41,7 @@ fun Context.insertSmsOrThrow( threadId: Long, type: Int, subscriptionId: Int, + dateSent: Long = 0L, ): Long { val id = insertNewSMS( address = address, @@ -50,7 +51,8 @@ fun Context.insertSmsOrThrow( read = read, threadId = threadId, type = type, - subscriptionId = subscriptionId + subscriptionId = subscriptionId, + dateSent = dateSent, ) if (id <= 0L) throw SmsInsertException("Telephony provider did not store the SMS") return id @@ -74,6 +76,7 @@ fun Context.deliverIncomingSms( threadId: Long = getThreadId(address), read: Int = 0, type: Int = Telephony.Sms.MESSAGE_TYPE_INBOX, + dateSent: Long = 0L, ): Long { val context = this val photoUri = runCatching { SimpleContactsHelper(context).getPhotoUriFromPhoneNumber(address) }.getOrDefault("") @@ -91,7 +94,8 @@ fun Context.deliverIncomingSms( read = read, threadId = threadId, type = type, - subscriptionId = subscriptionId + subscriptionId = subscriptionId, + dateSent = dateSent, ) // From here on the SMS is safe in the provider. Nothing below may throw. 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 17cf456c..4c942bb7 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 @@ -52,6 +52,9 @@ interface SpamDao { @Query("SELECT * FROM blocked_messages") fun getAllBlocked(): List + @Query("SELECT * FROM blocked_messages WHERE receivedAt BETWEEN :from AND :to") + fun getBlockedBetween(from: Long, to: Long): List + @Query("SELECT * FROM blocked_messages WHERE id = :id") fun getBlocked(id: Long): BlockedMessageEntity? 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 11d41df5..84f8fcb7 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 @@ -94,14 +94,27 @@ abstract class SpamDatabase : RoomDatabase() { /** Schema version that added the unread flag of held messages. */ private const val VERSION_UNREAD = 6 + /** + * Incoming SMS keep the carrier's send time (core-3): a new column on the pending queue. Rows already queued + * have no send time, which is 0 (unknown). + */ + private val MIGRATION_6_7 = object : Migration(VERSION_UNREAD, VERSION_DATE_SENT) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE `pending_sms` ADD COLUMN `dateSent` INTEGER NOT NULL DEFAULT 0") + } + } + + /** Schema version that added the carrier send time to the pending queue. */ + private const val VERSION_DATE_SENT = 7 + internal const val DATABASE_NAME = "spamless.db" /** Must equal the `version` in [Database] above. */ - internal const val VERSION = VERSION_UNREAD + internal const val VERSION = VERSION_DATE_SENT /** 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) + arrayOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7) 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/ui/components/TimeFormat.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/components/TimeFormat.kt index bf3119a7..70e134c0 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/components/TimeFormat.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/components/TimeFormat.kt @@ -3,9 +3,12 @@ package com.glooboo.umessage.ui.components import android.content.Context import android.text.format.DateUtils import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import com.glooboo.umessage.R +import kotlinx.coroutines.delay import java.time.Instant import java.time.ZoneId import java.time.temporal.ChronoUnit @@ -64,5 +67,22 @@ fun formatClockTime(context: Context, millis: Long): String = @Composable fun rememberTimeLabel(timestamp: Long): String { val context = LocalContext.current - return remember(timestamp) { formatListTimeStyled(context, timestamp) } + // Only the "Now" and "N min" labels go stale in minutes; a minute ticker re-keys them, other buckets stay put. + val minuteTick = rememberMinuteTick(timestamp) + return remember(timestamp, minuteTick) { formatListTimeStyled(context, timestamp) } +} + +/** Ticks once a minute while [timestamp] is still a "Now" or "N min" label, else stays 0 and never recomposes. */ +@Composable +private fun rememberMinuteTick(timestamp: Long): Int { + val tick = remember(timestamp) { mutableIntStateOf(0) } + LaunchedEffect(timestamp) { + while ( + timeBucket(timestamp, System.currentTimeMillis()).let { it == TimeBucket.NOW || it == TimeBucket.MINUTES } + ) { + delay(MINUTE_MS) + tick.intValue++ + } + } + return tick.intValue } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationRowCache.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationRowCache.kt new file mode 100644 index 00000000..1849f82c --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/conversations/ConversationRowCache.kt @@ -0,0 +1,55 @@ +package com.glooboo.umessage.ui.conversations + +import java.util.Locale + +/** + * Everything a list row shows or is derived from, for one chat. While a chat's input equals the one its cached row was + * built from, the row is reused, so a selection tap or an unrelated change does not redo the regex, classification and + * formatting of every chat. [minute] makes relative dates refresh as time passes; [otpFresh] expires the code chip. + */ +internal data class RowInput( + val threadId: Long, + val title: String, + val snippet: String, + val date: Int, + val read: Boolean, + val unreadCount: Int, + val photoUri: String, + val isGroup: Boolean, + val phoneNumber: String, + val scheduled: Boolean, + val customTitle: Boolean, + val draft: String, + val simSlot: Int?, + val simName: String, + val pinned: Boolean, + val muted: Boolean, + val otpFresh: Boolean, + val hasNotes: Boolean, + val minute: Long, + val locale: Locale, +) + +/** Remembers one derived value per key together with the input it was derived from. Not thread safe. */ +internal class RowCache { + private val entries = HashMap>() + + /** The cached value when [input] equals the cached input of [key]; else [compute]d, and remembered. */ + fun get(key: K, input: I, compute: () -> V): V { + lookup(key, input)?.let { return it } + return compute().also { store(key, input, it) } + } + + fun lookup(key: K, input: I): V? = entries[key]?.takeIf { it.first == input }?.second + + fun store(key: K, input: I, value: V) { + entries[key] = input to value + } + + /** Forgets every key not in [keys], so deleted chats do not pile up. */ + fun retainOnly(keys: Set) { + entries.keys.retainAll(keys) + } + + val size: Int get() = entries.size +} 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 5b1a1a96..547f3589 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 @@ -31,6 +31,8 @@ data class ConversationRow( val simName: String = "", /** The chat has at least one private note on a message: a small note mark shows in the row. */ val hasNotes: Boolean = false, + /** A saved contact (a name, not a bare number): the block swipe asks first. Never set for a group. */ + val isContact: Boolean = false, ) /** What the contextual selection bar may offer, derived from the current selection. */ @@ -72,6 +74,8 @@ data class ConversationsUiState( val hiddenChats: Int = 0, /** B06: the hidden chats are unlocked, so they show in [rows]. */ val hiddenUnlocked: Boolean = false, + /** Chats waiting for the user to confirm their deletion; 0 shows no dialog. */ + val confirmDeleteCount: Int = 0, ) { val selecting: Boolean get() = selected.isNotEmpty() } @@ -106,6 +110,8 @@ class ConversationsCallbacks( val onMarkRead: (Boolean) -> Unit = {}, val onArchiveSelected: () -> Unit = {}, val onDeleteSelected: () -> Unit = {}, + val onConfirmDelete: () -> Unit = {}, + val onCancelDelete: () -> Unit = {}, val onArchiveOne: (Long) -> Unit = {}, val onDeleteOne: (Long) -> Unit = {}, val onBlockSelected: () -> 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 eb47b3d9..4a92fc9a 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 @@ -1,592 +1,660 @@ -package com.glooboo.umessage.ui.conversations - -import androidx.compose.animation.AnimatedVisibility -import androidx.compose.animation.EnterTransition -import androidx.compose.animation.ExitTransition -import androidx.compose.animation.scaleIn -import androidx.compose.animation.scaleOut -import androidx.compose.animation.core.tween -import androidx.compose.animation.fadeIn -import androidx.compose.animation.fadeOut -import androidx.compose.foundation.background -import androidx.compose.foundation.gestures.detectVerticalDragGestures -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.BoxScope -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.WindowInsets -import androidx.compose.foundation.layout.asPaddingValues -import androidx.compose.foundation.layout.navigationBars -import androidx.compose.foundation.layout.navigationBarsPadding -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.offset -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.LazyListState -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.ExtendedFloatingActionButton -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarDuration -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.SnackbarResult -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.derivedStateOf -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.setValue -import androidx.compose.runtime.snapshotFlow -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.ui.layout.onSizeChanged -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.res.pluralStringResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.clearAndSetSemantics -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.onClick -import androidx.compose.ui.semantics.role -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.unit.IntOffset -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.lifecycle.compose.LifecycleResumeEffect -import androidx.compose.runtime.withFrameNanos -import com.glooboo.umessage.ui.icons.Symbols -import kotlinx.coroutines.coroutineScope -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch -import com.glooboo.umessage.R -import com.glooboo.umessage.ui.components.EmptyState -import com.glooboo.umessage.ui.components.fabListBottomPadding -import com.glooboo.umessage.ui.components.readableOn -import com.glooboo.umessage.ui.main.InboxFilter -import com.glooboo.umessage.ui.main.InboxFilterPolicy -import com.glooboo.umessage.ui.main.filterTile -import com.glooboo.umessage.ui.components.LoadingState -import com.glooboo.umessage.ui.components.rememberReduceMotion -import kotlin.math.roundToInt - -/** Connects the ViewModel to the stateless [ConversationsScreen] and turns its events into snackbars. */ -@Composable -fun ConversationsRoute( - viewModel: ConversationsViewModel, - callbacks: ConversationsCallbacks, - modifier: Modifier = Modifier, - /** CL-13, N11: show only the conversations that belong to this filter. */ - filter: InboxFilter = InboxFilter.All, - /** I28: the conversations the Unknown, Starred, Images and Links filters keep. */ - filterThreads: Set = emptySet(), - /** B10: cards and filter chips shown above the rows; they scroll away with the list. */ - header: (@Composable () -> Unit)? = null, - /** B06: the "Hidden chats" line under the last row. */ - footer: (@Composable () -> Unit)? = null, -) { - val fullState by viewModel.state.collectAsStateWithLifecycle() - val state = remember(fullState, filter, filterThreads) { - if (filter == InboxFilter.All) { - fullState - } else { - fullState.copy(rows = InboxFilterPolicy.filterRows(fullState.rows, filter, filterThreads)) - } - } - val snackbar = remember { SnackbarHostState() } - - val undoLabel = stringResource(R.string.convlist_undo) - val failedText = stringResource(R.string.convlist_action_failed) - val resources = LocalContext.current.resources - - LaunchedEffect(viewModel) { - // After a rotation the previous snackbar was cancelled unanswered; offer its Undo again. - viewModel.replayPendingUndo() - // One coroutine per event so a new snackbar can replace the one still showing at once. - coroutineScope { - viewModel.events.collect { event -> - snackbar.currentSnackbarData?.dismiss() - launch { showEvent(event, snackbar, callbacks, resources, undoLabel, failedText) } - } - } - } - - ConversationsScreen( - state = state, - snackbarHostState = snackbar, - callbacks = callbacks, - modifier = modifier, - filter = filter, - header = header, - footer = footer, - ) -} - -private suspend fun showEvent( - event: ConversationsEvent, - snackbar: SnackbarHostState, - callbacks: ConversationsCallbacks, - resources: android.content.res.Resources, - undoLabel: String, - failedText: String, -) { - when (event) { - is ConversationsEvent.Deleted -> { - val result = snackbar.showSnackbar( - message = resources.getQuantityString(R.plurals.convlist_deleted, event.count, event.count), - actionLabel = undoLabel, - withDismissAction = false, - duration = SnackbarDuration.Short, - ) - if (result == SnackbarResult.ActionPerformed) { - callbacks.onUndoDelete(event.token) - } else { - callbacks.onCommitDelete(event.token) - } - } - is ConversationsEvent.Archived -> { - val result = snackbar.showSnackbar( - // P3-02: says where the chat went; Undo stays the only action. - message = resources.getQuantityString(R.plurals.w2b1_archived_find, event.count, event.count), - actionLabel = undoLabel, - duration = SnackbarDuration.Short, - ) - if (result == SnackbarResult.ActionPerformed) callbacks.onUndoArchive(event.token) - } - is ConversationsEvent.Blocked -> { - val result = snackbar.showSnackbar( - message = resources.getQuantityString(R.plurals.convlist_blocked_done, event.count, event.count), - actionLabel = undoLabel, - duration = SnackbarDuration.Long, - ) - if (result == SnackbarResult.ActionPerformed) { - callbacks.onUndoReportSpam(event.token) - } else { - callbacks.onCommitReportSpam(event.token) - } - } - is ConversationsEvent.ReportedSpam -> { - val text = if (event.archived) { - R.plurals.convlist_reported_spam_archived - } else { - R.plurals.convlist_reported_spam - } - val result = snackbar.showSnackbar( - message = resources.getQuantityString(text, event.count, event.count), - actionLabel = undoLabel, - duration = SnackbarDuration.Long, - ) - if (result == SnackbarResult.ActionPerformed) { - callbacks.onUndoReportSpam(event.token) - } else { - callbacks.onCommitReportSpam(event.token) - } - } - ConversationsEvent.Failed -> snackbar.showSnackbar(failedText) - } -} - -@Composable -fun ConversationsScreen( - state: ConversationsUiState, - snackbarHostState: SnackbarHostState, - callbacks: ConversationsCallbacks, - modifier: Modifier = Modifier, - /** The rows are filtered: an empty list then says so instead of offering a first chat. */ - filter: InboxFilter = InboxFilter.All, - /** Shown above the rows and scrolled with them; above the empty or loading state when there are no rows. */ - header: (@Composable () -> Unit)? = null, - footer: (@Composable () -> Unit)? = null, -) { - val listState = rememberLazyListState() - val reduceMotion = rememberReduceMotion() - - Scaffold( - modifier = modifier, - containerColor = MaterialTheme.colorScheme.background, - contentWindowInsets = WindowInsets(0, 0, 0, 0), - snackbarHost = { SnackbarHost(snackbarHostState, Modifier.navigationBarsPadding()) }, - floatingActionButton = { - // Google Messages hides the FAB while conversations are selected. - NewConversationFab( - visible = !state.selecting, - listState = listState, - reduceMotion = reduceMotion, - onNewConversation = callbacks.onNewConversation, - ) - }, - ) { padding -> - val showList = !(state.loading || state.importing) && state.rows.isNotEmpty() - Column(Modifier.fillMaxSize().padding(padding)) { - if (!showList) header?.invoke() - // With no rows to scroll, the line sits under the header, so hidden chats stay reachable. - if (!showList) footer?.invoke() - Box(Modifier.weight(1f).fillMaxWidth()) { - ConversationsContent(state, filter, listState, callbacks, reduceMotion, header, footer) - } - } - } -} - -/** What the list area shows: the loading state, an empty state for the filter, or the rows. */ -@Composable -private fun BoxScope.ConversationsContent( - state: ConversationsUiState, - filter: InboxFilter, - listState: LazyListState, - callbacks: ConversationsCallbacks, - reduceMotion: Boolean, - header: (@Composable () -> Unit)?, - footer: (@Composable () -> Unit)?, -) { - val tile = filterTile(filter) - when { - state.loading || state.importing -> LoadingState(label = stringResource(R.string.convlist_loading)) - state.rows.isEmpty() && tile != null -> EmptyState( - icon = tile.icon, - title = stringResource(tile.emptyTitleRes), - body = stringResource(tile.emptyBodyRes), - modifier = Modifier.align(Alignment.Center), - ) - state.rows.isEmpty() && filter == InboxFilter.Label -> EmptyState( - icon = Symbols.Tag, - title = stringResource(R.string.i29_empty_title), - body = stringResource(R.string.i29_empty_body), - modifier = Modifier.align(Alignment.Center), - ) - state.rows.isEmpty() && filter == InboxFilter.Sim -> EmptyState( - icon = Symbols.SimCard, - title = stringResource(R.string.search_page_sim_empty_title), - body = stringResource(R.string.search_page_sim_empty_body), - modifier = Modifier.align(Alignment.Center), - ) - state.rows.isEmpty() -> EmptyConversations(callbacks) - else -> ConversationList(state, listState, callbacks, reduceMotion, header, footer) - } -} - -/** Which way the list moved since the last position the FAB acted on. */ -internal enum class FabScrollDirection { UP, DOWN, NONE } - -/** - * The direction from [fromIndex]/[fromOffset] to [toIndex]/[toOffset]. A change of first visible item decides it at - * once; within one item, moves shorter than [jitterPx] are ignored so a resting finger or a fling's last pixel does not - * flip the FAB back and forth. - */ -internal fun fabScrollDirection( - fromIndex: Int, - fromOffset: Int, - toIndex: Int, - toOffset: Int, - jitterPx: Int, -): FabScrollDirection = - when { - toIndex > fromIndex -> FabScrollDirection.DOWN - toIndex < fromIndex -> FabScrollDirection.UP - toOffset - fromOffset > jitterPx -> FabScrollDirection.DOWN - fromOffset - toOffset > jitterPx -> FabScrollDirection.UP - else -> FabScrollDirection.NONE - } - -/** Shorter moves than this do not change the FAB (jitter). */ -private val FabScrollJitter = 8.dp - -/** - * Owner note R3: the labelled "Start chat" FAB at the top of the list, as before, without the outline - * UMessageFab draws on light pages. It shrinks to the icon while the list scrolls down (CL-01), so it does not cover - * the dates and badges of the rows beneath it while reading, and grows back as soon as the list scrolls up. - */ -@Composable -private fun NewConversationFab( - visible: Boolean, - listState: LazyListState, - reduceMotion: Boolean, - onNewConversation: () -> Unit, -) { - // At the very top it is always expanded. Derived from the list's position alone, so it is right again on the first - // frame after a tab switch, a filter change or new rows. - val atTop by remember(listState) { - derivedStateOf { - !listState.canScrollBackward || - (listState.firstVisibleItemIndex == 0 && listState.firstVisibleItemScrollOffset < 24) - } - } - // Elsewhere it follows the last scroll direction: expanded after scrolling up, folded after scrolling down. - var scrolledUp by remember(listState) { mutableStateOf(false) } - val jitterPx = with(LocalDensity.current) { FabScrollJitter.roundToPx() } - LaunchedEffect(listState, jitterPx) { - var anchorIndex = listState.firstVisibleItemIndex - var anchorOffset = listState.firstVisibleItemScrollOffset - snapshotFlow { listState.firstVisibleItemIndex to listState.firstVisibleItemScrollOffset } - .collect { (index, offset) -> - val direction = fabScrollDirection(anchorIndex, anchorOffset, index, offset, jitterPx) - if (direction != FabScrollDirection.NONE) { - scrolledUp = direction == FabScrollDirection.UP - anchorIndex = index - anchorOffset = offset - } - } - } - val expanded = atTop || scrolledUp - val fabLabel = stringResource(R.string.search_page_start_chat) - AnimatedVisibility( - visible = visible, - enter = if (reduceMotion) EnterTransition.None else scaleIn() + fadeIn(), - exit = if (reduceMotion) ExitTransition.None else scaleOut() + fadeOut(), - ) { - ExtendedFloatingActionButton( - onClick = onNewConversation, - expanded = expanded, - icon = { Icon(Symbols.ChatBubble, contentDescription = null) }, - text = { Text(fabLabel) }, - containerColor = MaterialTheme.colorScheme.primaryContainer, - // U34: checked against the fill, so the label reads on any theme (a mid-blue fill took white at under - // 4.5:1). - contentColor = readableOn( - MaterialTheme.colorScheme.primaryContainer, - MaterialTheme.colorScheme.onPrimaryContainer, - ), - // The label leaves composition when the FAB collapses, so the accessible name is set here. - modifier = Modifier - .navigationBarsPadding() - .heightIn(min = 56.dp) - .clearAndSetSemantics { - contentDescription = fabLabel - role = Role.Button - onClick { onNewConversation(); true } - }, - ) - } -} - -@Composable -private fun EmptyConversations(callbacks: ConversationsCallbacks) { - Column(Modifier.fillMaxSize()) { - Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) { - EmptyState( - icon = Symbols.ChatBubble, - title = stringResource(R.string.convlist_empty_title), - body = stringResource(R.string.convlist_empty_body), - action = { - TextButton(onClick = callbacks.onNewConversation, modifier = Modifier.heightIn(min = 48.dp)) { - Text(stringResource(R.string.convlist_start_conversation)) - } - }, - ) - } - } -} - -@Composable -private fun ConversationList( - state: ConversationsUiState, - listState: LazyListState, - callbacks: ConversationsCallbacks, - reduceMotion: Boolean, - header: (@Composable () -> Unit)? = null, - footer: (@Composable () -> Unit)? = null, -) { - // Keep the newest thread in view: when the user was at the top and a different thread becomes the first row - // (a message was sent or received), LazyColumn would keep the old first row anchored and push the new one off - // screen. - // Both values are saveable: a rotation recreates the activity, and with plain `remember` the effect saw a "new" - // top row and a reset "at top" flag on the first frame, so it threw the restored scroll position away. - var userWasAtTop by rememberSaveable { mutableStateOf(true) } - var lastTopThreadId by rememberSaveable { mutableStateOf(null) } - LaunchedEffect(listState) { - snapshotFlow { - Triple( - listState.isScrollInProgress, - listState.firstVisibleItemIndex, - listState.firstVisibleItemScrollOffset, - ) - }.collect { (scrolling, index, offset) -> - if (scrolling) userWasAtTop = index == 0 && offset < 24 - } - } - val topThreadId = state.rows.firstOrNull()?.threadId - LaunchedEffect(topThreadId) { - val previous = lastTopThreadId - lastTopThreadId = topThreadId - if (shouldReturnToTop(previous, topThreadId, userWasAtTop)) { - // B15: let the list lay out the new rows first; it anchors on the old first row, then we move to the top. - withFrameNanos { } - listState.scrollToItem(0) - } - } - // B15: coming back from a thread, the rows may have changed while the list was hidden; a user who was at the top - // sees the top row again instead of the list anchored one row down. - val scope = rememberCoroutineScope() - LifecycleResumeEffect(listState) { - if (userWasAtTop && listState.firstVisibleItemIndex != 0 && !listState.isScrollInProgress) { - scope.launch { listState.scrollToItem(0) } - } - onPauseOrDispose { } - } - // CL-12: right archives, left blocks the sender (both undoable); a group chat has no single sender to block. - val archiveLabel = stringResource(R.string.convlist_archive) - val blockLabel = stringResource(R.string.w2b1_swipe_block) - val archiveAction = remember(archiveLabel, callbacks) { - SwipeAction(Symbols.Archive, archiveLabel) { callbacks.onArchiveOne(it) } - } - val blockAction = remember(blockLabel, callbacks) { - SwipeAction(Symbols.Block, blockLabel, destructive = true) { callbacks.onBlockOne(it) } - } - val rowLabels = rememberRowLabels() - // U55: only the newest fresh code gets its Copy chip, so the rows keep an even height. - val codeChipThread = remember(state.rows) { newestCodeThread(state.rows) } - Box(Modifier.fillMaxSize()) { - LazyColumn( - state = listState, - modifier = Modifier.fillMaxSize(), - // Room so the last row can scroll clear of the FAB. The tab bar below already covers the navigation bar. - contentPadding = PaddingValues(bottom = fabListBottomPadding()), - ) { - // Never zero height: LazyColumn skips an empty first item, so at the top it reported the first conversation - // as item 1 and anchored on it. A card appearing in the header then grew above the screen edge, and the - // FAB, reading "not at item 0", stayed folded at the top of the list (owner notes A and B). - header?.let { content -> - item(key = "header", contentType = "header") { - Box(Modifier.fillMaxWidth().heightIn(min = HeaderMinHeight)) { content() } - } - } - items(items = state.rows, key = { it.threadId }, contentType = { "conversation" }) { row -> - SwipeableConversation( - row = row, - selected = row.threadId in state.selected, - selecting = state.selecting, - canArchive = state.archiveAvailable, - callbacks = callbacks, - startToEnd = archiveAction.takeIf { state.archiveAvailable }, - endToStart = blockAction.takeIf { !row.isGroup && row.phoneNumber.isNotBlank() }, - labels = rowLabels[row.threadId].orEmpty(), - showCodeChip = row.threadId == codeChipThread, - modifier = if (reduceMotion) { - Modifier.animateItem(fadeInSpec = null, placementSpec = null, fadeOutSpec = null) - } else { - Modifier.animateItem() - }, - ) - } - footer?.let { content -> item(key = "footer", contentType = "footer") { content() } } - } - FastScrollThumb(listState = listState, rows = state.rows, modifier = Modifier.align(Alignment.CenterEnd)) - } -} - - -/** The header item's floor; one dp of background keeps it a real, measurable first item. */ -private val HeaderMinHeight = 1.dp - -// ---- Fast scroll --------------------------------------------------------------------------------------- - -private const val FAST_SCROLL_MIN_ROWS = 40 -private const val THUMB_HIDE_DELAY_MS = 1200L - -/** - * Draggable thumb for long lists (hundreds of threads). It only reads list state, so it costs nothing per - * row, and shows the title initial of the row it points at while dragging. - */ -@Composable -private fun FastScrollThumb(listState: LazyListState, rows: List, modifier: Modifier = Modifier) { - if (rows.size < FAST_SCROLL_MIN_ROWS) return - val scope = rememberCoroutineScope() - val density = LocalDensity.current - var trackHeight by remember { mutableIntStateOf(0) } - var dragging by remember { mutableStateOf(false) } - var recentlyScrolled by remember { mutableStateOf(false) } - val scrolling = listState.isScrollInProgress - LaunchedEffect(scrolling, dragging) { - if (scrolling || dragging) { - recentlyScrolled = true - } else { - delay(THUMB_HIDE_DELAY_MS) - recentlyScrolled = false - } - } - val fraction by remember(rows.size) { - derivedStateOf { - val total = listState.layoutInfo.totalItemsCount - if (total <= 1) 0f else listState.firstVisibleItemIndex.toFloat() / (total - 1).coerceAtLeast(1) - } - } - val thumbHeight = 56.dp - val thumbPx = with(density) { thumbHeight.toPx() } - val color = MaterialTheme.colorScheme.primary - val label = stringResource(R.string.convlist_scroll_handle) - var dragFraction by remember { mutableFloatStateOf(0f) } - - Box( - modifier = modifier - .fillMaxHeight() - .width(48.dp) - .onSizeChanged { trackHeight = it.height }, - ) { - AnimatedVisibility( - visible = recentlyScrolled, - enter = fadeIn(tween(120)), - exit = fadeOut(tween(300)), - ) { - val travel = (trackHeight - thumbPx).coerceAtLeast(0f) - Box( - modifier = Modifier - .offset { IntOffset(0, (travel * fraction).roundToInt()) } - .size(width = 48.dp, height = thumbHeight) - .semantics { contentDescription = label } - .pointerInput(rows.size, trackHeight) { - detectVerticalDragGestures( - onDragStart = { - dragging = true - dragFraction = fraction - }, - onDragEnd = { dragging = false }, - onDragCancel = { dragging = false }, - ) { change, dragAmount -> - change.consume() - val usable = (trackHeight - thumbPx).coerceAtLeast(1f) - dragFraction = (dragFraction + dragAmount / usable).coerceIn(0f, 1f) - val total = listState.layoutInfo.totalItemsCount - scope.launch { listState.scrollToItem(((total - 1) * dragFraction).roundToInt()) } - } - }, - contentAlignment = Alignment.CenterEnd, - ) { - Box( - modifier = Modifier - .padding(end = 4.dp) - .size(width = 6.dp, height = 40.dp) - .clip(RoundedCornerShape(3.dp)) - .background(if (dragging) color else color.copy(alpha = 0.55f)), - ) - } - } - } -} - -/** - * B15: whether the list jumps back to its first row: the newest conversation changed (a message was sent or received, - * or the list was just shown) while the user was at the top. A user scrolled down stays where they are. - */ -internal fun shouldReturnToTop(previousTop: Long?, currentTop: Long?, userWasAtTop: Boolean): Boolean = - userWasAtTop && currentTop != null && previousTop != currentTop +@file:Suppress("TooManyFunctions") // The list screen is one set of small composables. + +package com.glooboo.umessage.ui.conversations + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.EnterTransition +import androidx.compose.animation.ExitTransition +import androidx.compose.animation.scaleIn +import androidx.compose.animation.scaleOut +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.background +import androidx.compose.foundation.gestures.detectVerticalDragGestures +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.asPaddingValues +import androidx.compose.foundation.layout.navigationBars +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ExtendedFloatingActionButton +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarDuration +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarResult +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.runtime.snapshotFlow +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.onClick +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.compose.runtime.withFrameNanos +import com.glooboo.umessage.ui.icons.Symbols +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import com.glooboo.umessage.R +import com.glooboo.umessage.ui.components.EmptyState +import com.glooboo.umessage.ui.components.fabListBottomPadding +import com.glooboo.umessage.ui.components.readableOn +import com.glooboo.umessage.ui.main.InboxFilter +import com.glooboo.umessage.ui.main.InboxFilterPolicy +import com.glooboo.umessage.ui.main.filterTile +import com.glooboo.umessage.ui.components.LoadingState +import com.glooboo.umessage.ui.components.rememberReduceMotion +import kotlin.math.roundToInt + +/** Connects the ViewModel to the stateless [ConversationsScreen] and turns its events into snackbars. */ +@Composable +fun ConversationsRoute( + viewModel: ConversationsViewModel, + callbacks: ConversationsCallbacks, + modifier: Modifier = Modifier, + /** CL-13, N11: show only the conversations that belong to this filter. */ + filter: InboxFilter = InboxFilter.All, + /** I28: the conversations the Unknown, Starred, Images and Links filters keep. */ + filterThreads: Set = emptySet(), + /** B10: cards and filter chips shown above the rows; they scroll away with the list. */ + header: (@Composable () -> Unit)? = null, + /** B06: the "Hidden chats" line under the last row. */ + footer: (@Composable () -> Unit)? = null, +) { + val fullState by viewModel.state.collectAsStateWithLifecycle() + val state = remember(fullState, filter, filterThreads) { + if (filter == InboxFilter.All) { + fullState + } else { + fullState.copy(rows = InboxFilterPolicy.filterRows(fullState.rows, filter, filterThreads)) + } + } + val snackbar = remember { SnackbarHostState() } + + val undoLabel = stringResource(R.string.convlist_undo) + val failedText = stringResource(R.string.convlist_action_failed) + val resources = LocalContext.current.resources + + LaunchedEffect(viewModel) { + // After a rotation the previous snackbar was cancelled unanswered; offer its Undo again. + viewModel.replayPendingUndo() + // One coroutine per event so a new snackbar can replace the one still showing at once. + coroutineScope { + viewModel.events.collect { event -> + snackbar.currentSnackbarData?.dismiss() + launch { showEvent(event, snackbar, callbacks, resources, undoLabel, failedText) } + } + } + } + + ConversationsScreen( + state = state, + snackbarHostState = snackbar, + callbacks = callbacks, + modifier = modifier, + filter = filter, + header = header, + footer = footer, + ) +} + +private suspend fun showEvent( + event: ConversationsEvent, + snackbar: SnackbarHostState, + callbacks: ConversationsCallbacks, + resources: android.content.res.Resources, + undoLabel: String, + failedText: String, +) { + when (event) { + is ConversationsEvent.Deleted -> { + val result = snackbar.showSnackbar( + message = resources.getQuantityString(R.plurals.convlist_deleted, event.count, event.count), + actionLabel = undoLabel, + withDismissAction = false, + duration = SnackbarDuration.Long, + ) + if (result == SnackbarResult.ActionPerformed) { + callbacks.onUndoDelete(event.token) + } else { + callbacks.onCommitDelete(event.token) + } + } + is ConversationsEvent.Archived -> { + val result = snackbar.showSnackbar( + // P3-02: says where the chat went; Undo stays the only action. + message = resources.getQuantityString(R.plurals.w2b1_archived_find, event.count, event.count), + actionLabel = undoLabel, + duration = SnackbarDuration.Short, + ) + if (result == SnackbarResult.ActionPerformed) callbacks.onUndoArchive(event.token) + } + is ConversationsEvent.Blocked -> { + val result = snackbar.showSnackbar( + message = resources.getQuantityString(R.plurals.convlist_blocked_done, event.count, event.count), + actionLabel = undoLabel, + duration = SnackbarDuration.Long, + ) + if (result == SnackbarResult.ActionPerformed) { + callbacks.onUndoReportSpam(event.token) + } else { + callbacks.onCommitReportSpam(event.token) + } + } + is ConversationsEvent.ReportedSpam -> { + val text = if (event.archived) { + R.plurals.convlist_reported_spam_archived + } else { + R.plurals.convlist_reported_spam + } + val result = snackbar.showSnackbar( + message = resources.getQuantityString(text, event.count, event.count), + actionLabel = undoLabel, + duration = SnackbarDuration.Long, + ) + if (result == SnackbarResult.ActionPerformed) { + callbacks.onUndoReportSpam(event.token) + } else { + callbacks.onCommitReportSpam(event.token) + } + } + ConversationsEvent.Failed -> snackbar.showSnackbar(failedText) + } +} + +@Composable +fun ConversationsScreen( + state: ConversationsUiState, + snackbarHostState: SnackbarHostState, + callbacks: ConversationsCallbacks, + modifier: Modifier = Modifier, + /** The rows are filtered: an empty list then says so instead of offering a first chat. */ + filter: InboxFilter = InboxFilter.All, + /** Shown above the rows and scrolled with them; above the empty or loading state when there are no rows. */ + header: (@Composable () -> Unit)? = null, + footer: (@Composable () -> Unit)? = null, +) { + val listState = rememberLazyListState() + val reduceMotion = rememberReduceMotion() + + Scaffold( + modifier = modifier, + containerColor = MaterialTheme.colorScheme.background, + contentWindowInsets = WindowInsets(0, 0, 0, 0), + snackbarHost = { SnackbarHost(snackbarHostState, Modifier.navigationBarsPadding()) }, + floatingActionButton = { + // Google Messages hides the FAB while conversations are selected. + NewConversationFab( + visible = !state.selecting, + listState = listState, + reduceMotion = reduceMotion, + onNewConversation = callbacks.onNewConversation, + ) + }, + ) { padding -> + val showList = !(state.loading || state.importing) && state.rows.isNotEmpty() + Column(Modifier.fillMaxSize().padding(padding)) { + if (!showList) header?.invoke() + // With no rows to scroll, the line sits under the header, so hidden chats stay reachable. + if (!showList) footer?.invoke() + Box(Modifier.weight(1f).fillMaxWidth()) { + ConversationsContent(state, filter, listState, callbacks, reduceMotion, header, footer) + } + } + } + if (state.confirmDeleteCount > 0) { + // main-1: whole chats are deleted for good once the Undo window closes, so ask first and show how many. + AlertDialog( + onDismissRequest = callbacks.onCancelDelete, + title = { + Text( + pluralStringResource( + R.plurals.convlist_delete_confirm_title, state.confirmDeleteCount, state.confirmDeleteCount, + ), + ) + }, + text = { + Text(pluralStringResource(R.plurals.convlist_delete_confirm_message, state.confirmDeleteCount)) + }, + confirmButton = { + TextButton(onClick = callbacks.onConfirmDelete) { Text(stringResource(R.string.convlist_delete)) } + }, + dismissButton = { + TextButton(onClick = callbacks.onCancelDelete) { Text(stringResource(R.string.convlist_cancel)) } + }, + ) + } +} + +/** What the list area shows: the loading state, an empty state for the filter, or the rows. */ +@Composable +private fun BoxScope.ConversationsContent( + state: ConversationsUiState, + filter: InboxFilter, + listState: LazyListState, + callbacks: ConversationsCallbacks, + reduceMotion: Boolean, + header: (@Composable () -> Unit)?, + footer: (@Composable () -> Unit)?, +) { + val tile = filterTile(filter) + when { + state.loading || state.importing -> LoadingState(label = stringResource(R.string.convlist_loading)) + state.rows.isEmpty() && tile != null -> EmptyState( + icon = tile.icon, + title = stringResource(tile.emptyTitleRes), + body = stringResource(tile.emptyBodyRes), + modifier = Modifier.align(Alignment.Center), + ) + state.rows.isEmpty() && filter == InboxFilter.Label -> EmptyState( + icon = Symbols.Tag, + title = stringResource(R.string.i29_empty_title), + body = stringResource(R.string.i29_empty_body), + modifier = Modifier.align(Alignment.Center), + ) + state.rows.isEmpty() && filter == InboxFilter.Sim -> EmptyState( + icon = Symbols.SimCard, + title = stringResource(R.string.search_page_sim_empty_title), + body = stringResource(R.string.search_page_sim_empty_body), + modifier = Modifier.align(Alignment.Center), + ) + state.rows.isEmpty() -> EmptyConversations(callbacks) + else -> ConversationList(state, listState, callbacks, reduceMotion, header, footer) + } +} + +/** Which way the list moved since the last position the FAB acted on. */ +internal enum class FabScrollDirection { UP, DOWN, NONE } + +/** + * The direction from [fromIndex]/[fromOffset] to [toIndex]/[toOffset]. A change of first visible item decides it at + * once; within one item, moves shorter than [jitterPx] are ignored so a resting finger or a fling's last pixel does not + * flip the FAB back and forth. + */ +internal fun fabScrollDirection( + fromIndex: Int, + fromOffset: Int, + toIndex: Int, + toOffset: Int, + jitterPx: Int, +): FabScrollDirection = + when { + toIndex > fromIndex -> FabScrollDirection.DOWN + toIndex < fromIndex -> FabScrollDirection.UP + toOffset - fromOffset > jitterPx -> FabScrollDirection.DOWN + fromOffset - toOffset > jitterPx -> FabScrollDirection.UP + else -> FabScrollDirection.NONE + } + +/** Shorter moves than this do not change the FAB (jitter). */ +private val FabScrollJitter = 8.dp + +/** + * Owner note R3: the labelled "Start chat" FAB at the top of the list, as before, without the outline + * UMessageFab draws on light pages. It shrinks to the icon while the list scrolls down (CL-01), so it does not cover + * the dates and badges of the rows beneath it while reading, and grows back as soon as the list scrolls up. + */ +@Composable +private fun NewConversationFab( + visible: Boolean, + listState: LazyListState, + reduceMotion: Boolean, + onNewConversation: () -> Unit, +) { + // At the very top it is always expanded. Derived from the list's position alone, so it is right again on the first + // frame after a tab switch, a filter change or new rows. + val atTop by remember(listState) { + derivedStateOf { + !listState.canScrollBackward || + (listState.firstVisibleItemIndex == 0 && listState.firstVisibleItemScrollOffset < 24) + } + } + // Elsewhere it follows the last scroll direction: expanded after scrolling up, folded after scrolling down. + var scrolledUp by remember(listState) { mutableStateOf(false) } + val jitterPx = with(LocalDensity.current) { FabScrollJitter.roundToPx() } + LaunchedEffect(listState, jitterPx) { + var anchorIndex = listState.firstVisibleItemIndex + var anchorOffset = listState.firstVisibleItemScrollOffset + snapshotFlow { listState.firstVisibleItemIndex to listState.firstVisibleItemScrollOffset } + .collect { (index, offset) -> + val direction = fabScrollDirection(anchorIndex, anchorOffset, index, offset, jitterPx) + if (direction != FabScrollDirection.NONE) { + scrolledUp = direction == FabScrollDirection.UP + anchorIndex = index + anchorOffset = offset + } + } + } + val expanded = atTop || scrolledUp + val fabLabel = stringResource(R.string.search_page_start_chat) + AnimatedVisibility( + visible = visible, + enter = if (reduceMotion) EnterTransition.None else scaleIn() + fadeIn(), + exit = if (reduceMotion) ExitTransition.None else scaleOut() + fadeOut(), + ) { + ExtendedFloatingActionButton( + onClick = onNewConversation, + expanded = expanded, + icon = { Icon(Symbols.ChatBubble, contentDescription = null) }, + text = { Text(fabLabel) }, + containerColor = MaterialTheme.colorScheme.primaryContainer, + // U34: checked against the fill, so the label reads on any theme (a mid-blue fill took white at under + // 4.5:1). + contentColor = readableOn( + MaterialTheme.colorScheme.primaryContainer, + MaterialTheme.colorScheme.onPrimaryContainer, + ), + // The label leaves composition when the FAB collapses, so the accessible name is set here. + modifier = Modifier + .navigationBarsPadding() + .heightIn(min = 56.dp) + .clearAndSetSemantics { + contentDescription = fabLabel + role = Role.Button + onClick { onNewConversation(); true } + }, + ) + } +} + +@Composable +private fun EmptyConversations(callbacks: ConversationsCallbacks) { + Column(Modifier.fillMaxSize()) { + Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) { + EmptyState( + icon = Symbols.ChatBubble, + title = stringResource(R.string.convlist_empty_title), + body = stringResource(R.string.convlist_empty_body), + action = { + TextButton(onClick = callbacks.onNewConversation, modifier = Modifier.heightIn(min = 48.dp)) { + Text(stringResource(R.string.convlist_start_conversation)) + } + }, + ) + } + } +} + +@Composable +private fun KeepNewestInView(topThreadId: Long?, listState: LazyListState) { + // Keep the newest thread in view: when the user was at the top and a different thread becomes the first row + // (a message was sent or received), LazyColumn would keep the old first row anchored and push the new one off + // screen. + // Both values are saveable: a rotation recreates the activity, and with plain `remember` the effect saw a "new" + // top row and a reset "at top" flag on the first frame, so it threw the restored scroll position away. + var userWasAtTop by rememberSaveable { mutableStateOf(true) } + var lastTopThreadId by rememberSaveable { mutableStateOf(null) } + LaunchedEffect(listState) { + snapshotFlow { + Triple( + listState.isScrollInProgress, + listState.firstVisibleItemIndex, + listState.firstVisibleItemScrollOffset, + ) + }.collect { (scrolling, index, offset) -> + if (scrolling) userWasAtTop = index == 0 && offset < 24 + } + } + LaunchedEffect(topThreadId) { + val previous = lastTopThreadId + lastTopThreadId = topThreadId + if (shouldReturnToTop(previous, topThreadId, userWasAtTop)) { + // B15: let the list lay out the new rows first; it anchors on the old first row, then we move to the top. + withFrameNanos { } + listState.scrollToItem(0) + } + } + // B15: coming back from a thread, the rows may have changed while the list was hidden; a user who was at the top + // sees the top row again instead of the list anchored one row down. + val scope = rememberCoroutineScope() + LifecycleResumeEffect(listState) { + if (userWasAtTop && listState.firstVisibleItemIndex != 0 && !listState.isScrollInProgress) { + scope.launch { listState.scrollToItem(0) } + } + onPauseOrDispose { } + } +} + +@Composable +private fun BlockContactDialog(title: String, onDismiss: () -> Unit, onConfirm: () -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.convlist_block_title)) }, + text = { Text(stringResource(R.string.convlist_block_contact_message, title)) }, + confirmButton = { + TextButton(onClick = onConfirm) { Text(stringResource(R.string.convlist_block_confirm)) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(stringResource(R.string.convlist_cancel)) + } + }, + ) +} + +@Composable +private fun ConversationList( + state: ConversationsUiState, + listState: LazyListState, + callbacks: ConversationsCallbacks, + reduceMotion: Boolean, + header: (@Composable () -> Unit)? = null, + footer: (@Composable () -> Unit)? = null, +) { + KeepNewestInView(state.rows.firstOrNull()?.threadId, listState) + // CL-12: right archives, left blocks the sender (both undoable); a group chat has no single sender to block. + val archiveLabel = stringResource(R.string.convlist_archive) + val blockLabel = stringResource(R.string.w2b1_swipe_block) + val archiveAction = remember(archiveLabel, callbacks) { + SwipeAction(Symbols.Archive, archiveLabel) { callbacks.onArchiveOne(it) } + } + // main-17: a saved contact is blocked only after a confirmation; an unknown number is blocked at once (with Undo). + var confirmBlockThread by rememberSaveable { mutableStateOf(null) } + val currentRows by rememberUpdatedState(state.rows) + val blockAction = remember(blockLabel, callbacks) { + SwipeAction(Symbols.Block, blockLabel, destructive = true) { threadId -> + if (currentRows.firstOrNull { it.threadId == threadId }?.isContact == true) { + confirmBlockThread = threadId + } else { + callbacks.onBlockOne(threadId) + } + } + } + val blockRow = confirmBlockThread?.let { id -> state.rows.firstOrNull { it.threadId == id } } + if (confirmBlockThread != null && blockRow == null) confirmBlockThread = null + if (blockRow != null) { + BlockContactDialog( + title = blockRow.title, + onDismiss = { confirmBlockThread = null }, + onConfirm = { + confirmBlockThread = null + callbacks.onBlockOne(blockRow.threadId) + }, + ) + } + val rowLabels = rememberRowLabels() + // U55: only the newest fresh code gets its Copy chip, so the rows keep an even height. + val codeChipThread = remember(state.rows) { newestCodeThread(state.rows) } + Box(Modifier.fillMaxSize()) { + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize(), + // Room so the last row can scroll clear of the FAB. The tab bar below already covers the navigation bar. + contentPadding = PaddingValues(bottom = fabListBottomPadding()), + ) { + // Never zero height: LazyColumn skips an empty first item, so at the top it reported the first conversation + // as item 1 and anchored on it. A card appearing in the header then grew above the screen edge, and the + // FAB, reading "not at item 0", stayed folded at the top of the list (owner notes A and B). + header?.let { content -> + item(key = "header", contentType = "header") { + Box(Modifier.fillMaxWidth().heightIn(min = HeaderMinHeight)) { content() } + } + } + items(items = state.rows, key = { it.threadId }, contentType = { "conversation" }) { row -> + SwipeableConversation( + row = row, + selected = row.threadId in state.selected, + selecting = state.selecting, + canArchive = state.archiveAvailable, + callbacks = callbacks, + startToEnd = archiveAction.takeIf { state.archiveAvailable }, + endToStart = blockAction.takeIf { !row.isGroup && row.phoneNumber.isNotBlank() }, + labels = rowLabels[row.threadId].orEmpty(), + showCodeChip = row.threadId == codeChipThread, + modifier = if (reduceMotion) { + Modifier.animateItem(fadeInSpec = null, placementSpec = null, fadeOutSpec = null) + } else { + Modifier.animateItem() + }, + ) + } + footer?.let { content -> item(key = "footer", contentType = "footer") { content() } } + } + FastScrollThumb(listState = listState, rows = state.rows, modifier = Modifier.align(Alignment.CenterEnd)) + } +} + + +/** The header item's floor; one dp of background keeps it a real, measurable first item. */ +private val HeaderMinHeight = 1.dp + +// ---- Fast scroll --------------------------------------------------------------------------------------- + +private const val FAST_SCROLL_MIN_ROWS = 40 +private const val THUMB_HIDE_DELAY_MS = 1200L + +/** + * Draggable thumb for long lists (hundreds of threads). It only reads list state, so it costs nothing per + * row, and shows the title initial of the row it points at while dragging. + */ +@Composable +private fun FastScrollThumb(listState: LazyListState, rows: List, modifier: Modifier = Modifier) { + if (rows.size < FAST_SCROLL_MIN_ROWS) return + val scope = rememberCoroutineScope() + val density = LocalDensity.current + var trackHeight by remember { mutableIntStateOf(0) } + var dragging by remember { mutableStateOf(false) } + var recentlyScrolled by remember { mutableStateOf(false) } + val scrolling = listState.isScrollInProgress + LaunchedEffect(scrolling, dragging) { + if (scrolling || dragging) { + recentlyScrolled = true + } else { + delay(THUMB_HIDE_DELAY_MS) + recentlyScrolled = false + } + } + val fraction by remember(rows.size) { + derivedStateOf { + val total = listState.layoutInfo.totalItemsCount + if (total <= 1) 0f else listState.firstVisibleItemIndex.toFloat() / (total - 1).coerceAtLeast(1) + } + } + val thumbHeight = 56.dp + val thumbPx = with(density) { thumbHeight.toPx() } + val color = MaterialTheme.colorScheme.primary + val label = stringResource(R.string.convlist_scroll_handle) + var dragFraction by remember { mutableFloatStateOf(0f) } + + Box( + modifier = modifier + .fillMaxHeight() + .width(48.dp) + .onSizeChanged { trackHeight = it.height }, + ) { + AnimatedVisibility( + visible = recentlyScrolled, + enter = fadeIn(tween(120)), + exit = fadeOut(tween(300)), + ) { + val travel = (trackHeight - thumbPx).coerceAtLeast(0f) + Box( + modifier = Modifier + .offset { IntOffset(0, (travel * fraction).roundToInt()) } + .size(width = 48.dp, height = thumbHeight) + .semantics { contentDescription = label } + .pointerInput(rows.size, trackHeight) { + detectVerticalDragGestures( + onDragStart = { + dragging = true + dragFraction = fraction + }, + onDragEnd = { dragging = false }, + onDragCancel = { dragging = false }, + ) { change, dragAmount -> + change.consume() + val usable = (trackHeight - thumbPx).coerceAtLeast(1f) + dragFraction = (dragFraction + dragAmount / usable).coerceIn(0f, 1f) + val total = listState.layoutInfo.totalItemsCount + scope.launch { listState.scrollToItem(((total - 1) * dragFraction).roundToInt()) } + } + }, + contentAlignment = Alignment.CenterEnd, + ) { + Box( + modifier = Modifier + .padding(end = 4.dp) + .size(width = 6.dp, height = 40.dp) + .clip(RoundedCornerShape(3.dp)) + .background(if (dragging) color else color.copy(alpha = 0.55f)), + ) + } + } + } +} + +/** + * B15: whether the list jumps back to its first row: the newest conversation changed (a message was sent or received, + * or the list was just shown) while the user was at the top. A user scrolled down stays where they are. + */ +internal fun shouldReturnToTop(previousTop: Long?, currentTop: Long?, userWasAtTop: Boolean): Boolean = + userWasAtTop && currentTop != null && previousTop != currentTop 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 a44c4d09..bbb6a94b 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 @@ -79,6 +79,12 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic private var hasData = false private var importing = false + /** Chats the user asked to delete and has not confirmed yet; the screen shows a dialog while this is set. */ + private var confirmDeleteIds: List = emptyList() + + /** Derived rows, reused while nothing a row shows has changed (main-3). Touched only by [build]. */ + private val rowCache = RowCache() + /** Thread ids hidden from the list while a delete or archive is pending or in flight. */ private val hidden = HashSet() private val pendingDeletes = LinkedHashMap>() @@ -105,8 +111,8 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic viewModelScope.launch { for (ignored in rebuild) { val snapshot = Snapshot( - source, drafts, sims, selected, hidden.toSet(), newBlockedCount, - archiveAvailable, hasData, importing, + source, drafts, sims, selected, hidden.toSet(), + Status(newBlockedCount, archiveAvailable, hasData, importing, confirmDeleteIds.size), ) _state.value = withContext(Dispatchers.Default) { build(snapshot) } } @@ -371,14 +377,35 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic } } - fun deleteSelected() = delete(selected.toList()) + /** The Delete button: asks the screen to confirm first; nothing is hidden or deleted until [confirmDelete]. */ + fun deleteSelected() = requestDelete(selected.toList()) + + fun deleteOne(threadId: Long) = requestDelete(listOf(threadId)) - fun deleteOne(threadId: Long) = delete(listOf(threadId)) + private fun requestDelete(threadIds: List) { + if (threadIds.isEmpty()) return + confirmDeleteIds = threadIds + requestRebuild() + } + + /** The user said yes in the confirmation dialog. Undo stays available from the snackbar. */ + fun confirmDelete() { + val ids = confirmDeleteIds + confirmDeleteIds = emptyList() + delete(ids) + requestRebuild() + } + + fun cancelDelete() { + if (confirmDeleteIds.isEmpty()) return + confirmDeleteIds = emptyList() + requestRebuild() + } /** * Hides the conversations and deletes them for real once the undo window closes ([commitDelete]). - * Like the classic list, whole-thread deletion is permanent; the recycle bin setting only governs - * deleting single messages inside a thread. + * Like the classic list, whole-thread deletion is permanent (the recycle bin holds single messages, not + * whole chats, so it cannot make this undoable); the confirmation dialog and the long Undo window guard it. */ private fun delete(threadIds: List) { if (threadIds.isEmpty()) return @@ -401,16 +428,17 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic fun commitDelete(token: Long) { val ids = pendingDeletes.remove(token) ?: return viewModelScope.launch(Dispatchers.IO + NonCancellable) { - runCatching { - ids.forEach { + val deleted = ids.filter { + runCatching { app.deleteConversation(it) app.notificationManager.cancel(it.hashCode()) - } + }.isSuccess } withContext(Dispatchers.Main) { - source = source.filterNot { it.threadId in ids } + source = source.filterNot { it.threadId in deleted } hidden -= ids.toSet() requestRebuild() + if (deleted.size < ids.size) _events.trySend(ConversationsEvent.Failed) } refreshConversations() } @@ -600,10 +628,16 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic val sims: List, val selected: Set, val hidden: Set, + val status: Status, + ) + + /** The flags and counts of a [Snapshot] that are not lists. */ + private class Status( val newBlockedCount: Int, val archiveAvailable: Boolean, val hasData: Boolean, val importing: Boolean, + val confirmDeleteCount: Int, ) /** A group, a renamed thread, or a title that is a name rather than the number: someone the user knows. */ @@ -615,8 +649,10 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic val config = app.config val withNotes = noteThreads val pinned = config.pinnedConversations - val manager = app.notificationManager val customNotifications = config.customNotifications + // One binder call per rebuild instead of one per chat with its own notification channel. + val mutedChannels = if (customNotifications.isEmpty()) emptySet() else mutedChannelIds(app.notificationManager) + val locale = app.uiLocale val mutePrefs = MutePrefs.get(app) // B06: chats hidden behind the app lock stay out of the list until they are unlocked. val hiddenChats = HiddenChats.get(app) @@ -638,52 +674,67 @@ 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 hasDraft = !draft.isNullOrEmpty() - val unread = !c.read val simSlot = if (showSim && !c.isGroupConversation) { val subscription = threadSims[c.threadId] ?: config.getUseSIMIdAtNumber(c.phoneNumber) SimBadge.slotToShow(subscription, s.sims, defaultSim) } else { null } - ConversationRow( - threadId = c.threadId, - // Cached titles from before control characters were stripped may still hold a NUL. - // CL-10: the shared display form, also used by Archived, search, the thread header and Details. - // N2: each number of a group title too, joined with the language's comma. - title = displayTitle(app, c.title.stripControlCharacters()), - snippet = conversationPreview(c.snippet, draft, noTextLabel), - dateLabel = formatListTimeStyled(app, c.date * 1000L), - unread = unread, - unreadBadge = when { - !unread -> "" - c.unreadCount > MAX_BADGE -> localizeDigits("$MAX_BADGE+", app.uiLocale) - c.unreadCount <= 0 -> "" - else -> localizedNumber(c.unreadCount, app.uiLocale) - }, - unreadCount = c.unreadCount, + val input = RowInput( + threadId = c.threadId, title = c.title, snippet = c.snippet, date = c.date, read = c.read, + unreadCount = c.unreadCount, photoUri = c.photoUri, isGroup = c.isGroupConversation, + phoneNumber = c.phoneNumber, scheduled = c.isScheduled, customTitle = c.usesCustomTitle, + draft = draft.orEmpty(), simSlot = simSlot, simName = simSlot?.let { simNames[it] }.orEmpty(), pinned = pinned.contains(c.threadId.toString()), muted = mutePrefs.isMuted(c.threadId) || - (customNotifications.contains(c.threadId.toString()) && isMuted(manager, c.threadId)), - hasDraft = hasDraft, - scheduled = c.isScheduled, - simSlot = simSlot, - simName = simSlot?.let { simNames[it] }.orEmpty(), - photoUri = c.photoUri, - isGroup = c.isGroupConversation, - phoneNumber = c.phoneNumber, - // CL-11: only a fresh, unread message offers its code; the chip goes away after OTP_CHIP_MS. - otpCode = if (unread && now - c.date * 1000L in 0..OTP_CHIP_MS) { - runCatching { OtpCodeExtractor.extract(c.snippet) }.getOrNull() - } else { - null - }, - category = MessageCategories.classify(c.phoneNumber, c.snippet, isContact = isContact(c)), + (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, ) + rowCache.get(c.threadId, input) { + val unread = !c.read + ConversationRow( + threadId = c.threadId, + // Cached titles from before control characters were stripped may still hold a NUL. + // CL-10: the shared display form, also used by Archived, search, the thread header and Details. + // N2: each number of a group title too, joined with the language's comma. + title = displayTitle(app, c.title.stripControlCharacters()), + snippet = conversationPreview(c.snippet, draft, noTextLabel), + dateLabel = formatListTimeStyled(app, c.date * 1000L), + unread = unread, + unreadBadge = when { + !unread -> "" + c.unreadCount > MAX_BADGE -> localizeDigits("$MAX_BADGE+", app.uiLocale) + c.unreadCount <= 0 -> "" + else -> localizedNumber(c.unreadCount, app.uiLocale) + }, + unreadCount = c.unreadCount, + pinned = input.pinned, + muted = input.muted, + hasDraft = !draft.isNullOrEmpty(), + scheduled = c.isScheduled, + simSlot = simSlot, + simName = input.simName, + photoUri = c.photoUri, + isGroup = c.isGroupConversation, + phoneNumber = c.phoneNumber, + // CL-11: only a fresh, unread message offers its code; the chip goes away after OTP_CHIP_MS. + otpCode = if (input.otpFresh) { + runCatching { OtpCodeExtractor.extract(c.snippet) }.getOrNull() + } else { + null + }, + category = MessageCategories.classify(c.phoneNumber, c.snippet, isContact = isContact(c)), + isContact = !c.isGroupConversation && isContact(c), + hasNotes = input.hasNotes, + ) + } } + rowCache.retainOnly(sorted.mapTo(HashSet()) { it.threadId }) val rowIds = rows.mapTo(HashSet()) { it.threadId } val selectedIds = s.selected.filterTo(HashSet()) { it in rowIds } @@ -698,7 +749,7 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic canUnpin = chosen.all { pinned.contains(it.threadId.toString()) }, canMarkRead = chosen.any { !it.read }, canMarkUnread = chosen.any { it.read }, - canArchive = s.archiveAvailable, + canArchive = s.status.archiveAvailable, canReportSpam = chosen.none { it.isGroupConversation }, canAddContact = single != null && !single.isGroupConversation, canCopyNumber = single != null && !single.isGroupConversation, @@ -712,24 +763,29 @@ class ConversationsViewModel(application: Application) : AndroidViewModel(applic } return ConversationsUiState( - loading = !s.hasData, - importing = s.importing, + loading = !s.status.hasData, + importing = s.status.importing, rows = rows, selected = selectedIds, selection = actions, - newBlockedCount = s.newBlockedCount, - archiveAvailable = s.archiveAvailable, + newBlockedCount = s.status.newBlockedCount, + archiveAvailable = s.status.archiveAvailable, hiddenChats = if (hiddenChats.isLockOn()) s.source.count { hiddenChats.isChosen(it.threadId) } else 0, hiddenUnlocked = concealed.isEmpty(), + confirmDeleteCount = s.status.confirmDeleteCount, ) } - private fun isMuted(manager: NotificationManager, threadId: Long): Boolean = runCatching { - manager.getNotificationChannel(threadId.toString())?.importance == NotificationManager.IMPORTANCE_NONE - }.getOrDefault(false) + /** Ids of the notification channels switched off, read with one call. */ + private fun mutedChannelIds(manager: NotificationManager): Set = runCatching { + manager.notificationChannels + .filter { it.importance == NotificationManager.IMPORTANCE_NONE } + .mapTo(HashSet()) { it.id } + }.getOrDefault(emptySet()) private companion object { const val MAX_BADGE = 99 + const val MINUTE_MS = 60_000L /** A code chip is shown for this long after the message arrived (ten minutes). */ const val OTP_CHIP_MS = 10 * 60 * 1000L diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/details/ConversationMediaScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/details/ConversationMediaScreen.kt index 8cad7808..5dcc4af3 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/details/ConversationMediaScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/details/ConversationMediaScreen.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.lazy.grid.itemsIndexed import androidx.compose.foundation.lazy.items import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Tab @@ -91,9 +92,11 @@ private fun PicturesTab( horizontalArrangement = Arrangement.spacedBy(4.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { - items(images.take(shown), key = { it.attachment.uriString }) { image -> + itemsIndexed(images.take(shown), key = { _, entry -> entry.attachment.uriString }) { index, image -> MediaThumb( image, + position = index + 1, + total = images.size, onClick = { onOpen(image) }, onLongClick = { onShowInChat(image.message) }, ) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/details/ConversationSearch.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/details/ConversationSearch.kt index 245aefde..1831ec2a 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/details/ConversationSearch.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/details/ConversationSearch.kt @@ -22,6 +22,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue @@ -48,6 +49,9 @@ import com.glooboo.umessage.ui.icons.Symbols import com.glooboo.umessage.ui.main.highlightRanges import com.glooboo.umessage.ui.main.isSearchable import com.glooboo.umessage.ui.main.searchExcerpt +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext /** * CL-23: the messages of one conversation whose text holds [query], newest first. Read through [TextNormalizer.fold] as @@ -74,7 +78,11 @@ fun ConversationSearchScreen( modifier: Modifier = Modifier, ) { var query by rememberSaveable { mutableStateOf("") } - val hits = remember(messages, query) { messages?.let { searchConversation(it, query) }.orEmpty() } + // Folding every body is slow in a long chat: wait for a pause in typing and search off the main thread. + val hits by produceState(emptyList(), messages, query) { + if (query.isNotEmpty()) delay(SEARCH_DEBOUNCE_MS) + value = withContext(Dispatchers.Default) { messages?.let { searchConversation(it, query) }.orEmpty() } + } val focus = remember { FocusRequester() } BackHandler(onBack = onBack) LaunchedEffect(Unit) { runCatching { focus.requestFocus() } } @@ -157,3 +165,4 @@ private fun highlighted(text: String, query: String, style: SpanStyle): Annotate } private const val MILLIS_PER_SECOND = 1000L +private const val SEARCH_DEBOUNCE_MS = 200L diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/details/MediaActions.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/details/MediaActions.kt index fb1396aa..68e814dc 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/details/MediaActions.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/details/MediaActions.kt @@ -13,6 +13,7 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme @@ -61,8 +62,15 @@ internal fun LazyListScope.mediaItems(media: ConversationMedia?, actions: MediaA contentPadding = PaddingValues(horizontal = 16.dp, vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { - items(media.images.take(RECENT_IMAGES), key = { it.attachment.uriString }) { image -> - MediaThumb(image, onClick = { actions.onOpenImage(image) }, modifier = Modifier.size(ThumbSize)) + val recent = media.images.take(RECENT_IMAGES) + itemsIndexed(recent, key = { _, entry -> entry.attachment.uriString }) { index, image -> + MediaThumb( + image, + onClick = { actions.onOpenImage(image) }, + modifier = Modifier.size(ThumbSize), + position = index + 1, + total = recent.size, + ) } } } @@ -100,10 +108,22 @@ internal fun MediaThumb( onClick: () -> Unit, modifier: Modifier = Modifier, onLongClick: (() -> Unit)? = null, + position: Int = 0, + total: Int = 0, ) { val side = with(LocalDensity.current) { ThumbSize.roundToPx() } val load by rememberGlideBitmap(image.attachment.getUri(), side, side) - val description = stringResource(R.string.i56_picture_description) + val context = androidx.compose.ui.platform.LocalContext.current + val tapToOpen = stringResource(R.string.i56_picture_description) + val description = if (position > 0 && total > 0) { + val date = android.text.format.DateUtils.formatDateTime( + context, image.message.date * MILLIS_PER_SECOND, android.text.format.DateUtils.FORMAT_SHOW_DATE or + android.text.format.DateUtils.FORMAT_ABBREV_MONTH, + ) + stringResource(R.string.i56_picture_position, position, total, date) + } else { + tapToOpen + } val showInChat = stringResource(R.string.i56_show_in_chat) Box( modifier @@ -123,3 +143,5 @@ internal fun MediaThumb( } } } + +private const val MILLIS_PER_SECOND = 1000L diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/labels/LabelEditDialog.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/labels/LabelEditDialog.kt index 1a5a6c13..19e11856 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/labels/LabelEditDialog.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/labels/LabelEditDialog.kt @@ -113,11 +113,10 @@ private fun VerdictText(verdict: LabelResult) { @Composable private fun ColorSwatches(selected: Int, onPick: (Int) -> Unit) { Column(verticalArrangement = Arrangement.spacedBy(LabelSectionGap)) { - LabelColor.entries.chunked(SWATCHES_PER_ROW).forEachIndexed { rowIndex, row -> + LabelColor.entries.chunked(SWATCHES_PER_ROW).forEach { row -> Row(horizontalArrangement = Arrangement.spacedBy(LabelSectionGap)) { - row.forEachIndexed { index, swatch -> - val number = rowIndex * SWATCHES_PER_ROW + index + 1 - val description = stringResource(R.string.i29_color_description, number) + row.forEach { swatch -> + val description = stringResource(swatch.nameRes()) Swatch(swatch.color, swatch.color == selected, description) { onPick(swatch.color) } } } @@ -125,6 +124,17 @@ private fun ColorSwatches(selected: Int, onPick: (Int) -> Unit) { } } +private fun LabelColor.nameRes(): Int = when (this) { + LabelColor.Red -> R.string.i29_color_red + LabelColor.Orange -> R.string.i29_color_orange + LabelColor.Yellow -> R.string.i29_color_yellow + LabelColor.Green -> R.string.i29_color_green + LabelColor.Teal -> R.string.i29_color_teal + LabelColor.Blue -> R.string.i29_color_blue + LabelColor.Purple -> R.string.i29_color_purple + LabelColor.Brown -> R.string.i29_color_brown +} + @Composable private fun Swatch(argb: Int, on: Boolean, description: String, onClick: () -> Unit) { val ring = if (on) Modifier.border(SwatchRingWidth, MaterialTheme.colorScheme.onSurface, CircleShape) else Modifier diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/lock/LockScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/lock/LockScreen.kt index 10053b5d..26d10452 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/lock/LockScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/lock/LockScreen.kt @@ -281,6 +281,13 @@ private fun Header(state: LockUiState, modifier: Modifier = Modifier) { if (state.inputType == PROTECTION_PIN) { Spacer(Modifier.height(16.dp)) PinDots(state.pinLength) + // The allowed range only, never the real length of the stored PIN. + Text( + stringResource(R.string.lock_pin_length_hint, AppLockLogic.MIN_PIN_LENGTH, AppLockLogic.MAX_PIN_LENGTH), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant, + textAlign = TextAlign.Center, + ) } } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/log/DecisionLogActivity.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/log/DecisionLogActivity.kt index d794568d..b5a5bb40 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/log/DecisionLogActivity.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/log/DecisionLogActivity.kt @@ -56,7 +56,10 @@ import androidx.compose.ui.text.withStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.repeatOnLifecycle import com.glooboo.umessage.R import com.glooboo.umessage.helpers.refreshConversations import com.glooboo.umessage.spam.BlockedMessage @@ -101,6 +104,7 @@ class DecisionLogActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { applyUMessageWindow() super.onCreate(savedInstanceState) + DecisionLogCsv.deleteOldExports(this) setContent { UMessageTheme { DecisionLogRoute(onBack = ::finish) } } } } @@ -130,7 +134,13 @@ private fun DecisionLogRoute(onBack: () -> Unit) { forwardRules = runCatching { SpamEngine.forwardRepository(context).currentRules() } .getOrDefault(emptyList()) sims = runCatching { SimCards.load(context) }.getOrDefault(emptyList()) - entries = log.entries() + } + } + // Reads the log on every resume (first open included), so decisions made while the app was away show at once. + val lifecycleOwner = LocalLifecycleOwner.current + LaunchedEffect(log, lifecycleOwner) { + lifecycleOwner.repeatOnLifecycle(Lifecycle.State.RESUMED) { + entries = withContext(Dispatchers.IO) { log.entries() } } } val snackbar = remember { SnackbarHostState() } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/log/DecisionLogCsv.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/log/DecisionLogCsv.kt index 76ec0687..7cf3de59 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/log/DecisionLogCsv.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/log/DecisionLogCsv.kt @@ -1,74 +1,81 @@ -package com.glooboo.umessage.ui.log - -import android.content.Context -import android.content.Intent -import androidx.core.content.FileProvider -import com.glooboo.umessage.R -import com.glooboo.umessage.spam.SpamLogEntry -import java.io.File -import java.time.Instant -import java.time.ZoneId -import java.time.format.DateTimeFormatter - -/** - * ID-39: the shown decisions as CSV. One line per decision (collapsed rows are expanded again), never message text. - * Columns use the log's own tokens (BLOCK, UNKNOWN_SENDER, ...), so a shared file reads the same in every language. - */ -internal object DecisionLogCsv { - private const val HEADER = "time,sender,sim,decision,reason,rule,source,fixed" - private const val FILE_DIR = "shared_logs" - private const val FILE_NAME = "uMessage-decisions.csv" - - private val timeFormat: DateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME - - /** [slotOf] gives the SIM slot to write (B4), or null to leave the column empty. */ - fun build( - entries: List, - slotOf: (SpamLogEntry) -> Int?, - zone: ZoneId = ZoneId.systemDefault(), - ): String = buildString { - append(HEADER).append("\r\n") - entries.forEach { e -> - val columns = listOf( - Instant.ofEpochMilli(e.time).atZone(zone).format(timeFormat), - e.sender, - slotOf(e)?.toString().orEmpty(), - e.decision, - e.reason, - e.ruleLabel.ifEmpty { e.ruleId?.let { "#$it" }.orEmpty() }, - e.source, - e.fix, - ) - append(columns.joinToString(",") { field(it) }).append("\r\n") - } - } - - /** - * RFC 4180 quoting; a leading = + - @ gets a ' in front, so a spreadsheet never runs a sender name as a formula. - */ - internal fun field(value: String): String { - val safe = if (value.firstOrNull() in FORMULA_STARTS && !value.isPhoneNumberLike()) "'$value" else value - val needsQuotes = safe.any { it == ',' || it == '"' || it == '\n' || it == '\r' } || safe != safe.trim() - return if (needsQuotes) "\"" + safe.replace("\"", "\"\"") + "\"" else safe - } - - private val FORMULA_STARTS = setOf('=', '+', '-', '@') - - /** "+14155550133" stays as-is: numbers are the most common sender and are not formulas. */ - private fun String.isPhoneNumberLike(): Boolean = drop(1).isNotEmpty() && drop(1).all { it.isDigit() || it == ' ' } - - /** Writes [csv] to the app cache and opens the share sheet for it. */ - fun share(context: Context, csv: String, count: Int) { - val dir = File(context.cacheDir, FILE_DIR).apply { mkdirs() } - val file = File(dir, FILE_NAME) - file.writeText(csv) - val uri = FileProvider.getUriForFile(context, "${context.packageName}.provider", file) - val send = Intent(Intent.ACTION_SEND) - .setType("text/csv") - .putExtra(Intent.EXTRA_STREAM, uri) - .putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.declog_csv_subject)) - .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) - val title = context.resources.getQuantityString(R.plurals.declog_share_count, count, count) - context.startActivity(Intent.createChooser(send, title).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) - } -} +package com.glooboo.umessage.ui.log + +import android.content.Context +import android.content.Intent +import androidx.core.content.FileProvider +import com.glooboo.umessage.R +import com.glooboo.umessage.spam.SpamLogEntry +import java.io.File +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter + +/** + * ID-39: the shown decisions as CSV. One line per decision (collapsed rows are expanded again), never message text. + * Columns use the log's own tokens (BLOCK, UNKNOWN_SENDER, ...), so a shared file reads the same in every language. + */ +internal object DecisionLogCsv { + private const val HEADER = "time,sender,sim,decision,reason,rule,source,fixed" + private const val FILE_DIR = "shared_logs" + private const val FILE_NAME = "uMessage-decisions.csv" + + private val timeFormat: DateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME + + /** [slotOf] gives the SIM slot to write (B4), or null to leave the column empty. */ + fun build( + entries: List, + slotOf: (SpamLogEntry) -> Int?, + zone: ZoneId = ZoneId.systemDefault(), + ): String = buildString { + append(HEADER).append("\r\n") + entries.forEach { e -> + val columns = listOf( + Instant.ofEpochMilli(e.time).atZone(zone).format(timeFormat), + e.sender, + slotOf(e)?.toString().orEmpty(), + e.decision, + e.reason, + e.ruleLabel.ifEmpty { e.ruleId?.let { "#$it" }.orEmpty() }, + e.source, + e.fix, + ) + append(columns.joinToString(",") { field(it) }).append("\r\n") + } + } + + /** + * RFC 4180 quoting; a leading = + - @ gets a ' in front, so a spreadsheet never runs a sender name as a formula. + */ + internal fun field(value: String): String { + val safe = if (value.firstOrNull() in FORMULA_STARTS && !value.isPhoneNumberLike()) "'$value" else value + val needsQuotes = safe.any { it == ',' || it == '"' || it == '\n' || it == '\r' } || safe != safe.trim() + return if (needsQuotes) "\"" + safe.replace("\"", "\"\"") + "\"" else safe + } + + private val FORMULA_STARTS = setOf('=', '+', '-', '@') + + /** "+14155550133" stays as-is: numbers are the most common sender and are not formulas. */ + private fun String.isPhoneNumberLike(): Boolean = drop(1).isNotEmpty() && drop(1).all { it.isDigit() || it == ' ' } + + /** Removes earlier exports (sender numbers) from the cache; called when the log screen opens. */ + fun deleteOldExports(context: Context) { + runCatching { File(context.cacheDir, FILE_DIR).listFiles()?.forEach { it.delete() } } + } + + /** Writes [csv] to the app cache and opens the share sheet for it. */ + fun share(context: Context, csv: String, count: Int) { + val dir = File(context.cacheDir, FILE_DIR).apply { mkdirs() } + dir.listFiles()?.forEach { it.delete() } + val file = File(dir, "${System.currentTimeMillis()}-$FILE_NAME") + file.writeText(csv) + val uri = FileProvider.getUriForFile(context, "${context.packageName}.provider", file) + val send = Intent(Intent.ACTION_SEND) + .setType("text/csv") + .putExtra(Intent.EXTRA_STREAM, uri) + .putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.declog_csv_subject)) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + val title = context.resources.getQuantityString(R.plurals.declog_share_count, count, count) + context.startActivity(Intent.createChooser(send, title).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + com.glooboo.umessage.helpers.CacheCleanup.deleteAfterShare(file) + } +} 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 8f843cf9..2f8b4640 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 @@ -16,7 +16,7 @@ import com.glooboo.umessage.ui.components.isBareNumber /** Searching starts with this many characters; shorter input shows a hint instead of results. */ const val MIN_SEARCH_LENGTH = 2 -fun isSearchable(query: String): Boolean = query.length >= MIN_SEARCH_LENGTH +fun isSearchable(query: String): Boolean = query.trim().length >= MIN_SEARCH_LENGTH /** MC-17: typing waits this long for the next key before searching, so "hello" runs one search, not five. */ const val SEARCH_DEBOUNCE_MS = 250L @@ -79,7 +79,14 @@ fun isWholeWordHit(text: String, query: String): Boolean = highlightRanges(text, } /** Fewer digits than this in a query is not looked up in phone numbers ("12" would match nearly every chat). */ -private const val MIN_NUMBER_QUERY_DIGITS = 3 +internal const val MIN_NUMBER_QUERY_DIGITS = 3 + +/** + * True when [query] has no letters and at least [MIN_NUMBER_QUERY_DIGITS] digits (any script), so a number lookup + * can match. + */ +fun isNumberQuery(query: String): Boolean = + !query.any { it.isLetter() } && asciiDigits(query).length >= MIN_NUMBER_QUERY_DIGITS /** * CL-15: the conversations whose phone number holds the digits of [query], however either is written (spaces, dashes, 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 9165924a..37b3451d 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 @@ -70,7 +70,7 @@ internal fun MainSearchPage( // 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) } + 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() } 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 3239a3ba..32662d82 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 @@ -15,6 +15,8 @@ import com.glooboo.umessage.ui.components.displayTitle import com.glooboo.umessage.ui.components.formatListTimeStyled import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -63,8 +65,8 @@ class MainSearchViewModel(application: Application, handle: SavedStateHandle) : } searchJob = viewModelScope.launch { delay(SEARCH_DEBOUNCE_MS) // cancelled by the next key press (MC-17) - state.results = runSearch(text) - state.noteHits = runNoteSearch(text) + state.results = runSearch(text.trim()) + state.noteHits = runNoteSearch(text.trim()) } } @@ -72,23 +74,39 @@ class MainSearchViewModel(application: Application, handle: SavedStateHandle) : val app = getApplication() // B06: nothing of a hidden chat is found, by its title, its number or its text, until it is unlocked. val hiddenChats = HiddenChats.get(app) - // Persian/Arabic letter forms, digits and zero-width marks are folded on both sides (MC-15). - val messages = try { - hiddenChats.withoutHidden(app.messagesDB.searchMessages(text)) { it.threadId } - } catch (_: Exception) { - emptyList() - } - val byTitle = try { - hiddenChats.withoutHidden(app.conversationsDB.searchConversations(text)) { it.threadId } - } catch (_: Exception) { - emptyList() - } - // CL-15: a number typed in any form ("0555 345", Persian digits) also finds the chat with that number. - val byNumber = try { - val all = app.conversationsDB.getNonArchived() + app.conversationsDB.getAllArchived() - conversationsByNumber(hiddenChats.withoutHidden(all) { it.threadId }, text) - } catch (_: Exception) { - emptyList() + // main-7: the three lookups are independent, so they run side by side. + val (messages, byTitle, byNumber) = coroutineScope { + val messagesJob = async { + // Persian/Arabic letter forms, digits and zero-width marks are folded on both sides (MC-15). + try { + hiddenChats.withoutHidden(app.messagesDB.searchMessages(text)) { it.threadId } + } catch (_: Exception) { + emptyList() + } + } + val titleJob = async { + try { + hiddenChats.withoutHidden(app.conversationsDB.searchConversations(text)) { it.threadId } + } catch (_: Exception) { + emptyList() + } + } + val numberJob = async { + // CL-15: a number typed in any form ("0555 345", Persian digits) also finds the chat with that number. + // Only the plain chat rows are read (no newest-message preview per chat), and only for a number query. + if (!isNumberQuery(text)) { + emptyList() + } else { + try { + conversationsByNumber( + hiddenChats.withoutHidden(app.conversationsDB.getAllForNumberSearch()) { it.threadId }, text + ) + } catch (_: Exception) { + emptyList() + } + } + } + Triple(messagesJob.await(), titleJob.await(), numberJob.await()) } buildSearchResults( conversations = mergeConversationHits(byTitle, byNumber), diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/NotificationsOffBanner.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/NotificationsOffBanner.kt index 0e227229..9b17879d 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/NotificationsOffBanner.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/NotificationsOffBanner.kt @@ -15,6 +15,7 @@ import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface +import androidx.compose.material3.TextButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect @@ -81,7 +82,10 @@ fun NotificationsOffBanner(modifier: Modifier = Modifier) { lifecycleOwner.lifecycle.addObserver(observer) onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } } + var dismissed by remember { mutableStateOf(false) } val current = block ?: return + // Hidden for a few weeks after "Not now"; a different kind of block (or the dismiss expiring) shows it again. + if (dismissed || isBannerDismissed(context, current)) return Surface( color = MaterialTheme.colorScheme.errorContainer, @@ -99,13 +103,35 @@ fun NotificationsOffBanner(modifier: Modifier = Modifier) { Text(stringResource(R.string.notifications_off_title), style = MaterialTheme.typography.titleSmall) Text(stringResource(R.string.notifications_off_body), style = MaterialTheme.typography.bodyMedium) } - FilledTonalButton(onClick = { openNotificationSettings(context, current) }) { - Text(stringResource(R.string.notifications_off_fix)) + Column(horizontalAlignment = Alignment.End) { + FilledTonalButton(onClick = { openNotificationSettings(context, current) }) { + Text(stringResource(R.string.notifications_off_fix)) + } + TextButton(onClick = { + dismissBanner(context, current) + dismissed = true + }) { + Text(stringResource(R.string.notifications_off_dismiss)) + } } } } } +private const val BANNER_PREFS = "notifications_off_banner" +private const val BANNER_DISMISS_MS = 28L * 24 * 60 * 60 * 1000 + +private fun isBannerDismissed(context: Context, block: NotificationsBlock): Boolean { + val prefs = context.getSharedPreferences(BANNER_PREFS, Context.MODE_PRIVATE) + if (prefs.getString("block", null) != block.name) return false + return System.currentTimeMillis() - prefs.getLong("at", 0L) in 0 until BANNER_DISMISS_MS +} + +private fun dismissBanner(context: Context, block: NotificationsBlock) { + context.getSharedPreferences(BANNER_PREFS, Context.MODE_PRIVATE).edit() + .putString("block", block.name).putLong("at", System.currentTimeMillis()).apply() +} + private fun openNotificationSettings(context: Context, block: NotificationsBlock) { try { context.startActivity(context.notificationsFixIntent(block)) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/main/ShortcutHits.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/main/ShortcutHits.kt index 4aace7c4..adf5e6dc 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/main/ShortcutHits.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/main/ShortcutHits.kt @@ -33,7 +33,9 @@ internal fun rememberShortcutHits(filter: InboxFilter, rows: List() - if (preview.content.rules.isNotEmpty()) { + if (preview.newRules.isNotEmpty()) { parts += context.getString(R.string.settings_f_restore_rules, preview.allowRules, preview.blockRules) } + if (preview.rulesPresent > 0) { + parts += context.getString(R.string.settings_f_restore_rules_present, preview.rulesPresent) + } + 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 if (forwards.toAdd.isNotEmpty()) { parts += context.getString(R.string.settings_f_restore_forwards, forwards.toAdd.size) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/settings/SettingsScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/settings/SettingsScreen.kt index f0eacb4c..26dff3ba 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/settings/SettingsScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/settings/SettingsScreen.kt @@ -14,9 +14,13 @@ import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.clickable import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.runtime.remember import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable @@ -88,7 +92,9 @@ fun SettingsScreen(state: SettingsUiState, actions: SettingsActions, initialPage ) } } - SettingsFrame(topBar) { padding -> + val snackbar = remember { SnackbarHostState() } + CompositionLocalProvider(LocalSettingsSnackbar provides snackbar) { + SettingsFrame(topBar, snackbar) { padding -> Column( modifier = Modifier .fillMaxSize() @@ -116,6 +122,7 @@ fun SettingsScreen(state: SettingsUiState, actions: SettingsActions, initialPage Spacer(Modifier.height(24.dp + padding.calculateBottomPadding())) } } + } } @Composable @@ -143,10 +150,21 @@ private fun PageContent( /** U62: every page, the main list too, uses the same small top bar, so the first rows start right under the title. */ @Composable -private fun SettingsFrame(topBar: @Composable () -> Unit, content: @Composable (PaddingValues) -> Unit) { - UMessageScaffold(topBar = topBar, content = content) +private fun SettingsFrame( + topBar: @Composable () -> Unit, + snackbar: SnackbarHostState, + content: @Composable (PaddingValues) -> Unit, +) { + UMessageScaffold(topBar = topBar, snackbarHostState = snackbar, content = content) } +/** + * The snackbar host of the settings screen, so a row can show a message with Undo (the read-codes cleanup does). + * Null outside [SettingsScreen] (previews, tests): rows then skip the snackbar. + */ +@Suppress("CompositionLocalAllowlist") // Scoped to the settings pages; a lambda would thread through every row. +internal val LocalSettingsSnackbar = compositionLocalOf { null } + private fun pageTitle(page: SettingsPage): Int = when (page) { SettingsPage.Main -> R.string.settings_title SettingsPage.Spam -> R.string.settings_nav_spam_page_title diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/settings/StorageCleanupRows.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/settings/StorageCleanupRows.kt index 005491f8..a5e485fc 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/settings/StorageCleanupRows.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/settings/StorageCleanupRows.kt @@ -1,212 +1,264 @@ -package com.glooboo.umessage.ui.settings - -import android.content.Context -import androidx.annotation.StringRes -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.res.pluralStringResource -import androidx.compose.ui.res.stringResource -import com.glooboo.umessage.R -import com.glooboo.umessage.helpers.RetentionRunner -import com.glooboo.umessage.helpers.cleanupPrefs -import com.glooboo.umessage.ui.components.ChoiceDialog -import com.glooboo.umessage.ui.components.ConfirmDialog -import com.glooboo.umessage.ui.components.SettingsRow -import com.glooboo.umessage.ui.components.SettingsSwitchRow -import com.glooboo.umessage.ui.icons.Symbols -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import org.fossify.commons.helpers.ensureBackgroundThread - -private const val DAYS_WEEK = 7 -private const val DAYS_MONTH = 30 -private const val DAYS_QUARTER = 90 -private const val YEAR_DAYS = 365 -private val CODE_CHOICES = listOf(0, 1, DAYS_WEEK, DAYS_MONTH) -private val KEEP_CHOICES = listOf(0, DAYS_MONTH, DAYS_QUARTER, YEAR_DAYS) - -/** - * I02 and I45: the two rows of Settings > Storage and cleanup that clean up by themselves. Both only move messages to - * the recycle bin, so the page shows them only while the bin is on (U26); the ask-first dialog stays as a safeguard. - * They read and write [com.glooboo.umessage.helpers.CleanupPrefs] themselves; [onBinChange] is the host's switch of - * the recycle bin. - */ -@Composable -fun StorageCleanupRows(binOn: Boolean, onBinChange: (Boolean) -> Unit) { - CodesCleanupRow(binOn, onBinChange) - KeepMessagesRow(binOn, onBinChange) -} - -/** After an age was chosen: moves what is already older than that, off the main thread. */ -private fun moveDueNow(context: Context) { - ensureBackgroundThread { RetentionRunner(context).runNow(System.currentTimeMillis()) } -} - -/** I02: "Delete read codes after" Never / 24 hours / 7 days / 30 days. */ -@Composable -private fun CodesCleanupRow(binOn: Boolean, onBinChange: (Boolean) -> Unit) { - val context = LocalContext.current - val prefs = remember(context) { context.cleanupPrefs } - var days by remember { mutableIntStateOf(prefs.codeDays) } - var picking by remember { mutableStateOf(false) } - var needBin by remember { mutableStateOf(null) } - val applyChoice = { chosen: Int -> - prefs.codeDays = chosen - days = chosen - if (chosen > 0) moveDueNow(context) - } - SettingsRow( - title = stringResource(R.string.cleanup_codes_title), - summary = stringResource(R.string.cleanup_codes_summary), - value = cleanupLabel(days, R.string.cleanup_never), - icon = Symbols.Code, - onClick = { picking = true }, - showChevron = true, - ) - if (picking) { - ChoiceDialog( - title = stringResource(R.string.cleanup_codes_title), - options = CODE_CHOICES.map { cleanupLabel(it, R.string.cleanup_never) }, - selectedIndex = CODE_CHOICES.indexOf(days), - onSelect = { - picking = false - val chosen = CODE_CHOICES[it] - if (chosen == 0 || binOn) applyChoice(chosen) else needBin = chosen - }, - onDismiss = { picking = false }, - ) - } - needBin?.let { chosen -> - BinNeededDialog( - onConfirm = { - onBinChange(true) - applyChoice(chosen) - needBin = null - }, - onDismiss = { needBin = null }, - ) - } -} - -/** I45: "Keep messages for" Forever / 30 days / 90 days / 1 year, confirmed with the number that would move now. */ -@Composable -private fun KeepMessagesRow(binOn: Boolean, onBinChange: (Boolean) -> Unit) { - val context = LocalContext.current - val prefs = remember(context) { context.cleanupPrefs } - var days by remember { mutableIntStateOf(prefs.oldMessageDays) } - var picking by remember { mutableStateOf(false) } - var pending by remember { mutableStateOf(null) } - var binAsked by remember { mutableStateOf(false) } - SettingsRow( - title = stringResource(R.string.cleanup_old_title), - summary = stringResource(R.string.cleanup_old_summary), - value = cleanupLabel(days, R.string.cleanup_forever), - icon = Symbols.Schedule, - onClick = { picking = true }, - showChevron = true, - ) - if (picking) { - ChoiceDialog( - title = stringResource(R.string.cleanup_old_title), - options = KEEP_CHOICES.map { cleanupLabel(it, R.string.cleanup_forever) }, - selectedIndex = KEEP_CHOICES.indexOf(days), - onSelect = { - picking = false - val chosen = KEEP_CHOICES[it] - if (chosen == 0) { - prefs.oldMessageDays = 0 - days = 0 - } else { - binAsked = !binOn - pending = chosen - } - }, - onDismiss = { picking = false }, - ) - } - val chosen = pending ?: return - if (binAsked) { - BinNeededDialog( - onConfirm = { - onBinChange(true) - binAsked = false - }, - onDismiss = { pending = null }, - ) - } else { - ConfirmMoveDialog(chosen, onDismiss = { pending = null }) { - prefs.oldMessageDays = chosen - days = chosen - pending = null - moveDueNow(context) - } - } -} - -@Composable -private fun BinNeededDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) { - ConfirmDialog( - title = stringResource(R.string.cleanup_bin_title), - message = stringResource(R.string.cleanup_bin_body), - confirmLabel = stringResource(R.string.cleanup_bin_confirm), - onConfirm = onConfirm, - onDismiss = onDismiss, - ) -} - -/** Says how many messages are older than [days] and would move to the recycle bin now, then asks. */ -@Composable -private fun ConfirmMoveDialog(days: Int, onDismiss: () -> Unit, onConfirm: () -> Unit) { - val context = LocalContext.current - var count by remember(days) { mutableStateOf(null) } - LaunchedEffect(days) { - count = withContext(Dispatchers.IO) { RetentionRunner(context).countOld(days, System.currentTimeMillis()) } - } - val shown = count ?: return - ConfirmDialog( - title = stringResource(R.string.cleanup_old_confirm_title), - message = if (shown == 0) { - stringResource(R.string.cleanup_old_confirm_none) - } else { - pluralStringResource(R.plurals.cleanup_old_confirm_body, shown, shown) - }, - confirmLabel = stringResource(R.string.cleanup_old_confirm_action), - onConfirm = onConfirm, - onDismiss = onDismiss, - ) -} - -@Composable -private fun cleanupLabel(days: Int, @StringRes zeroLabel: Int): String = when (days) { - 0 -> stringResource(zeroLabel) - 1 -> stringResource(R.string.cleanup_24_hours) - YEAR_DAYS -> stringResource(R.string.cleanup_one_year) - else -> pluralStringResource(R.plurals.cleanup_days, days, days) -} - -/** - * I08: the switch of the weekly summary of blocked messages, in Settings > Notifications. Off on a new install - * (U42). - */ -@Composable -fun WeeklyDigestRow() { - val context = LocalContext.current - val prefs = remember(context) { context.cleanupPrefs } - var on by remember { mutableStateOf(prefs.digestOn) } - SettingsSwitchRow( - title = stringResource(R.string.digest_row_title), - summary = stringResource(R.string.digest_row_summary), - icon = Symbols.CalendarMonth, - checked = on, - onCheckedChange = { - on = it - prefs.digestOn = it - }, - ) -} +package com.glooboo.umessage.ui.settings + +import android.content.Context +import androidx.annotation.PluralsRes +import androidx.annotation.StringRes +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import com.glooboo.umessage.R +import com.glooboo.umessage.helpers.RetentionRunner +import com.glooboo.umessage.helpers.cleanupPrefs +import com.glooboo.umessage.ui.components.ChoiceDialog +import com.glooboo.umessage.ui.components.ConfirmDialog +import com.glooboo.umessage.ui.components.SettingsRow +import com.glooboo.umessage.ui.components.SettingsSwitchRow +import com.glooboo.umessage.ui.components.showUndo +import com.glooboo.umessage.ui.icons.Symbols +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import org.fossify.commons.helpers.ensureBackgroundThread + +private const val DAYS_WEEK = 7 +private const val DAYS_MONTH = 30 +private const val DAYS_QUARTER = 90 +private const val YEAR_DAYS = 365 +private val CODE_CHOICES = listOf(0, 1, DAYS_WEEK, DAYS_MONTH) +private val KEEP_CHOICES = listOf(0, DAYS_MONTH, DAYS_QUARTER, YEAR_DAYS) + +/** + * I02 and I45: the two rows of Settings > Storage and cleanup that clean up by themselves. Both only move messages to + * the recycle bin, so the page shows them only while the bin is on (U26); the ask-first dialog stays as a safeguard. + * They read and write [com.glooboo.umessage.helpers.CleanupPrefs] themselves; [onBinChange] is the host's switch of + * the recycle bin. + */ +@Composable +fun StorageCleanupRows(binOn: Boolean, onBinChange: (Boolean) -> Unit) { + CodesCleanupRow(binOn, onBinChange) + KeepMessagesRow(binOn, onBinChange) +} + +/** After an age was chosen: moves what is already older than that, off the main thread. */ +private fun moveDueNow(context: Context) { + ensureBackgroundThread { RetentionRunner(context).runNow(System.currentTimeMillis()) } +} + +/** I02: "Delete read codes after" Never / 24 hours / 7 days / 30 days. */ +@Composable +private fun CodesCleanupRow(binOn: Boolean, onBinChange: (Boolean) -> Unit) { + val context = LocalContext.current + val prefs = remember(context) { context.cleanupPrefs } + var days by remember { mutableIntStateOf(prefs.codeDays) } + var picking by remember { mutableStateOf(false) } + var needBin by remember { mutableStateOf(null) } + var pending by remember { mutableStateOf(null) } + val snackbar = LocalSettingsSnackbar.current + val scope = rememberCoroutineScope() + val undoLabel = stringResource(R.string.cleanup_codes_undo) + val applyChoice = { chosen: Int -> + prefs.codeDays = chosen + days = chosen + if (chosen > 0) { + scope.launch { + val runner = RetentionRunner(context) + val moved = withContext(Dispatchers.IO) { runner.moveCodesNow(chosen, System.currentTimeMillis()) } + if (moved.isNotEmpty() && snackbar != null) { + snackbar.showUndo( + message = context.resources.getQuantityString( + R.plurals.cleanup_codes_moved, moved.size, moved.size + ), + undoLabel = undoLabel, + onUndo = { ensureBackgroundThread { runner.restore(moved) } }, + ) + } + } + } + } + SettingsRow( + title = stringResource(R.string.cleanup_codes_title), + summary = stringResource(R.string.cleanup_codes_summary), + value = cleanupLabel(days, R.string.cleanup_never), + icon = Symbols.Code, + onClick = { picking = true }, + showChevron = true, + ) + if (picking) { + ChoiceDialog( + title = stringResource(R.string.cleanup_codes_title), + options = CODE_CHOICES.map { cleanupLabel(it, R.string.cleanup_never) }, + selectedIndex = CODE_CHOICES.indexOf(days), + onSelect = { + picking = false + val chosen = CODE_CHOICES[it] + when { + chosen == 0 -> applyChoice(0) + binOn -> pending = chosen + else -> needBin = chosen + } + }, + onDismiss = { picking = false }, + ) + } + needBin?.let { chosen -> + BinNeededDialog( + onConfirm = { + onBinChange(true) + pending = chosen + needBin = null + }, + onDismiss = { needBin = null }, + ) + } + pending?.let { chosen -> + ConfirmMoveDialog( + days = chosen, + onDismiss = { pending = null }, + titleRes = R.string.cleanup_codes_confirm_title, + count = { RetentionRunner(context).countCodes(chosen, System.currentTimeMillis()) }, + bodyPlural = R.plurals.cleanup_codes_confirm_body, + noneRes = R.string.cleanup_codes_confirm_none, + ) { + pending = null + applyChoice(chosen) + } + } +} + +/** I45: "Keep messages for" Forever / 30 days / 90 days / 1 year, confirmed with the number that would move now. */ +@Composable +private fun KeepMessagesRow(binOn: Boolean, onBinChange: (Boolean) -> Unit) { + val context = LocalContext.current + val prefs = remember(context) { context.cleanupPrefs } + var days by remember { mutableIntStateOf(prefs.oldMessageDays) } + var picking by remember { mutableStateOf(false) } + var pending by remember { mutableStateOf(null) } + var binAsked by remember { mutableStateOf(false) } + SettingsRow( + title = stringResource(R.string.cleanup_old_title), + summary = stringResource(R.string.cleanup_old_summary), + value = cleanupLabel(days, R.string.cleanup_forever), + icon = Symbols.Schedule, + onClick = { picking = true }, + showChevron = true, + ) + if (picking) { + ChoiceDialog( + title = stringResource(R.string.cleanup_old_title), + options = KEEP_CHOICES.map { cleanupLabel(it, R.string.cleanup_forever) }, + selectedIndex = KEEP_CHOICES.indexOf(days), + onSelect = { + picking = false + val chosen = KEEP_CHOICES[it] + if (chosen == 0) { + prefs.oldMessageDays = 0 + days = 0 + } else { + binAsked = !binOn + pending = chosen + } + }, + onDismiss = { picking = false }, + ) + } + val chosen = pending ?: return + if (binAsked) { + BinNeededDialog( + onConfirm = { + onBinChange(true) + binAsked = false + }, + onDismiss = { pending = null }, + ) + } else { + ConfirmMoveDialog( + days = chosen, + onDismiss = { pending = null }, + count = { RetentionRunner(context).countOld(chosen, System.currentTimeMillis()) }, + ) { + prefs.oldMessageDays = chosen + days = chosen + pending = null + moveDueNow(context) + } + } +} + +@Composable +private fun BinNeededDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) { + ConfirmDialog( + title = stringResource(R.string.cleanup_bin_title), + message = stringResource(R.string.cleanup_bin_body), + confirmLabel = stringResource(R.string.cleanup_bin_confirm), + onConfirm = onConfirm, + onDismiss = onDismiss, + ) +} + +/** Says how many messages are older than [days] and would move to the recycle bin now, then asks. */ +@Composable +private fun ConfirmMoveDialog( + days: Int, + count: () -> Int, + onDismiss: () -> Unit, + @StringRes titleRes: Int = R.string.cleanup_old_confirm_title, + @PluralsRes bodyPlural: Int = R.plurals.cleanup_old_confirm_body, + @StringRes noneRes: Int = R.string.cleanup_old_confirm_none, + onConfirm: () -> Unit, +) { + var counted by remember(days) { mutableStateOf(null) } + val currentCount by rememberUpdatedState(count) + LaunchedEffect(days) { + counted = withContext(Dispatchers.IO) { currentCount() } + } + val shown = counted ?: return + ConfirmDialog( + title = stringResource(titleRes), + message = if (shown == 0) { + stringResource(noneRes) + } else { + pluralStringResource(bodyPlural, shown, shown) + }, + confirmLabel = stringResource(R.string.cleanup_old_confirm_action), + onConfirm = onConfirm, + onDismiss = onDismiss, + ) +} + +@Composable +private fun cleanupLabel(days: Int, @StringRes zeroLabel: Int): String = when (days) { + 0 -> stringResource(zeroLabel) + 1 -> stringResource(R.string.cleanup_24_hours) + YEAR_DAYS -> stringResource(R.string.cleanup_one_year) + else -> pluralStringResource(R.plurals.cleanup_days, days, days) +} + +/** + * I08: the switch of the weekly summary of blocked messages, in Settings > Notifications. Off on a new install + * (U42). + */ +@Composable +fun WeeklyDigestRow() { + val context = LocalContext.current + val prefs = remember(context) { context.cleanupPrefs } + var on by remember { mutableStateOf(prefs.digestOn) } + SettingsSwitchRow( + title = stringResource(R.string.digest_row_title), + summary = stringResource(R.string.digest_row_summary), + icon = Symbols.CalendarMonth, + checked = on, + onCheckedChange = { + on = it + prefs.digestOn = it + }, + ) +} 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 0e174968..f51dd954 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 @@ -15,6 +15,8 @@ class BlockedActions( val onSelectAll: () -> Unit = {}, val onNotSpam: (Set) -> Unit = {}, val onDelete: (Set) -> Unit = {}, + /** "Delete all" of the menu, after its confirmation: also clears the restored list (spamui-15). */ + val onDeleteAll: () -> Unit = {}, /** A chip under the banner (ID-14). */ val onSetFilter: (BlockedFilter) -> Unit = {}, /** I32: sends the one selected sender's newest message to the carrier; asked and confirmed by the screen first. */ diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedNumbersViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedNumbersViewModel.kt index c286eaca..f05e2915 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedNumbersViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedNumbersViewModel.kt @@ -226,7 +226,17 @@ class BlockedNumbersViewModel @JvmOverloads constructor( viewModelScope.launch { val event = withContext(Dispatchers.IO) { val text = runCatching { - app.contentResolver.openInputStream(uri)?.bufferedReader()?.use { it.readText() } + app.contentResolver.openInputStream(uri)?.bufferedReader()?.use { reader -> + // A wrong or huge file is refused instead of read whole into memory. + val buffer = CharArray(MAX_IMPORT_CHARS + 1) + var total = 0 + while (total < buffer.size) { + val n = reader.read(buffer, total, buffer.size - total) + if (n < 0) break + total += n + } + if (total > MAX_IMPORT_CHARS) null else String(buffer, 0, total) + } }.getOrNull() ?: return@withContext BlockedNumbersEvent.ImportFailed val parsed = BlockedNumberFormat.parseImportChecked(text) if (parsed.numbers.isEmpty()) return@withContext BlockedNumbersEvent.ImportEmpty @@ -256,4 +266,9 @@ class BlockedNumbersViewModel @JvmOverloads constructor( events.trySend(event) } } + + private companion object { + /** About 1 MB of text: far more than any real block list. */ + const val MAX_IMPORT_CHARS = 1_000_000 + } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedRestored.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedRestored.kt index c6935fc5..e815352d 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedRestored.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedRestored.kt @@ -1,113 +1,138 @@ -package com.glooboo.umessage.ui.spam - -import android.content.Context -import android.content.SharedPreferences -import androidx.core.content.edit -import java.time.Instant -import java.time.LocalDate -import java.time.ZoneId -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow - -/** One message the user moved from Blocked to the inbox (BR-10). No message text is kept, only who and when. */ -data class RestoredEntry(val address: String, val receivedAt: Long, val restoredAt: Long) - -/** - * The text form of the restored list: one `restoredAt TAB receivedAt TAB address` line per entry, newest first. - * Entries older than [RestoredLog.KEEP_MS] or beyond [RestoredLog.MAX_ENTRIES] are dropped. - */ -object RestoredLogCodec { - private val breaks = Regex("[\\t\\n\\r]") - - fun encode(entries: List): String = - entries.joinToString("\n") { "${it.restoredAt}\t${it.receivedAt}\t${it.address.replace(breaks, " ")}" } - - fun decode(text: String?): List = text.orEmpty().lineSequence().mapNotNull { line -> - val parts = line.split('\t', limit = 3) - val restoredAt = parts.getOrNull(0)?.toLongOrNull() ?: return@mapNotNull null - val receivedAt = parts.getOrNull(1)?.toLongOrNull() ?: return@mapNotNull null - val address = parts.getOrNull(2)?.takeIf { it.isNotBlank() } ?: return@mapNotNull null - RestoredEntry(address, receivedAt, restoredAt) - }.toList() - - /** [added] in front of [current], newest first, without expired entries and capped at [max]. */ - fun merge( - current: List, - added: List, - now: Long, - keepMs: Long, - max: Int, - ): List = - (added + current) - .filter { now - it.restoredAt in 0..keepMs } - .sortedByDescending { it.restoredAt } - .take(max) -} - -/** - * The recently restored messages behind the "N restored" link of the Blocked banner (BR-10), kept in a small private - * preferences file. Never throws: a storage failure just means an empty list. - */ -class RestoredLog(private val prefs: SharedPreferences?, private val now: () -> Long = System::currentTimeMillis) { - private val state = MutableStateFlow(read()) - - val entries: StateFlow> = state.asStateFlow() - - fun record(added: List) { - if (added.isEmpty()) return - val merged = RestoredLogCodec.merge(state.value, added, now(), KEEP_MS, MAX_ENTRIES) - state.value = merged - runCatching { prefs?.edit { putString(KEY, RestoredLogCodec.encode(merged)) } } - } - - /** Undo of a restore takes its entries back out. */ - fun remove(entries: List) { - if (entries.isEmpty()) return - val gone = entries.toSet() - val kept = state.value.filterNot { it in gone } - state.value = kept - runCatching { prefs?.edit { putString(KEY, RestoredLogCodec.encode(kept)) } } - } - - private fun read(): List = runCatching { - val stored = RestoredLogCodec.decode(prefs?.getString(KEY, null)) - RestoredLogCodec.merge(stored, emptyList(), now(), KEEP_MS, MAX_ENTRIES) - }.getOrDefault(emptyList()) - - companion object { - const val KEEP_DAYS = 30 - const val KEEP_MS = KEEP_DAYS * 24L * 60 * 60 * 1000 - const val MAX_ENTRIES = 100 - private const val PREFS = "spamless_restored" - private const val KEY = "entries" - - @Volatile private var shared: RestoredLog? = null - - /** One log per process, so the list and the Blocked screen agree after a rotation. */ - fun get(context: Context): RestoredLog = shared ?: synchronized(this) { - shared ?: RestoredLog( - runCatching { context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) } - .getOrNull(), - ).also { shared = it } - } - } -} - -/** A day header of the Blocked list (BR-17) and the sender groups whose newest message came that day. */ -data class BlockedDay(val day: LocalDate, val groups: List) - -/** Splits [groups] (newest first) by the day of each group's newest message. */ -fun groupByDay(groups: List, zone: ZoneId = ZoneId.systemDefault()): List { - val days = mutableListOf() - groups.forEach { group -> - val day = Instant.ofEpochMilli(group.latest.receivedAt).atZone(zone).toLocalDate() - val last = days.lastOrNull() - if (last != null && last.day == day) { - days[days.lastIndex] = last.copy(groups = last.groups + group) - } else { - days += BlockedDay(day, listOf(group)) - } - } - return days -} +package com.glooboo.umessage.ui.spam + +import android.content.Context +import android.content.SharedPreferences +import androidx.core.content.edit +import java.time.Instant +import java.time.LocalDate +import java.time.ZoneId +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +/** One message the user moved from Blocked to the inbox (BR-10). No message text is kept, only who and when. */ +data class RestoredEntry(val address: String, val receivedAt: Long, val restoredAt: Long) + +/** + * The text form of the restored list: one `restoredAt TAB receivedAt TAB address` line per entry, newest first. + * Entries older than [RestoredLog.KEEP_MS] or beyond [RestoredLog.MAX_ENTRIES] are dropped. + */ +private const val DAY_MS = 24L * 60 * 60 * 1000 + +object RestoredLogCodec { + private val breaks = Regex("[\\t\\n\\r]") + + fun encode(entries: List): String = + entries.joinToString("\n") { "${it.restoredAt}\t${it.receivedAt}\t${it.address.replace(breaks, " ")}" } + + fun decode(text: String?): List = text.orEmpty().lineSequence().mapNotNull { line -> + val parts = line.split('\t', limit = 3) + val restoredAt = parts.getOrNull(0)?.toLongOrNull() ?: return@mapNotNull null + val receivedAt = parts.getOrNull(1)?.toLongOrNull() ?: return@mapNotNull null + val address = parts.getOrNull(2)?.takeIf { it.isNotBlank() } ?: return@mapNotNull null + RestoredEntry(address, receivedAt, restoredAt) + }.toList() + + /** [added] in front of [current], newest first, without expired entries and capped at [max]. */ + fun merge( + current: List, + added: List, + now: Long, + keepMs: Long, + max: Int, + ): List = + (added + current) + .filter { now - it.restoredAt in 0..keepMs } + .sortedByDescending { it.restoredAt } + .take(max) + + /** [entries] restored within the last [days] days; the rest goes with the purged blocked messages. */ + fun dropOlderThan(entries: List, days: Int, now: Long): List { + val keepMs = days * DAY_MS + return entries.filter { now - it.restoredAt <= keepMs } + } +} + +/** + * The recently restored messages behind the "N restored" link of the Blocked banner (BR-10), kept in a small private + * preferences file. Never throws: a storage failure just means an empty list. + */ +class RestoredLog(private val prefs: SharedPreferences?, private val now: () -> Long = System::currentTimeMillis) { + private val state = MutableStateFlow(read()) + + val entries: StateFlow> = state.asStateFlow() + + fun record(added: List) { + if (added.isEmpty()) return + val merged = RestoredLogCodec.merge(state.value, added, now(), KEEP_MS, MAX_ENTRIES) + state.value = merged + runCatching { prefs?.edit { putString(KEY, RestoredLogCodec.encode(merged)) } } + } + + /** Forgets every listed entry (the sheet's "Clear list"). */ + fun clear() { + state.value = emptyList() + runCatching { prefs?.edit { remove(KEY) } } + } + + /** The blocked messages were purged after [days] days: older entries go too (spamui-15). */ + fun dropOlderThan(days: Int) { + val kept = RestoredLogCodec.dropOlderThan(state.value, days, now()) + if (kept.size == state.value.size) return + state.value = kept + runCatching { + prefs?.edit { if (kept.isEmpty()) remove(KEY) else putString(KEY, RestoredLogCodec.encode(kept)) } + } + } + + /** Undo of a restore takes its entries back out. */ + fun remove(entries: List) { + if (entries.isEmpty()) return + // One equal entry goes per undone entry, so two identical rows do not both vanish for one undo. + val kept = state.value.toMutableList() + entries.forEach { kept.remove(it) } + state.value = kept + runCatching { prefs?.edit { putString(KEY, RestoredLogCodec.encode(kept)) } } + } + + private fun read(): List = runCatching { + val stored = RestoredLogCodec.decode(prefs?.getString(KEY, null)) + RestoredLogCodec.merge(stored, emptyList(), now(), KEEP_MS, MAX_ENTRIES) + }.getOrDefault(emptyList()) + + companion object { + const val KEEP_DAYS = 30 + const val KEEP_MS = KEEP_DAYS * DAY_MS + const val MAX_ENTRIES = 100 + private const val PREFS = "spamless_restored" + private const val KEY = "entries" + + @Volatile private var shared: RestoredLog? = null + + /** One log per process, so the list and the Blocked screen agree after a rotation. */ + fun get(context: Context): RestoredLog = shared ?: synchronized(this) { + shared ?: RestoredLog( + runCatching { context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) } + .getOrNull(), + ).also { shared = it } + } + } +} + +/** A day header of the Blocked list (BR-17) and the sender groups whose newest message came that day. */ +data class BlockedDay(val day: LocalDate, val groups: List) + +/** Splits [groups] (newest first) by the day of each group's newest message. */ +fun groupByDay(groups: List, zone: ZoneId = ZoneId.systemDefault()): List { + val days = mutableListOf() + groups.forEach { group -> + val day = Instant.ofEpochMilli(group.latest.receivedAt).atZone(zone).toLocalDate() + val last = days.lastOrNull() + if (last != null && last.day == day) { + days[days.lastIndex] = last.copy(groups = last.groups + group) + } else { + days += BlockedDay(day, listOf(group)) + } + } + return days +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedRestoredSheet.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedRestoredSheet.kt index 69feae22..80bad02a 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedRestoredSheet.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedRestoredSheet.kt @@ -10,13 +10,14 @@ import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ListItem import androidx.compose.material3.ListItemDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.remember @@ -65,8 +66,17 @@ fun RestoredSheet(entries: List, onDismiss: () -> Unit) { color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp), ) + if (entries.isNotEmpty()) { + TextButton( + onClick = { RestoredLog.get(context).clear() }, + modifier = Modifier.padding(horizontal = 12.dp), + ) { Text(stringResource(R.string.e_restored_clear)) } + } LazyColumn(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(0.dp)) { - items(entries, key = { "${it.restoredAt}-${it.receivedAt}-${it.address}" }) { entry -> + itemsIndexed( + entries, + key = { i, e -> "$i-${e.restoredAt}-${e.receivedAt}-${e.address}" } + ) { _, entry -> RestoredRow(entry) { scope.launch { openConversation(context, entry.address) } } } } 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 9899ee55..49a062cd 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 @@ -104,6 +104,7 @@ fun BlockedRoute(onBack: (() -> Unit)?, onOpenRules: () -> Unit, onOpenSettings: onSelectAll = viewModel::selectAll, onNotSpam = { addresses -> viewModel.notSpam(addresses) }, onDelete = viewModel::delete, + onDeleteAll = viewModel::deleteAll, onSetFilter = viewModel::setFilter, onReportSpam = { selected -> scope.launch { reportToCarrier(context, groups, selected, snackbar) } }, ) @@ -129,15 +130,23 @@ internal fun BlockedEvents( LaunchedEffect(viewModel) { // After a rotation the previous snackbar was cancelled unanswered; offer its Undo again. viewModel.replayPending() + var undoOpen = false viewModel.eventFlow.collect { event -> - snackbar.currentSnackbarData?.dismiss() + // A dismiss counts as "not undone" and commits the delete or restore, so a snackbar that still offers + // Undo is left to run out; the newer one queues behind it. + if (!undoOpen) snackbar.currentSnackbarData?.dismiss() launch { val text = eventText(resources, event, failedText) { number -> isolateNumbers(displayNumber(context, number)) } when (event) { is BlockedEvent.Restored -> { - val result = snackbar.showSnackbar(text, undoLabel, duration = SnackbarDuration.Long) + undoOpen = true + val result = try { + snackbar.showSnackbar(text, undoLabel, duration = SnackbarDuration.Long) + } finally { + undoOpen = false + } if (result == SnackbarResult.ActionPerformed) { viewModel.undoRestore(event.token) } else { @@ -150,7 +159,12 @@ internal fun BlockedEvents( if (result == SnackbarResult.ActionPerformed) viewModel.undoMode(event.previous) } is BlockedEvent.Deleted -> { - val result = snackbar.showSnackbar(text, undoLabel, duration = SnackbarDuration.Long) + undoOpen = true + val result = try { + snackbar.showSnackbar(text, undoLabel, duration = SnackbarDuration.Long) + } finally { + undoOpen = false + } if (result == SnackbarResult.ActionPerformed) { viewModel.undoDelete(event.token) } else { @@ -267,7 +281,7 @@ fun BlockedScreen( destructive = true, onConfirm = { confirmDeleteAll = false - actions.onDelete(state.groups.map { it.address }.toSet()) + actions.onDeleteAll() }, onDismiss = { confirmDeleteAll = false }, ) diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedSenderRow.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedSenderRow.kt index a3fd3a46..e59739a4 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedSenderRow.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedSenderRow.kt @@ -127,10 +127,14 @@ private fun SenderRowContent( val unreadText = if (unread) stringResource(R.string.convlist_unread_count, group.unreadCount) else null val badge = unreadBadgeText(group.unreadCount) val shown = isolateNumbers(displayNumber(group.address)) + val resources = LocalResources.current + // Regex work: once per message and rules change, not on every recomposition (swipe, selection animation). // "Hide codes on the lock screen" hides the code in the row (and so in what TalkBack reads) too. - val body = rememberCodeHidden(blockedBodyText(LocalResources.current, latest)) + val body = rememberCodeHidden(remember(resources, latest) { blockedBodyText(resources, latest) }) val reason = reasonText(latest, rules) - val important = latest.reason == DecisionReason.UNKNOWN_SENDER && BlockedHints.looksImportant(latest.body) + val important = remember(latest) { + latest.reason == DecisionReason.UNKNOWN_SENDER && BlockedHints.looksImportant(latest.body) + } val importantText = stringResource(R.string.blocked_may_be_important) val mmsText = mmsMediaLabel(latest)?.takeIf { latest.hasText }?.let { stringResource(it) } // One SIM chip when all the sender's messages came on one SIM, as a conversation row shows it. 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 7568c084..1e236659 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 @@ -3,6 +3,7 @@ package com.glooboo.umessage.ui.spam import android.content.Context import android.text.format.DateFormat import android.text.format.DateUtils +import androidx.activity.compose.BackHandler import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.combinedClickable @@ -44,6 +45,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -56,6 +58,7 @@ import androidx.compose.ui.platform.LocalResources import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.selected import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview @@ -131,6 +134,10 @@ class BlockedThreadActions( /** Puts one message in the inbox without allowing the sender (ID-16), with Undo. */ val onReleaseOnce: (Long) -> Unit = {}, val onDeleteMessage: (Long) -> Unit = {}, + /** "Move to inbox" for the messages chosen by long press (spamui-11): no allow question, one Undo. */ + val onReleaseMessages: (Set) -> Unit = {}, + /** Deletes the chosen messages, with Undo. */ + val onDeleteMessages: (Set) -> Unit = {}, val onOpenRules: () -> Unit = {}, ) @@ -185,6 +192,8 @@ fun BlockedThreadRoute( onDeleteAll = { viewModel.delete(setOf(address)) }, onReleaseOnce = viewModel::releaseOnce, onDeleteMessage = { id -> viewModel.deleteMessages(setOf(id)) }, + onReleaseMessages = viewModel::releaseMessages, + onDeleteMessages = viewModel::deleteMessages, onOpenRules = onOpenRules, ) } @@ -194,8 +203,9 @@ fun BlockedThreadRoute( /** * A blocked sender's messages as a thread (owner notes r3): incoming bubbles under day headers, newest at the * bottom, and no compose box. The bar at the bottom says the messages are held and offers Move to inbox; Delete is - * in the top bar. Each message has its own menu (tap or long press): Release once, Copy, Copy code, Why blocked, - * Delete. Links are not made tappable: these texts are held as possible spam or phishing. + * in the top bar. Each message has its own menu (tap): Release once, Copy, Copy code, Why blocked, Delete. A long + * press chooses the message instead, and more can be tapped; the bar then offers Select all, Move to inbox and Delete + * for the chosen ones (spamui-11). Links are not made tappable: these texts are held as possible spam or phishing. */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -211,16 +221,32 @@ fun BlockedThreadScreen( val group = state.groups.firstOrNull { it.hasAddress(address) } val shown = isolateNumbers(displayNumber(address)) var whyId by rememberSaveable { mutableStateOf(null) } + var chosen by rememberSaveable( + stateSaver = listSaver, Long>(save = { it.toList() }, restore = { it.toSet() }), + ) { mutableStateOf(emptySet()) } + val messages = group?.messages.orEmpty() + val selection = presentSelection(messages, chosen) + val selecting = selection.isNotEmpty() + BackHandler(enabled = selecting) { chosen = emptySet() } val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() Scaffold( modifier = modifier.nestedScroll(scrollBehavior.nestedScrollConnection), containerColor = MaterialTheme.colorScheme.background, contentColor = MaterialTheme.colorScheme.onBackground, topBar = { - UMessageTopBar(title = shown, onBack = actions.onBack, scrollBehavior = scrollBehavior) + if (selecting) { + BlockedSelectionBar( + messages = messages, + selection = selection, + actions = actions, + onChosenChange = { chosen = it }, + ) + } else { + UMessageTopBar(title = shown, onBack = actions.onBack, scrollBehavior = scrollBehavior) + } }, contentWindowInsets = chromeInsets(), - bottomBar = { if (group != null) HeldFooter(shown, actions, moving) }, + bottomBar = { if (group != null && !selecting) HeldFooter(shown, actions, moving) }, snackbarHost = { SnackbarHost(snackbarHostState) }, ) { inner -> val content = Modifier.fillMaxSize().padding(inner) @@ -257,6 +283,9 @@ fun BlockedThreadScreen( simLabel = simLabel(state.sims, item.message.subscriptionId), actions = actions, onWhy = { whyId = item.message.id }, + selecting = selecting, + selected = item.message.id in selection, + onToggle = { chosen = toggleMessageSelection(selection, item.message.id) }, ) } } @@ -372,8 +401,8 @@ private fun blockedDayText(context: Context, day: LocalDate, today: LocalDate): } /** - * One held message as an incoming bubble, with its time (and SIM on a dual-SIM phone) under it. Tap or long press - * opens its menu. + * One held message as an incoming bubble, with its time (and SIM on a dual-SIM phone) under it. Tap opens its menu; + * long press chooses it (and a tap then chooses or drops more) for Move to inbox or Delete of several at once. */ @OptIn(ExperimentalFoundationApi::class) @Composable @@ -383,6 +412,9 @@ private fun HeldBubble( simLabel: String?, actions: BlockedThreadActions, onWhy: () -> Unit, + selecting: Boolean, + selected: Boolean, + onToggle: () -> Unit, ) { val colors = MaterialTheme.colorScheme val context = LocalContext.current @@ -413,19 +445,23 @@ private fun HeldBubble( val shape = bubbleShape(sent = false, group = BubbleGroup.Single) Surface( shape = shape, - color = colors.surfaceContainerHighest, - contentColor = colors.onSurface, + color = if (selected) colors.primaryContainer else colors.surfaceContainerHighest, + contentColor = if (selected) colors.onPrimaryContainer else colors.onSurface, // An incoming bubble gets a hairline against a light page, as in a normal thread (TH-08). border = if (dark) null else BorderStroke(1.dp, colors.outlineVariant), modifier = Modifier .widthIn(max = maxWidth) .clip(shape) - .semantics(mergeDescendants = true) { contentDescription = "$body, $caption" } + .semantics(mergeDescendants = true) { + contentDescription = "$body, $caption" + if (selecting) this.selected = selected + } + // Tap: the message's menu, or choose it while choosing. Long press starts or extends choosing. .combinedClickable( - onClickLabel = actionsLabel, - onLongClickLabel = actionsLabel, - onClick = { menuOpen = true }, - onLongClick = { menuOpen = true }, + onClickLabel = if (selecting) null else actionsLabel, + onLongClickLabel = null, + onClick = { if (selecting) onToggle() else menuOpen = true }, + onLongClick = onToggle, ), ) { Column { diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedThreadSelection.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedThreadSelection.kt new file mode 100644 index 00000000..31298dbe --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/BlockedThreadSelection.kt @@ -0,0 +1,53 @@ +package com.glooboo.umessage.ui.spam + +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import com.glooboo.umessage.R +import com.glooboo.umessage.spam.BlockedMessage +import com.glooboo.umessage.ui.components.SelectionTopBar +import com.glooboo.umessage.ui.icons.Symbols + +/** The chosen ids after a tap on [id]: in when it was out, out when it was in. */ +internal fun toggleMessageSelection(selected: Set, id: Long): Set = + if (id in selected) selected - id else selected + id + +/** Of the [selected] ids only those still in [messages]: a message that left (moved, deleted, purged) drops out. */ +internal fun presentSelection(messages: List, selected: Set): Set { + if (selected.isEmpty()) return selected + return messages.mapTo(mutableSetOf()) { it.id }.intersect(selected) +} + +/** The chosen messages that "Move to inbox" can restore (an empty picture message has nothing to restore). */ +internal fun releasableSelection(messages: List, selected: Set): Set = + messages.filter { it.id in selected && it.canRestoreContent }.mapTo(mutableSetOf()) { it.id } + +/** The top bar while messages are chosen: Select all, Move to inbox and Delete for the chosen ones. */ +@Composable +internal fun BlockedSelectionBar( + messages: List, + selection: Set, + actions: BlockedThreadActions, + onChosenChange: (Set) -> Unit, +) { + val releasable = releasableSelection(messages, selection) + SelectionTopBar(count = selection.size, onClose = { onChosenChange(emptySet()) }) { + if (selection.size < messages.size) { + IconButton(onClick = { onChosenChange(messages.mapTo(mutableSetOf()) { it.id }) }) { + Icon( + Symbols.SelectAll, + contentDescription = stringResource(R.string.spam_action_select_all) + ) + } + } + if (releasable.isNotEmpty()) { + IconButton(onClick = { actions.onReleaseMessages(releasable); onChosenChange(emptySet()) }) { + Icon(Symbols.Inbox, contentDescription = stringResource(R.string.blocked_action_move_inbox)) + } + } + IconButton(onClick = { actions.onDeleteMessages(selection); onChosenChange(emptySet()) }) { + Icon(Symbols.Delete, contentDescription = stringResource(R.string.spam_action_delete)) + } + } +} 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 b66ba1cb..fce74f77 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 @@ -15,6 +15,7 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update @@ -163,6 +164,8 @@ class BlockedViewModel( */ private val pendingRestores = MutableStateFlow>(emptyMap()) + /** Tokens of "Delete all" deletions that also clear the restored list once they are final. */ + private val clearLogTokens = mutableSetOf() private var nextToken = 1L /** Restores being committed or undone, so the snackbar and the undo-window timer cannot run one twice. */ @@ -278,7 +281,15 @@ class BlockedViewModel( viewModelScope.launch { sims.value = withContext(Dispatchers.IO) { SimDirectory.load(getApplication()) } } - viewModelScope.launch { runCatching { repository.purgeExpired() } } + viewModelScope.launch { + runCatching { repository.purgeExpired() } + // The restored list goes with the blocked messages the purge deletes (spamui-15): its entries live no + // longer than the purge setting, and 30 days at most. + runCatching { + val days = repository.settings.first().purgeAfterDays + if (days > 0) restoredLog.dropOlderThan(days) + } + } } /** @@ -318,13 +329,22 @@ class BlockedViewModel( * "Release once" (ID-16): puts this one message in the inbox without allowing the sender. It is the restore * "Not spam" does, minus the allow rule, with the same Undo. */ - fun releaseOnce(messageId: Long) { + fun releaseOnce(messageId: Long) = releaseMessages(setOf(messageId)) + + /** + * "Move to inbox" for the messages chosen in the sender thread (spamui-11): one restore for all of them, without + * allowing the sender, with a single Undo. + */ + fun releaseMessages(messageIds: Set) { // A double tap can arrive before the state hides the message; the pending list is the up-to-date one (L4). - if (messageId in pendingIds()) return - val message = state.value.groups.firstNotNullOfOrNull { g -> g.messages.firstOrNull { it.id == messageId } } - ?: return + val pending = pendingIds() + val messages = state.value.groups.flatMap { it.messages } + .filter { it.id in messageIds && it.id !in pending } + if (messages.isEmpty()) return val token = nextToken++ - val restore = PendingRestore(listOf(message.id), emptyList(), messages = mapOf(message.id to message)) + val restore = PendingRestore( + messages.map { it.id }, emptyList(), messages = messages.associateBy { it.id }, + ) pendingRestores.update { it + (token to restore) } startRestore(token) } @@ -518,6 +538,16 @@ class BlockedViewModel( selected.value = emptySet() } + /** + * "Delete all": deletes every held message. When that really empties Blocked, the restored list is cleared with + * them once the deletion is final (spamui-15), so no sender numbers stay behind. + */ + fun deleteAll() { + val ids = idsOf(state.value.groups.map { it.address }.toSet()) + hideAndDelete(ids, clearsRestoredLog = ids.size >= state.value.heldCount) + selected.value = emptySet() + } + /** Delete of single messages from the sender thread, with the same Undo as [delete]. */ fun deleteMessages(messageIds: Set) { val pending = pendingIds() @@ -525,19 +555,25 @@ class BlockedViewModel( hideAndDelete(messageIds.filter { it in held && it !in pending }) } - private fun hideAndDelete(ids: List) { + private fun hideAndDelete(ids: List, clearsRestoredLog: Boolean = false) { if (ids.isEmpty()) return val token = nextToken++ + if (clearsRestoredLog) clearLogTokens += token pendingDeletes.update { it + (token to ids) } events.trySend(BlockedEvent.Deleted(token, ids.size)) } - fun undoDelete(token: Long) = pendingDeletes.update { it - token } + fun undoDelete(token: Long) { + clearLogTokens -= token + pendingDeletes.update { it - token } + } fun commitDelete(token: Long) { val ids = pendingDeletes.value[token] ?: return viewModelScope.launch { - runCatching { repository.deleteBlocked(ids) }.onFailure { events.trySend(BlockedEvent.Failed) } + runCatching { repository.deleteBlocked(ids) } + .onSuccess { if (clearLogTokens.remove(token)) restoredLog.clear() } + .onFailure { events.trySend(BlockedEvent.Failed) } pendingDeletes.update { it - token } } } @@ -562,6 +598,7 @@ class BlockedViewModel( // one being committed or undone finishes on its own). cleared = true val leftovers = pendingDeletes.value.values.flatten() + if (clearLogTokens.any { it in pendingDeletes.value }) restoredLog.clear() val finished = pendingRestores.value.filterKeys { it !in committing }.values .flatMap { it.receipts.orEmpty().values } if (leftovers.isNotEmpty() || finished.isNotEmpty()) { diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/CarrierReport.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/CarrierReport.kt index 25a28759..b4061dae 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/CarrierReport.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/CarrierReport.kt @@ -1,69 +1,79 @@ -package com.glooboo.umessage.ui.spam - -import android.content.Context -import com.glooboo.umessage.extensions.config -import com.glooboo.umessage.extensions.messagingUtils -import com.glooboo.umessage.spam.BlockedMessage -import com.klinker.android.send_message.Settings - -/** Sends [text] as an SMS to [number]. Tests give [CarrierReport] a fake one, so no test ever sends a real SMS. */ -fun interface ReportSender { - fun send(context: Context, text: String, number: String, subscriptionId: Int) -} - -/** The normal path: the app's own SMS sending, from the SIM [subscriptionId] when it is a real one. */ -object SmsReportSender : ReportSender { - override fun send(context: Context, text: String, number: String, subscriptionId: Int) { - context.messagingUtils.sendSmsMessage( - text = text, - addresses = setOf(number), - subId = subscriptionId.takeIf { it >= 0 } ?: Settings.DEFAULT_SUBSCRIPTION_ID, - requireDeliveryReport = false, - ) - } -} - -/** - * I32: "Report spam" to the carrier. Many carriers take a forwarded spam text at a short number (7726 in many - * countries), which needs no internet. The number is empty until the user enters their carrier's own, so nothing can - * be reported by accident or to a wrong number. It is a real, possibly paid SMS: [send] is only ever called after the - * user confirmed it in the dialog, and it sends nothing but the text of the one message being reported. - */ -class CarrierReport(context: Context, private val sender: ReportSender = SmsReportSender) { - - private val app = context.applicationContext - private val prefs = app.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) - - /** The carrier's short number, digits only; empty = not set, and Report spam is not offered. */ - var number: String - get() = prefs.getString(KEY_NUMBER, null).orEmpty() - set(value) = prefs.edit().putString(KEY_NUMBER, value.trim()).apply() - - /** Sends [message]'s text to [number]. False (and nothing sent) when no number is set or there is no text. */ - fun send(message: BlockedMessage): Boolean { - val target = number - if (!isValidNumber(target) || !message.hasText) return false - sender.send(app, message.body, target, message.subscriptionId) - return true - } - - companion object { - private const val PREFS_NAME = "umessage_carrier_report" - private const val KEY_NUMBER = "carrier_spam_number" - private const val MIN_DIGITS = 3 - private const val MAX_DIGITS = 8 - - /** A short number: 3 to 8 digits and nothing else. */ - fun isValidNumber(value: String): Boolean = - value.length in MIN_DIGITS..MAX_DIGITS && value.all { it in '0'..'9' } - - /** - * The one message a Report spam tap would send: the newest readable message of the single selected sender. - * Null when not exactly one sender is selected, so one tap never sends several paid SMS. - */ - fun pick(groups: List, selected: Set): BlockedMessage? = - selected.singleOrNull()?.let { address -> - groups.firstOrNull { it.address == address }?.messages?.firstOrNull { it.hasText } - } - } -} +package com.glooboo.umessage.ui.spam + +import android.content.Context +import com.glooboo.umessage.extensions.config +import com.glooboo.umessage.extensions.messagingUtils +import com.glooboo.umessage.spam.BlockedMessage +import com.klinker.android.send_message.Settings + +/** Sends [text] as an SMS to [number]. Tests give [CarrierReport] a fake one, so no test ever sends a real SMS. */ +fun interface ReportSender { + fun send(context: Context, text: String, number: String, subscriptionId: Int) +} + +/** The normal path: the app's own SMS sending, from the SIM [subscriptionId] when it is a real one. */ +object SmsReportSender : ReportSender { + override fun send(context: Context, text: String, number: String, subscriptionId: Int) { + context.messagingUtils.sendSmsMessage( + text = text, + addresses = setOf(number), + subId = subscriptionId.takeIf { it >= 0 } ?: Settings.DEFAULT_SUBSCRIPTION_ID, + requireDeliveryReport = false, + ) + } +} + +/** + * I32: "Report spam" to the carrier. Many carriers take a forwarded spam text at a short number (7726 in many + * countries), which needs no internet. The number is empty until the user enters their carrier's own, so nothing can + * be reported by accident or to a wrong number. It is a real, possibly paid SMS: [send] is only ever called after the + * user confirmed it in the dialog, and it sends nothing but the text of the one message being reported and, under + * it, the number it came from (carriers answer a report with "which number sent this?"). + */ +class CarrierReport(context: Context, private val sender: ReportSender = SmsReportSender) { + + private val app = context.applicationContext + private val prefs = app.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + + /** The carrier's short number, digits only; empty = not set, and Report spam is not offered. */ + var number: String + get() = prefs.getString(KEY_NUMBER, null).orEmpty() + set(value) = prefs.edit().putString(KEY_NUMBER, value.trim()).apply() + + /** + * Sends [message]'s text and its sender to [number], as one SMS. False (and nothing sent) when no number is set or + * there is no text. + */ + fun send(message: BlockedMessage): Boolean { + val target = number + if (!isValidNumber(target) || !message.hasText) return false + sender.send(app, reportText(message), target, message.subscriptionId) + return true + } + + companion object { + private const val PREFS_NAME = "umessage_carrier_report" + private const val KEY_NUMBER = "carrier_spam_number" + private const val MIN_DIGITS = 3 + private const val MAX_DIGITS = 8 + + /** What a report says: the message text, then the number or name it came from on a line of its own. */ + fun reportText(message: BlockedMessage): String { + val sender = message.address.trim() + return if (sender.isEmpty()) message.body else message.body.trimEnd() + "\n" + sender + } + + /** A short number: 3 to 8 digits and nothing else. */ + fun isValidNumber(value: String): Boolean = + value.length in MIN_DIGITS..MAX_DIGITS && value.all { it in '0'..'9' } + + /** + * The one message a Report spam tap would send: the newest readable message of the single selected sender. + * Null when not exactly one sender is selected, so one tap never sends several paid SMS. + */ + fun pick(groups: List, selected: Set): BlockedMessage? = + selected.singleOrNull()?.let { address -> + groups.firstOrNull { it.address == address }?.messages?.firstOrNull { it.hasText } + } + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleDryRun.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleDryRun.kt new file mode 100644 index 00000000..98188828 --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleDryRun.kt @@ -0,0 +1,139 @@ +package com.glooboo.umessage.ui.spam + +import android.content.Context +import android.provider.Telephony.Sms +import com.glooboo.umessage.spam.BlockedMessage +import com.glooboo.umessage.spam.IncomingMessage +import com.glooboo.umessage.spam.SpamRule +import com.glooboo.umessage.spam.engine.NumberNormalizer +import com.glooboo.umessage.spam.engine.RuleMatcher +import com.glooboo.umessage.spam.engine.defaultRegion +import com.glooboo.umessage.spam.engine.subscriptionRegion +import com.glooboo.umessage.ui.lock.LockScope +import org.fossify.commons.extensions.appLockManager + +/** + * One message the "test this rule" preview tries the rule on. Held only while the scan runs; never stored or + * logged. + */ +class DryRunMessage(val address: String, val body: String, val subscriptionId: Int) + +/** What the rule would match in one place (the inbox or Blocked history). [senders] is empty when they are hidden. */ +data class DryRunPart(val scanned: Int = 0, val matched: Int = 0, val senders: List = emptyList()) + +data class RuleDryRunResult(val inbox: DryRunPart = DryRunPart(), val blocked: DryRunPart = DryRunPart()) { + val isEmpty: Boolean get() = inbox.scanned == 0 && blocked.scanned == 0 +} + +/** State of the preview in the rule sheet. */ +sealed interface RulePreviewState { + data object Idle : RulePreviewState + data object Loading : RulePreviewState + data class Done(val result: RuleDryRunResult) : RulePreviewState + data object Failed : RulePreviewState +} + +/** + * The pure counting behind "Test this rule": the same [RuleMatcher] the filter uses, over a capped list of + * messages. + */ +object RuleDryRun { + /** Newest messages tried in each place, so a big inbox never makes the preview slow. */ + const val MAX_SCAN = 100 + const val MAX_EXAMPLES = 3 + + /** + * How many of the newest [cap] [messages] (given newest first) [rule] matches, with up to [MAX_EXAMPLES] different + * senders as examples when [showSenders]. A rule for one SIM only sees that SIM's messages, as in the filter. + * [keepGoing] is asked between messages so a stale scan can stop early. + */ + fun scan( + matcher: RuleMatcher, + rule: SpamRule, + messages: List, + showSenders: Boolean = true, + cap: Int = MAX_SCAN, + keepGoing: () -> Boolean = { true }, + ): DryRunPart { + var scanned = 0 + var matched = 0 + val senders = LinkedHashSet() + for (message in messages) { + if (scanned >= cap || !keepGoing()) break + scanned++ + if (hits(matcher, rule, message)) { + matched++ + if (showSenders && senders.size < MAX_EXAMPLES && message.address.isNotBlank()) { + senders += message.address + } + } + } + return DryRunPart(scanned, matched, senders.toList()) + } + + /** Whether [rule] matches [message]; a rule for one SIM never sees another SIM's messages. */ + private fun hits(matcher: RuleMatcher, rule: SpamRule, message: DryRunMessage): Boolean { + if (rule.subscriptionId != null && rule.subscriptionId != message.subscriptionId) return false + return runCatching { + matcher.matches(rule, IncomingMessage(message.address, message.body, message.subscriptionId)) + }.getOrDefault(false) + } + + fun blockedMessages(blocked: List, cap: Int = MAX_SCAN): List = + blocked.asSequence() + .filter { it.hasText } + .sortedByDescending { it.receivedAt } + .take(cap) + .map { DryRunMessage(it.address, it.body, it.subscriptionId) } + .toList() +} + +/** Where the preview reads the inbox and the matcher from. Blocking; call off the main thread. */ +interface RulePreviewSource { + fun matcher(): RuleMatcher + + /** The newest received texts, newest first, at most [limit]. Empty when the inbox cannot be read. */ + fun inbox(limit: Int): List + + /** False while the app lock covers Blocked and is locked: counts stay, example senders are not shown. */ + fun blockedSendersVisible(): Boolean +} + +object NoRulePreviewSource : RulePreviewSource { + override fun matcher() = RuleMatcher(NumberNormalizer { "GB" }) + override fun inbox(limit: Int): List = emptyList() + override fun blockedSendersVisible() = true +} + +class AndroidRulePreviewSource(context: Context) : RulePreviewSource { + private val app = context.applicationContext + + override fun matcher() = RuleMatcher( + NumberNormalizer { defaultRegion(app) }, + regionForSubscription = { subscriptionRegion(app, it) }, + ) + + override fun inbox(limit: Int): List = runCatching { + val out = ArrayList() + app.contentResolver.query( + Sms.Inbox.CONTENT_URI, + arrayOf(Sms.ADDRESS, Sms.BODY, Sms.SUBSCRIPTION_ID), + null, + null, + "${Sms.DATE} DESC", + )?.use { cursor -> + val address = cursor.getColumnIndexOrThrow(Sms.ADDRESS) + val body = cursor.getColumnIndexOrThrow(Sms.BODY) + val sub = cursor.getColumnIndexOrThrow(Sms.SUBSCRIPTION_ID) + while (out.size < limit && cursor.moveToNext()) { + out += DryRunMessage( + cursor.getString(address).orEmpty(), cursor.getString(body).orEmpty(), cursor.getInt(sub) + ) + } + } + out + }.getOrDefault(emptyList()) + + override fun blockedSendersVisible(): Boolean = + runCatching { !(LockScope.blockedLocked(app) && app.appLockManager.isLocked()) }.getOrDefault(false) +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleRecentTest.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleRecentTest.kt new file mode 100644 index 00000000..bdabeb64 --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/RuleRecentTest.kt @@ -0,0 +1,94 @@ +package com.glooboo.umessage.ui.spam + +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.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import com.glooboo.umessage.R +import com.glooboo.umessage.ui.components.displayNumber +import com.glooboo.umessage.ui.components.isolateNumbers +import com.glooboo.umessage.ui.icons.Symbols + +/** + * "Test on recent messages" (spam-21): how many of the newest inbox texts and Blocked messages the rule being edited + * would match, with a few sender examples. Shown for every rule type once the value is valid; runs only when tapped. + * Nothing is stored or logged. + */ +@Composable +fun RuleRecentTest(valid: Boolean, preview: RulePreviewState, onRun: () -> Unit, modifier: Modifier = Modifier) { + if (!valid) return + Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) { + TextButton(onClick = onRun, enabled = preview != RulePreviewState.Loading) { + Icon(Symbols.Search, contentDescription = null, modifier = Modifier.size(18.dp)) + Text(stringResource(R.string.rule_preview_button), modifier = Modifier.padding(start = 8.dp)) + } + val live = Modifier.semantics { liveRegion = LiveRegionMode.Polite } + when (preview) { + RulePreviewState.Idle -> Unit + RulePreviewState.Loading -> Row(live, verticalAlignment = Alignment.CenterVertically) { + CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) + Text( + stringResource(R.string.rule_preview_loading), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 8.dp), + ) + } + RulePreviewState.Failed -> Text( + stringResource(R.string.rule_preview_failed), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + modifier = live, + ) + is RulePreviewState.Done -> Column(live, verticalArrangement = Arrangement.spacedBy(8.dp)) { + if (preview.result.isEmpty) { + PreviewLine(stringResource(R.string.rule_preview_nothing)) + } else { + PreviewPart(R.string.rule_preview_inbox, R.string.rule_preview_inbox_empty, preview.result.inbox) + PreviewPart( + R.string.rule_preview_blocked, R.string.rule_preview_blocked_empty, preview.result.blocked + ) + } + } + } + } +} + +@Composable +private fun PreviewPart(summary: Int, empty: Int, part: DryRunPart) { + if (part.scanned == 0) { + PreviewLine(stringResource(empty)) + return + } + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + PreviewLine(stringResource(summary, part.matched, part.scanned)) + if (part.senders.isNotEmpty()) { + val names = part.senders.map { isolateNumbers(displayNumber(it)) }.joinToString(", ") + PreviewLine(stringResource(R.string.rule_preview_examples, names), small = true) + } + } +} + +@Composable +private fun PreviewLine(text: String, small: Boolean = false) { + Text( + text, + style = if (small) MaterialTheme.typography.bodySmall else MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} 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 50857d42..b65c804e 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 @@ -162,6 +162,8 @@ class RulesActions( val onDeleteEditing: () -> Unit = {}, // Wave 3: starter examples of the empty tabs (ID-53) val onExample: (ListKind, RuleType, String) -> Unit = { _, _, _ -> }, + // spam-21: "Test this rule" against recent messages + val onPreview: () -> Unit = {}, ) @Composable @@ -222,6 +224,7 @@ fun RulesRoute( onKind = viewModel::setKind, onDeleteEditing = viewModel::deleteEditing, onExample = viewModel::openExample, + onPreview = viewModel::previewRule, ) } RulesScreen(state, snackbar, actions) @@ -233,6 +236,7 @@ private fun RulesEvents(viewModel: RulesViewModel, snackbar: SnackbarHostState) val resources = LocalContext.current.resources val undoLabel = stringResource(R.string.spam_undo) val deletedText = stringResource(R.string.spam_rules_deleted) + val failedText = stringResource(R.string.spam_snack_failed) LaunchedEffect(viewModel) { viewModel.eventFlow.collect { event -> snackbar.currentSnackbarData?.dismiss() @@ -252,6 +256,7 @@ private fun RulesEvents(viewModel: RulesViewModel, snackbar: SnackbarHostState) snackbar.showSnackbar(migratedText(resources, event), duration = SnackbarDuration.Long) is RulesEvent.AddedFromContacts -> snackbar.showSnackbar(contactsAddedText(resources, event), duration = SnackbarDuration.Long) + RulesEvent.Failed -> snackbar.showSnackbar(failedText, duration = SnackbarDuration.Long) } } } @@ -312,7 +317,7 @@ fun RulesScreen( modifier = Modifier.padding(top = inner.calculateTopPadding()).fillMaxSize(), ) } - state.form?.let { AddRuleSheet(it, state.sims, actions) } + state.form?.let { AddRuleSheet(it, state.sims, actions, state.preview) } if (testOpen) { TestMessageSheet( sims = state.sims, @@ -1019,7 +1024,12 @@ internal suspend fun SnackbarHostState.showUndo(message: String, actionLabel: St @OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable -fun AddRuleSheet(form: RuleForm, sims: List, actions: RulesActions) { +fun AddRuleSheet( + form: RuleForm, + sims: List, + actions: RulesActions, + preview: RulePreviewState = RulePreviewState.Idle, +) { val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) var pickingContacts by rememberSaveable { mutableStateOf(false) } val error = form.visibleError @@ -1036,14 +1046,7 @@ fun AddRuleSheet(form: RuleForm, sims: List, actions: RulesActions) { verticalArrangement = Arrangement.spacedBy(16.dp), ) { Text( - stringResource( - when { - form.isEdit && form.kind == ListKind.ALLOW -> R.string.rules_sheet_title_edit_allow - form.isEdit -> R.string.rules_sheet_title_edit_block - form.kind == ListKind.ALLOW -> R.string.ux8d_sheet_title_allow - else -> R.string.ux8d_sheet_title_block - }, - ), + stringResource(ruleSheetTitle(form)), style = MaterialTheme.typography.titleLarge, modifier = Modifier.semantics { heading() }, ) @@ -1052,36 +1055,7 @@ fun AddRuleSheet(form: RuleForm, sims: List, actions: RulesActions) { RuleKindChoice(form.kind, actions.onKind) if (form.type == RuleType.REGEX) PatternBlockChips(form.pattern, actions.onPattern) - val clearCd = stringResource(R.string.spam_sheet_clear_value) - OutlinedTextField( - value = form.pattern, - onValueChange = actions.onPattern, - modifier = Modifier.fillMaxWidth(), - label = { Text(stringResource(valueLabel(form.type))) }, - placeholder = { Text(typeHint(form.type)) }, - singleLine = true, - isError = error != null, - supportingText = { Text(if (error != null) errorText(error) else typeHelp(form.kind, form.type)) }, - textStyle = MaterialTheme.typography.bodyLarge.let { - if (form.type == RuleType.REGEX) it.copy(fontFamily = FontFamily.Monospace) else it - }, - keyboardOptions = KeyboardOptions( - capitalization = KeyboardCapitalization.None, - autoCorrectEnabled = false, - keyboardType = if (form.type.isSender && form.type != RuleType.SENDER_ID) { - KeyboardType.Phone - } else { - KeyboardType.Text - }, - ), - trailingIcon = { - if (form.pattern.isNotEmpty()) { - IconButton(onClick = { actions.onPattern("") }) { - Icon(Symbols.Close, contentDescription = clearCd) - } - } - }, - ) + RuleValueField(form, error, actions.onPattern) // Several contacts at once: one rule per number, in the list chosen above. if (form.type == RuleType.NUMBER && !form.isEdit) { @@ -1093,6 +1067,8 @@ fun AddRuleSheet(form: RuleForm, sims: List, actions: RulesActions) { // Try a keyword or pattern on a sample message before it is saved. RulePatternTest(form.kind, form.type, form.pattern, valid = form.validation is RuleValidation.Valid) + RuleRecentTest(form.validation is RuleValidation.Valid, preview, actions.onPreview) + RuleSheetExtras(form, sims, actions) if (error == null && form.warnings.isNotEmpty()) RuleWarnings(form.warnings) @@ -1107,31 +1083,12 @@ fun AddRuleSheet(form: RuleForm, sims: List, actions: RulesActions) { } // Deleting lives here, away from the save button, and is undoable from the snackbar. - if (form.isEdit) { - TextButton(onClick = actions.onDeleteEditing, modifier = Modifier.heightIn(min = 48.dp)) { - Icon( - Symbols.Delete, - contentDescription = null, - tint = MaterialTheme.colorScheme.error, - modifier = Modifier.size(18.dp), - ) - Text( - stringResource(R.string.rules2_sheet_delete), - color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(start = 8.dp), - ) - } - } + if (form.isEdit) DeleteRuleButton(actions.onDeleteEditing) } RuleSheetBar( saveLabel = stringResource(if (form.isEdit) R.string.rules_sheet_save else R.string.spam_sheet_add), enabled = form.canSubmit, - hint = when { - form.saving -> null - form.pattern.isBlank() -> stringResource(R.string.rules2_sheet_hint_empty) - error != null -> stringResource(R.string.rules2_sheet_hint_fix) - else -> null - }, + hint = ruleSheetHint(form, error), onCancel = actions.onDismissForm, onSave = actions.onSubmit, ) @@ -1150,6 +1107,73 @@ fun AddRuleSheet(form: RuleForm, sims: List, actions: RulesActions) { if (form.confirming) ConfirmRuleDialog(form, actions) } +private fun ruleSheetTitle(form: RuleForm): Int = when { + form.isEdit && form.kind == ListKind.ALLOW -> R.string.rules_sheet_title_edit_allow + form.isEdit -> R.string.rules_sheet_title_edit_block + form.kind == ListKind.ALLOW -> R.string.ux8d_sheet_title_allow + else -> R.string.ux8d_sheet_title_block +} + +@Composable +private fun ruleSheetHint(form: RuleForm, error: RuleValidation.Invalid?): String? = when { + form.saving -> null + form.pattern.isBlank() -> stringResource(R.string.rules2_sheet_hint_empty) + error != null -> stringResource(R.string.rules2_sheet_hint_fix) + else -> null +} + +@Composable +private fun RuleValueField(form: RuleForm, error: RuleValidation.Invalid?, onPattern: (String) -> Unit) { + val clearCd = stringResource(R.string.spam_sheet_clear_value) + OutlinedTextField( + value = form.pattern, + onValueChange = onPattern, + modifier = Modifier.fillMaxWidth(), + label = { Text(stringResource(valueLabel(form.type))) }, + placeholder = { Text(typeHint(form.type)) }, + singleLine = true, + isError = error != null, + supportingText = { Text(if (error != null) errorText(error) else typeHelp(form.kind, form.type)) }, + textStyle = MaterialTheme.typography.bodyLarge.let { + if (form.type == RuleType.REGEX) it.copy(fontFamily = FontFamily.Monospace) else it + }, + keyboardOptions = KeyboardOptions( + capitalization = KeyboardCapitalization.None, + autoCorrectEnabled = false, + keyboardType = if (form.type.isSender && form.type != RuleType.SENDER_ID) { + KeyboardType.Phone + } else { + KeyboardType.Text + }, + ), + trailingIcon = { + if (form.pattern.isNotEmpty()) { + IconButton(onClick = { onPattern("") }) { + Icon(Symbols.Close, contentDescription = clearCd) + } + } + }, + ) +} + +/** Deleting lives here, away from the save button, and is undoable from the snackbar. */ +@Composable +private fun DeleteRuleButton(onClick: () -> Unit) { + TextButton(onClick = onClick, modifier = Modifier.heightIn(min = 48.dp)) { + Icon( + Symbols.Delete, + contentDescription = null, + tint = MaterialTheme.colorScheme.error, + modifier = Modifier.size(18.dp), + ) + Text( + stringResource(R.string.rules2_sheet_delete), + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(start = 8.dp), + ) + } +} + /** Sender types first, then the ones about the message text: the same two groups as the forward editor (BR-44). */ private val RuleType.isSender: Boolean get() = this == RuleType.NUMBER || this == RuleType.PREFIX || this == RuleType.SENDER_ID 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 bacb9a50..3ed5d8fa 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 @@ -8,6 +8,7 @@ import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted @@ -17,6 +18,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import com.glooboo.umessage.spam.ListKind @@ -86,6 +88,8 @@ data class RulesUiState( /** The old Fossify lists not yet moved into rules, shown read-only on the Blocked tab. */ val legacy: LegacyLists = LegacyLists(offerDismissed = true), val migration: MigrationDialog? = null, + /** "Test this rule" on the open sheet: how many recent messages it would match. */ + val preview: RulePreviewState = RulePreviewState.Idle, ) { val current: List get() = if (tab == ListKind.ALLOW) allowed else blocked val filtering: Boolean get() = query.isNotBlank() || typeFilter != null @@ -125,6 +129,9 @@ sealed interface RulesEvent { /** Rules made from contacts picked in the add sheet; [skipped] numbers already had a rule or were not usable. */ data class AddedFromContacts(val added: Int, val skipped: Int) : RulesEvent + + /** A delete or an undo could not be saved. */ + data object Failed : RulesEvent } class RulesViewModel( @@ -132,6 +139,7 @@ class RulesViewModel( private val repository: SpamRepository, private val legacyStore: LegacyBlockStore = NoLegacyBlockStore, private val io: CoroutineDispatcher = Dispatchers.IO, + private val previewSource: RulePreviewSource = NoRulePreviewSource, ) : AndroidViewModel(application) { private data class View( @@ -153,7 +161,12 @@ class RulesViewModel( private val events = Channel(Channel.BUFFERED) val eventFlow = events.receiveAsFlow() - val state: StateFlow = combine(repository.rules, view, form, extras) { rules, view, form, extras -> + private val preview = MutableStateFlow(RulePreviewState.Idle) + private var previewJob: Job? = null + + val state: StateFlow = combine( + repository.rules, view, form, extras, preview + ) { rules, view, form, extras, preview -> val sorted = rules.sortedByDescending { it.createdAt } val ids = sorted.map { it.id }.toSet() RulesUiState( @@ -168,6 +181,7 @@ class RulesViewModel( selected = view.selected intersect ids, legacy = extras.legacy, migration = extras.migration, + preview = preview, ) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), RulesUiState()) @@ -203,7 +217,9 @@ class RulesViewModel( if (rules.isEmpty()) return clearSelection() viewModelScope.launch { - runCatching { repository.removeRules(rules.map { it.id }) }.onSuccess { events.trySend(RulesEvent.Deleted(rules)) } + runCatching { repository.removeRules(rules.map { it.id }) } + .onSuccess { events.trySend(RulesEvent.Deleted(rules)) } + .onFailure { events.trySend(RulesEvent.Failed) } } } @@ -211,19 +227,62 @@ class RulesViewModel( // region Add and edit - fun openForm() { form.value = RuleForm(kind = view.value.tab) } + fun openForm() { + resetPreview() + form.value = RuleForm(kind = view.value.tab) + } + + private fun resetPreview() { + previewJob?.cancel() + previewJob = null + preview.value = RulePreviewState.Idle + } + + /** + * "Test this rule": counts what the rule in the open sheet would match among the newest inbox texts and Blocked + * messages, off the main thread. Nothing is stored or logged; the form's own state is not changed. + */ + fun previewRule() { + val f = form.value ?: return + val valid = f.validation as? RuleValidation.Valid ?: return + val rule = SpamRule(kind = f.kind, type = f.type, pattern = valid.pattern, subscriptionId = f.subscriptionId) + previewJob?.cancel() + preview.value = RulePreviewState.Loading + val job = viewModelScope.launch { + val outcome = runCatching { + val blocked = repository.blocked.first() + withContext(io) { + val matcher = previewSource.matcher() + val inbox = RuleDryRun.scan( + matcher, rule, previewSource.inbox(RuleDryRun.MAX_SCAN), keepGoing = { isActive }, + ) + val showSenders = previewSource.blockedSendersVisible() + val history = RuleDryRun.scan( + matcher, rule, RuleDryRun.blockedMessages(blocked), showSenders = showSenders, + keepGoing = { isActive }, + ) + RuleDryRunResult(inbox, history) + } + } + if (!isActive) return@launch + preview.value = outcome.fold({ RulePreviewState.Done(it) }, { RulePreviewState.Failed }) + } + previewJob = job + } /** * The starter examples of the empty tabs (ID-53): the add sheet, already set to [kind] and [type], with a * concrete [value] filled in when the example has one. */ fun openExample(kind: ListKind, type: RuleType, value: String = "") { + resetPreview() val blank = RuleForm(kind = kind, type = type) form.value = if (value.isEmpty()) blank else revalidate(blank.copy(pattern = value)) } /** Opens the same sheet as Add, filled in with [rule]; saving changes the rule in place. */ fun openEdit(rule: SpamRule) { + resetPreview() form.value = revalidate( RuleForm( kind = rule.kind, @@ -237,7 +296,10 @@ class RulesViewModel( ) } - fun dismissForm() { form.value = null } + fun dismissForm() { + resetPreview() + form.value = null + } /** * One rule per picked contact number in the sheet's list (Always allow or Always block), in the sheet's SIM @@ -276,6 +338,8 @@ class RulesViewModel( fun setNote(note: String) = editForm { it.copy(note = note.take(80)) } private fun editForm(change: (RuleForm) -> RuleForm) = form.update { current -> + // A changed rule makes an earlier count stale. + if (preview.value != RulePreviewState.Idle) resetPreview() current?.let { revalidate(change(it).copy(saveFailed = false)) } } @@ -375,13 +439,17 @@ class RulesViewModel( fun delete(rule: SpamRule) { viewModelScope.launch { - runCatching { repository.removeRule(rule.id) }.onSuccess { events.trySend(RulesEvent.Deleted(listOf(rule))) } + runCatching { repository.removeRule(rule.id) } + .onSuccess { events.trySend(RulesEvent.Deleted(listOf(rule))) } + .onFailure { events.trySend(RulesEvent.Failed) } } } /** Undo of a delete: the rules come back with their old ids, so blocked messages' reasons find them again. */ fun restore(rules: List) { - viewModelScope.launch { runCatching { repository.restoreRules(rules) } } + viewModelScope.launch { + runCatching { repository.restoreRules(rules) }.onFailure { events.trySend(RulesEvent.Failed) } + } } // region Old block lists (SU-33) @@ -485,7 +553,10 @@ class RulesViewModel( val Factory = viewModelFactory { initializer { val app = this[APPLICATION_KEY] as Application - RulesViewModel(app, SpamRepositoryProvider.get(app), AndroidLegacyBlockStore(app)) + RulesViewModel( + app, SpamRepositoryProvider.get(app), AndroidLegacyBlockStore(app), + previewSource = AndroidRulePreviewSource(app), + ) } } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/SenderBlocking.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/SenderBlocking.kt index 796b0b09..d8e84325 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/SenderBlocking.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/SenderBlocking.kt @@ -8,7 +8,9 @@ import com.glooboo.umessage.spam.SpamFilter import com.glooboo.umessage.spam.SpamRepository import com.glooboo.umessage.spam.SpamRule import com.glooboo.umessage.ui.thread.planSpamReport +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.first import kotlinx.coroutines.withContext @@ -99,12 +101,22 @@ object SenderBlocking { * The allow rules of "Not spam" on the Blocked screen: removes the senders' own block rules (they would be * dead weight under an allow rule) and adds an allow rule for each. */ + @Suppress("TooGenericExceptionCaught") // Any failure undoes the partial change and is rethrown. suspend fun alwaysAllow(repository: SpamRepository, addresses: Collection): AllowChange { val removed = mutableListOf() val added = mutableListOf() - addresses.map { it.trim() }.filter { it.isNotEmpty() }.distinct().forEach { address -> - removed += unblock(repository, address) - added += allow(repository, address) + try { + addresses.map { it.trim() }.filter { it.isNotEmpty() }.distinct().forEach { address -> + removed += unblock(repository, address) + added += allow(repository, address) + } + } catch (e: CancellationException) { + withContext(NonCancellable) { runCatching { undoAllow(repository, AllowChange(added, removed)) } } + throw e + } catch (e: Exception) { + // Put back what was already changed, so a failure never leaves a sender with neither rule. + runCatching { undoAllow(repository, AllowChange(added, removed)) } + throw e } return AllowChange(added, removed) } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/SettingsScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/SettingsScreen.kt index b8f1605b..d0d4a7ac 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/SettingsScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/SettingsScreen.kt @@ -1,398 +1,406 @@ -package com.glooboo.umessage.ui.spam - -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.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.Card -import androidx.compose.material3.CardDefaults -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.material3.TopAppBarDefaults -import androidx.compose.runtime.Composable -import androidx.compose.runtime.Immutable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import com.glooboo.umessage.ui.components.ChoiceDialog -import androidx.compose.runtime.remember -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.LiveRegionMode -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.heading -import androidx.compose.ui.semantics.liveRegion -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.tooling.preview.Preview -import androidx.compose.ui.unit.dp -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.lifecycle.viewmodel.compose.viewModel -import com.glooboo.umessage.R -import com.glooboo.umessage.spam.SpamSettings -import com.glooboo.umessage.spam.UnknownInboxNotify -import com.glooboo.umessage.spam.UnknownSenderMode -import com.glooboo.umessage.ui.components.SettingsGroup -import com.glooboo.umessage.ui.components.SettingsRadioRow -import com.glooboo.umessage.ui.components.SettingsRow -import com.glooboo.umessage.ui.components.SettingsSwitchRow -import com.glooboo.umessage.ui.icons.Symbols -import com.glooboo.umessage.ui.theme.UMessageTheme -import androidx.compose.ui.unit.Dp -import com.glooboo.umessage.ui.components.UMessageScaffold -import com.glooboo.umessage.ui.components.UMessageTopBar -import com.glooboo.umessage.ui.components.uiLocale -import androidx.compose.ui.platform.LocalContext -import com.glooboo.umessage.helpers.threadPrefs - -@Immutable -class SettingsActions( - val onBack: () -> Unit = {}, - val onOpenRules: () -> Unit = {}, - val onOpenBlocked: () -> Unit = {}, - val onMode: (UnknownSenderMode) -> Unit = {}, - val onPurgeDays: (Int) -> Unit = {}, - val onNotify: (Boolean) -> Unit = {}, - val onUnknownNotify: (UnknownInboxNotify) -> Unit = {}, - val onOpenLinkAction: (Boolean) -> Unit = {}, - val onOutsideRegion: (String) -> Unit = {}, - /** Null hides the "Why was it blocked?" row (no engine log in this build). */ - val onOpenDecisionLog: (() -> Unit)? = null, -) - -@Composable -fun SettingsRoute( - onBack: () -> Unit, - onOpenRules: () -> Unit, - onOpenBlocked: () -> Unit, - onOpenDecisionLog: (() -> Unit)? = null, -) { - val viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory) - val state by viewModel.state.collectAsStateWithLifecycle() - val actions = remember(viewModel, onBack, onOpenRules, onOpenBlocked, onOpenDecisionLog) { - SettingsActions( - onBack = onBack, - onOpenRules = onOpenRules, - onOpenBlocked = onOpenBlocked, - onMode = viewModel::setMode, - onPurgeDays = viewModel::setPurgeDays, - onNotify = viewModel::setNotifyOnBlock, - onUnknownNotify = viewModel::setUnknownInboxNotify, - onOpenLinkAction = viewModel::setOpenLinkAction, - onOutsideRegion = viewModel::setBlockOutsideRegion, - onOpenDecisionLog = onOpenDecisionLog, - ) - } - SettingsScreen(state, actions) -} - -@Composable -fun SettingsScreen(state: SettingsUiState, actions: SettingsActions) { - UMessageScaffold( - topBar = { - UMessageTopBar(title = stringResource(R.string.settings_nav_spam_page_title), onBack = actions.onBack) - }, - ) { inner -> - if (state.loading) { - Column(Modifier.padding(top = inner.calculateTopPadding()).fillMaxWidth().padding(48.dp), horizontalAlignment = Alignment.CenterHorizontally) { - val label = stringResource(R.string.spam_loading) - CircularProgressIndicator(Modifier.semantics { contentDescription = label }) - } - } else { - SettingsContent(state, actions, Modifier.padding(top = inner.calculateTopPadding()), inner.calculateBottomPadding()) - } - } -} - -@Composable -private fun SettingsContent(state: SettingsUiState, actions: SettingsActions, modifier: Modifier = Modifier, bottomInset: Dp = 0.dp) { - val settings = state.settings - // SE-23: choosing Strict first asks, because it also blocks verification codes. - var confirmStrict by rememberSaveable { mutableStateOf(false) } - var purgeDialog by rememberSaveable { mutableStateOf(false) } - var unknownNotifyDialog by rememberSaveable { mutableStateOf(false) } - var regionDialog by rememberSaveable { mutableStateOf(false) } - var restoredOpen by rememberSaveable { mutableStateOf(false) } - val chooseMode: (UnknownSenderMode) -> Unit = { mode -> - if (mode == UnknownSenderMode.STRICT && settings.mode != UnknownSenderMode.STRICT) { - confirmStrict = true - } else { - actions.onMode(mode) - } - } - Column( - modifier = modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 32.dp + bottomInset), - ) { - // U02: the one Spam protection page: the mode, the rules, retention, countries, links and alerts. - SettingsGroup( - title = stringResource(R.string.spam_settings_unknown_title), - description = stringResource(R.string.spam_settings_unknown_body), - ) { - ModeChoice( - UnknownSenderMode.STRICT, R.string.spam_mode_strict, R.string.spam_mode_strict_body, - settings, chooseMode, - ) - ModeChoice( - UnknownSenderMode.SMART, R.string.spam_mode_smart, R.string.spam_mode_smart_body, - settings, chooseMode, - badge = stringResource(R.string.settings_nav_recommended), - ) - ModeChoice( - UnknownSenderMode.OFF, R.string.spam_mode_off, R.string.spam_mode_off_body, - settings, chooseMode, - ) - } - if (settings.mode == UnknownSenderMode.STRICT) { - StrictWarning( - onReview = actions.onOpenBlocked, - modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 8.dp), - ) - } - - SettingsGroup(stringResource(R.string.settings_f_group_rules)) { - SettingsRow( - title = stringResource(R.string.settings_spam_open_rules), - summary = stringResource(R.string.settings_spam_open_rules_body), - onClick = actions.onOpenRules, - showChevron = true, - ) - SettingsRow( - title = stringResource(R.string.blocked_menu_restored), - summary = stringResource(R.string.blocked_menu_restored_summary), - onClick = { restoredOpen = true }, - showChevron = true, - ) - } - - SettingsGroup(stringResource(R.string.spam_settings_cleanup_title)) { - // SE-25: one dropdown-style row instead of chips that wrap onto a second line. - SettingsRow( - title = stringResource(R.string.settings_nav_purge_row), - summary = stringResource(R.string.spam_purge_body), - value = purgeLabel(settings.purgeAfterDays), - onClick = { purgeDialog = true }, - showChevron = true, - ) - } - - SettingsGroup(stringResource(R.string.region_group_title)) { - SettingsRow( - title = stringResource(R.string.region_title), - summary = stringResource(R.string.region_summary), - value = regionValue(settings.blockOutsideRegion), - onClick = { regionDialog = true }, - showChevron = true, - ) - } - - LinksGroup() - - CarrierReportGroup() - - SettingsGroup(stringResource(R.string.settings_nav_group_alerts)) { - SettingsSwitchRow( - title = stringResource(R.string.spam_notify_title), - summary = stringResource(R.string.settings_nav_notify_body), - checked = settings.notifyOnBlock, - onCheckedChange = actions.onNotify, - ) - SettingsRow( - title = stringResource(R.string.unotify_title), - summary = stringResource(R.string.unotify_summary), - value = unknownNotifyLabel(settings.unknownInboxNotify), - onClick = { unknownNotifyDialog = true }, - showChevron = true, - ) - SettingsSwitchRow( - title = stringResource(R.string.notif_open_link_title), - summary = stringResource(R.string.notif_open_link_summary), - checked = settings.openLinkAction, - onCheckedChange = actions.onOpenLinkAction, - ) - } - - // U45: the log is named Recent activity and linked once, from here. - val openLog = actions.onOpenDecisionLog - if (openLog != null) { - SettingsGroup(stringResource(R.string.settings_ui_more)) { - SettingsRow( - title = stringResource(R.string.settings_nav_decision_log), - summary = stringResource(R.string.settings_nav_decision_log_body), - onClick = openLog, - showChevron = true, - ) - } - } - } - - if (restoredOpen) { - val restored by RestoredLog.get(LocalContext.current).entries.collectAsStateWithLifecycle() - RestoredSheet(restored, onDismiss = { restoredOpen = false }) - } - if (confirmStrict) { - AlertDialog( - onDismissRequest = { confirmStrict = false }, - title = { Text(stringResource(R.string.settings_nav_strict_confirm_title)) }, - text = { Text(stringResource(R.string.settings_nav_strict_confirm_body)) }, - confirmButton = { - TextButton(onClick = { - confirmStrict = false - actions.onMode(UnknownSenderMode.STRICT) - }) { Text(stringResource(R.string.settings_nav_strict_confirm_action)) } - }, - dismissButton = { - TextButton(onClick = { confirmStrict = false }) { - Text(stringResource(R.string.settings_nav_strict_confirm_cancel)) - } - }, - ) - } - if (regionDialog) { - CountryPicker( - selected = settings.blockOutsideRegion, - onSelect = { region -> - regionDialog = false - actions.onOutsideRegion(region) - }, - onDismiss = { regionDialog = false }, - ) - } - if (unknownNotifyDialog) { - val choices = UnknownInboxNotify.entries - ChoiceDialog( - title = stringResource(R.string.unotify_title), - options = choices.map { unknownNotifyLabel(it) }, - selectedIndex = choices.indexOf(settings.unknownInboxNotify), - onSelect = { index -> - unknownNotifyDialog = false - actions.onUnknownNotify(choices[index]) - }, - onDismiss = { unknownNotifyDialog = false }, - ) - } - if (purgeDialog) { - val options = state.purgeOptions - ChoiceDialog( - title = stringResource(R.string.settings_nav_purge_row), - options = options.map { purgeLabel(it) }, - selectedIndex = options.indexOf(settings.purgeAfterDays), - onSelect = { index -> - purgeDialog = false - actions.onPurgeDays(options[index]) - }, - onDismiss = { purgeDialog = false }, - ) - } -} - -@Composable -private fun LinksGroup() { - val prefs = LocalContext.current.threadPrefs - var locked by remember { mutableStateOf(prefs.riskyLinksLocked) } - SettingsGroup(stringResource(R.string.i07_group_title)) { - SettingsSwitchRow( - title = stringResource(R.string.i07_lock_title), - summary = stringResource(R.string.i07_lock_summary), - checked = locked, - onCheckedChange = { - locked = it - prefs.riskyLinksLocked = it - }, - ) - } -} - -@Composable -private fun regionValue(region: String): String = - if (region.isBlank()) stringResource(R.string.region_off) else CountryOptions.nameOf(region, uiLocale()) - -@Composable -private fun unknownNotifyLabel(choice: UnknownInboxNotify): String = stringResource( - when (choice) { - UnknownInboxNotify.NOTIFY -> R.string.unotify_notify - UnknownInboxNotify.SILENT -> R.string.unotify_silent - UnknownInboxNotify.NONE -> R.string.unotify_none - }, -) - -@Composable -private fun purgeLabel(days: Int): String = - if (days == 0) stringResource(R.string.spam_purge_forever) else stringResource(R.string.spam_purge_days, days) - -@Composable -private fun ModeChoice( - mode: UnknownSenderMode, - title: Int, - body: Int, - settings: SpamSettings, - onChoose: (UnknownSenderMode) -> Unit, - badge: String? = null, -) { - SettingsRadioRow( - title = stringResource(title), - summary = stringResource(body), - selected = settings.mode == mode, - onSelect = { onChoose(mode) }, - badge = badge, - ) -} - -@Composable -private fun StrictWarning(onReview: () -> Unit, modifier: Modifier = Modifier) { - val colors = MaterialTheme.colorScheme - Card( - modifier = modifier.fillMaxWidth().semantics { liveRegion = LiveRegionMode.Polite }, - colors = CardDefaults.cardColors(containerColor = colors.errorContainer, contentColor = colors.onErrorContainer), - shape = androidx.compose.foundation.shape.RoundedCornerShape(28.dp), - ) { - Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { - Icon(Symbols.Warning, contentDescription = null, modifier = Modifier.size(24.dp)) - Text(stringResource(R.string.spam_strict_warning_title), style = MaterialTheme.typography.titleMedium) - } - Text(stringResource(R.string.spam_strict_warning_body), style = MaterialTheme.typography.bodyMedium) - TextButton(onClick = onReview, modifier = Modifier.heightIn(min = 48.dp)) { - Text(stringResource(R.string.spam_strict_warning_action)) - } - } - } -} - -// region Previews - -@Composable -private fun PreviewHost(settings: SpamSettings) = UMessageTheme { - SettingsScreen(SettingsUiState(loading = false, settings = settings), SettingsActions()) -} - -@Preview(name = "Settings - strict", showBackground = true, widthDp = 360, heightDp = 1100) -@Composable -private fun SettingsStrictPreview() = PreviewHost(SpamSettings(mode = UnknownSenderMode.STRICT)) - -@Preview(name = "Settings - smart", showBackground = true, widthDp = 360, heightDp = 1100) -@Composable -private fun SettingsSmartPreview() = PreviewHost(SpamSettings(mode = UnknownSenderMode.SMART, purgeAfterDays = 60)) - -@Preview( - name = "Settings - dark", showBackground = true, widthDp = 360, heightDp = 1100, - uiMode = android.content.res.Configuration.UI_MODE_NIGHT_YES, -) -@Composable -private fun SettingsDarkPreview() = PreviewHost(SpamSettings(notifyOnBlock = true)) - -// endregion +package com.glooboo.umessage.ui.spam + +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.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHostState +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import com.glooboo.umessage.ui.components.ChoiceDialog +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewmodel.compose.viewModel +import com.glooboo.umessage.R +import com.glooboo.umessage.spam.SpamSettings +import com.glooboo.umessage.spam.UnknownInboxNotify +import com.glooboo.umessage.spam.UnknownSenderMode +import com.glooboo.umessage.ui.components.SettingsGroup +import com.glooboo.umessage.ui.components.SettingsRadioRow +import com.glooboo.umessage.ui.components.SettingsRow +import com.glooboo.umessage.ui.components.SettingsSwitchRow +import com.glooboo.umessage.ui.icons.Symbols +import com.glooboo.umessage.ui.theme.UMessageTheme +import androidx.compose.ui.unit.Dp +import com.glooboo.umessage.ui.components.UMessageScaffold +import com.glooboo.umessage.ui.components.UMessageTopBar +import com.glooboo.umessage.ui.components.uiLocale +import androidx.compose.ui.platform.LocalContext +import com.glooboo.umessage.helpers.threadPrefs + +@Immutable +class SettingsActions( + val onBack: () -> Unit = {}, + val onOpenRules: () -> Unit = {}, + val onOpenBlocked: () -> Unit = {}, + val onMode: (UnknownSenderMode) -> Unit = {}, + val onPurgeDays: (Int) -> Unit = {}, + val onNotify: (Boolean) -> Unit = {}, + val onUnknownNotify: (UnknownInboxNotify) -> Unit = {}, + val onOpenLinkAction: (Boolean) -> Unit = {}, + val onOutsideRegion: (String) -> Unit = {}, + /** Null hides the "Why was it blocked?" row (no engine log in this build). */ + val onOpenDecisionLog: (() -> Unit)? = null, +) + +@Composable +fun SettingsRoute( + onBack: () -> Unit, + onOpenRules: () -> Unit, + onOpenBlocked: () -> Unit, + onOpenDecisionLog: (() -> Unit)? = null, +) { + val viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory) + val state by viewModel.state.collectAsStateWithLifecycle() + val actions = remember(viewModel, onBack, onOpenRules, onOpenBlocked, onOpenDecisionLog) { + SettingsActions( + onBack = onBack, + onOpenRules = onOpenRules, + onOpenBlocked = onOpenBlocked, + onMode = viewModel::setMode, + onPurgeDays = viewModel::setPurgeDays, + onNotify = viewModel::setNotifyOnBlock, + onUnknownNotify = viewModel::setUnknownInboxNotify, + onOpenLinkAction = viewModel::setOpenLinkAction, + onOutsideRegion = viewModel::setBlockOutsideRegion, + onOpenDecisionLog = onOpenDecisionLog, + ) + } + val snackbar = remember { SnackbarHostState() } + val failedText = stringResource(R.string.spam_snack_failed) + LaunchedEffect(viewModel) { + viewModel.failureFlow.collect { snackbar.showSnackbar(failedText) } + } + SettingsScreen(state, actions, snackbar) +} + +@Composable +fun SettingsScreen(state: SettingsUiState, actions: SettingsActions, snackbarHostState: SnackbarHostState? = null) { + UMessageScaffold( + snackbarHostState = snackbarHostState, + topBar = { + UMessageTopBar(title = stringResource(R.string.settings_nav_spam_page_title), onBack = actions.onBack) + }, + ) { inner -> + if (state.loading) { + Column(Modifier.padding(top = inner.calculateTopPadding()).fillMaxWidth().padding(48.dp), horizontalAlignment = Alignment.CenterHorizontally) { + val label = stringResource(R.string.spam_loading) + CircularProgressIndicator(Modifier.semantics { contentDescription = label }) + } + } else { + SettingsContent(state, actions, Modifier.padding(top = inner.calculateTopPadding()), inner.calculateBottomPadding()) + } + } +} + +@Composable +private fun SettingsContent(state: SettingsUiState, actions: SettingsActions, modifier: Modifier = Modifier, bottomInset: Dp = 0.dp) { + val settings = state.settings + // SE-23: choosing Strict first asks, because it also blocks verification codes. + var confirmStrict by rememberSaveable { mutableStateOf(false) } + var purgeDialog by rememberSaveable { mutableStateOf(false) } + var unknownNotifyDialog by rememberSaveable { mutableStateOf(false) } + var regionDialog by rememberSaveable { mutableStateOf(false) } + var restoredOpen by rememberSaveable { mutableStateOf(false) } + val chooseMode: (UnknownSenderMode) -> Unit = { mode -> + if (mode == UnknownSenderMode.STRICT && settings.mode != UnknownSenderMode.STRICT) { + confirmStrict = true + } else { + actions.onMode(mode) + } + } + Column( + modifier = modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 32.dp + bottomInset), + ) { + // U02: the one Spam protection page: the mode, the rules, retention, countries, links and alerts. + SettingsGroup( + title = stringResource(R.string.spam_settings_unknown_title), + description = stringResource(R.string.spam_settings_unknown_body), + ) { + ModeChoice( + UnknownSenderMode.STRICT, R.string.spam_mode_strict, R.string.spam_mode_strict_body, + settings, chooseMode, + ) + ModeChoice( + UnknownSenderMode.SMART, R.string.spam_mode_smart, R.string.spam_mode_smart_body, + settings, chooseMode, + badge = stringResource(R.string.settings_nav_recommended), + ) + ModeChoice( + UnknownSenderMode.OFF, R.string.spam_mode_off, R.string.spam_mode_off_body, + settings, chooseMode, + ) + } + if (settings.mode == UnknownSenderMode.STRICT) { + StrictWarning( + onReview = actions.onOpenBlocked, + modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 8.dp), + ) + } + + SettingsGroup(stringResource(R.string.settings_f_group_rules)) { + SettingsRow( + title = stringResource(R.string.settings_spam_open_rules), + summary = stringResource(R.string.settings_spam_open_rules_body), + onClick = actions.onOpenRules, + showChevron = true, + ) + SettingsRow( + title = stringResource(R.string.blocked_menu_restored), + summary = stringResource(R.string.blocked_menu_restored_summary), + onClick = { restoredOpen = true }, + showChevron = true, + ) + } + + SettingsGroup(stringResource(R.string.spam_settings_cleanup_title)) { + // SE-25: one dropdown-style row instead of chips that wrap onto a second line. + SettingsRow( + title = stringResource(R.string.settings_nav_purge_row), + summary = stringResource(R.string.spam_purge_body), + value = purgeLabel(settings.purgeAfterDays), + onClick = { purgeDialog = true }, + showChevron = true, + ) + } + + SettingsGroup(stringResource(R.string.region_group_title)) { + SettingsRow( + title = stringResource(R.string.region_title), + summary = stringResource(R.string.region_summary), + value = regionValue(settings.blockOutsideRegion), + onClick = { regionDialog = true }, + showChevron = true, + ) + } + + LinksGroup() + + CarrierReportGroup() + + SettingsGroup(stringResource(R.string.settings_nav_group_alerts)) { + SettingsSwitchRow( + title = stringResource(R.string.spam_notify_title), + summary = stringResource(R.string.settings_nav_notify_body), + checked = settings.notifyOnBlock, + onCheckedChange = actions.onNotify, + ) + SettingsRow( + title = stringResource(R.string.unotify_title), + summary = stringResource(R.string.unotify_summary), + value = unknownNotifyLabel(settings.unknownInboxNotify), + onClick = { unknownNotifyDialog = true }, + showChevron = true, + ) + SettingsSwitchRow( + title = stringResource(R.string.notif_open_link_title), + summary = stringResource(R.string.notif_open_link_summary), + checked = settings.openLinkAction, + onCheckedChange = actions.onOpenLinkAction, + ) + } + + // U45: the log is named Recent activity and linked once, from here. + val openLog = actions.onOpenDecisionLog + if (openLog != null) { + SettingsGroup(stringResource(R.string.settings_ui_more)) { + SettingsRow( + title = stringResource(R.string.settings_nav_decision_log), + summary = stringResource(R.string.settings_nav_decision_log_body), + onClick = openLog, + showChevron = true, + ) + } + } + } + + if (restoredOpen) { + val restored by RestoredLog.get(LocalContext.current).entries.collectAsStateWithLifecycle() + RestoredSheet(restored, onDismiss = { restoredOpen = false }) + } + if (confirmStrict) { + AlertDialog( + onDismissRequest = { confirmStrict = false }, + title = { Text(stringResource(R.string.settings_nav_strict_confirm_title)) }, + text = { Text(stringResource(R.string.settings_nav_strict_confirm_body)) }, + confirmButton = { + TextButton(onClick = { + confirmStrict = false + actions.onMode(UnknownSenderMode.STRICT) + }) { Text(stringResource(R.string.settings_nav_strict_confirm_action)) } + }, + dismissButton = { + TextButton(onClick = { confirmStrict = false }) { + Text(stringResource(R.string.settings_nav_strict_confirm_cancel)) + } + }, + ) + } + if (regionDialog) { + CountryPicker( + selected = settings.blockOutsideRegion, + onSelect = { region -> + regionDialog = false + actions.onOutsideRegion(region) + }, + onDismiss = { regionDialog = false }, + ) + } + if (unknownNotifyDialog) { + val choices = UnknownInboxNotify.entries + ChoiceDialog( + title = stringResource(R.string.unotify_title), + options = choices.map { unknownNotifyLabel(it) }, + selectedIndex = choices.indexOf(settings.unknownInboxNotify), + onSelect = { index -> + unknownNotifyDialog = false + actions.onUnknownNotify(choices[index]) + }, + onDismiss = { unknownNotifyDialog = false }, + ) + } + if (purgeDialog) { + val options = state.purgeOptions + ChoiceDialog( + title = stringResource(R.string.settings_nav_purge_row), + options = options.map { purgeLabel(it) }, + selectedIndex = options.indexOf(settings.purgeAfterDays), + onSelect = { index -> + purgeDialog = false + actions.onPurgeDays(options[index]) + }, + onDismiss = { purgeDialog = false }, + ) + } +} + +@Composable +private fun LinksGroup() { + val prefs = LocalContext.current.threadPrefs + var locked by remember { mutableStateOf(prefs.riskyLinksLocked) } + SettingsGroup(stringResource(R.string.i07_group_title)) { + SettingsSwitchRow( + title = stringResource(R.string.i07_lock_title), + summary = stringResource(R.string.i07_lock_summary), + checked = locked, + onCheckedChange = { + locked = it + prefs.riskyLinksLocked = it + }, + ) + } +} + +@Composable +private fun regionValue(region: String): String = + if (region.isBlank()) stringResource(R.string.region_off) else CountryOptions.nameOf(region, uiLocale()) + +@Composable +private fun unknownNotifyLabel(choice: UnknownInboxNotify): String = stringResource( + when (choice) { + UnknownInboxNotify.NOTIFY -> R.string.unotify_notify + UnknownInboxNotify.SILENT -> R.string.unotify_silent + UnknownInboxNotify.NONE -> R.string.unotify_none + }, +) + +@Composable +private fun purgeLabel(days: Int): String = + if (days == 0) stringResource(R.string.spam_purge_forever) else stringResource(R.string.spam_purge_days, days) + +@Composable +private fun ModeChoice( + mode: UnknownSenderMode, + title: Int, + body: Int, + settings: SpamSettings, + onChoose: (UnknownSenderMode) -> Unit, + badge: String? = null, +) { + SettingsRadioRow( + title = stringResource(title), + summary = stringResource(body), + selected = settings.mode == mode, + onSelect = { onChoose(mode) }, + badge = badge, + ) +} + +@Composable +private fun StrictWarning(onReview: () -> Unit, modifier: Modifier = Modifier) { + val colors = MaterialTheme.colorScheme + Card( + modifier = modifier.fillMaxWidth().semantics { liveRegion = LiveRegionMode.Polite }, + colors = CardDefaults.cardColors(containerColor = colors.errorContainer, contentColor = colors.onErrorContainer), + shape = androidx.compose.foundation.shape.RoundedCornerShape(28.dp), + ) { + Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Icon(Symbols.Warning, contentDescription = null, modifier = Modifier.size(24.dp)) + Text(stringResource(R.string.spam_strict_warning_title), style = MaterialTheme.typography.titleMedium) + } + Text(stringResource(R.string.spam_strict_warning_body), style = MaterialTheme.typography.bodyMedium) + TextButton(onClick = onReview, modifier = Modifier.heightIn(min = 48.dp)) { + Text(stringResource(R.string.spam_strict_warning_action)) + } + } + } +} + +// region Previews + +@Composable +private fun PreviewHost(settings: SpamSettings) = UMessageTheme { + SettingsScreen(SettingsUiState(loading = false, settings = settings), SettingsActions()) +} + +@Preview(name = "Settings - strict", showBackground = true, widthDp = 360, heightDp = 1100) +@Composable +private fun SettingsStrictPreview() = PreviewHost(SpamSettings(mode = UnknownSenderMode.STRICT)) + +@Preview(name = "Settings - smart", showBackground = true, widthDp = 360, heightDp = 1100) +@Composable +private fun SettingsSmartPreview() = PreviewHost(SpamSettings(mode = UnknownSenderMode.SMART, purgeAfterDays = 60)) + +@Preview( + name = "Settings - dark", showBackground = true, widthDp = 360, heightDp = 1100, + uiMode = android.content.res.Configuration.UI_MODE_NIGHT_YES, +) +@Composable +private fun SettingsDarkPreview() = PreviewHost(SpamSettings(notifyOnBlock = true)) + +// endregion diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/SettingsViewModel.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/SettingsViewModel.kt index af02099b..7813898c 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/spam/SettingsViewModel.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/spam/SettingsViewModel.kt @@ -1,60 +1,70 @@ -package com.glooboo.umessage.ui.spam - -import android.app.Application -import androidx.lifecycle.AndroidViewModel -import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY -import androidx.lifecycle.viewModelScope -import androidx.lifecycle.viewmodel.initializer -import androidx.lifecycle.viewmodel.viewModelFactory -import kotlinx.coroutines.flow.SharingStarted -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.stateIn -import kotlinx.coroutines.launch -import com.glooboo.umessage.spam.SpamRepository -import com.glooboo.umessage.spam.SpamSettings -import com.glooboo.umessage.spam.UnknownInboxNotify -import com.glooboo.umessage.spam.UnknownSenderMode - -data class SettingsUiState( - val loading: Boolean = true, - val settings: SpamSettings = SpamSettings(), -) { - /** Preset retention choices plus the stored value if it is custom. 0 (keep forever) is last. */ - val purgeOptions: List - get() = (PRESET_PURGE_DAYS + settings.purgeAfterDays).distinct().sortedBy { if (it == 0) Int.MAX_VALUE else it } - - companion object { - val PRESET_PURGE_DAYS = listOf(7, 14, 30, 90, 0) - } -} - -class SettingsViewModel( - application: Application, - private val repository: SpamRepository, -) : AndroidViewModel(application) { - - val state: StateFlow = repository.settings - .map { SettingsUiState(loading = false, settings = it) } - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SettingsUiState()) - - fun setMode(mode: UnknownSenderMode) = update { it.copy(mode = mode) } - fun setPurgeDays(days: Int) = update { it.copy(purgeAfterDays = days) } - fun setNotifyOnBlock(enabled: Boolean) = update { it.copy(notifyOnBlock = enabled) } - fun setUnknownInboxNotify(choice: UnknownInboxNotify) = update { it.copy(unknownInboxNotify = choice) } - fun setOpenLinkAction(enabled: Boolean) = update { it.copy(openLinkAction = enabled) } - fun setBlockOutsideRegion(region: String) = update { it.copy(blockOutsideRegion = region) } - - private fun update(transform: (SpamSettings) -> SpamSettings) { - viewModelScope.launch { runCatching { repository.updateSettings(transform) } } - } - - companion object { - val Factory = viewModelFactory { - initializer { - val app = this[APPLICATION_KEY] as Application - SettingsViewModel(app, SpamRepositoryProvider.get(app)) - } - } - } -} +package com.glooboo.umessage.ui.spam + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch +import com.glooboo.umessage.spam.SpamRepository +import com.glooboo.umessage.spam.SpamSettings +import com.glooboo.umessage.spam.UnknownInboxNotify +import com.glooboo.umessage.spam.UnknownSenderMode + +data class SettingsUiState( + val loading: Boolean = true, + val settings: SpamSettings = SpamSettings(), +) { + /** Preset retention choices plus the stored value if it is custom. 0 (keep forever) is last. */ + val purgeOptions: List + get() = (PRESET_PURGE_DAYS + settings.purgeAfterDays).distinct().sortedBy { if (it == 0) Int.MAX_VALUE else it } + + companion object { + val PRESET_PURGE_DAYS = listOf(7, 14, 30, 90, 0) + } +} + +class SettingsViewModel( + application: Application, + private val repository: SpamRepository, +) : AndroidViewModel(application) { + + val state: StateFlow = repository.settings + .map { SettingsUiState(loading = false, settings = it) } + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SettingsUiState()) + + private val failures = Channel(Channel.CONFLATED) + + /** Fires when a settings write failed, so the screen can say so. */ + val failureFlow: Flow = failures.receiveAsFlow() + + fun setMode(mode: UnknownSenderMode) = update { it.copy(mode = mode) } + fun setPurgeDays(days: Int) = update { it.copy(purgeAfterDays = days) } + fun setNotifyOnBlock(enabled: Boolean) = update { it.copy(notifyOnBlock = enabled) } + fun setUnknownInboxNotify(choice: UnknownInboxNotify) = update { it.copy(unknownInboxNotify = choice) } + fun setOpenLinkAction(enabled: Boolean) = update { it.copy(openLinkAction = enabled) } + fun setBlockOutsideRegion(region: String) = update { it.copy(blockOutsideRegion = region) } + + private fun update(transform: (SpamSettings) -> SpamSettings) { + viewModelScope.launch { + runCatching { repository.updateSettings(transform) }.onFailure { failures.trySend(Unit) } + } + } + + companion object { + val Factory = viewModelFactory { + initializer { + val app = this[APPLICATION_KEY] as Application + SettingsViewModel(app, SpamRepositoryProvider.get(app)) + } + } + } +} 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 da88a044..4f52cda7 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 @@ -17,6 +17,7 @@ import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.lerp @@ -24,6 +25,7 @@ import androidx.compose.ui.graphics.luminance import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat +import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.unit.dp @@ -237,7 +239,11 @@ fun UMessageTheme( val chosen by ThemePresets.flow(ctx).collectAsStateWithLifecycle() chosen } - val scheme = resolveColorScheme(ctx, choice, darkTheme, dynamicColor, isSystemInDarkTheme()) + val systemDark = isSystemInDarkTheme() + val uiMode = LocalConfiguration.current.uiMode + val scheme = remember(choice, darkTheme, dynamicColor, systemDark, uiMode) { + resolveColorScheme(ctx, choice, darkTheme, dynamicColor, systemDark) + } if (syncWindow) SyncWindowWithScheme(scheme) UMessageFontScale { MaterialTheme( diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/PhoneMatch.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/PhoneMatch.kt new file mode 100644 index 00000000..4eabfb6d --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/PhoneMatch.kt @@ -0,0 +1,92 @@ +package com.glooboo.umessage.ui.thread + +/* Phone numbers written in a message text: found for tappable links, kept strict so codes, prices and dates are not. */ + +/** A phone number found in a text: [range] is where it is written, [number] is what to dial ("+989121234567"). */ +internal data class PhoneMatch(val range: IntRange, val number: String) + +private const val TEL = "tel:" +private const val MIN_DIGITS = 7 +private const val MAX_DIGITS = 15 +private const val DECIMAL_RADIX = 10 + +/** Fewest digits of a number written as one run without a "+" or a leading 0: shorter runs are mostly codes. */ +private const val MIN_PLAIN_RUN_DIGITS = 10 + +/** + * Letters, digits and signs that, right before a number, mean it is part of something else (a price, a path, a + * word). + */ +private const val NOT_BEFORE = "\\p{L}\\p{N}_@/\\\\.,$€£¥#%*+-" + +private val candidate = Regex( + "(? if (d >= 0) '0' + d else it } else it + } + .joinToString("") + +/** True for "+" or "00" (international) and for a leading 0 (national): a code or price never starts like that. */ +private fun hasPhonePrefix(shown: String): Boolean = + shown.startsWith("0") || shown.startsWith("+") + +/** The digit count, and not a date, a dotted price or version, or a decimal amount. */ +private fun isNumberShaped(shown: String, digits: String): Boolean { + val local = hasPhonePrefix(shown) + return digits.length in MIN_DIGITS..MAX_DIGITS && + !dateLike.matches(shown) && + !(dottedOnly.matches(shown) && !local && !dottedPhone.matches(shown)) && + !decimalTail.matches(shown) +} + +/** Not a short plain run (a code), and no doubled separators or unbalanced parentheses. */ +private fun isCleanRun(shown: String, digits: String): Boolean { + val plainRun = shown.all { it in '0'..'9' || it == '+' } + return !(plainRun && !hasPhonePrefix(shown) && digits.length < MIN_PLAIN_RUN_DIGITS) && + !shown.contains("..") && !shown.contains("--") && + !hasUnbalancedParens(shown) +} + +/** + * The phone numbers in [text], in order. Strict on purpose: 7 to 15 digits, no verification codes (short runs, or a + * run of 7 to 9 digits with no "+" or leading 0), no prices ("1.234.567", "$1234567", "1234567.50"), version + * numbers, no dates ("2026-11-11", "11.11.2026") and nothing inside a word, an address or a path. + */ +internal fun findPhoneNumbers(text: String): List { + if (text.length < MIN_DIGITS) return emptyList() + return candidate.findAll(text).mapNotNull { match -> + val shown = asciiDigits(match.value).trim() + val digits = shown.filter { it in '0'..'9' } + if (!isNumberShaped(shown, digits) || !isCleanRun(shown, digits)) return@mapNotNull null + val dial = when { + shown.startsWith("00") -> "+" + digits.drop(2) + shown.startsWith("+") -> "+$digits" + else -> digits + } + PhoneMatch(match.range.first..match.range.last, dial) + }.toList() +} + +private fun hasUnbalancedParens(value: String): Boolean = value.count { it == '(' } != value.count { it == ')' } + +/** True for the "tel:" links [findPhoneNumbers] makes. */ +internal fun isPhoneLink(uri: String): Boolean = uri.startsWith(TEL, ignoreCase = true) + +/** The number of a "tel:" link ("+989121234567"), else null. */ +internal fun phoneOf(uri: String): String? = if (isPhoneLink(uri)) uri.substring(TEL.length).ifBlank { null } else null + +/** The "tel:" link for [number]. */ +internal fun phoneLink(number: String): String = TEL + number diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/Tapbacks.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/Tapbacks.kt index d468d574..b328b3d2 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/Tapbacks.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/Tapbacks.kt @@ -58,7 +58,9 @@ fun parseTapback(body: String): Tapback? { return null } -private fun folded(text: String): String = text.trim().replace(Regex("\\s+"), " ").lowercase() +private val WHITESPACE_RUN = Regex("\\s+") + +private fun folded(text: String): String = text.trim().replace(WHITESPACE_RUN, " ").lowercase() /** * The message among [candidates] (oldest first, all before the reaction) that [tapback] names: the newest exact match, @@ -67,11 +69,13 @@ private fun folded(text: String): String = text.trim().replace(Regex("\\s+"), " */ fun findTapbackTarget(tapback: Tapback, candidates: List): Message? { val quoted = tapback.quoted + candidates.lastOrNull { it.body == quoted }?.let { return it } + if (tapback.truncated) candidates.lastOrNull { it.body.startsWith(quoted) }?.let { return it } val foldedQuote = folded(quoted) - return candidates.lastOrNull { it.body == quoted } - ?: candidates.lastOrNull { tapback.truncated && it.body.startsWith(quoted) } - ?: candidates.lastOrNull { folded(it.body) == foldedQuote } - ?: candidates.lastOrNull { tapback.truncated && folded(it.body).startsWith(foldedQuote) } + // Folding only trims, collapses spaces and lowercases: a body far shorter than the quote cannot match. + val possible = candidates.filter { it.body.length >= foldedQuote.length } + possible.lastOrNull { folded(it.body) == foldedQuote }?.let { return it } + return if (tapback.truncated) possible.lastOrNull { folded(it.body).startsWith(foldedQuote) } else null } /** @@ -82,11 +86,17 @@ fun findTapbackTarget(tapback: Tapback, candidates: List): Message? { fun applyTapbacks(sorted: List): TapbackResult { val hidden = HashSet() val found = LinkedHashMap>>() - sorted.forEachIndexed { index, message -> - if (!message.isReceivedMessage() || message.attachment?.attachments?.isNotEmpty() == true) return@forEachIndexed - val tapback = parseTapback(message.body) ?: return@forEachIndexed - val candidates = sorted.subList(0, index).filter { it.body.isNotEmpty() && it.getStableId() !in hidden } - val target = findTapbackTarget(tapback, candidates) ?: return@forEachIndexed + // Earlier messages with a text, built once while walking the list instead of copied for every reaction. + val earlier = ArrayList(sorted.size) + sorted.forEach { message -> + val isReaction = message.isReceivedMessage() && message.attachment?.attachments?.isNotEmpty() != true + val tapback = if (isReaction) parseTapback(message.body) else null + val target = tapback?.let { parsed -> + val candidates = if (hidden.isEmpty()) earlier else earlier.filter { it.getStableId() !in hidden } + findTapbackTarget(parsed, candidates) + } + if (message.body.isNotEmpty()) earlier.add(message) + if (tapback == null || target == null) return@forEach hidden.add(message.getStableId()) found.getOrPut(target.getStableId()) { LinkedHashMap() } .getOrPut(tapback.kind) { ArrayList() } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadAttachmentController.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadAttachmentController.kt index ef5863d1..b173167d 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadAttachmentController.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadAttachmentController.kt @@ -152,6 +152,15 @@ class ThreadAttachmentController( onChanged() } + /** + * After a send that went out in part: drops the attachments that were handed off and keeps the ones in + * [remaining], so another tap on Send resends only those. + */ + fun keepOnly(remaining: List) { + val keep = remaining.map { it.uriString }.toSet() + vm.attachments.filter { it.uri.toString() !in keep }.forEach { remove(it) } + } + /** Empties the composer's attachments (after a send), stopping any that was playing. */ fun clear() { fileSizes.clear() diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadBubbleStyle.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadBubbleStyle.kt index d7c70589..50fc67db 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadBubbleStyle.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadBubbleStyle.kt @@ -1,149 +1,174 @@ -package com.glooboo.umessage.ui.thread - -import android.text.SpannableString -import android.text.style.URLSpan -import android.text.util.Linkify -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.Shape -import androidx.compose.ui.graphics.lerp -import androidx.compose.ui.graphics.luminance -import androidx.compose.ui.text.AnnotatedString -import androidx.compose.ui.text.LinkAnnotation -import androidx.compose.ui.text.SpanStyle -import androidx.compose.ui.text.TextLinkStyles -import androidx.compose.ui.text.buildAnnotatedString -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextDecoration -import androidx.compose.ui.unit.dp - -/* The look of a chat bubble that needs no composition: its corners, colours and the text with links and matches. */ - -private val BigCorner = 20.dp -private val SmallCorner = 4.dp - -/** Corners of a chat bubble: the side facing the previous or next bubble of the same run is squared off. */ -fun bubbleShape(sent: Boolean, group: BubbleGroup): Shape { - val continuesAbove = group == BubbleGroup.Middle || group == BubbleGroup.Last - val continuesBelow = group == BubbleGroup.First || group == BubbleGroup.Middle - val inner = SmallCorner - val top = if (continuesAbove) inner else BigCorner - val bottom = if (continuesBelow) inner else BigCorner - return if (sent) { - RoundedCornerShape(topStart = BigCorner, topEnd = top, bottomEnd = bottom, bottomStart = BigCorner) - } else { - RoundedCornerShape(topStart = top, topEnd = BigCorner, bottomEnd = BigCorner, bottomStart = bottom) - } -} - -/** Plain text with web and e-mail addresses turned into tappable links, as the old bubbles did with autoLink. */ -internal fun linkify(text: String, color: Color): AnnotatedString { - if (text.isEmpty()) return AnnotatedString("") - val spannable = SpannableString(text) - Linkify.addLinks(spannable, Linkify.WEB_URLS or Linkify.EMAIL_ADDRESSES) - val spans = spannable.getSpans(0, spannable.length, URLSpan::class.java) - if (spans.isEmpty()) return AnnotatedString(text) - val style = TextLinkStyles( - SpanStyle(color = color, textDecoration = TextDecoration.Underline, fontWeight = FontWeight.Medium), - ) - return buildAnnotatedString { - // TH-04: each link sits in a left-to-right isolate, so a URL inside right-to-left text keeps its own order - // and lines up with the surrounding text instead of drifting to the other edge. - var last = 0 - spans.sortedBy { spannable.getSpanStart(it) }.forEach { span -> - val start = spannable.getSpanStart(span) - val end = spannable.getSpanEnd(span) - if (start < last) return@forEach - append(text.substring(last, start)) - append(LRI) - val from = length - append(keepSchemeTogether(text.substring(start, end))) - addLink(LinkAnnotation.Url(span.url, style), from, length) - append(PDI) - last = end - } - append(text.substring(last)) - } -} - -private const val LRI = "\u2066" -private const val PDI = "\u2069" -private const val WORD_JOINER = "\u2060" - -/** - * TH-04: a word joiner after "://", so a line never ends at "https://" with the address on the next line. Only the - * shown text changes; the link opens [URLSpan.getURL] as it was. - */ -internal fun keepSchemeTogether(link: String): String = link.replaceFirst("://", "://$WORD_JOINER") - -/** [text] with every match of [query] (Search in conversation) drawn in [style]. */ -internal fun highlightMatches(text: AnnotatedString, query: String, style: SpanStyle): AnnotatedString { - val ranges = searchRanges(text.text, query) - if (ranges.isEmpty()) return text - return AnnotatedString.Builder(text).apply { - ranges.forEach { addStyle(style, it.first, it.last + 1) } - }.toAnnotatedString() -} - -/** Share of primary mixed into the page colour for a dark sent bubble, and the darkest container used as it is. */ -private const val DARK_SENT_PRIMARY_SHARE = 0.3f -private const val DARK_CONTAINER_MAX_LUMINANCE = 0.12f - -/** N6: more primary is mixed in, a step at a time up to the most, until sent and received bubbles differ enough. */ -private const val DARK_SENT_SHARE_STEP = 0.05f -private const val DARK_SENT_MAX_STEPS = 6 - -/** N6: the least contrast between the sent and received bubble colours that reads as two tones at a glance. */ -private const val MIN_BUBBLE_TONE_CONTRAST = 1.5f - -/** The text on a sent bubble keeps at least normal-text contrast while the bubble gets lighter. */ -private const val MIN_TEXT_CONTRAST = 4.5f - -/** The flare term of the WCAG contrast formula. */ -private const val CONTRAST_FLARE = 0.05f - -/** WCAG contrast ratio of two colours, 1 (same luminance) to 21. */ -internal fun contrastRatio(a: Color, b: Color): Float { - val la = a.luminance() + CONTRAST_FLARE - val lb = b.luminance() + CONTRAST_FLARE - return maxOf(la, lb) / minOf(la, lb) -} - -/** - * TH-31: a sent bubble in a dark theme is a dark tone of the accent with light text, never a bright pastel slab. - * The theme's primaryContainer is used when it is dark enough, else primary mixed into the page colour. - * N6: either way it must stand apart from the [received] bubble colour; when it does not, more primary is mixed in - * (as long as [onSurface] text stays readable on it). Returns the bubble colour and its text colour. - */ -internal fun darkSentBubbleColors( - primaryContainer: Color, - onPrimaryContainer: Color, - primary: Color, - surface: Color, - onSurface: Color, - received: Color, -): Pair { - if (primaryContainer.luminance() <= DARK_CONTAINER_MAX_LUMINANCE && - contrastRatio(primaryContainer, received) >= MIN_BUBBLE_TONE_CONTRAST - ) { - return primaryContainer to onPrimaryContainer - } - // The mixes from the usual share up to the most, kept while the text stays readable; the first that stands apart - // from the received bubble wins, else the strongest readable one. - val mixes = (0..DARK_SENT_MAX_STEPS) - .map { step -> lerp(surface, primary, DARK_SENT_PRIMARY_SHARE + step * DARK_SENT_SHARE_STEP) } - .filterIndexed { step, mix -> step == 0 || contrastRatio(onSurface, mix) >= MIN_TEXT_CONTRAST } - val bubble = mixes.firstOrNull { contrastRatio(it, received) >= MIN_BUBBLE_TONE_CONTRAST } ?: mixes.last() - return bubble to onSurface -} - -/** TH-05: links in a received bubble take the accent colour; on a sent or selected bubble they keep the text colour. */ -internal fun bubbleLinkColor(sent: Boolean, selected: Boolean, content: Color, accent: Color): Color = - if (sent || selected) content else accent - -/** Share of the text colour mixed into the received bubble in a dark theme (U58). */ -private const val DARK_RECEIVED_LIFT = 0.08f - -/** U58: the received bubble colour; in a dark theme [highest] lifted one tonal step towards [onSurface]. */ -internal fun receivedBubbleColor(highest: Color, onSurface: Color, dark: Boolean): Color = - if (dark) lerp(highest, onSurface, DARK_RECEIVED_LIFT) else highest +package com.glooboo.umessage.ui.thread + +import android.text.SpannableString +import android.text.style.URLSpan +import android.text.util.Linkify +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.graphics.lerp +import androidx.compose.ui.graphics.luminance +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLinkStyles +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.unit.dp + +/* The look of a chat bubble that needs no composition: its corners, colours and the text with links and matches. */ + +private val BigCorner = 20.dp +private val SmallCorner = 4.dp + +/** Corners of a chat bubble: the side facing the previous or next bubble of the same run is squared off. */ +fun bubbleShape(sent: Boolean, group: BubbleGroup): Shape { + val continuesAbove = group == BubbleGroup.Middle || group == BubbleGroup.Last + val continuesBelow = group == BubbleGroup.First || group == BubbleGroup.Middle + val inner = SmallCorner + val top = if (continuesAbove) inner else BigCorner + val bottom = if (continuesBelow) inner else BigCorner + return if (sent) { + RoundedCornerShape(topStart = BigCorner, topEnd = top, bottomEnd = bottom, bottomStart = BigCorner) + } else { + RoundedCornerShape(topStart = top, topEnd = BigCorner, bottomEnd = BigCorner, bottomStart = bottom) + } +} + +/** + * Plain text with web and e-mail addresses and phone numbers turned into tappable links, as the old bubbles did with + * autoLink. A phone number becomes a "tel:" link; the link sheet then offers Call (opens the dialer, never dials), + * Copy and Add contact. + */ +internal fun linkify(text: String, color: Color): AnnotatedString { + if (text.isEmpty()) return AnnotatedString("") + val spannable = SpannableString(text) + Linkify.addLinks(spannable, Linkify.WEB_URLS or Linkify.EMAIL_ADDRESSES) + val urlLinks = spannable.getSpans(0, spannable.length, URLSpan::class.java).map { + TextLink(spannable.getSpanStart(it), spannable.getSpanEnd(it), it.url, isUrl = true) + } + // A number inside a web or e-mail link stays part of that link. + val phoneLinks = findPhoneNumbers(text) + .filter { m -> urlLinks.none { m.range.first < it.end && it.start <= m.range.last } } + .map { TextLink(it.range.first, it.range.last + 1, phoneLink(it.number), isUrl = false) } + val links = (urlLinks + phoneLinks).sortedBy { it.start } + if (links.isEmpty()) return AnnotatedString(text) + val style = TextLinkStyles( + SpanStyle(color = color, textDecoration = TextDecoration.Underline, fontWeight = FontWeight.Medium), + ) + return buildAnnotatedString { + // TH-04: each link sits in a left-to-right isolate, so a URL inside right-to-left text keeps its own order + // and lines up with the surrounding text instead of drifting to the other edge. + var last = 0 + links.forEach { link -> + val start = link.start + val end = link.end + if (start < last) return@forEach + append(text.substring(last, start)) + append(LRI) + val from = length + val shown = text.substring(start, end) + append(if (link.isUrl) keepSchemeTogether(shown) else shown) + addLink(LinkAnnotation.Url(if (link.isUrl) secureUrl(link.url, shown) else link.url, style), from, length) + append(PDI) + last = end + } + append(text.substring(last)) + } +} + +private data class TextLink(val start: Int, val end: Int, val url: String, val isUrl: Boolean) + +/** + * A link written without a scheme ("example.com") is given http:// by Linkify. Open it on https:// instead, so the + * link sheet does not warn "not encrypted" about what the sender never wrote as http. A written "http://" stays. + */ +internal fun secureUrl(url: String, shown: String): String = + if (url.startsWith("http://", ignoreCase = true) && !shown.startsWith("http://", ignoreCase = true)) { + "https://" + url.substring("http://".length) + } else { + url + } + +private const val LRI = "\u2066" +private const val PDI = "\u2069" +private const val WORD_JOINER = "\u2060" + +/** + * TH-04: a word joiner after "://", so a line never ends at "https://" with the address on the next line. Only the + * shown text changes; the link opens [URLSpan.getURL] as it was. + */ +internal fun keepSchemeTogether(link: String): String = link.replaceFirst("://", "://$WORD_JOINER") + +/** [text] with every match of [query] (Search in conversation) drawn in [style]. */ +internal fun highlightMatches(text: AnnotatedString, query: String, style: SpanStyle): AnnotatedString { + val ranges = searchRanges(text.text, query) + if (ranges.isEmpty()) return text + return AnnotatedString.Builder(text).apply { + ranges.forEach { addStyle(style, it.first, it.last + 1) } + }.toAnnotatedString() +} + +/** Share of primary mixed into the page colour for a dark sent bubble, and the darkest container used as it is. */ +private const val DARK_SENT_PRIMARY_SHARE = 0.3f +private const val DARK_CONTAINER_MAX_LUMINANCE = 0.12f + +/** N6: more primary is mixed in, a step at a time up to the most, until sent and received bubbles differ enough. */ +private const val DARK_SENT_SHARE_STEP = 0.05f +private const val DARK_SENT_MAX_STEPS = 6 + +/** N6: the least contrast between the sent and received bubble colours that reads as two tones at a glance. */ +private const val MIN_BUBBLE_TONE_CONTRAST = 1.5f + +/** The text on a sent bubble keeps at least normal-text contrast while the bubble gets lighter. */ +private const val MIN_TEXT_CONTRAST = 4.5f + +/** The flare term of the WCAG contrast formula. */ +private const val CONTRAST_FLARE = 0.05f + +/** WCAG contrast ratio of two colours, 1 (same luminance) to 21. */ +internal fun contrastRatio(a: Color, b: Color): Float { + val la = a.luminance() + CONTRAST_FLARE + val lb = b.luminance() + CONTRAST_FLARE + return maxOf(la, lb) / minOf(la, lb) +} + +/** + * TH-31: a sent bubble in a dark theme is a dark tone of the accent with light text, never a bright pastel slab. + * The theme's primaryContainer is used when it is dark enough, else primary mixed into the page colour. + * N6: either way it must stand apart from the [received] bubble colour; when it does not, more primary is mixed in + * (as long as [onSurface] text stays readable on it). Returns the bubble colour and its text colour. + */ +internal fun darkSentBubbleColors( + primaryContainer: Color, + onPrimaryContainer: Color, + primary: Color, + surface: Color, + onSurface: Color, + received: Color, +): Pair { + if (primaryContainer.luminance() <= DARK_CONTAINER_MAX_LUMINANCE && + contrastRatio(primaryContainer, received) >= MIN_BUBBLE_TONE_CONTRAST + ) { + return primaryContainer to onPrimaryContainer + } + // The mixes from the usual share up to the most, kept while the text stays readable; the first that stands apart + // from the received bubble wins, else the strongest readable one. + val mixes = (0..DARK_SENT_MAX_STEPS) + .map { step -> lerp(surface, primary, DARK_SENT_PRIMARY_SHARE + step * DARK_SENT_SHARE_STEP) } + .filterIndexed { step, mix -> step == 0 || contrastRatio(onSurface, mix) >= MIN_TEXT_CONTRAST } + val bubble = mixes.firstOrNull { contrastRatio(it, received) >= MIN_BUBBLE_TONE_CONTRAST } ?: mixes.last() + return bubble to onSurface +} + +/** TH-05: links in a received bubble take the accent colour; on a sent or selected bubble they keep the text colour. */ +internal fun bubbleLinkColor(sent: Boolean, selected: Boolean, content: Color, accent: Color): Color = + if (sent || selected) content else accent + +/** Share of the text colour mixed into the received bubble in a dark theme (U58). */ +private const val DARK_RECEIVED_LIFT = 0.08f + +/** U58: the received bubble colour; in a dark theme [highest] lifted one tonal step towards [onSurface]. */ +internal fun receivedBubbleColor(highest: Color, onSurface: Color, dark: Boolean): Color = + if (dark) lerp(highest, onSurface, DARK_RECEIVED_LIFT) else highest diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadExportController.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadExportController.kt index 52a07bb8..4aae3209 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadExportController.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadExportController.kt @@ -1,120 +1,121 @@ -package com.glooboo.umessage.ui.thread - -import android.content.Intent -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Row -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.unit.dp -import androidx.core.content.FileProvider -import com.glooboo.umessage.R -import com.glooboo.umessage.export.ConversationExportJob -import com.glooboo.umessage.ui.components.showComposeDialog -import org.fossify.commons.activities.BaseSimpleActivity -import org.fossify.commons.helpers.ensureBackgroundThread -import java.util.concurrent.atomic.AtomicBoolean - -/** - * The thread menu's "Export conversation": asks PDF or text and which dates, builds the file in the background with - * a Cancel button, then hands it to the share sheet. Nothing is kept: the file lives in the app cache until the next - * export replaces it. - */ -class ThreadExportController( - private val activity: BaseSimpleActivity, - private val threadId: () -> Long, - private val title: () -> String, - private val numbers: () -> List, - /** Shows a short note to the user (a snackbar). */ - private val showMessage: (String) -> Unit, -) { - private var progressDone by mutableStateOf(false) - - fun start() { - ThreadExportSheet(activity, ::export) - } - - private fun export(options: ThreadExportOptions) { - val cancelled = AtomicBoolean(false) - progressDone = false - showProgress(cancelled) - val id = threadId() - val name = title() - val phoneNumbers = numbers() - ensureBackgroundThread { - val result = try { - ConversationExportJob(activity) - .run(id, name, phoneNumbers, options.format, options.range, cancelled::get) - } catch (_: Exception) { - null - } - activity.runOnUiThread { - progressDone = true - finish(result, cancelled.get()) - } - } - } - - private fun finish(result: ConversationExportJob.Result?, cancelled: Boolean) { - when { - cancelled || result is ConversationExportJob.Result.Cancelled -> Unit - result == null -> showMessage(activity.getString(R.string.export_conv_failed)) - result is ConversationExportJob.Result.Empty -> - showMessage(activity.getString(R.string.export_conv_nothing)) - - result is ConversationExportJob.Result.Done -> share(result) - } - } - - private fun share(done: ConversationExportJob.Result.Done) { - val total = done.export.count - val count = activity.resources.getQuantityString(R.plurals.export_pdf_count, total, total) - val subject = activity.getString(R.string.export_conv_subject) - val uri = FileProvider.getUriForFile(activity, "${activity.packageName}.provider", done.file) - val send = Intent(Intent.ACTION_SEND) - .setType(done.mimeType) - .putExtra(Intent.EXTRA_STREAM, uri) - .putExtra(Intent.EXTRA_SUBJECT, subject) - .putExtra( - Intent.EXTRA_TEXT, - activity.getString(R.string.export_conv_share_text, done.export.title, count, done.export.sha256), - ) - .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) - activity.startActivity(Intent.createChooser(send, subject)) - } - - private fun showProgress(cancelled: AtomicBoolean) { - activity.showComposeDialog { dismiss -> - LaunchedEffect(progressDone) { if (progressDone) dismiss() } - AlertDialog( - onDismissRequest = {}, - title = { Text(stringResource(R.string.export_conv_title)) }, - text = { - Row( - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(16.dp), - ) { - CircularProgressIndicator() - Text(stringResource(R.string.export_conv_preparing)) - } - }, - confirmButton = {}, - dismissButton = { - TextButton( - onClick = { - cancelled.set(true) - dismiss() - }, - ) { Text(stringResource(R.string.screens_cancel)) } - }, - ) - } - } -} +package com.glooboo.umessage.ui.thread + +import android.content.Intent +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.core.content.FileProvider +import com.glooboo.umessage.R +import com.glooboo.umessage.export.ConversationExportJob +import com.glooboo.umessage.ui.components.showComposeDialog +import org.fossify.commons.activities.BaseSimpleActivity +import org.fossify.commons.helpers.ensureBackgroundThread +import java.util.concurrent.atomic.AtomicBoolean + +/** + * The thread menu's "Export conversation": asks PDF or text and which dates, builds the file in the background with + * a Cancel button, then hands it to the share sheet. Nothing is kept: the file lives in the app cache until the next + * export replaces it. + */ +class ThreadExportController( + private val activity: BaseSimpleActivity, + private val threadId: () -> Long, + private val title: () -> String, + private val numbers: () -> List, + /** Shows a short note to the user (a snackbar). */ + private val showMessage: (String) -> Unit, +) { + private var progressDone by mutableStateOf(false) + + fun start() { + ThreadExportSheet(activity, ::export) + } + + private fun export(options: ThreadExportOptions) { + val cancelled = AtomicBoolean(false) + progressDone = false + showProgress(cancelled) + val id = threadId() + val name = title() + val phoneNumbers = numbers() + ensureBackgroundThread { + val result = try { + ConversationExportJob(activity) + .run(id, name, phoneNumbers, options.format, options.range, cancelled::get) + } catch (_: Exception) { + null + } + activity.runOnUiThread { + progressDone = true + finish(result, cancelled.get()) + } + } + } + + private fun finish(result: ConversationExportJob.Result?, cancelled: Boolean) { + when { + cancelled || result is ConversationExportJob.Result.Cancelled -> Unit + result == null -> showMessage(activity.getString(R.string.export_conv_failed)) + result is ConversationExportJob.Result.Empty -> + showMessage(activity.getString(R.string.export_conv_nothing)) + + result is ConversationExportJob.Result.Done -> share(result) + } + } + + private fun share(done: ConversationExportJob.Result.Done) { + val total = done.export.count + val count = activity.resources.getQuantityString(R.plurals.export_pdf_count, total, total) + val subject = activity.getString(R.string.export_conv_subject) + val uri = FileProvider.getUriForFile(activity, "${activity.packageName}.provider", done.file) + val send = Intent(Intent.ACTION_SEND) + .setType(done.mimeType) + .putExtra(Intent.EXTRA_STREAM, uri) + .putExtra(Intent.EXTRA_SUBJECT, subject) + .putExtra( + Intent.EXTRA_TEXT, + activity.getString(R.string.export_conv_share_text, done.export.title, count, done.export.sha256), + ) + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + activity.startActivity(Intent.createChooser(send, subject)) + com.glooboo.umessage.helpers.CacheCleanup.deleteAfterShare(done.file) + } + + private fun showProgress(cancelled: AtomicBoolean) { + activity.showComposeDialog { dismiss -> + LaunchedEffect(progressDone) { if (progressDone) dismiss() } + AlertDialog( + onDismissRequest = {}, + title = { Text(stringResource(R.string.export_conv_title)) }, + text = { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(16.dp), + ) { + CircularProgressIndicator() + Text(stringResource(R.string.export_conv_preparing)) + } + }, + confirmButton = {}, + dismissButton = { + TextButton( + onClick = { + cancelled.set(true) + dismiss() + }, + ) { Text(stringResource(R.string.screens_cancel)) } + }, + ) + } + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadLinks.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadLinks.kt index 4c64ab95..58aefc97 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadLinks.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadLinks.kt @@ -1,120 +1,190 @@ -package com.glooboo.umessage.ui.thread - -import android.content.Context -import android.content.Intent -import android.widget.Toast -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.navigationBarsPadding -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.text.selection.SelectionContainer -import androidx.compose.material3.Button -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ModalBottomSheet -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Text -import androidx.compose.material3.rememberModalBottomSheetState -import androidx.compose.runtime.Composable -import androidx.compose.runtime.remember -import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.UriHandler -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextDirection -import androidx.compose.ui.unit.dp -import com.glooboo.umessage.R - -/** - * Link taps in a thread (TH-05). A tap never opens the link straight away: [onTap] shows the link sheet with the - * domain and the whole address, so a phishing text's link text cannot hide where it really goes. - */ -internal fun linkSheetUriHandler(onTap: (String) -> Unit): UriHandler = object : UriHandler { - override fun openUri(uri: String) = onTap(uri) -} - -/** "Share" in the link sheet: the address as plain text, through the system share sheet. */ -internal fun shareLink(context: Context, uri: String) { - val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, linkCopyText(uri)) - try { - context.startActivity(Intent.createChooser(send, null)) - } catch (_: Exception) { - Toast.makeText(context, R.string.thread_no_app, Toast.LENGTH_SHORT).show() - } -} - -private const val MAILTO = "mailto:" -private val schemeHost = Regex("^[a-zA-Z][a-zA-Z0-9+.-]*://([^/?#:@\\s]+)") - -/** The domain of a web link without "www." ("bit.ly"), the address of a mailto link, else null. */ -internal fun linkHost(uri: String): String? { - if (uri.startsWith(MAILTO, ignoreCase = true)) { - return uri.substring(MAILTO.length).substringBefore('?').ifBlank { null } - } - val host = runCatching { java.net.URI(uri).host }.getOrNull() ?: schemeHost.find(uri)?.groupValues?.get(1) - return host?.removePrefix("www.")?.ifBlank { null } -} - -/** What "Copy link" copies: the address itself, without "mailto:" for an e-mail address. */ -internal fun linkCopyText(uri: String): String = - if (uri.startsWith(MAILTO, ignoreCase = true)) uri.substring(MAILTO.length) else uri - -/** - * TH-05: the domain in bold, the whole address (selectable), then Copy link, Share and Open. A sender who is not a - * saved contact ([trusted] false) also gets the line asking to check the address first. - */ -@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) -@Composable -internal fun LinkSheet( - uri: String, - trusted: Boolean, - onOpen: () -> Unit, - onCopy: () -> Unit, - onShare: () -> Unit, - onDismiss: () -> Unit, - /** I07: a risky link cannot be opened from here (the setting); the sheet says why and still copies and shares. */ - lockRisky: Boolean = false, -) { - val state = rememberModalBottomSheetState(skipPartiallyExpanded = true) - val report = remember(uri) { LinkSafety.check(uri) } - val locked = lockRisky && report.isRisky - ModalBottomSheet(onDismissRequest = onDismiss, sheetState = state) { - Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 24.dp) - .padding(bottom = 16.dp) - .navigationBarsPadding(), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - val ltr = MaterialTheme.typography.bodyMedium.copy(textDirection = TextDirection.Ltr) - linkHost(uri)?.let { host -> - Text(host, style = MaterialTheme.typography.titleLarge.copy(textDirection = TextDirection.Ltr)) - } - if (!trusted) { - Text( - stringResource(R.string.thread_link_confirm_body), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - LinkWarnings(report, locked) - SelectionContainer { - Text(uri, style = ltr, fontWeight = FontWeight.Medium) - } - FlowRow( - modifier = Modifier - .fillMaxWidth() - .padding(top = 8.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp, androidx.compose.ui.Alignment.End), - ) { - OutlinedButton(onClick = onCopy) { Text(stringResource(R.string.thread_r2_link_copy)) } - OutlinedButton(onClick = onShare) { Text(stringResource(R.string.thread_r2_link_share)) } - if (!locked) Button(onClick = onOpen) { Text(stringResource(R.string.thread_link_confirm_open)) } - } - } - } -} +package com.glooboo.umessage.ui.thread + +import android.content.Context +import android.content.Intent +import android.provider.ContactsContract +import android.widget.Toast +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.UriHandler +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextDirection +import androidx.compose.ui.unit.dp +import com.glooboo.umessage.R + +/** + * Link taps in a thread (TH-05). A tap never opens the link straight away: [onTap] shows the link sheet with the + * domain and the whole address, so a phishing text's link text cannot hide where it really goes. + */ +internal fun linkSheetUriHandler(onTap: (String) -> Unit): UriHandler = object : UriHandler { + override fun openUri(uri: String) = onTap(uri) +} + +/** "Share" in the link sheet: the address as plain text, through the system share sheet. */ +internal fun shareLink(context: Context, uri: String) { + val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, linkCopyText(uri)) + try { + context.startActivity(Intent.createChooser(send, null)) + } catch (_: Exception) { + Toast.makeText(context, R.string.thread_no_app, Toast.LENGTH_SHORT).show() + } +} + +private const val MAILTO = "mailto:" +private val schemeHost = Regex("^[a-zA-Z][a-zA-Z0-9+.-]*://([^/?#:@\\s]+)") + +/** The domain of a web link without "www." ("bit.ly"), the address of a mailto link, else null. */ +internal fun linkHost(uri: String): String? { + if (uri.startsWith(MAILTO, ignoreCase = true)) { + return uri.substring(MAILTO.length).substringBefore('?').ifBlank { null } + } + val host = runCatching { java.net.URI(uri).host }.getOrNull() ?: schemeHost.find(uri)?.groupValues?.get(1) + return host?.removePrefix("www.")?.ifBlank { null } +} + +/** What "Copy link" copies: the address itself, without "mailto:" for an e-mail address. */ +internal fun linkCopyText(uri: String): String = when { + uri.startsWith(MAILTO, ignoreCase = true) -> uri.substring(MAILTO.length) + isPhoneLink(uri) -> phoneOf(uri) ?: uri + else -> uri +} + +/** + * "Add contact" for a phone number: the system's new-contact screen with the number filled in; nothing is saved + * here. + */ +internal fun addPhoneContact(context: Context, number: String) { + val insert = Intent(ContactsContract.Intents.Insert.ACTION) + .setType(ContactsContract.RawContacts.CONTENT_TYPE) + .putExtra(ContactsContract.Intents.Insert.PHONE, number) + try { + context.startActivity(insert) + } catch (_: Exception) { + Toast.makeText(context, R.string.thread_no_app, Toast.LENGTH_SHORT).show() + } +} + +/** + * TH-05: the domain in bold, the whole address (selectable), then Copy link, Share and Open. A sender who is not a + * saved contact ([trusted] false) also gets the line asking to check the address first. + */ +@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) +@Composable +internal fun LinkSheet( + uri: String, + trusted: Boolean, + onOpen: () -> Unit, + onCopy: () -> Unit, + onShare: () -> Unit, + onDismiss: () -> Unit, + /** I07: a risky link cannot be opened from here (the setting); the sheet says why and still copies and shares. */ + lockRisky: Boolean = false, +) { + val phone = phoneOf(uri) + if (phone != null) { + PhoneSheet(phone, onOpen, onCopy, onShare, onDismiss) + return + } + val state = rememberModalBottomSheetState(skipPartiallyExpanded = true) + val report = remember(uri) { LinkSafety.check(uri) } + val locked = lockRisky && report.isRisky + ModalBottomSheet(onDismissRequest = onDismiss, sheetState = state) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 24.dp) + .padding(bottom = 16.dp) + .navigationBarsPadding(), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + val ltr = MaterialTheme.typography.bodyMedium.copy(textDirection = TextDirection.Ltr) + linkHost(uri)?.let { host -> + Text(host, style = MaterialTheme.typography.titleLarge.copy(textDirection = TextDirection.Ltr)) + } + if (!trusted) { + Text( + stringResource(R.string.thread_link_confirm_body), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + LinkWarnings(report, locked) + SelectionContainer { + Text(uri, style = ltr, fontWeight = FontWeight.Medium) + } + FlowRow( + modifier = Modifier + .fillMaxWidth() + .padding(top = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp, androidx.compose.ui.Alignment.End), + ) { + OutlinedButton(onClick = onCopy) { Text(stringResource(R.string.thread_r2_link_copy)) } + OutlinedButton(onClick = onShare) { Text(stringResource(R.string.thread_r2_link_share)) } + if (!locked) Button(onClick = onOpen) { Text(stringResource(R.string.thread_link_confirm_open)) } + } + } + } +} + +/** + * A phone number tapped in a bubble: the number, then Copy, Add contact and Call. Call only opens the dialer with the + * number ([onOpen] hands the "tel:" link to the system, which never dials by itself). + */ +@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) +@Composable +private fun PhoneSheet( + number: String, + onOpen: () -> Unit, + onCopy: () -> Unit, + onShare: () -> Unit, + onDismiss: () -> Unit +) { + val state = rememberModalBottomSheetState(skipPartiallyExpanded = true) + val context = LocalContext.current + ModalBottomSheet(onDismissRequest = onDismiss, sheetState = state) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 24.dp) + .padding(bottom = 16.dp) + .navigationBarsPadding(), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + SelectionContainer { + Text(number, style = MaterialTheme.typography.titleLarge.copy(textDirection = TextDirection.Ltr)) + } + FlowRow( + modifier = Modifier + .fillMaxWidth() + .padding(top = 8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp, androidx.compose.ui.Alignment.End), + ) { + OutlinedButton(onClick = onCopy) { Text(stringResource(R.string.thread_phone_copy)) } + OutlinedButton(onClick = onShare) { Text(stringResource(R.string.thread_r2_link_share)) } + OutlinedButton(onClick = { + onDismiss() + addPhoneContact(context, number) + }) { Text(stringResource(R.string.thread_phone_add_contact)) } + Button(onClick = onOpen) { Text(stringResource(R.string.thread_phone_call)) } + } + } + } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadLookupCache.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadLookupCache.kt new file mode 100644 index 00000000..1f794803 --- /dev/null +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadLookupCache.kt @@ -0,0 +1,86 @@ +package com.glooboo.umessage.ui.thread + +import com.glooboo.umessage.models.Message + +/** + * Results that do not change from one message to the next, kept while a conversation is open: whether the sender is + * a saved contact or a stranger, and the SIM header labels. Every refresh used to ask the contacts, the database and + * the telephony service again. + * + * A result is valid for the [stamp] it was computed with; asking with another stamp computes it again. Contacts and + * SIM changes call [invalidateContacts] and [invalidateSims]. + */ +class ThreadLookupCache { + private data class Entry(val stamp: Any?, val value: T) + + private var contacts: Entry? = null + private var stranger: Entry? = null + private var sims: Entry? = null + + /** The contacts changed: the saved-contact and stranger results are looked up again. */ + @Synchronized + fun invalidateContacts() { + contacts = null + stranger = null + } + + /** The SIM cards changed. */ + @Synchronized + fun invalidateSims() { + sims = null + } + + /** Forgets everything, as when another conversation is loaded in place. */ + @Synchronized + fun clear() { + contacts = null + stranger = null + sims = null + } + + /** Whether [number] is a saved contact: [compute] runs once per [number] until the contacts change. */ + fun isSaved(number: String, compute: () -> Boolean): Boolean { + synchronized(this) { contacts?.takeIf { it.stamp == number }?.let { return it.value } } + return compute().also { value -> synchronized(this) { contacts = Entry(number, value) } } + } + + /** + * Whether the sender is a stranger. The answer depends on [number], on [isSaved], and on whether the user has + * [hasSent] a message to them (writing to someone makes them known), so a change of any of these asks again. + */ + fun isStranger(number: String?, isSaved: Boolean, hasSent: Boolean, compute: () -> Boolean): Boolean { + val stamp = Triple(number, isSaved, hasSent) + synchronized(this) { stranger?.takeIf { it.stamp == stamp }?.let { return it.value } } + return compute().also { value -> synchronized(this) { stranger = Entry(stamp, value) } } + } + + /** The SIM-derived value [compute] makes, kept until [invalidateSims]. */ + @Suppress("UNCHECKED_CAST") + fun sims(compute: () -> T): T { + synchronized(this) { sims?.let { return it.value as T } } + return compute().also { value -> synchronized(this) { sims = Entry(null, value) } } + } +} + +/** + * The loaded messages that are new or changed against the app's cached copy [cached]: only these are written back to + * the database when a conversation opens, instead of the whole first page every time. + */ +internal fun messagesToCache(fresh: List, cached: List): List { + if (cached.isEmpty()) return fresh + val byKey = HashMap(cached.size * 2) + cached.forEach { byKey[it.key] = it } + return fresh.filter { byKey[it.key] != it } +} + +/** + * How many rows above [anchorKey] count as new, in a list of row keys that is newest first: the rows that arrived + * since the reader scrolled away from the bottom, where [anchorKey] was the newest row. Null or a row that is gone: 0. + * Only rows for which [counted] is true add up (received messages; not date headers or the user's own messages). + */ +internal fun newRowsSince(rowKeys: List, anchorKey: String?, counted: (String) -> Boolean = { true }): Int { + if (anchorKey == null) return 0 + val at = rowKeys.indexOf(anchorKey) + if (at <= 0) return 0 + return rowKeys.subList(0, at).count(counted) +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadMediaSizes.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadMediaSizes.kt index 9d6b9a29..b47032b7 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadMediaSizes.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadMediaSizes.kt @@ -1,82 +1,107 @@ -package com.glooboo.umessage.ui.thread - -import android.content.Context -import android.content.SharedPreferences -import androidx.core.content.edit -import com.glooboo.umessage.models.Message -import java.util.concurrent.ConcurrentHashMap - -/** - * Width-to-height ratios of message photos and videos seen before, so a bubble is drawn at its final size before the - * picture has loaded. TU-25: every bubble started as a 4:3 box and changed size once the picture came in, which made - * the chat jump while scrolling. A ratio is learnt the first time a picture loads and kept on disk, keyed by its uri - * (MMS part uris do not change). - */ -object MediaSizes { - /** Ratio for a picture never seen before. */ - const val DEFAULT_ASPECT = 4f / 3f - - private const val PREFS = "media_sizes" - private const val MAX_ENTRIES = 4000 - - private val memory = ConcurrentHashMap() - private val warmed = ConcurrentHashMap.newKeySet() - - @Volatile - private var prefs: SharedPreferences? = null - - private fun prefs(context: Context): SharedPreferences = - prefs ?: context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE).also { prefs = it } - - /** The ratio already in memory, or null. Safe on the main thread. */ - fun cached(key: String): Float? = memory[key] - - /** - * Reads the saved ratios of every picture in [messages] into memory. Call off the main thread while the chat - * loads, before its rows are shown. - */ - fun warm(context: Context, messages: List) { - val keys = messages.asSequence() - .mapNotNull { it.attachment?.attachments } - .flatten() - .filter { it.mimetype.startsWith("image/") || it.mimetype.startsWith("video/") } - .map { it.uriString } - .filter { it !in warmed } - .toList() - if (keys.isEmpty()) return - val saved = prefs(context) - keys.forEach { key -> - warmed += key - val aspect = saved.getFloat(key, 0f) - if (aspect > 0f) memory[key] = aspect - } - } - - /** Remembers the size of a loaded picture, in memory at once and on disk in the background. */ - fun store(context: Context, key: String, width: Int, height: Int) { - if (width <= 0 || height <= 0) return - val aspect = width.toFloat() / height - if (memory[key] == aspect) return - memory[key] = aspect - val saved = prefs(context) - saved.edit { - // A rough bound: forgetting old ratios only means one more jump for those pictures. - if (saved.all.size >= MAX_ENTRIES) clear() - putFloat(key, aspect) - } - } - - /** Forgets the in-memory copy, as after the process was killed; the disk copy stays. For tests. */ - internal fun clearMemory() { - memory.clear() - warmed.clear() - } -} - -/** The ratio a media bubble is drawn at: the loaded picture's, else the one learnt earlier, else 4:3. */ -internal fun mediaAspect(loadedWidth: Int?, loadedHeight: Int?, cached: Float?): Float = - if (loadedWidth != null && loadedHeight != null && loadedWidth > 0 && loadedHeight > 0) { - loadedWidth.toFloat() / loadedHeight - } else { - cached ?: MediaSizes.DEFAULT_ASPECT - } +package com.glooboo.umessage.ui.thread + +import android.content.Context +import android.content.SharedPreferences +import androidx.core.content.edit +import com.glooboo.umessage.models.Message +import java.util.concurrent.ConcurrentHashMap + +/** + * Width-to-height ratios of message photos and videos seen before, so a bubble is drawn at its final size before the + * picture has loaded. TU-25: every bubble started as a 4:3 box and changed size once the picture came in, which made + * the chat jump while scrolling. A ratio is learnt the first time a picture loads and kept on disk, keyed by its uri + * (MMS part uris do not change). + */ +object MediaSizes { + /** Ratio for a picture never seen before. */ + const val DEFAULT_ASPECT = 4f / 3f + + private const val PREFS = "media_sizes" + private const val MAX_ENTRIES = 4000 + + private val memory = ConcurrentHashMap() + private val warmed = ConcurrentHashMap.newKeySet() + + @Volatile + private var prefs: SharedPreferences? = null + + /** + * Keys on disk in the order they were learnt, read once (SharedPreferences.getAll copies the whole map) and then + * kept by [store]. Keys that were already saved before this process started come first, in unspecified order. + */ + private var savedKeys: LinkedHashSet? = null + + private fun prefs(context: Context): SharedPreferences = + prefs ?: context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE).also { prefs = it } + + /** The ratio already in memory, or null. Safe on the main thread. */ + fun cached(key: String): Float? = memory[key] + + /** + * Reads the saved ratios of every picture in [messages] into memory. Call off the main thread while the chat + * loads, before its rows are shown. + */ + fun warm(context: Context, messages: List) { + val keys = messages.asSequence() + .mapNotNull { it.attachment?.attachments } + .flatten() + .filter { it.mimetype.startsWith("image/") || it.mimetype.startsWith("video/") } + .map { it.uriString } + .filter { it !in warmed } + .toList() + if (keys.isEmpty()) return + val saved = prefs(context) + keys.forEach { key -> + warmed += key + val aspect = saved.getFloat(key, 0f) + if (aspect > 0f) memory[key] = aspect + } + } + + /** Remembers the size of a loaded picture, in memory at once and on disk in the background. */ + fun store(context: Context, key: String, width: Int, height: Int) { + if (width <= 0 || height <= 0) return + val aspect = width.toFloat() / height + if (memory[key] == aspect) return + memory[key] = aspect + val saved = prefs(context) + synchronized(this) { + val keys = savedKeys ?: LinkedHashSet(saved.all.keys).also { savedKeys = it } + val isNew = keys.add(key) + val evicted = if (isNew) evictionBatch(keys, MAX_ENTRIES) else emptyList() + saved.edit { + // Forget the oldest tenth when full: that only means one more jump for those pictures. + evicted.forEach { remove(it) } + putFloat(key, aspect) + } + keys.removeAll(evicted.toSet()) + } + } + + /** Forgets the in-memory copy, as after the process was killed; the disk copy stays. For tests. */ + internal fun clearMemory() { + memory.clear() + warmed.clear() + synchronized(this) { savedKeys = null } + } +} + +private const val EVICT_FRACTION = 10 + +/** + * The oldest keys to drop once [keys] (oldest first) has grown past [max]: enough to leave a tenth of [max] free, so + * eviction does not run for every new picture. Empty while within the bound. + */ +internal fun evictionBatch(keys: Collection, max: Int): List { + if (keys.size <= max) return emptyList() + val drop = keys.size - max + (max / EVICT_FRACTION).coerceAtLeast(1) + return keys.take(drop.coerceAtMost(keys.size - 1)) +} + +/** The ratio a media bubble is drawn at: the loaded picture's, else the one learnt earlier, else 4:3. */ +internal fun mediaAspect(loadedWidth: Int?, loadedHeight: Int?, cached: Float?): Float = + if (loadedWidth != null && loadedHeight != null && loadedWidth > 0 && loadedHeight > 0) { + loadedWidth.toFloat() / loadedHeight + } else { + cached ?: MediaSizes.DEFAULT_ASPECT + } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadScheduleUi.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadScheduleUi.kt index a373f4a4..1a8c2977 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadScheduleUi.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadScheduleUi.kt @@ -1,208 +1,215 @@ -package com.glooboo.umessage.ui.thread - -import android.app.AlarmManager -import android.content.Context -import android.os.Build -import androidx.core.app.AlarmManagerCompat -import com.glooboo.umessage.BuildConfig -import com.glooboo.umessage.R -import com.glooboo.umessage.dialogs.ScheduleMessageDialog -import com.glooboo.umessage.helpers.DateStyle -import com.glooboo.umessage.helpers.threadPrefs -import com.glooboo.umessage.helpers.w3cPrefs -import com.glooboo.umessage.messaging.RepeatRule -import com.glooboo.umessage.messaging.bookNextRepeat -import com.glooboo.umessage.messaging.deleteScheduledRepeat -import com.glooboo.umessage.messaging.getScheduledRepeat -import com.glooboo.umessage.models.Message -import com.glooboo.umessage.ui.components.ChoiceItem -import com.glooboo.umessage.ui.components.askYesNo -import com.glooboo.umessage.ui.components.showChoiceDialog -import org.fossify.commons.activities.BaseSimpleActivity -import org.fossify.commons.extensions.openRequestExactAlarmSettings -import org.fossify.commons.helpers.ensureBackgroundThread - -/** - * The scheduling dialogs of the thread screen: the time picker (after offering "Alarms & reminders" when needed), - * the composer's schedule mode, and the choices on a scheduled bubble (edit, send now, delete; a held message only - * offers retry or delete). - * - * [cancel] deletes a scheduled message (keeping its attachment copies when the composer still shows them); - * [sendNow] sends one at once; [loadIntoComposer] empties the composer and puts the message's text and - * attachments in it. - */ -class ThreadScheduleUi( - private val activity: BaseSimpleActivity, - private val vm: ThreadViewModel, - private val cancel: (messageId: Long, keepAttachmentFiles: Boolean) -> Unit, - private val sendNow: (Message) -> Unit, - private val loadIntoComposer: (Message) -> Unit, -) { - /** Scheduling to continue with once the user is back from the "Alarms & reminders" setting. */ - private var afterExactAlarmSettings: (() -> Unit)? = null - - /** Call from onResume: continues scheduling after the user came back from the setting. */ - fun onResume() { - afterExactAlarmSettings?.let { - afterExactAlarmSettings = null - it() - } - } - - /** - * Without "Alarms & reminders" (off by default on Android 14+) scheduling still works with an inexact alarm, so - * this only offers the setting: it used to wait for the permission and do nothing until it was granted. Back - * from the setting, scheduling continues whatever the user chose there. USE_EXACT_ALARM is not used: Play allows - * it only for alarm-clock and calendar apps. B12: the offer is made once; after that a short toast on saving says - * the time is approximate. - */ - private fun askForExactAlarmPermissionIfNeeded(callback: () -> Unit) { - val alarmManager = activity.getSystemService(Context.ALARM_SERVICE) as AlarmManager - // Always true before Android 12, where the setting does not exist. - val exact = Build.VERSION.SDK_INT < Build.VERSION_CODES.S || - AlarmManagerCompat.canScheduleExactAlarms(alarmManager) - val prefs = activity.threadPrefs - if (exact || prefs.exactAlarmAsked) { - callback() - return - } - prefs.exactAlarmAsked = true - activity.showExactAlarmDialog( - onOpenSettings = { - afterExactAlarmSettings = callback - try { - activity.openRequestExactAlarmSettings(BuildConfig.APPLICATION_ID) - } catch (_: Exception) { - afterExactAlarmSettings = null - callback() - } - }, - onScheduleAnyway = callback, - ) - } - - /** Opens the time picker, at [originalMillis] when the message already has a time. */ - fun pickTime(originalMillis: Long? = null) { - askForExactAlarmPermissionIfNeeded { - val repeat = RepeatRule.fromName(vm.scheduledRepeat) - ScheduleMessageDialog(activity, originalMillis, repeat) { newMillis, newRepeat -> - vm.scheduledRepeat = newRepeat.takeUnless { it == RepeatRule.NONE }?.name - if (newMillis != null) show(newMillis) - } - } - } - - /** Puts the composer in "schedule" mode for [millis]; the time lives in the view model's saved state. */ - fun show(millis: Long) { - vm.scheduledMillis = millis - val time = scheduleLabel(activity, millis, jalali = activity.w3cPrefs.dateStyle != DateStyle.GREGORIAN) - val repeatNote = bannerRepeatNote(RepeatRule.fromName(vm.scheduledRepeat)) - vm.scheduledLabel = if (repeatNote == null) time else "$time · ${activity.getString(repeatNote)}" - } - - /** "x" on the schedule banner: back to sending now; a scheduled message being edited is deleted. */ - fun discard() { - val editedId = vm.scheduledMessageId - vm.clearSchedule() - if (editedId != null) cancel(editedId, true) - } - - /** A tap on a scheduled bubble. */ - fun showOptions(message: Message) { - if (message.isHeldScheduled()) { - // Its send failed: it waits for the user, who can only try again or throw it away. - val heldItems = listOf( - ChoiceItem(activity.getString(R.string.ui_retry_send), TYPE_SEND), - ChoiceItem(activity.getString(org.fossify.commons.R.string.delete), TYPE_DELETE), - ) - activity.showChoiceDialog(heldItems, title = activity.getString(R.string.thread_scheduled_not_sent)) { any -> - when (any) { - TYPE_DELETE -> cancel(message.id, false) - TYPE_SEND -> sendNow(message) - } - } - return - } - val items = listOf( - ChoiceItem(activity.getString(R.string.update_message), TYPE_EDIT), - ChoiceItem(activity.getString(R.string.send_now), TYPE_SEND), - ChoiceItem(activity.getString(org.fossify.commons.R.string.delete), TYPE_DELETE), - ) - activity.showChoiceDialog(items, title = activity.getString(R.string.scheduled_message)) { any -> - when (any) { - TYPE_DELETE -> confirmDelete(message) - TYPE_EDIT -> confirmEdit(message) - TYPE_SEND -> sendOccurrenceNow(message) - } - } - } - - /** Send now on a repeating message sends this one; the repeat goes on, so the next copy is booked first. */ - private fun sendOccurrenceNow(message: Message) { - ensureBackgroundThread { - // This copy becomes a one-off, so a failed send held for Retry cannot book a second next copy. - if (runCatching { activity.bookNextRepeat(message) }.getOrNull() != null) { - activity.deleteScheduledRepeat(message.id) - } - activity.runOnUiThread { sendNow(message) } - } - } - - /** A repeating message asks whether only this one goes or all the later ones too (B04). */ - private fun confirmDelete(message: Message) { - ensureBackgroundThread { - val repeating = runCatching { activity.getScheduledRepeat(message.id) }.getOrNull() != null - if (!repeating) { - cancel(message.id, false) - return@ensureBackgroundThread - } - activity.runOnUiThread { - val items = listOf( - ChoiceItem(activity.getString(R.string.scheduled_delete_this_one), TYPE_DELETE_THIS), - ChoiceItem(activity.getString(R.string.scheduled_delete_all_future), TYPE_DELETE), - ) - activity.showChoiceDialog(items, title = activity.getString(R.string.scheduled_delete_repeating)) { - if (it == TYPE_DELETE) { - cancel(message.id, false) - } else { - // Books the next copy first, then deletes this one: the repeat goes on. - ensureBackgroundThread { - runCatching { activity.bookNextRepeat(message) } - cancel(message.id, false) - } - } - } - } - } - } - - /** Editing loads the scheduled message into the composer; ask first when that would replace a draft. */ - private fun confirmEdit(message: Message) { - val hasDraft = vm.text.text.isNotBlank() || vm.attachments.isNotEmpty() - if (hasDraft && vm.scheduledMessageId != message.id) { - activity.askYesNo(activity.getString(R.string.thread_edit_scheduled_replaces_draft)) { edit(message) } - } else { - edit(message) - } - } - - private fun edit(message: Message) { - loadIntoComposer(message) - vm.scheduledMessageId = message.id - show(message.millis()) - ensureBackgroundThread { - val repeat = runCatching { activity.getScheduledRepeat(message.id) }.getOrNull() - activity.runOnUiThread { - vm.scheduledRepeat = repeat?.rule - if (vm.scheduledMessageId == message.id) show(vm.scheduledMillis ?: message.millis()) - } - } - } - - private companion object { - const val TYPE_EDIT = 14 - const val TYPE_SEND = 15 - const val TYPE_DELETE = 16 - const val TYPE_DELETE_THIS = 17 - } -} +package com.glooboo.umessage.ui.thread + +import android.app.AlarmManager +import android.content.Context +import android.os.Build +import androidx.core.app.AlarmManagerCompat +import com.glooboo.umessage.BuildConfig +import com.glooboo.umessage.R +import com.glooboo.umessage.dialogs.ScheduleMessageDialog +import com.glooboo.umessage.helpers.DateStyle +import com.glooboo.umessage.helpers.threadPrefs +import com.glooboo.umessage.helpers.w3cPrefs +import com.glooboo.umessage.messaging.RepeatRule +import com.glooboo.umessage.messaging.bookNextRepeat +import com.glooboo.umessage.messaging.deleteScheduledRepeat +import com.glooboo.umessage.messaging.getScheduledRepeat +import com.glooboo.umessage.models.Message +import com.glooboo.umessage.ui.components.ChoiceItem +import com.glooboo.umessage.ui.components.askYesNo +import com.glooboo.umessage.ui.components.showChoiceDialog +import org.fossify.commons.activities.BaseSimpleActivity +import org.fossify.commons.extensions.openRequestExactAlarmSettings +import org.fossify.commons.helpers.ensureBackgroundThread + +/** + * The scheduling dialogs of the thread screen: the time picker (after offering "Alarms & reminders" when needed), + * the composer's schedule mode, and the choices on a scheduled bubble (edit, send now, delete; a held message only + * offers retry or delete). + * + * [cancel] deletes a scheduled message (keeping its attachment copies when the composer still shows them); + * [sendNow] sends one at once; [loadIntoComposer] empties the composer and puts the message's text and + * attachments in it. + */ +class ThreadScheduleUi( + private val activity: BaseSimpleActivity, + private val vm: ThreadViewModel, + private val cancel: (messageId: Long, keepAttachmentFiles: Boolean) -> Unit, + private val sendNow: (Message) -> Unit, + private val loadIntoComposer: (Message) -> Unit, +) { + /** Scheduling to continue with once the user is back from the "Alarms & reminders" setting. */ + private var afterExactAlarmSettings: (() -> Unit)? = null + + /** Call from onResume: continues scheduling after the user came back from the setting. */ + fun onResume() { + afterExactAlarmSettings?.let { + afterExactAlarmSettings = null + it() + } + } + + /** + * Without "Alarms & reminders" (off by default on Android 14+) scheduling still works with an inexact alarm, so + * this only offers the setting: it used to wait for the permission and do nothing until it was granted. Back + * from the setting, scheduling continues whatever the user chose there. USE_EXACT_ALARM is not used: Play allows + * it only for alarm-clock and calendar apps. B12: the offer is made once; after that a short toast on saving says + * the time is approximate. + */ + private fun askForExactAlarmPermissionIfNeeded(callback: () -> Unit) { + val alarmManager = activity.getSystemService(Context.ALARM_SERVICE) as AlarmManager + // Always true before Android 12, where the setting does not exist. + val exact = Build.VERSION.SDK_INT < Build.VERSION_CODES.S || + AlarmManagerCompat.canScheduleExactAlarms(alarmManager) + val prefs = activity.threadPrefs + if (exact || prefs.exactAlarmAsked) { + callback() + return + } + prefs.exactAlarmAsked = true + activity.showExactAlarmDialog( + onOpenSettings = { + afterExactAlarmSettings = callback + try { + activity.openRequestExactAlarmSettings(BuildConfig.APPLICATION_ID) + } catch (_: Exception) { + afterExactAlarmSettings = null + callback() + } + }, + onScheduleAnyway = callback, + ) + } + + /** Opens the time picker, at [originalMillis] when the message already has a time. */ + fun pickTime(originalMillis: Long? = null) { + askForExactAlarmPermissionIfNeeded { + val repeat = RepeatRule.fromName(vm.scheduledRepeat) + ScheduleMessageDialog(activity, originalMillis, repeat) { newMillis, newRepeat -> + vm.scheduledRepeat = newRepeat.takeUnless { it == RepeatRule.NONE }?.name + if (newMillis != null) show(newMillis) + } + } + } + + /** Puts the composer in "schedule" mode for [millis]; the time lives in the view model's saved state. */ + fun show(millis: Long) { + vm.scheduledMillis = millis + val time = scheduleLabel(activity, millis, jalali = activity.w3cPrefs.dateStyle != DateStyle.GREGORIAN) + val repeatNote = bannerRepeatNote(RepeatRule.fromName(vm.scheduledRepeat)) + vm.scheduledLabel = if (repeatNote == null) time else "$time · ${activity.getString(repeatNote)}" + } + + /** "x" on the schedule banner: back to sending now; a scheduled message being edited is deleted. */ + fun discard() { + val editedId = vm.scheduledMessageId + if (editedId == null) { + vm.clearSchedule() + return + } + // The stored message and its alarm go for good, so ask first. + activity.askYesNo(activity.getString(R.string.thread_schedule_discard_confirm)) { + vm.clearSchedule() + cancel(editedId, true) + } + } + + /** A tap on a scheduled bubble. */ + fun showOptions(message: Message) { + if (message.isHeldScheduled()) { + // Its send failed: it waits for the user, who can only try again or throw it away. + val heldItems = listOf( + ChoiceItem(activity.getString(R.string.ui_retry_send), TYPE_SEND), + ChoiceItem(activity.getString(org.fossify.commons.R.string.delete), TYPE_DELETE), + ) + activity.showChoiceDialog(heldItems, title = activity.getString(R.string.thread_scheduled_not_sent)) { any -> + when (any) { + TYPE_DELETE -> cancel(message.id, false) + TYPE_SEND -> sendNow(message) + } + } + return + } + val items = listOf( + ChoiceItem(activity.getString(R.string.update_message), TYPE_EDIT), + ChoiceItem(activity.getString(R.string.send_now), TYPE_SEND), + ChoiceItem(activity.getString(org.fossify.commons.R.string.delete), TYPE_DELETE), + ) + activity.showChoiceDialog(items, title = activity.getString(R.string.scheduled_message)) { any -> + when (any) { + TYPE_DELETE -> confirmDelete(message) + TYPE_EDIT -> confirmEdit(message) + TYPE_SEND -> sendOccurrenceNow(message) + } + } + } + + /** Send now on a repeating message sends this one; the repeat goes on, so the next copy is booked first. */ + private fun sendOccurrenceNow(message: Message) { + ensureBackgroundThread { + // This copy becomes a one-off, so a failed send held for Retry cannot book a second next copy. + if (runCatching { activity.bookNextRepeat(message) }.getOrNull() != null) { + activity.deleteScheduledRepeat(message.id) + } + activity.runOnUiThread { sendNow(message) } + } + } + + /** A repeating message asks whether only this one goes or all the later ones too (B04). */ + private fun confirmDelete(message: Message) { + ensureBackgroundThread { + val repeating = runCatching { activity.getScheduledRepeat(message.id) }.getOrNull() != null + if (!repeating) { + cancel(message.id, false) + return@ensureBackgroundThread + } + activity.runOnUiThread { + val items = listOf( + ChoiceItem(activity.getString(R.string.scheduled_delete_this_one), TYPE_DELETE_THIS), + ChoiceItem(activity.getString(R.string.scheduled_delete_all_future), TYPE_DELETE), + ) + activity.showChoiceDialog(items, title = activity.getString(R.string.scheduled_delete_repeating)) { + if (it == TYPE_DELETE) { + cancel(message.id, false) + } else { + // Books the next copy first, then deletes this one: the repeat goes on. + ensureBackgroundThread { + runCatching { activity.bookNextRepeat(message) } + cancel(message.id, false) + } + } + } + } + } + } + + /** Editing loads the scheduled message into the composer; ask first when that would replace a draft. */ + private fun confirmEdit(message: Message) { + val hasDraft = vm.text.text.isNotBlank() || vm.attachments.isNotEmpty() + if (hasDraft && vm.scheduledMessageId != message.id) { + activity.askYesNo(activity.getString(R.string.thread_edit_scheduled_replaces_draft)) { edit(message) } + } else { + edit(message) + } + } + + private fun edit(message: Message) { + loadIntoComposer(message) + vm.scheduledMessageId = message.id + show(message.millis()) + ensureBackgroundThread { + val repeat = runCatching { activity.getScheduledRepeat(message.id) }.getOrNull() + activity.runOnUiThread { + vm.scheduledRepeat = repeat?.rule + if (vm.scheduledMessageId == message.id) show(vm.scheduledMillis ?: message.millis()) + } + } + } + + private companion object { + const val TYPE_EDIT = 14 + const val TYPE_SEND = 15 + const val TYPE_DELETE = 16 + const val TYPE_DELETE_THIS = 17 + } +} 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 8bb41fca..5decd7b4 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 @@ -28,6 +28,7 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExtendedFloatingActionButton import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon @@ -153,6 +154,7 @@ fun ThreadScreen(vm: ThreadViewModel, actions: ThreadActions) { query = vm.searchQuery, matchCount = vm.searchMatches.size, matchIndex = vm.searchIndex, + searchingOlder = vm.searchingOlder, onQueryChange = vm::updateSearch, onClose = vm::closeSearch, onOlder = vm::showOlderMatch, @@ -240,6 +242,18 @@ private fun MessageList(vm: ThreadViewModel, actions: ThreadActions, modifier: M val showScrollToBottom by remember { derivedStateOf { listState.firstVisibleItemIndex > SCROLL_TO_BOTTOM_FAB_LIMIT } } + // New messages that arrive while the reader is up in the history are counted on the down button. The anchor is + // the newest row at the moment the reader left the bottom; reaching the bottom again clears it. + val atBottom by remember { derivedStateOf { listState.firstVisibleItemIndex <= NEAR_BOTTOM_ROWS } } + var anchorKey by remember { mutableStateOf(null) } + LaunchedEffect(atBottom) { anchorKey = if (atBottom) null else vm.rows.firstOrNull()?.key } + val newCount = remember(rows, anchorKey) { + val received = rows.mapNotNullTo(HashSet()) { row -> + (row as? ThreadRow.Bubble)?.takeIf { it.message.isReceivedMessage() }?.key + } + newRowsSince(rows.map { it.key }, anchorKey) { it in received } + } + val context = LocalContext.current val pinchZoom = remember { context.w3cPrefs.pinchZoomText } var zoomedTo by remember { mutableStateOf(null) } @@ -268,7 +282,7 @@ private fun MessageList(vm: ThreadViewModel, actions: ThreadActions, modifier: M } zoomedTo?.let { PinchZoomLabel(it, Modifier.align(Alignment.Center)) } AnimatedVisibility( - visible = showScrollToBottom, + visible = showScrollToBottom || newCount > 0, enter = fadeIn() + scaleIn(), exit = fadeOut() + scaleOut(), modifier = Modifier @@ -276,12 +290,25 @@ private fun MessageList(vm: ThreadViewModel, actions: ThreadActions, modifier: M .padding(16.dp), ) { val scope = rememberCoroutineScope() - SmallFloatingActionButton( - onClick = { scope.launch { listState.animateScrollToItem(0) } }, - containerColor = MaterialTheme.colorScheme.secondaryContainer, - contentColor = MaterialTheme.colorScheme.onSecondaryContainer, - ) { - Icon(Symbols.KeyboardArrowDown, contentDescription = stringResource(R.string.thread_scroll_to_latest)) + if (newCount > 0) { + ExtendedFloatingActionButton( + onClick = { scope.launch { listState.animateScrollToItem(0) } }, + containerColor = MaterialTheme.colorScheme.primaryContainer, + contentColor = MaterialTheme.colorScheme.onPrimaryContainer, + icon = { Icon(Symbols.KeyboardArrowDown, contentDescription = null) }, + text = { Text(pluralStringResource(R.plurals.thread_new_messages_chip, newCount, newCount)) }, + ) + } else { + SmallFloatingActionButton( + onClick = { scope.launch { listState.animateScrollToItem(0) } }, + containerColor = MaterialTheme.colorScheme.secondaryContainer, + contentColor = MaterialTheme.colorScheme.onSecondaryContainer, + ) { + Icon( + Symbols.KeyboardArrowDown, + contentDescription = stringResource(R.string.thread_scroll_to_latest) + ) + } } } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSearch.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSearch.kt index 997dcf87..c01c54c5 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSearch.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSearch.kt @@ -1,5 +1,7 @@ package com.glooboo.umessage.ui.thread +import com.glooboo.umessage.models.MessageKey + /** * "Search in conversation" (TH-20). Matching ignores case, reads Persian and Arabic digits as 0-9 and Arabic ي/ك as * the Persian letters, so "۴۸۲" finds "482913" and the other way round. Every character maps to exactly one, so a @@ -42,3 +44,19 @@ internal fun olderMatch(current: Int, count: Int): Int = if (count == 0) 0 else /** "Next": the next newer match, wrapping to the oldest. */ internal fun newerMatch(current: Int, count: Int): Int = if (count == 0) 0 else (current - 1 + count) % count + +/** A message that matches a search, with its date in seconds, so matches from different sources sort together. */ +data class SearchHit(val key: MessageKey, val date: Int) + +/** + * The matches of an in-conversation search, newest first: those among the loaded messages ([loaded], newest first) + * plus those [older] found in the database that are not loaded yet. A message in both counts once. + */ +internal fun mergeSearchHits(loaded: List, older: List): List { + if (older.isEmpty()) return loaded.map { it.key } + val seen = HashSet(loaded.size + older.size) + val all = ArrayList(loaded.size + older.size) + for (hit in loaded) if (seen.add(hit.key)) all += hit + for (hit in older) if (seen.add(hit.key)) all += hit + return all.sortedByDescending { it.date }.map { it.key } +} diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSearchBar.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSearchBar.kt index 9c04941e..4bded41a 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSearchBar.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSearchBar.kt @@ -3,8 +3,11 @@ package com.glooboo.umessage.ui.thread import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.BasicTextField +import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton @@ -20,6 +23,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp @@ -37,6 +41,7 @@ internal fun SearchTopBar( query: String, matchCount: Int, matchIndex: Int, + searchingOlder: Boolean, onQueryChange: (String) -> Unit, onClose: () -> Unit, onOlder: () -> Unit, @@ -46,6 +51,7 @@ internal fun SearchTopBar( val colors = MaterialTheme.colorScheme val focusRequester = remember { FocusRequester() } LaunchedEffect(Unit) { focusRequester.requestFocus() } + val keyboard = LocalSoftwareKeyboardController.current TopAppBar( modifier = modifier, windowInsets = topBarInsets(), @@ -62,6 +68,8 @@ internal fun SearchTopBar( textStyle = MaterialTheme.typography.titleMedium.copy(color = colors.onSurface), cursorBrush = SolidColor(colors.primary), keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + // Search: the keyboard gives way to the results. + keyboardActions = KeyboardActions(onSearch = { keyboard?.hide() }), modifier = Modifier .fillMaxWidth() .focusRequester(focusRequester), @@ -81,9 +89,14 @@ internal fun SearchTopBar( }, actions = { if (query.isNotBlank()) { + if (searchingOlder && matchCount > 0) { + CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(16.dp)) + } Text( if (matchCount == 0) { - stringResource(R.string.thread_r2_search_none) + stringResource( + if (searchingOlder) R.string.thread_search_older_busy else R.string.thread_r2_search_none, + ) } else { stringResource(R.string.thread_r2_search_count, matchIndex + 1, matchCount) }, diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSelectionActions.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSelectionActions.kt index cf2f3ba5..9f206e36 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSelectionActions.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSelectionActions.kt @@ -161,11 +161,16 @@ class ThreadSelectionActions( } private fun forward(message: Message) { - val attachment = message.attachment?.attachments?.firstOrNull() + val attachments = message.attachment?.attachments.orEmpty() Intent(activity, NewConversationActivity::class.java).apply { - action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT, message.body) - if (attachment != null) putExtra(Intent.EXTRA_STREAM, attachment.getUri()) + if (attachments.size > 1) { + action = Intent.ACTION_SEND_MULTIPLE + putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(attachments.map { it.getUri() })) + } else { + action = Intent.ACTION_SEND + attachments.firstOrNull()?.let { putExtra(Intent.EXTRA_STREAM, it.getUri()) } + } activity.startActivity(this) } } diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSendController.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSendController.kt index ef7346bc..e77d9c5e 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSendController.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/thread/ThreadSendController.kt @@ -1,7 +1,8 @@ package com.glooboo.umessage.ui.thread import android.content.Context -import com.glooboo.umessage.messaging.sendMessageCompat +import com.glooboo.umessage.messaging.SendOutcome +import com.glooboo.umessage.messaging.sendMessageDetailed import com.glooboo.umessage.models.Attachment import com.glooboo.umessage.models.MessageKey @@ -20,14 +21,17 @@ data class OutgoingMessage( val onAttachmentHandedOff: (Attachment) -> Unit = {}, ) -/** Hands a message to the system. Returns false when nothing reached the provider; may throw. */ +/** + * Hands a message to the system. [SendOutcome.handedOff] is false when something did not reach the provider (for a + * message with several attachments, [SendOutcome] says which parts did); may throw. + */ fun interface MessageSender { - fun send(message: OutgoingMessage): Boolean + fun send(message: OutgoingMessage): SendOutcome } /** [MessageSender] through the app's SMS/MMS code. */ class ContextMessageSender(private val context: Context) : MessageSender { - override fun send(message: OutgoingMessage): Boolean = context.sendMessageCompat( + override fun send(message: OutgoingMessage): SendOutcome = context.sendMessageDetailed( text = message.text, addresses = message.addresses, subId = message.subscriptionId, @@ -50,10 +54,16 @@ class ThreadSendController( * [completed] is false when the send threw: nothing new can be in the provider then. A send that returned, * even unsuccessfully, may have left a failed row (with Retry) to show. */ - data class Result(val handedOff: Boolean, val clearComposer: Boolean, val completed: Boolean) + data class Result( + val handedOff: Boolean, + val clearComposer: Boolean, + val completed: Boolean, + /** Set when only some attachments went out: what is left to send, and whether the text already went. */ + val partial: SendOutcome? = null, + ) fun send(message: OutgoingMessage, fromComposer: Boolean): Result { - val handedOff = try { + val outcome = try { sender.send(message) } catch (e: Exception) { onError(e) @@ -62,7 +72,13 @@ class ThreadSendController( onError(e) return Result(handedOff = false, clearComposer = false, completed = false) } - return Result(handedOff, shouldClearComposerAfterSend(handedOff, fromComposer), completed = true) + val handedOff = outcome.handedOff + return Result( + handedOff, + shouldClearComposerAfterSend(handedOff, fromComposer), + completed = true, + partial = outcome.takeIf { it.partlySent }, + ) } } 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 02a7447e..c36eb012 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 @@ -12,6 +12,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.text.TextRange import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope import com.glooboo.umessage.models.Attachment import com.glooboo.umessage.messaging.RepeatRule import com.glooboo.umessage.models.AttachmentSelection @@ -19,7 +20,13 @@ import com.glooboo.umessage.models.Message import com.glooboo.umessage.models.MessageKey import com.glooboo.umessage.models.SIMCard import com.glooboo.umessage.models.ThreadItem +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow @@ -281,12 +288,31 @@ class ThreadViewModel(private val saved: SavedStateHandle = SavedStateHandle(emp var searchIndex by mutableIntStateOf(0) private set - /** The loaded messages whose text holds [searchQuery], newest first. */ + /** Matches found in the database among messages that are not loaded yet; see [searchOlder]. */ + private var olderHits by mutableStateOf>(emptyList()) + + /** True while the database is searched for older messages: the search bar says so. */ + var searchingOlder by mutableStateOf(false) + private set + + /** + * Set by the activity: the matches for a query among all messages of the thread, read off the main thread (the + * list holds only the newest page and the pages scrolled in). Null: only loaded messages are searched. + */ + var olderSearch: ((threadId: Long, query: String) -> List)? = null + + /** Set by the activity: loads history up to a message that is not loaded yet, then scrolls to it. */ + var loadAndScrollTo: ((MessageKey) -> Unit)? = null + + private var searchJob: Job? = null + + /** The messages whose text holds [searchQuery], loaded or not, newest first. */ val searchMatches: List by derivedStateOf { if (searchQuery.isBlank()) { emptyList() } else { - messages().filter { matchesSearch(it.body, searchQuery) }.map { it.key }.asReversed() + val loaded = messages().filter { matchesSearch(it.body, searchQuery) }.map { SearchHit(it.key, it.date) } + mergeSearchHits(loaded.asReversed(), olderHits) } } @@ -302,6 +328,9 @@ class ThreadViewModel(private val saved: SavedStateHandle = SavedStateHandle(emp } fun closeSearch() { + searchJob?.cancel() + searchingOlder = false + olderHits = emptyList() searchOpen = false searchQuery = "" searchIndex = 0 @@ -310,7 +339,44 @@ class ThreadViewModel(private val saved: SavedStateHandle = SavedStateHandle(emp fun updateSearch(query: String) { searchQuery = query searchIndex = 0 - currentSearchMatch?.let(::scrollToMessage) + searchOlder(query) + currentSearchMatch?.let(::showSearchMatch) + } + + /** Looks for [query] in the messages that are not loaded yet, after a short pause in typing. */ + @Suppress("TooGenericExceptionCaught", "SwallowedException") // A failed search just shows no older hits. + private fun searchOlder(query: String) { + searchJob?.cancel() + olderHits = emptyList() + val search = olderSearch + val nothingToSearch = isRecycleBin || threadId == 0L + if (query.isBlank() || search == null || nothingToSearch) { + searchingOlder = false + return + } + searchingOlder = true + val thread = threadId + searchJob = viewModelScope.launch { + delay(SEARCH_PAUSE_MS) + val hits = try { + withContext(Dispatchers.IO) { search(thread, query) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + emptyList() + } + if (searchQuery != query) return@launch + val before = currentSearchMatch + olderHits = hits + searchingOlder = false + // Nothing was loaded to show: go to the newest match that was found only now. + if (before == null) currentSearchMatch?.let(::showSearchMatch) + } + } + + /** Scrolls to [message], first loading the history up to it when it is not among the loaded messages. */ + private fun showSearchMatch(message: MessageKey) { + if (messages().any { it.key == message }) scrollToMessage(message) else loadAndScrollTo?.invoke(message) } fun showOlderMatch() = moveSearch(olderMatch(searchIndex, searchMatches.size)) @@ -319,7 +385,7 @@ class ThreadViewModel(private val saved: SavedStateHandle = SavedStateHandle(emp private fun moveSearch(index: Int) { searchIndex = index - currentSearchMatch?.let(::scrollToMessage) + currentSearchMatch?.let(::showSearchMatch) } // endregion @@ -423,6 +489,7 @@ class ThreadViewModel(private val saved: SavedStateHandle = SavedStateHandle(emp // endregion private companion object { + const val SEARCH_PAUSE_MS = 250L const val KEY_SCHEDULED_MILLIS = "scheduled_millis" const val KEY_SCHEDULED_MESSAGE_ID = "scheduled_message_id" const val KEY_SCHEDULED_REPEAT = "scheduled_repeat" diff --git a/app/src/main/kotlin/com/glooboo/umessage/ui/vcard/VCardViewerScreen.kt b/app/src/main/kotlin/com/glooboo/umessage/ui/vcard/VCardViewerScreen.kt index b2b8a63c..7338e4b9 100644 --- a/app/src/main/kotlin/com/glooboo/umessage/ui/vcard/VCardViewerScreen.kt +++ b/app/src/main/kotlin/com/glooboo/umessage/ui/vcard/VCardViewerScreen.kt @@ -1,7 +1,13 @@ package com.glooboo.umessage.ui.vcard +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context import android.graphics.BitmapFactory +import android.widget.Toast import androidx.compose.foundation.Image +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -24,12 +30,15 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.Saver +import androidx.compose.runtime.saveable.rememberSaveable 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.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.stateDescription @@ -45,6 +54,8 @@ import com.glooboo.umessage.ui.components.UMessageScaffold import com.glooboo.umessage.ui.components.UMessageTopBar import com.glooboo.umessage.ui.conversations.ContactAvatar import com.glooboo.umessage.ui.icons.Symbols +import ezvcard.property.Email +import ezvcard.property.Telephone /** * Contacts inside a shared vCard. A single contact is shown open; several are collapsed rows that expand to @@ -59,7 +70,7 @@ fun VCardViewerScreen( isActionable: (VCardPropertyWrapper) -> Boolean, modifier: Modifier = Modifier, ) { - var expanded by remember { mutableStateOf(emptySet()) } + var expanded by rememberSaveable(stateSaver = ExpandedSaver) { mutableStateOf(emptySet()) } UMessageScaffold( modifier = modifier, topBar = { @@ -172,13 +183,42 @@ private fun VCardAvatar(name: String, photo: ByteArray?) { } } +/** The expanded contact indexes survive rotation. */ +private val ExpandedSaver = Saver, ArrayList>( + save = { ArrayList(it) }, + restore = { it.toSet() }, +) + +@OptIn(ExperimentalFoundationApi::class) @Composable private fun PropertyRow(property: VCardPropertyWrapper, actionable: Boolean, onClick: () -> Unit) { + val context = LocalContext.current + val copied = stringResource(R.string.screens_vcard_copied) + val actionLabel = stringResource( + if (property.property is Email) R.string.screens_vcard_email_action else R.string.convx_details_call, + ) + val copyLabel = stringResource(R.string.screens_copy) + val copy = { copyToClipboard(context, property.value, copied) } + val tappable = property.property is Telephone || property.property is Email Column( modifier = Modifier .fillMaxWidth() .heightIn(min = 56.dp) - .then(if (actionable) Modifier.clickable(role = Role.Button, onClick = onClick) else Modifier) + .then( + if (actionable) { + Modifier.combinedClickable( + role = Role.Button, + onClickLabel = actionLabel, + onClick = onClick, + onLongClickLabel = copyLabel, + onLongClick = copy, + ) + } else if (tappable) { + Modifier.combinedClickable(onClick = {}, onLongClickLabel = copyLabel, onLongClick = copy) + } else { + Modifier + }, + ) // Aligned with the contact name: 16dp gutter + 48dp avatar + 16dp gap. .padding(start = 80.dp, end = 16.dp, top = 8.dp, bottom = 8.dp), verticalArrangement = Arrangement.Center, @@ -193,3 +233,12 @@ private fun PropertyRow(property: VCardPropertyWrapper, actionable: Boolean, onC } } } + +private fun copyToClipboard(context: Context, text: String, confirmation: String) { + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager ?: return + clipboard.setPrimaryClip(ClipData.newPlainText(text, text)) + // Android 13+ shows its own "copied" confirmation. + if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) { + Toast.makeText(context, confirmation, Toast.LENGTH_SHORT).show() + } +} diff --git a/app/src/main/res/values-ar/strings_carrier_report.xml b/app/src/main/res/values-ar/strings_carrier_report.xml index 88a1ba55..97326b37 100644 --- a/app/src/main/res/values-ar/strings_carrier_report.xml +++ b/app/src/main/res/values-ar/strings_carrier_report.xml @@ -8,7 +8,7 @@ استخدم من 3 إلى 8 أرقام أبلغ مشغّل شبكة الجوال هل تريد إبلاغ مشغّل شبكة الجوال؟ - ستُرسل آخر رسالة من هذا المرسل إلى %1$s عبر SMS. قد يفرض مشغّل شبكة الجوال رسومًا عليها. + ستُرسل آخر رسالة من هذا المرسل، ورقم المرسل تحتها، إلى %1$s عبر SMS. قد يفرض مشغّل شبكة الجوال رسومًا عليها. أرسل تم إرسال البلاغ إلى مشغّل شبكة الجوال تعذر إرسال البلاغ diff --git a/app/src/main/res/values-ar/strings_review2_blocked_rules.xml b/app/src/main/res/values-ar/strings_review2_blocked_rules.xml index b430f1de..9a5af86b 100644 --- a/app/src/main/res/values-ar/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-ar/strings_review2_blocked_rules.xml @@ -15,6 +15,25 @@ الرسائل التي تنقلها إلى الرسائل الواردة من الآن ستظهر هنا لمدة 30 يومًا. نُقلت إلى الرسائل الواردة %1$s افتح المحادثة مع %1$s + أصبح %1$s مسموحًا دائمًا على شريحتي SIM + + أصبح %d مرسل مسموحًا دائمًا على شريحتي SIM + أصبح مرسل واحد (%d) مسموحًا دائمًا على شريحتي SIM + أصبح مرسلان (%d) مسموحين دائمًا على شريحتي SIM + أصبح %d مرسلين مسموحين دائمًا على شريحتي SIM + أصبح %d مرسلًا مسموحًا دائمًا على شريحتي SIM + أصبح %d مرسل مسموحًا دائمًا على شريحتي SIM + + أصبح %1$s مسموحًا دائمًا + + أصبح %d مرسل مسموحًا دائمًا + أصبح مرسل واحد (%d) مسموحًا دائمًا + أصبح مرسلان (%d) مسموحين دائمًا + أصبح %d مرسلين مسموحين دائمًا + أصبح %d مرسلًا مسموحًا دائمًا + أصبح %d مرسل مسموحًا دائمًا + + اعرض القاعدة القواعد انسخ احتياطيًا واستعد محظور بواسطتك @@ -29,6 +48,8 @@ احظر الرسائل التي تحتوي على لغو۱۱ احظر أرقام الإعلانات التي تبدأ بـ 3000 اسمح دائمًا برقم، مثل رقم مكتب البريد + المرسل + نص الرسالة رقم الهاتف يبدأ الرقم بـ اسم المرسل diff --git a/app/src/main/res/values-ar/strings_review_nov11.xml b/app/src/main/res/values-ar/strings_review_nov11.xml new file mode 100644 index 00000000..fa097c46 --- /dev/null +++ b/app/src/main/res/values-ar/strings_review_nov11.xml @@ -0,0 +1,83 @@ + + + أُرسلت بعض الصور والملفات ولم يُرسل الباقي. أعد الإرسال لإرسال الباقي فقط. + أُرسل جزء من رسالتك المجدولة إلى \'%s\' ولم يُرسل الباقي. افتح المحادثة واضغط على أعِد المحاولة لإرسال الباقي فقط. + نقل رموز التحقق المقروءة؟ + + لا توجد رسائل رموز مقروءة (%d) أقدم من ذلك. تبقى الرسائل المميّزة بنجمة. + رسالة رمز مقروءة واحدة (%d) أقدم من ذلك وتُنقل الآن إلى سلة المهملات. تبقى الرسائل المميّزة بنجمة. + رسالتا رمز مقروءتان (%d) أقدم من ذلك وتُنقلان الآن إلى سلة المهملات. تبقى الرسائل المميّزة بنجمة. + %d رسائل رموز مقروءة أقدم من ذلك وتُنقل الآن إلى سلة المهملات. تبقى الرسائل المميّزة بنجمة. + %d رسالة رمز مقروءة أقدم من ذلك وتُنقل الآن إلى سلة المهملات. تبقى الرسائل المميّزة بنجمة. + %d رسالة رمز مقروءة أقدم من ذلك وتُنقل الآن إلى سلة المهملات. تبقى الرسائل المميّزة بنجمة. + + لا يوجد رمز مقروء بهذا القدم بعد. ستُنقل الرموز الأقدم إلى سلة المهملات تلقائيًا. + + حذف %d محادثة؟ + حذف محادثة واحدة (%d)؟ + حذف محادثتين (%d)؟ + حذف %d محادثات؟ + حذف %d محادثة؟ + حذف %d محادثة؟ + + + ستُحذف المحادثات وكل رسائلها من هذا الهاتف. يمكنك التراجع لبضع ثوانٍ بعد ذلك. + ستُحذف المحادثة وكل رسائلها من هذا الهاتف. يمكنك التراجع لبضع ثوانٍ بعد ذلك. + ستُحذف المحادثتان وكل رسائلهما من هذا الهاتف. يمكنك التراجع لبضع ثوانٍ بعد ذلك. + ستُحذف المحادثات وكل رسائلها من هذا الهاتف. يمكنك التراجع لبضع ثوانٍ بعد ذلك. + ستُحذف المحادثات وكل رسائلها من هذا الهاتف. يمكنك التراجع لبضع ثوانٍ بعد ذلك. + ستُحذف المحادثات وكل رسائلها من هذا الهاتف. يمكنك التراجع لبضع ثوانٍ بعد ذلك. + + %1$s موجود في جهات اتصالك. هل تريد حظر هذا المرسل؟ ستذهب رسائله الجديدة إلى الرسائل المحظورة بدل صندوق الوارد. يمكنك التراجع مباشرة بعد ذلك. + أحمر + برتقالي + أصفر + أخضر + تركوازي + أزرق + بنفسجي + بني + الصورة %1$d من %2$d، %3$s. اضغط للفتح. + ليس الآن + امسح القائمة + رمز PIN: من %1$d إلى %2$d أرقام + تراجع + + لم يُنقل أي رمز مقروء إلى سلة المهملات (%d) + نُقل رمز مقروء واحد (%d) إلى سلة المهملات + نُقل رمزان مقروءان (%d) إلى سلة المهملات + نُقلت %d رموز مقروءة إلى سلة المهملات + نُقل %d رمزًا مقروءًا إلى سلة المهملات + نُقل %d رمز مقروء إلى سلة المهملات + + جرّب على الرسائل الأخيرة + جارٍ فحص الرسائل الأخيرة… + تعذّر فحص الرسائل الأخيرة. حاول مرة أخرى. + لا توجد رسائل أخيرة لفحصها بعد. + الوارد: تنطبق هذه القاعدة على %1$d من آخر %2$d رسالة + الوارد: لا توجد رسائل لفحصها + المحظورة: تنطبق هذه القاعدة على %1$d من آخر %2$d رسالة + المحظورة: لا توجد رسائل لفحصها + مثلًا: %1$s + هل تريد حذف هذا النص المحفوظ؟ + بريد إلكتروني + اضغط مطولًا للنسخ + تم النسخ + قواعد موجودة بالفعل على هذا الهاتف: %1$d، تم تخطيها. + قواعد في الملف تتجاوز الحد: %1$d، تم تخطيها. + هل تريد إزالة الجدولة وحذف الرسالة المجدولة المحفوظة؟ يبقى النص في الحقل. + اتصل + انسخ الرقم + أضف جهة اتصال + جارٍ البحث في الرسائل الأقدم… + + %d رسالة جديدة + رسالة جديدة واحدة (%d) + رسالتان جديدتان (%d) + %d رسائل جديدة + %d رسالة جديدة + %d رسالة جديدة + + نُقلت إلى سلة المهملات + تراجع + diff --git a/app/src/main/res/values-bn/strings_carrier_report.xml b/app/src/main/res/values-bn/strings_carrier_report.xml index e51ff333..6d303654 100644 --- a/app/src/main/res/values-bn/strings_carrier_report.xml +++ b/app/src/main/res/values-bn/strings_carrier_report.xml @@ -8,7 +8,7 @@ 3 থেকে 8টি সংখ্যা ব্যবহার করুন মোবাইল অপারেটরকে রিপোর্ট করুন আপনার মোবাইল অপারেটরকে রিপোর্ট করবেন? - এতে এই প্রেরকের সর্বশেষ বার্তাটি SMS হিসেবে %1$s নম্বরে পাঠানো হবে। আপনার মোবাইল অপারেটর এর জন্য টাকা কাটতে পারে। + এতে এই প্রেরকের সর্বশেষ বার্তাটি, নিচে প্রেরকের নম্বর সহ, SMS হিসেবে %1$s নম্বরে পাঠানো হবে। আপনার মোবাইল অপারেটর এর জন্য টাকা কাটতে পারে। পাঠান আপনার মোবাইল অপারেটরকে রিপোর্ট পাঠানো হয়েছে রিপোর্ট পাঠানো যায়নি diff --git a/app/src/main/res/values-bn/strings_review2_blocked_rules.xml b/app/src/main/res/values-bn/strings_review2_blocked_rules.xml index 4649e978..3a18a826 100644 --- a/app/src/main/res/values-bn/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-bn/strings_review2_blocked_rules.xml @@ -11,6 +11,17 @@ এখন থেকে আপনি যেসব বার্তা ইনবক্সে সরাবেন, সেগুলো এখানে 30 দিন দেখা যাবে। ইনবক্সে সরানো হয়েছে %1$s %1$s-এর সঙ্গে কথোপকথন খুলুন + এখন দুই SIM-এই %1$s-কে সবসময় অনুমতি দেওয়া হয়েছে + + এখন দুই SIM-এই %d জন প্রেরককে সবসময় অনুমতি দেওয়া হয়েছে + এখন দুই SIM-এই %d জন প্রেরককে সবসময় অনুমতি দেওয়া হয়েছে + + এখন %1$s-কে সবসময় অনুমতি দেওয়া হয়েছে + + এখন %d জন প্রেরককে সবসময় অনুমতি দেওয়া হয়েছে + এখন %d জন প্রেরককে সবসময় অনুমতি দেওয়া হয়েছে + + নিয়ম দেখুন নিয়ম ব্যাকআপ ও ফিরিয়ে আনা আপনার ব্লক করা @@ -25,6 +36,8 @@ لغو11 আছে এমন বার্তা ব্লক করুন 3000 দিয়ে শুরু বিজ্ঞাপনের নম্বর ব্লক করুন কোনো নম্বরকে সবসময় অনুমতি দিন, যেমন আপনার ডাকঘর + প্রেরক + বার্তার লেখা ফোন নম্বর নম্বরের শুরুতে যা থাকবে প্রেরকের নাম diff --git a/app/src/main/res/values-bn/strings_review_nov11.xml b/app/src/main/res/values-bn/strings_review_nov11.xml new file mode 100644 index 00000000..c0cb9383 --- /dev/null +++ b/app/src/main/res/values-bn/strings_review_nov11.xml @@ -0,0 +1,63 @@ + + + কিছু ছবি ও ফাইল পাঠানো হয়েছে, বাকিগুলো পাঠানো হয়নি। শুধু বাকিগুলো পাঠাতে আবার পাঠান। + \'%s\'-কে পাঠানোর জন্য শিডিউল করা আপনার বার্তার একটি অংশ পাঠানো হয়েছে, বাকিটা হয়নি। চ্যাট খুলে আবার চেষ্টা করুন চাপুন, শুধু বাকিটা পাঠানো হবে। + পড়া কোড সরাবেন? + + %dটি পড়া কোড বার্তা এর চেয়ে পুরোনো, এখন রিসাইকেল বিনে যাবে। তারকা দেওয়া বার্তা থাকবে। + %dটি পড়া কোড বার্তা এর চেয়ে পুরোনো, এখন রিসাইকেল বিনে যাবে। তারকা দেওয়া বার্তা থাকবে। + + এখনো কোনো পড়া কোড এত পুরোনো নয়। পুরোনো কোড নিজে থেকেই রিসাইকেল বিনে যাবে। + + %dটি কথোপকথন মুছবেন? + %dটি কথোপকথন মুছবেন? + + + কথোপকথন ও এর সব বার্তা এই ফোন থেকে মুছে যাবে। পরে কয়েক সেকেন্ড আপনি এটি ফিরিয়ে আনতে পারবেন। + কথোপকথনগুলো ও এগুলোর সব বার্তা এই ফোন থেকে মুছে যাবে। পরে কয়েক সেকেন্ড আপনি এটি ফিরিয়ে আনতে পারবেন। + + %1$s আপনার পরিচিতিতে আছে। এই প্রেরককে ব্লক করবেন? তার নতুন বার্তা ইনবক্সের বদলে ব্লক করা বার্তায় যাবে। সঙ্গে সঙ্গে আপনি এটি ফিরিয়ে আনতে পারবেন। + লাল + কমলা + হলুদ + সবুজ + টিল + নীল + বেগুনি + বাদামি + %2$dটির মধ্যে %1$d নম্বর ছবি, %3$s। খুলতে চাপুন। + এখন নয় + তালিকা সাফ করুন + পিন: %1$d থেকে %2$d অঙ্ক + আগের অবস্থায় ফিরুন + + %dটি পড়া কোড রিসাইকেল বিনে সরানো হয়েছে + %dটি পড়া কোড রিসাইকেল বিনে সরানো হয়েছে + + সাম্প্রতিক বার্তায় পরীক্ষা করুন + সাম্প্রতিক বার্তা দেখা হচ্ছে… + সাম্প্রতিক বার্তা দেখা যায়নি। আবার চেষ্টা করুন। + দেখার মতো সাম্প্রতিক বার্তা এখনো নেই। + ইনবক্স: এই নিয়ম শেষ %2$dটির মধ্যে %1$dটি বার্তার সঙ্গে মেলে + ইনবক্স: দেখার মতো কোনো বার্তা নেই + ব্লক করা: এই নিয়ম শেষ %2$dটির মধ্যে %1$dটি বার্তার সঙ্গে মেলে + ব্লক করা: দেখার মতো কোনো বার্তা নেই + যেমন: %1$s + এই সেভ করা লেখা মুছবেন? + ইমেইল + কপি করতে চেপে ধরুন + কপি হয়েছে + এই ফোনে আগে থেকেই থাকা নিয়ম: %1$d, বাদ দেওয়া হয়েছে। + ফাইলে সীমার বেশি নিয়ম: %1$d, বাদ দেওয়া হয়েছে। + শিডিউল সরিয়ে সেভ করা শিডিউল বার্তা মুছবেন? লেখাটি বক্সেই থাকবে। + কল করুন + নম্বর কপি করুন + পরিচিতি যোগ করুন + পুরোনো বার্তা খোঁজা হচ্ছে… + + %dটি নতুন বার্তা + %dটি নতুন বার্তা + + রিসাইকেল বিনে সরানো হয়েছে + আগের অবস্থায় ফিরুন + diff --git a/app/src/main/res/values-de/strings_carrier_report.xml b/app/src/main/res/values-de/strings_carrier_report.xml index f259e46d..e7e0a90d 100644 --- a/app/src/main/res/values-de/strings_carrier_report.xml +++ b/app/src/main/res/values-de/strings_carrier_report.xml @@ -8,7 +8,7 @@ Gib 3 bis 8 Ziffern ein An Mobilfunkanbieter melden An deinen Mobilfunkanbieter melden? - Die neueste Nachricht dieses Absenders wird als SMS an %1$s gesendet. Dein Mobilfunkanbieter kann dafür Gebühren berechnen. + Die neueste Nachricht dieses Absenders wird zusammen mit der Nummer des Absenders darunter als SMS an %1$s gesendet. Dein Mobilfunkanbieter kann dafür Gebühren berechnen. Senden Meldung an deinen Mobilfunkanbieter gesendet Die Meldung konnte nicht gesendet werden diff --git a/app/src/main/res/values-de/strings_review2_blocked_rules.xml b/app/src/main/res/values-de/strings_review2_blocked_rules.xml index e34dc519..aba8dacf 100644 --- a/app/src/main/res/values-de/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-de/strings_review2_blocked_rules.xml @@ -11,6 +11,17 @@ Nachrichten, die du ab jetzt in den Posteingang verschiebst, werden hier 30 Tage lang angezeigt. In den Posteingang verschoben: %1$s Unterhaltung mit %1$s öffnen + %1$s ist jetzt auf beiden SIMs immer erlaubt + + %d Absender ist jetzt auf beiden SIMs immer erlaubt + %d Absender sind jetzt auf beiden SIMs immer erlaubt + + %1$s ist jetzt immer erlaubt + + %d Absender ist jetzt immer erlaubt + %d Absender sind jetzt immer erlaubt + + Regel ansehen Regeln Sichern und wiederherstellen Von dir blockiert @@ -25,6 +36,8 @@ Nachrichten mit لغو۱۱ blockieren Werbenummern blockieren, die mit 3000 beginnen Eine Nummer immer erlauben, etwa die deiner Postfiliale + Absender + Nachrichtentext Telefonnummer Nummer beginnt mit Absendername diff --git a/app/src/main/res/values-de/strings_review_nov11.xml b/app/src/main/res/values-de/strings_review_nov11.xml new file mode 100644 index 00000000..0472ab70 --- /dev/null +++ b/app/src/main/res/values-de/strings_review_nov11.xml @@ -0,0 +1,63 @@ + + + Einige Bilder und Dateien wurden gesendet, der Rest nicht. Sende erneut, um nur den Rest zu senden. + Ein Teil deiner geplanten Nachricht an \'%s\' wurde gesendet, der Rest nicht. Öffne den Chat und tippe auf „Erneut versuchen“, um nur den Rest zu senden. + Gelesene Codes verschieben? + + %d gelesene Code-Nachricht ist älter und wird jetzt in den Papierkorb verschoben. Mit Stern markierte Nachrichten bleiben. + %d gelesene Code-Nachrichten sind älter und werden jetzt in den Papierkorb verschoben. Mit Stern markierte Nachrichten bleiben. + + Noch kein gelesener Code ist so alt. Ältere Codes werden automatisch in den Papierkorb verschoben. + + %d Unterhaltung löschen? + %d Unterhaltungen löschen? + + + Die Unterhaltung und alle ihre Nachrichten werden von diesem Telefon gelöscht. Du kannst das noch einige Sekunden lang rückgängig machen. + Die Unterhaltungen und alle ihre Nachrichten werden von diesem Telefon gelöscht. Du kannst das noch einige Sekunden lang rückgängig machen. + + %1$s ist in deinen Kontakten. Diesen Absender blockieren? Neue Nachrichten von ihm landen dann in den blockierten Nachrichten statt im Posteingang. Du kannst das gleich danach rückgängig machen. + Rot + Orange + Gelb + Grün + Türkis + Blau + Lila + Braun + Bild %1$d von %2$d, %3$s. Zum Öffnen tippen. + Nicht jetzt + Liste leeren + PIN: %1$d bis %2$d Ziffern + Rückgängig + + %d gelesener Code in den Papierkorb verschoben + %d gelesene Codes in den Papierkorb verschoben + + An letzten Nachrichten testen + Letzte Nachrichten werden geprüft… + Die letzten Nachrichten konnten nicht geprüft werden. Versuche es erneut. + Es gibt noch keine letzten Nachrichten zum Prüfen. + Posteingang: Diese Regel trifft auf %1$d der letzten %2$d Nachrichten zu + Posteingang: keine Nachrichten zum Prüfen + Blockiert: Diese Regel trifft auf %1$d der letzten %2$d Nachrichten zu + Blockiert: keine Nachrichten zum Prüfen + Zum Beispiel: %1$s + Diesen gespeicherten Text löschen? + E-Mail + Zum Kopieren gedrückt halten + Kopiert + Regeln, die schon auf diesem Telefon sind: %1$d, übersprungen. + Regeln in der Datei über dem Limit: %1$d, übersprungen. + Zeitplan entfernen und die gespeicherte geplante Nachricht löschen? Der Text bleibt im Eingabefeld. + Anrufen + Nummer kopieren + Kontakt hinzufügen + Ältere Nachrichten werden durchsucht… + + %d neue Nachricht + %d neue Nachrichten + + In den Papierkorb verschoben + Rückgängig + diff --git a/app/src/main/res/values-es/strings_carrier_report.xml b/app/src/main/res/values-es/strings_carrier_report.xml index 25535c7b..82626b5e 100644 --- a/app/src/main/res/values-es/strings_carrier_report.xml +++ b/app/src/main/res/values-es/strings_carrier_report.xml @@ -8,7 +8,7 @@ Usa de 3 a 8 dígitos Denunciar al operador ¿Denunciar a tu operador? - Se enviará el último mensaje de este remitente al %1$s por SMS. Tu operador podría cobrarte por el envío. + Se enviará por SMS al %1$s el último mensaje de este remitente, con el número del remitente debajo. Tu operador podría cobrarte por el envío. Enviar Denuncia enviada a tu operador No se pudo enviar la denuncia diff --git a/app/src/main/res/values-es/strings_review2_blocked_rules.xml b/app/src/main/res/values-es/strings_review2_blocked_rules.xml index 0d26a925..1cedd7a2 100644 --- a/app/src/main/res/values-es/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-es/strings_review2_blocked_rules.xml @@ -11,6 +11,17 @@ Los mensajes que muevas a la bandeja de entrada a partir de ahora aparecerán aquí durante 30 días. Movido a la bandeja de entrada: %1$s Abrir la conversación con %1$s + %1$s ahora está permitido siempre en ambas SIM + + %d remitente ahora está permitido siempre en ambas SIM + %d remitentes ahora están permitidos siempre en ambas SIM + + %1$s ahora está permitido siempre + + %d remitente ahora está permitido siempre + %d remitentes ahora están permitidos siempre + + Ver regla Reglas Copia de seguridad y restauración Bloqueado por ti @@ -25,6 +36,8 @@ Bloquear mensajes que contengan لغو۱۱ Bloquear números de publicidad que empiecen con 3000 Permitir siempre un número, como el de tu oficina de correos + Remitente + Texto del mensaje Número de teléfono El número empieza con Nombre del remitente diff --git a/app/src/main/res/values-es/strings_review_nov11.xml b/app/src/main/res/values-es/strings_review_nov11.xml new file mode 100644 index 00000000..c6c27c6d --- /dev/null +++ b/app/src/main/res/values-es/strings_review_nov11.xml @@ -0,0 +1,63 @@ + + + Se enviaron algunas fotos y archivos, pero no el resto. Envía de nuevo para enviar solo lo que falta. + Una parte de tu mensaje programado para \'%s\' se envió y el resto no. Abre el chat y toca Reintentar para enviar solo lo que falta. + ¿Mover los códigos leídos? + + %d mensaje de código leído es más antiguo y pasa ahora a la papelera. Los mensajes destacados se quedan. + %d mensajes de código leídos son más antiguos y pasan ahora a la papelera. Los mensajes destacados se quedan. + + Todavía no hay ningún código leído tan antiguo. Los más antiguos pasarán a la papelera automáticamente. + + ¿Eliminar %d conversación? + ¿Eliminar %d conversaciones? + + + La conversación y todos sus mensajes se eliminarán de este teléfono. Puedes deshacerlo durante unos segundos. + Las conversaciones y todos sus mensajes se eliminarán de este teléfono. Puedes deshacerlo durante unos segundos. + + %1$s está en tus contactos. ¿Bloquear a este remitente? Sus mensajes nuevos irán a Bloqueados en lugar de a tu bandeja de entrada. Puedes deshacerlo justo después. + Rojo + Naranja + Amarillo + Verde + Turquesa + Azul + Morado + Marrón + Foto %1$d de %2$d, %3$s. Toca para abrir. + Ahora no + Borrar lista + PIN: de %1$d a %2$d dígitos + Deshacer + + %d código leído movido a la papelera + %d códigos leídos movidos a la papelera + + Probar con mensajes recientes + Revisando mensajes recientes… + No se pudieron revisar los mensajes recientes. Inténtalo de nuevo. + Todavía no hay mensajes recientes para revisar. + Bandeja de entrada: esta regla coincide con %1$d de los últimos %2$d mensajes + Bandeja de entrada: no hay mensajes para revisar + Bloqueados: esta regla coincide con %1$d de los últimos %2$d mensajes + Bloqueados: no hay mensajes para revisar + Por ejemplo: %1$s + ¿Eliminar este texto guardado? + Correo + Mantén pulsado para copiar + Copiado + Reglas que ya están en este teléfono: %1$d, omitidas. + Reglas del archivo que superan el límite: %1$d, omitidas. + ¿Quitar la programación y eliminar el mensaje programado guardado? El texto se queda en el cuadro. + Llamar + Copiar número + Agregar contacto + Buscando mensajes más antiguos… + + %d mensaje nuevo + %d mensajes nuevos + + Movido a la papelera + Deshacer + diff --git a/app/src/main/res/values-fa/strings.xml b/app/src/main/res/values-fa/strings.xml index 13e4cd53..b02347b0 100644 --- a/app/src/main/res/values-fa/strings.xml +++ b/app/src/main/res/values-fa/strings.xml @@ -5,6 +5,8 @@ ارسال نشد. برای تلاش دوباره لمس کنید. پیام شما به «%s» ارسال نشد پیام زمان‌بندی‌شدهٔ شما به «%s» ارسال نشد: پیوست آن دیگر باز نمی‌شود. گفتگو را باز کنید و پیوست را دوباره اضافه کنید. + بعضی از عکس‌ها و فایل‌ها رفت و بقیه نرفت. دوباره بزنید تا فقط بقیه فرستاده شود. + بخشی از پیام زمان‌بندی‌شده‌تان به «%s» فرستاده شد و بقیه نرفت. گفتگو را باز کنید و «تلاش دوباره» را بزنید تا فقط بقیه فرستاده شود. افزودن فرد پیوست پاسخ diff --git a/app/src/main/res/values-fa/strings_auto_delete.xml b/app/src/main/res/values-fa/strings_auto_delete.xml index a6956829..6aab355f 100644 --- a/app/src/main/res/values-fa/strings_auto_delete.xml +++ b/app/src/main/res/values-fa/strings_auto_delete.xml @@ -14,4 +14,10 @@ هنوز هیچ پیامی به این قدمت نیست. پیام‌های قدیمی‌تر خودکار به سطل زباله می‌روند. پیام‌های ستاره‌دار و خوانده‌نشده و گفتگوهای سنجاق‌شده باقی می‌مانند. بردن به سطل زباله + کدهای خوانده‌شده منتقل شوند؟ + + %d پیام کد خوانده‌شده قدیمی‌تر از این مدت است و اکنون به سطل بازیافت منتقل می‌شود. پیام‌های ستاره‌دار باقی می‌مانند. + %d پیام کد خوانده‌شده قدیمی‌تر از این مدت است و اکنون به سطل بازیافت منتقل می‌شوند. پیام‌های ستاره‌دار باقی می‌مانند. + + هنوز هیچ کدی به این قدمت نیست. کدهای قدیمی‌تر خودکار به سطل بازیافت منتقل می‌شوند. diff --git a/app/src/main/res/values-fa/strings_carrier_report.xml b/app/src/main/res/values-fa/strings_carrier_report.xml index 72739012..3792a1e9 100644 --- a/app/src/main/res/values-fa/strings_carrier_report.xml +++ b/app/src/main/res/values-fa/strings_carrier_report.xml @@ -8,7 +8,7 @@ ۳ تا ۸ رقم وارد کنید گزارش به اپراتور به اپراتور گزارش می‌دهید؟ - آخرین پیام این فرستنده با SMS به %1$s ارسال می‌شود. اپراتور ممکن است بابت آن هزینه بگیرد. + آخرین پیام این فرستنده، همراه با شماره‌ی فرستنده، با SMS به %1$s ارسال می‌شود. اپراتور ممکن است بابت آن هزینه بگیرد. ارسال گزارش به اپراتور ارسال شد گزارش ارسال نشد diff --git a/app/src/main/res/values-fa/strings_conversations.xml b/app/src/main/res/values-fa/strings_conversations.xml index 28ccdeee..1d03f589 100644 --- a/app/src/main/res/values-fa/strings_conversations.xml +++ b/app/src/main/res/values-fa/strings_conversations.xml @@ -42,6 +42,15 @@ %d گفتگو حذف شد %d گفتگو حذف شد + + %d گفتگو حذف شود؟ + %d گفتگو حذف شود؟ + + + گفتگو با همهٔ پیام‌هایش از این گوشی پاک می‌شود. چند ثانیه بعدش می‌توانید واگرد بزنید. + گفتگوها با همهٔ پیام‌هایشان از این گوشی پاک می‌شوند. چند ثانیه بعدش می‌توانید واگرد بزنید. + + %1$s در مخاطبین شماست. این فرستنده مسدود شود؟ پیام‌های جدیدش به‌جای صندوق ورودی به پیام‌های مسدودشده می‌روند. بلافاصله بعدش می‌توانید واگرد بزنید. %d گفتگو آرشیو شد %d گفتگو آرشیو شد diff --git a/app/src/main/res/values-fa/strings_labels.xml b/app/src/main/res/values-fa/strings_labels.xml index dfca4ab8..75f86bf3 100644 --- a/app/src/main/res/values-fa/strings_labels.xml +++ b/app/src/main/res/values-fa/strings_labels.xml @@ -17,6 +17,14 @@ ویرایش برچسب نام برچسب ذخیره + قرمز + نارنجی + زرد + سبز + فیروزه‌ای + آبی + بنفش + قهوه‌ای رنگ %1$d از قبل برچسبی با این نام دارید. می‌توانید حداکثر %1$d برچسب داشته باشید. diff --git a/app/src/main/res/values-fa/strings_media_links.xml b/app/src/main/res/values-fa/strings_media_links.xml index 246aeba0..7ebb9fa7 100644 --- a/app/src/main/res/values-fa/strings_media_links.xml +++ b/app/src/main/res/values-fa/strings_media_links.xml @@ -8,6 +8,7 @@ لینکی در این گفتگو نیست. نمایش در گفتگو نمایش بیشتر + عکس %1$d از %2$d، %3$s. برای باز کردن ضربه بزنید. عکس. برای باز کردن ضربه بزنید. %d عکس diff --git a/app/src/main/res/values-fa/strings_notify.xml b/app/src/main/res/values-fa/strings_notify.xml index a5384a44..7f78698f 100644 --- a/app/src/main/res/values-fa/strings_notify.xml +++ b/app/src/main/res/values-fa/strings_notify.xml @@ -7,4 +7,5 @@ اعلان‌ها خاموش‌اند از پیام‌های جدید باخبر نمی‌شوید. روشن کردن + فعلاً نه diff --git a/app/src/main/res/values-fa/strings_review2_blocked_rules.xml b/app/src/main/res/values-fa/strings_review2_blocked_rules.xml index ff12d372..bcce40fb 100644 --- a/app/src/main/res/values-fa/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-fa/strings_review2_blocked_rules.xml @@ -8,9 +8,21 @@ بازیابی‌شده‌های اخیر پیام‌هایی که در ۳۰ روز گذشته به صندوق ورودی برگردانده‌اید. برای باز کردن گفتگو، روی یکی بزنید. + پاک کردن فهرست پیام‌هایی که از این پس به صندوق ورودی برگردانید، به‌مدت ۳۰ روز اینجا لیست می‌شوند. بردن به صندوق ورودی در %1$s باز کردن گفتگو با %1$s + %1$s اکنون در هر دو سیم‌کارت همیشه مجاز است + + %d فرستنده اکنون در هر دو سیم‌کارت همیشه مجاز است + %d فرستنده اکنون در هر دو سیم‌کارت همیشه مجاز هستند + + %1$s اکنون همیشه مجاز است + + %d فرستنده اکنون همیشه مجاز است + %d فرستنده اکنون همیشه مجاز هستند + + مشاهدهٔ قانون قانون‌ها گرفتن بک‌آپ از قانون‌ها شما بلاکش کرده‌اید @@ -25,6 +37,8 @@ بلاک کردن پیام‌های دارای لغو۱۱ بلاک کردن شماره‌های تبلیغاتی با پیش‌شمارهٔ 3000 اجازه دادن همیشگی به یک شماره، مثل ادارهٔ پست + فرستنده + متن پیام شماره تلفن شماره شروع می‌شود با نام فرستنده diff --git a/app/src/main/res/values-fa/strings_round2x.xml b/app/src/main/res/values-fa/strings_round2x.xml new file mode 100644 index 00000000..3dd16dbe --- /dev/null +++ b/app/src/main/res/values-fa/strings_round2x.xml @@ -0,0 +1,9 @@ + + + پین: %1$d تا %2$d رقم + برگردون + + %d کد خوانده‌شده رفت سطل بازیافت + %d کد خوانده‌شده رفت سطل بازیافت + + diff --git a/app/src/main/res/values-fa/strings_rule_preview.xml b/app/src/main/res/values-fa/strings_rule_preview.xml new file mode 100644 index 00000000..5c4908a5 --- /dev/null +++ b/app/src/main/res/values-fa/strings_rule_preview.xml @@ -0,0 +1,12 @@ + + + آزمایش روی پیام‌های اخیر + در حال بررسی پیام‌های اخیر… + بررسی پیام‌های اخیر نشد. دوباره امتحان کنید. + هنوز پیام اخیری برای بررسی نیست. + صندوق ورودی: این قانون با %1$d پیام از %2$d پیام آخر جور درمیاد + صندوق ورودی: پیامی برای بررسی نیست + مسدودشده‌ها: این قانون با %1$d پیام از %2$d پیام آخر جور درمیاد + مسدودشده‌ها: پیامی برای بررسی نیست + مثلاً: %1$s + diff --git a/app/src/main/res/values-fa/strings_saved_texts.xml b/app/src/main/res/values-fa/strings_saved_texts.xml index 69f73c2d..c05580c1 100644 --- a/app/src/main/res/values-fa/strings_saved_texts.xml +++ b/app/src/main/res/values-fa/strings_saved_texts.xml @@ -9,6 +9,7 @@ متن ذخیره حذف + این متن ذخیره‌شده پاک شود؟ فقط روی همین گوشی نگه داشته می‌شود و رمزنگاری نمی‌شود. رمز عبور یا پین ذخیره نکنید. ذخیره در متن‌های ذخیره‌شده ذخیره شد diff --git a/app/src/main/res/values-fa/strings_screens.xml b/app/src/main/res/values-fa/strings_screens.xml index e88a683d..75a696da 100644 --- a/app/src/main/res/values-fa/strings_screens.xml +++ b/app/src/main/res/values-fa/strings_screens.xml @@ -51,6 +51,9 @@ افزودن به مخاطب‌ها نمایش جزئیات پنهان کردن جزئیات + ایمیل + برای کپی نگه دارید + کپی شد مخاطبی در این فایل پیدا نشد نام فایل تاریخ diff --git a/app/src/main/res/values-fa/strings_settings_f.xml b/app/src/main/res/values-fa/strings_settings_f.xml index 45ad4259..1cad63d9 100644 --- a/app/src/main/res/values-fa/strings_settings_f.xml +++ b/app/src/main/res/values-fa/strings_settings_f.xml @@ -3,6 +3,8 @@ ذخیرهٔ پیام‌ها، قانون‌ها و تنظیمات در فایل از این فایل بازیابی شود؟ قانون‌های اجازه دادن: %1$d، قانون‌های بلاک کردن: %2$d. قانون‌های موجود نادیده گرفته می‌شوند. + قانون‌هایی که از قبل روی این گوشی هستند: %1$d، نادیده گرفته می‌شوند. + قانون‌های فایل که بیشتر از حد مجاز بودند: %1$d، نادیده گرفته می‌شوند. قانون‌های فوروارد برای افزودن: %1$d، به‌صورت خاموش. آن‌ها را در قانون‌ها › فوروارد روشن کنید. قانون‌های فوروارد نادیده‌گرفته‌شده: %1$d (از قبل موجودند یا شماره‌ای برای دریافت پیام‌ها ندارند). تنظیماتی که تغییر می‌کنند: %1$s diff --git a/app/src/main/res/values-fa/strings_thread_composer.xml b/app/src/main/res/values-fa/strings_thread_composer.xml index 2aa0a17d..32fb7c3e 100644 --- a/app/src/main/res/values-fa/strings_thread_composer.xml +++ b/app/src/main/res/values-fa/strings_thread_composer.xml @@ -3,6 +3,7 @@ ایموجی نمایش کیبورد پیام زمان‌بندی‌شده ارسال نشد + زمان‌بندی برداشته شود و پیام زمان‌بندی‌شدهٔ ذخیره‌شده پاک شود؟ متن توی کادر می‌ماند. با ویرایش پیام زمان‌بندی‌شده، متن در حال نوشتن جایگزین می‌شود. ادامه می‌دهید؟ علامت‌گذاری به‌عنوان اسپم به‌عنوان اسپم علامت‌گذاری شود؟ diff --git a/app/src/main/res/values-fa/strings_thread_phone.xml b/app/src/main/res/values-fa/strings_thread_phone.xml new file mode 100644 index 00000000..49420f31 --- /dev/null +++ b/app/src/main/res/values-fa/strings_thread_phone.xml @@ -0,0 +1,6 @@ + + + تماس + کپی شماره + ذخیره مخاطب + diff --git a/app/src/main/res/values-fa/strings_thread_round2.xml b/app/src/main/res/values-fa/strings_thread_round2.xml new file mode 100644 index 00000000..a6c673ae --- /dev/null +++ b/app/src/main/res/values-fa/strings_thread_round2.xml @@ -0,0 +1,10 @@ + + + دارم پیام‌های قدیمی‌تر رو می‌گردم… + + %d پیام جدید + %d پیام جدید + + به سطل بازیافت رفت + برگردون + diff --git a/app/src/main/res/values-fr/strings_carrier_report.xml b/app/src/main/res/values-fr/strings_carrier_report.xml index eed811f8..4e915ff1 100644 --- a/app/src/main/res/values-fr/strings_carrier_report.xml +++ b/app/src/main/res/values-fr/strings_carrier_report.xml @@ -8,7 +8,7 @@ Saisissez 3 à 8 chiffres Signaler à l\'opérateur Signaler à votre opérateur ? - Le dernier message de cet expéditeur sera envoyé au %1$s par SMS. Votre opérateur peut vous facturer cet envoi. + Le dernier message de cet expéditeur sera envoyé au %1$s par SMS, avec le numéro de l\'expéditeur en dessous. Votre opérateur peut vous facturer cet envoi. Envoyer Signalement envoyé à votre opérateur Le signalement n\'a pas pu être envoyé diff --git a/app/src/main/res/values-fr/strings_review2_blocked_rules.xml b/app/src/main/res/values-fr/strings_review2_blocked_rules.xml index 8cf6d2a5..14c4c5b8 100644 --- a/app/src/main/res/values-fr/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-fr/strings_review2_blocked_rules.xml @@ -11,6 +11,17 @@ Les messages que vous déplacez désormais vers la boîte de réception figurent ici pendant 30 jours. Déplacé vers la boîte de réception %1$s Ouvrir la conversation avec %1$s + %1$s est désormais toujours autorisé sur les deux SIM + + %d expéditeur est désormais toujours autorisé sur les deux SIM + %d expéditeurs sont désormais toujours autorisés sur les deux SIM + + %1$s est désormais toujours autorisé + + %d expéditeur est désormais toujours autorisé + %d expéditeurs sont désormais toujours autorisés + + Voir la règle Règles Sauvegarde et restauration Bloqué par vous @@ -25,6 +36,8 @@ Bloquer les messages contenant لغو۱۱ Bloquer les numéros publicitaires commençant par 3000 Toujours autoriser un numéro, comme celui de votre bureau de poste + Expéditeur + Texte du message Numéro de téléphone Le numéro commence par Nom de l\'expéditeur diff --git a/app/src/main/res/values-fr/strings_review_nov11.xml b/app/src/main/res/values-fr/strings_review_nov11.xml new file mode 100644 index 00000000..2e082db5 --- /dev/null +++ b/app/src/main/res/values-fr/strings_review_nov11.xml @@ -0,0 +1,63 @@ + + + Certaines photos et certains fichiers ont été envoyés, pas les autres. Renvoyez pour n\'envoyer que le reste. + Une partie de votre message programmé pour \'%s\' a été envoyée, pas le reste. Ouvrez la conversation et appuyez sur Réessayer pour n\'envoyer que le reste. + Déplacer les codes lus ? + + %d message de code lu est plus ancien et passe maintenant dans la corbeille. Les messages suivis d\'une étoile restent. + %d messages de code lus sont plus anciens et passent maintenant dans la corbeille. Les messages suivis d\'une étoile restent. + + Aucun code lu n\'est encore aussi ancien. Les plus anciens iront dans la corbeille automatiquement. + + Supprimer %d conversation ? + Supprimer %d conversations ? + + + La conversation et tous ses messages seront supprimés de ce téléphone. Vous pouvez annuler pendant quelques secondes. + Les conversations et tous leurs messages seront supprimés de ce téléphone. Vous pouvez annuler pendant quelques secondes. + + %1$s figure dans vos contacts. Bloquer cet expéditeur ? Ses nouveaux messages iront dans les messages bloqués au lieu de votre boîte de réception. Vous pouvez annuler juste après. + Rouge + Orange + Jaune + Vert + Turquoise + Bleu + Violet + Marron + Photo %1$d sur %2$d, %3$s. Appuyez pour ouvrir. + Pas maintenant + Effacer la liste + Code PIN : %1$d à %2$d chiffres + Annuler + + %d code lu déplacé dans la corbeille + %d codes lus déplacés dans la corbeille + + Tester sur les messages récents + Vérification des messages récents… + Impossible de vérifier les messages récents. Réessayez. + Il n\'y a pas encore de messages récents à vérifier. + Boîte de réception : cette règle correspond à %1$d des %2$d derniers messages + Boîte de réception : aucun message à vérifier + Bloqués : cette règle correspond à %1$d des %2$d derniers messages + Bloqués : aucun message à vérifier + Par exemple : %1$s + Supprimer ce texte enregistré ? + E-mail + Maintenez pour copier + Copié + Règles déjà présentes sur ce téléphone : %1$d, ignorées. + Règles du fichier au-delà de la limite : %1$d, ignorées. + Retirer la programmation et supprimer le message programmé enregistré ? Le texte reste dans la zone de saisie. + Appeler + Copier le numéro + Ajouter un contact + Recherche dans les anciens messages… + + %d nouveau message + %d nouveaux messages + + Déplacé dans la corbeille + Annuler + diff --git a/app/src/main/res/values-hi/strings_carrier_report.xml b/app/src/main/res/values-hi/strings_carrier_report.xml index f57e2421..b75600a4 100644 --- a/app/src/main/res/values-hi/strings_carrier_report.xml +++ b/app/src/main/res/values-hi/strings_carrier_report.xml @@ -8,7 +8,7 @@ 3 से 8 अंक डालें मोबाइल सेवा देने वाली कंपनी से शिकायत करें अपनी मोबाइल सेवा देने वाली कंपनी से शिकायत करें? - इस भेजने वाले का सबसे नया मैसेज SMS के तौर पर %1$s को भेजा जाएगा. आपकी मोबाइल सेवा देने वाली कंपनी इसके पैसे ले सकती है. + इस भेजने वाले का सबसे नया मैसेज, उसके नीचे भेजने वाले के नंबर के साथ, SMS के तौर पर %1$s को भेजा जाएगा. आपकी मोबाइल सेवा देने वाली कंपनी इसके पैसे ले सकती है. भेजें आपकी मोबाइल सेवा देने वाली कंपनी को शिकायत भेज दी गई शिकायत भेजी नहीं जा सकी diff --git a/app/src/main/res/values-hi/strings_review2_blocked_rules.xml b/app/src/main/res/values-hi/strings_review2_blocked_rules.xml index 04b55a2f..f5067cfe 100644 --- a/app/src/main/res/values-hi/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-hi/strings_review2_blocked_rules.xml @@ -11,6 +11,17 @@ अब से आप जिन मैसेज को इनबॉक्स में लाएंगे, वे यहां 30 दिनों तक दिखेंगे. %1$s को इनबॉक्स में लाया गया %1$s के साथ बातचीत खोलें + अब %1$s को दोनों सिम पर हमेशा अनुमति दी गई है + + अब %d भेजने वाले को दोनों सिम पर हमेशा अनुमति दी गई है + अब %d भेजने वालों को दोनों सिम पर हमेशा अनुमति दी गई है + + अब %1$s को हमेशा अनुमति दी गई है + + अब %d भेजने वाले को हमेशा अनुमति दी गई है + अब %d भेजने वालों को हमेशा अनुमति दी गई है + + नियम देखें नियम बैकअप और वापस लाएं आपने ब्लॉक किया @@ -25,6 +36,8 @@ لغو۱۱ वाले मैसेज ब्लॉक करें 3000 से शुरू होने वाले विज्ञापन नंबर ब्लॉक करें किसी नंबर को हमेशा अनुमति दें, जैसे आपके डाकघर का नंबर + भेजने वाला + मैसेज का टेक्स्ट फ़ोन नंबर नंबर की शुरुआत भेजने वाले का नाम diff --git a/app/src/main/res/values-hi/strings_review_nov11.xml b/app/src/main/res/values-hi/strings_review_nov11.xml new file mode 100644 index 00000000..0b1a398a --- /dev/null +++ b/app/src/main/res/values-hi/strings_review_nov11.xml @@ -0,0 +1,63 @@ + + + कुछ तस्वीरें और फ़ाइलें भेज दी गईं, बाकी नहीं भेजी गईं. सिर्फ़ बाकी भेजने के लिए दोबारा भेजें. + \'%s\' को भेजे जाने वाले आपके शेड्यूल किए मैसेज का एक हिस्सा भेज दिया गया, बाकी नहीं. चैट खोलें और सिर्फ़ बाकी भेजने के लिए फिर कोशिश करें पर टैप करें. + पढ़े गए कोड हटाएं? + + %d पढ़ा गया कोड मैसेज इससे पुराना है और अभी रीसायकल बिन में चला जाएगा. स्टार वाले मैसेज रहेंगे. + %d पढ़े गए कोड मैसेज इससे पुराने हैं और अभी रीसायकल बिन में चले जाएंगे. स्टार वाले मैसेज रहेंगे. + + अभी कोई पढ़ा गया कोड इतना पुराना नहीं है. पुराने कोड अपने आप रीसायकल बिन में चले जाएंगे. + + %d बातचीत मिटाएं? + %d बातचीत मिटाएं? + + + बातचीत और उसके सभी मैसेज इस फ़ोन से मिटा दिए जाएंगे. इसके बाद कुछ सेकंड तक आप इसे पहले जैसा कर सकते हैं. + ये बातचीत और इनके सभी मैसेज इस फ़ोन से मिटा दिए जाएंगे. इसके बाद कुछ सेकंड तक आप इसे पहले जैसा कर सकते हैं. + + %1$s आपके संपर्कों में है. क्या इस भेजने वाले को ब्लॉक करें? इसके नए मैसेज इनबॉक्स की जगह ब्लॉक किए गए मैसेज में जाएंगे. आप तुरंत बाद इसे पहले जैसा कर सकते हैं. + लाल + नारंगी + पीला + हरा + टील + नीला + बैंगनी + भूरा + तस्वीर %1$d / %2$d, %3$s. खोलने के लिए टैप करें. + अभी नहीं + सूची साफ़ करें + पिन: %1$d से %2$d अंक + पहले जैसा करें + + %d पढ़ा गया कोड रीसायकल बिन में भेजा गया + %d पढ़े गए कोड रीसायकल बिन में भेजे गए + + हाल के मैसेज पर जांचें + हाल के मैसेज जांचे जा रहे हैं… + हाल के मैसेज नहीं जांचे जा सके. फिर कोशिश करें. + जांचने के लिए अभी कोई हाल का मैसेज नहीं है. + इनबॉक्स: यह नियम पिछले %2$d में से %1$d मैसेज पर लागू होता है + इनबॉक्स: जांचने के लिए कोई मैसेज नहीं + ब्लॉक किए गए: यह नियम पिछले %2$d में से %1$d मैसेज पर लागू होता है + ब्लॉक किए गए: जांचने के लिए कोई मैसेज नहीं + जैसे: %1$s + यह सेव किया गया टेक्स्ट मिटाएं? + ईमेल + कॉपी करने के लिए दबाए रखें + कॉपी हो गया + इस फ़ोन पर पहले से मौजूद नियम: %1$d, छोड़ दिए गए. + फ़ाइल में सीमा से ज़्यादा नियम: %1$d, छोड़ दिए गए. + शेड्यूल हटाएं और सेव किया गया शेड्यूल मैसेज मिटाएं? टेक्स्ट बॉक्स में बना रहेगा. + कॉल करें + नंबर कॉपी करें + संपर्क जोड़ें + पुराने मैसेज खोजे जा रहे हैं… + + %d नया मैसेज + %d नए मैसेज + + रीसायकल बिन में भेजा गया + पहले जैसा करें + diff --git a/app/src/main/res/values-in/strings_carrier_report.xml b/app/src/main/res/values-in/strings_carrier_report.xml index 0780f745..58413fb0 100644 --- a/app/src/main/res/values-in/strings_carrier_report.xml +++ b/app/src/main/res/values-in/strings_carrier_report.xml @@ -8,7 +8,7 @@ Gunakan 3 hingga 8 digit Laporkan ke operator Laporkan ke operator? - Pesan terbaru dari pengirim ini akan dikirim ke %1$s melalui SMS. Operator mungkin mengenakan biaya. + Pesan terbaru dari pengirim ini, beserta nomor pengirimnya di bawahnya, akan dikirim ke %1$s melalui SMS. Operator mungkin mengenakan biaya. Kirim Laporan dikirim ke operator Laporan tidak dapat dikirim diff --git a/app/src/main/res/values-in/strings_review2_blocked_rules.xml b/app/src/main/res/values-in/strings_review2_blocked_rules.xml index c0114292..71c256d5 100644 --- a/app/src/main/res/values-in/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-in/strings_review2_blocked_rules.xml @@ -10,6 +10,15 @@ Pesan yang Anda pindahkan ke kotak masuk mulai sekarang akan tercantum di sini selama 30 hari. Dipindahkan ke kotak masuk %1$s Buka percakapan dengan %1$s + %1$s kini selalu diizinkan di kedua SIM + + %d pengirim kini selalu diizinkan di kedua SIM + + %1$s kini selalu diizinkan + + %d pengirim kini selalu diizinkan + + Lihat aturan Aturan Cadangkan dan pulihkan Diblokir oleh Anda @@ -24,6 +33,8 @@ Blokir pesan yang berisi لغو۱۱ Blokir nomor iklan yang diawali 3000 Selalu izinkan nomor, misalnya kantor pos Anda + Pengirim + Teks pesan Nomor telepon Nomor diawali dengan Nama pengirim diff --git a/app/src/main/res/values-in/strings_review_nov11.xml b/app/src/main/res/values-in/strings_review_nov11.xml new file mode 100644 index 00000000..589ae988 --- /dev/null +++ b/app/src/main/res/values-in/strings_review_nov11.xml @@ -0,0 +1,58 @@ + + + Sebagian gambar dan file terkirim, sisanya belum. Kirim lagi untuk mengirim sisanya saja. + Sebagian pesan terjadwal ke \'%s\' sudah terkirim, sisanya belum. Buka chat lalu ketuk Coba lagi untuk mengirim sisanya saja. + Pindahkan kode yang sudah dibaca? + + %d pesan kode yang sudah dibaca lebih lama dari itu dan sekarang dipindahkan ke sampah. Pesan berbintang tetap ada. + + Belum ada kode terbaca yang selama itu. Kode yang lebih lama akan pindah ke sampah dengan sendirinya. + + Hapus %d percakapan? + + + Percakapan dan semua pesannya akan dihapus dari ponsel ini. Kamu bisa membatalkannya beberapa detik setelahnya. + + %1$s ada di kontakmu. Blokir pengirim ini? Pesan baru darinya akan masuk ke Diblokir, bukan kotak masuk. Kamu bisa langsung membatalkannya. + Merah + Oranye + Kuning + Hijau + Hijau kebiruan + Biru + Ungu + Cokelat + Gambar %1$d dari %2$d, %3$s. Ketuk untuk membuka. + Nanti saja + Hapus daftar + PIN: %1$d sampai %2$d angka + Urungkan + + %d kode yang sudah dibaca dipindahkan ke sampah + + Coba pada pesan terbaru + Memeriksa pesan terbaru… + Tidak bisa memeriksa pesan terbaru. Coba lagi. + Belum ada pesan terbaru untuk diperiksa. + Kotak masuk: aturan ini cocok dengan %1$d dari %2$d pesan terakhir + Kotak masuk: tidak ada pesan untuk diperiksa + Diblokir: aturan ini cocok dengan %1$d dari %2$d pesan terakhir + Diblokir: tidak ada pesan untuk diperiksa + Misalnya: %1$s + Hapus teks tersimpan ini? + Email + Tahan untuk menyalin + Disalin + Aturan yang sudah ada di ponsel ini: %1$d, dilewati. + Aturan di file yang melebihi batas: %1$d, dilewati. + Hapus jadwal dan hapus pesan terjadwal yang tersimpan? Teksnya tetap ada di kotak ketik. + Telepon + Salin nomor + Tambahkan kontak + Mencari pesan yang lebih lama… + + %d pesan baru + + Dipindahkan ke sampah + Urungkan + diff --git a/app/src/main/res/values-it/strings_carrier_report.xml b/app/src/main/res/values-it/strings_carrier_report.xml index f6669d8d..e28afc4a 100644 --- a/app/src/main/res/values-it/strings_carrier_report.xml +++ b/app/src/main/res/values-it/strings_carrier_report.xml @@ -8,7 +8,7 @@ Usa da 3 a 8 cifre Segnala all\'operatore Segnalare al tuo operatore? - L\'ultimo messaggio di questo mittente verrà inviato a %1$s via SMS. Il tuo operatore potrebbe addebitarti un costo. + L\'ultimo messaggio di questo mittente, con sotto il numero del mittente, verrà inviato a %1$s via SMS. Il tuo operatore potrebbe addebitarti un costo. Invia Segnalazione inviata al tuo operatore Impossibile inviare la segnalazione diff --git a/app/src/main/res/values-it/strings_review2_blocked_rules.xml b/app/src/main/res/values-it/strings_review2_blocked_rules.xml index 443e4760..257d52ce 100644 --- a/app/src/main/res/values-it/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-it/strings_review2_blocked_rules.xml @@ -11,6 +11,17 @@ I messaggi che sposti in In arrivo da ora in poi restano in questo elenco per 30 giorni. Spostato in In arrivo %1$s Apri la conversazione con %1$s + %1$s è ora sempre consentito su entrambe le SIM + + %d mittente è ora sempre consentito su entrambe le SIM + %d mittenti sono ora sempre consentiti su entrambe le SIM + + %1$s è ora sempre consentito + + %d mittente è ora sempre consentito + %d mittenti sono ora sempre consentiti + + Vedi regola Regole Backup e ripristino Bloccato da te @@ -25,6 +36,8 @@ Blocca i messaggi che contengono لغو۱۱ Blocca i numeri pubblicitari che iniziano con 3000 Consenti sempre un numero, come quello del tuo ufficio postale + Mittente + Testo del messaggio Numero di telefono Il numero inizia con Nome del mittente diff --git a/app/src/main/res/values-it/strings_review_nov11.xml b/app/src/main/res/values-it/strings_review_nov11.xml new file mode 100644 index 00000000..390c0031 --- /dev/null +++ b/app/src/main/res/values-it/strings_review_nov11.xml @@ -0,0 +1,63 @@ + + + Alcune immagini e file sono stati inviati, gli altri no. Invia di nuovo per inviare solo il resto. + Una parte del messaggio programmato per \'%s\' è stata inviata, il resto no. Apri la chat e tocca Riprova per inviare solo il resto. + Spostare i codici letti? + + %d messaggio con codice letto è più vecchio di così e ora va nel cestino. I messaggi con la stella restano. + %d messaggi con codice letti sono più vecchi di così e ora vanno nel cestino. I messaggi con la stella restano. + + Nessun codice letto è ancora così vecchio. Quelli più vecchi andranno nel cestino da soli. + + Eliminare %d conversazione? + Eliminare %d conversazioni? + + + La conversazione e tutti i suoi messaggi verranno eliminati da questo telefono. Puoi annullare per qualche secondo dopo. + Le conversazioni e tutti i loro messaggi verranno eliminati da questo telefono. Puoi annullare per qualche secondo dopo. + + %1$s è nei tuoi contatti. Bloccare questo mittente? I nuovi messaggi andranno in Messaggi bloccati invece che in In arrivo. Puoi annullare subito dopo. + Rosso + Arancione + Giallo + Verde + Verde acqua + Blu + Viola + Marrone + Immagine %1$d di %2$d, %3$s. Tocca per aprire. + Non ora + Svuota elenco + PIN: da %1$d a %2$d cifre + Annulla + + %d codice letto spostato nel cestino + %d codici letti spostati nel cestino + + Prova sui messaggi recenti + Controllo dei messaggi recenti… + Impossibile controllare i messaggi recenti. Riprova. + Non ci sono ancora messaggi recenti da controllare. + In arrivo: questa regola corrisponde a %1$d degli ultimi %2$d messaggi + In arrivo: nessun messaggio da controllare + Bloccati: questa regola corrisponde a %1$d degli ultimi %2$d messaggi + Bloccati: nessun messaggio da controllare + Ad esempio: %1$s + Eliminare questo testo salvato? + Email + Tieni premuto per copiare + Copiato + Regole già presenti su questo telefono: %1$d, saltate. + Regole nel file oltre il limite: %1$d, saltate. + Rimuovere la programmazione ed eliminare il messaggio programmato salvato? Il testo resta nella casella. + Chiama + Copia numero + Aggiungi contatto + Ricerca nei messaggi più vecchi… + + %d nuovo messaggio + %d nuovi messaggi + + Spostato nel cestino + Annulla + diff --git a/app/src/main/res/values-ja/strings_carrier_report.xml b/app/src/main/res/values-ja/strings_carrier_report.xml index 0087f242..762c26c1 100644 --- a/app/src/main/res/values-ja/strings_carrier_report.xml +++ b/app/src/main/res/values-ja/strings_carrier_report.xml @@ -8,7 +8,7 @@ 3〜8桁の数字を入力してください。 通信事業者に報告 通信事業者に報告しますか? - この送信者からの最新メッセージをSMSで%1$sに送信します。通信事業者から料金を請求される場合があります。 + この送信者からの最新メッセージを、送信者の番号を添えてSMSで%1$sに送信します。通信事業者から料金を請求される場合があります。 送信 通信事業者に報告を送信しました。 報告を送信できませんでした。 diff --git a/app/src/main/res/values-ja/strings_review2_blocked_rules.xml b/app/src/main/res/values-ja/strings_review2_blocked_rules.xml index 41c2ef39..8aad7417 100644 --- a/app/src/main/res/values-ja/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-ja/strings_review2_blocked_rules.xml @@ -10,6 +10,15 @@ 今後、受信トレイに移したメッセージがここに30日間表示されます。 受信トレイへの移動日時:%1$s %1$sとの会話を開く + 両方のSIMで%1$sを常に許可しました。 + + 両方のSIMで%d件の送信者を常に許可しました。 + + %1$sを常に許可しました。 + + %d件の送信者を常に許可しました。 + + ルールを表示 ルール バックアップと復元 自分でブロック済み @@ -24,6 +33,8 @@ لغو۱۱を含むメッセージをブロック 3000で始まる広告の番号をブロック 郵便局などの番号を常に許可 + 送信者 + メッセージ本文 電話番号 番号の先頭 送信者名 diff --git a/app/src/main/res/values-ja/strings_review_nov11.xml b/app/src/main/res/values-ja/strings_review_nov11.xml new file mode 100644 index 00000000..5d3c2e12 --- /dev/null +++ b/app/src/main/res/values-ja/strings_review_nov11.xml @@ -0,0 +1,58 @@ + + + 一部の画像とファイルは送信されましたが、残りは送信されていません。もう一度送ると、残りだけが送信されます。 + 「%s」宛ての送信予約メッセージの一部は送信されましたが、残りは送信されていません。チャットを開いて「再試行」をタップすると、残りだけが送信されます。 + 既読のコードを移動しますか? + + それより古い既読の認証コードメッセージ%d件を、今すぐゴミ箱に移動します。スター付きのメッセージは残ります。 + + そこまで古い既読の認証コードはまだありません。古くなったものは自動でゴミ箱に移動します。 + + %d件の会話を削除しますか? + + + 会話とそのメッセージはすべて、このスマートフォンから削除されます。削除後の数秒間は元に戻せます。 + + %1$sは連絡先に登録されています。この送信者をブロックしますか?新しいメッセージは受信トレイではなく「ブロック済み」に届きます。直後なら元に戻せます。 + 赤 + オレンジ + 黄 + 緑 + 青緑 + 青 + 紫 + 茶 + 画像%2$d枚中%1$d枚目、%3$s。タップで開きます。 + 今はしない + リストを消去 + PIN:%1$d〜%2$d桁 + 元に戻す + + 既読のコード%d件をゴミ箱に移動しました + + 最近のメッセージで試す + 最近のメッセージを確認中… + 最近のメッセージを確認できませんでした。もう一度お試しください。 + 確認できる最近のメッセージはまだありません。 + 受信トレイ:直近%2$d件のうち%1$d件がこのルールに一致します + 受信トレイ:確認するメッセージはありません + ブロック済み:直近%2$d件のうち%1$d件がこのルールに一致します + ブロック済み:確認するメッセージはありません + 例:%1$s + この保存済みテキストを削除しますか? + メール + 長押しでコピー + コピーしました + このスマートフォンにすでにあるルール:%1$d件(スキップ) + 上限を超えたファイル内のルール:%1$d件(スキップ) + 送信予約を解除し、保存済みの予約メッセージを削除しますか?入力欄のテキストは残ります。 + 通話 + 番号をコピー + 連絡先を追加 + 古いメッセージを検索中… + + 新着メッセージ%d件 + + ゴミ箱に移動しました + 元に戻す + diff --git a/app/src/main/res/values-ko/strings_carrier_report.xml b/app/src/main/res/values-ko/strings_carrier_report.xml index 1f72c68c..0d3f1d9c 100644 --- a/app/src/main/res/values-ko/strings_carrier_report.xml +++ b/app/src/main/res/values-ko/strings_carrier_report.xml @@ -8,7 +8,7 @@ 숫자 3~8자리를 입력해 주세요. 통신사에 신고 통신사에 신고할까요? - 이 발신자의 최신 메시지를 SMS로 전송해요. 받는 번호는 %1$s이며, 통신사에서 요금을 부과할 수 있어요. + 이 발신자의 최신 메시지를 발신자 번호와 함께 SMS로 전송해요. 받는 번호는 %1$s이며, 통신사에서 요금을 부과할 수 있어요. 전송 통신사에 신고를 전송했어요. 신고를 전송하지 못했어요. diff --git a/app/src/main/res/values-ko/strings_review2_blocked_rules.xml b/app/src/main/res/values-ko/strings_review2_blocked_rules.xml index 5aebea58..c5650344 100644 --- a/app/src/main/res/values-ko/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-ko/strings_review2_blocked_rules.xml @@ -10,6 +10,15 @@ 지금부터 받은 메시지함으로 옮기는 메시지가 여기에 30일 동안 표시돼요. 받은 메시지함으로 이동: %1$s %1$s 대화 열기 + 두 SIM 모두에서 발신자 %1$s 항상 허용을 설정했어요. + + 두 SIM 모두에서 발신자 %d명을 항상 허용했어요. + + 발신자 %1$s 항상 허용을 설정했어요. + + 발신자 %d명을 항상 허용했어요. + + 규칙 보기 규칙 백업 및 복원 직접 차단함 @@ -24,6 +33,8 @@ لغو۱۱ 포함 메시지 차단 3000으로 시작하는 광고 번호 차단 우체국 같은 특정 번호 항상 허용 + 발신자 + 메시지 내용 전화번호 번호 시작 부분 발신자 이름 diff --git a/app/src/main/res/values-ko/strings_review_nov11.xml b/app/src/main/res/values-ko/strings_review_nov11.xml new file mode 100644 index 00000000..a26a6694 --- /dev/null +++ b/app/src/main/res/values-ko/strings_review_nov11.xml @@ -0,0 +1,58 @@ + + + 사진과 파일 일부는 보냈고 나머지는 보내지 못했어요. 다시 보내면 나머지만 보내요. + \'%s\'에게 예약한 메시지 일부는 보냈고 나머지는 보내지 못했어요. 대화를 열고 다시 시도를 누르면 나머지만 보내요. + 읽은 코드를 옮길까요? + + 그보다 오래된 읽은 인증 코드 메시지 %d개를 지금 휴지통으로 옮겨요. 별표 표시한 메시지는 그대로 둬요. + + 아직 그렇게 오래된 읽은 코드는 없어요. 오래된 코드는 자동으로 휴지통으로 옮겨져요. + + 대화 %d개를 삭제할까요? + + + 대화와 모든 메시지가 이 휴대폰에서 삭제돼요. 삭제 후 몇 초 동안은 실행 취소할 수 있어요. + + %1$s님은 연락처에 있어요. 이 발신자를 차단할까요? 새 메시지는 받은 메시지함 대신 차단함으로 들어가요. 바로 실행 취소할 수 있어요. + 빨강 + 주황 + 노랑 + 초록 + 청록 + 파랑 + 보라 + 갈색 + 사진 %2$d장 중 %1$d번째, %3$s. 눌러서 열어요. + 나중에 + 목록 지우기 + PIN: %1$d~%2$d자리 + 실행 취소 + + 읽은 코드 %d개를 휴지통으로 옮겼어요 + + 최근 메시지로 테스트 + 최근 메시지를 확인하는 중… + 최근 메시지를 확인하지 못했어요. 다시 시도해요. + 아직 확인할 최근 메시지가 없어요. + 받은 메시지함: 최근 메시지 %2$d개 중 %1$d개가 이 규칙에 해당해요 + 받은 메시지함: 확인할 메시지가 없어요 + 차단함: 최근 메시지 %2$d개 중 %1$d개가 이 규칙에 해당해요 + 차단함: 확인할 메시지가 없어요 + 예: %1$s + 저장한 문구를 삭제할까요? + 이메일 + 길게 눌러 복사 + 복사했어요 + 이 휴대폰에 이미 있는 규칙: %1$d개, 건너뛰었어요. + 파일에서 한도를 넘은 규칙: %1$d개, 건너뛰었어요. + 예약을 없애고 저장된 예약 메시지를 삭제할까요? 입력란의 내용은 그대로 남아요. + 전화 + 번호 복사 + 연락처 추가 + 이전 메시지를 검색하는 중… + + 새 메시지 %d개 + + 휴지통으로 옮겼어요 + 실행 취소 + diff --git a/app/src/main/res/values-pl/strings_carrier_report.xml b/app/src/main/res/values-pl/strings_carrier_report.xml index 499dbac4..1fd7d6d0 100644 --- a/app/src/main/res/values-pl/strings_carrier_report.xml +++ b/app/src/main/res/values-pl/strings_carrier_report.xml @@ -8,7 +8,7 @@ Wpisz od 3 do 8 cyfr Zgłoś operatorowi Zgłosić operatorowi? - Ostatnia wiadomość od tego nadawcy zostanie wysłana SMS-em na numer %1$s. Operator może pobrać za to opłatę. + Ostatnia wiadomość od tego nadawcy, a pod nią numer nadawcy, zostanie wysłana SMS-em na numer %1$s. Operator może pobrać za to opłatę. Wyślij Zgłoszenie wysłane do operatora Nie udało się wysłać zgłoszenia diff --git a/app/src/main/res/values-pl/strings_review2_blocked_rules.xml b/app/src/main/res/values-pl/strings_review2_blocked_rules.xml index 099ab5a2..b33653ad 100644 --- a/app/src/main/res/values-pl/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-pl/strings_review2_blocked_rules.xml @@ -13,6 +13,21 @@ Wiadomości, które od teraz przeniesiesz do odebranych, będą tu widoczne przez 30 dni. Przeniesiono do odebranych %1$s Otwórz rozmowę z %1$s + Nadawca %1$s jest teraz zawsze dozwolony na obu kartach SIM + + %d nadawca jest teraz zawsze dozwolony na obu kartach SIM + %d nadawcy są teraz zawsze dozwoleni na obu kartach SIM + %d nadawców jest teraz zawsze dozwolonych na obu kartach SIM + %d nadawcy jest teraz zawsze dozwolone na obu kartach SIM + + Nadawca %1$s jest teraz zawsze dozwolony + + %d nadawca jest teraz zawsze dozwolony + %d nadawcy są teraz zawsze dozwoleni + %d nadawców jest teraz zawsze dozwolonych + %d nadawcy jest teraz zawsze dozwolone + + Zobacz regułę Reguły Kopia zapasowa i przywracanie Zablokowane przez ciebie @@ -27,6 +42,8 @@ Zablokuj wiadomości zawierające لغو۱۱ Zablokuj numery reklamowe zaczynające się od 3000 Zawsze zezwól na numer, np. twojej poczty + Nadawca + Treść wiadomości Numer telefonu Numer zaczyna się od Nazwa nadawcy diff --git a/app/src/main/res/values-pl/strings_review_nov11.xml b/app/src/main/res/values-pl/strings_review_nov11.xml new file mode 100644 index 00000000..ba9a2662 --- /dev/null +++ b/app/src/main/res/values-pl/strings_review_nov11.xml @@ -0,0 +1,73 @@ + + + Część zdjęć i plików wysłano, reszty nie. Wyślij ponownie, aby wysłać tylko resztę. + Część zaplanowanej wiadomości do \'%s\' wysłano, reszty nie. Otwórz czat i dotknij Ponów, aby wysłać tylko resztę. + Przenieść przeczytane kody? + + %d przeczytana wiadomość z kodem jest starsza i trafi teraz do kosza. Wiadomości z gwiazdką zostają. + %d przeczytane wiadomości z kodem są starsze i trafią teraz do kosza. Wiadomości z gwiazdką zostają. + %d przeczytanych wiadomości z kodem jest starszych i trafi teraz do kosza. Wiadomości z gwiazdką zostają. + %d przeczytanej wiadomości z kodem jest starszych i trafi teraz do kosza. Wiadomości z gwiazdką zostają. + + Żaden przeczytany kod nie jest jeszcze tak stary. Starsze same trafią do kosza. + + Usunąć %d rozmowę? + Usunąć %d rozmowy? + Usunąć %d rozmów? + Usunąć %d rozmowy? + + + Rozmowa i wszystkie jej wiadomości zostaną usunięte z tego telefonu. Przez kilka sekund możesz to cofnąć. + Rozmowy i wszystkie ich wiadomości zostaną usunięte z tego telefonu. Przez kilka sekund możesz to cofnąć. + Rozmowy i wszystkie ich wiadomości zostaną usunięte z tego telefonu. Przez kilka sekund możesz to cofnąć. + Rozmowy i wszystkie ich wiadomości zostaną usunięte z tego telefonu. Przez kilka sekund możesz to cofnąć. + + %1$s jest w Twoich kontaktach. Zablokować tego nadawcę? Nowe wiadomości od niego trafią do Zablokowanych zamiast do odebranych. Możesz to od razu cofnąć. + Czerwony + Pomarańczowy + Żółty + Zielony + Morski + Niebieski + Fioletowy + Brązowy + Zdjęcie %1$d z %2$d, %3$s. Dotknij, aby otworzyć. + Nie teraz + Wyczyść listę + PIN: od %1$d do %2$d cyfr + Cofnij + + %d przeczytany kod przeniesiono do kosza + %d przeczytane kody przeniesiono do kosza + %d przeczytanych kodów przeniesiono do kosza + %d przeczytanego kodu przeniesiono do kosza + + Sprawdź na ostatnich wiadomościach + Sprawdzanie ostatnich wiadomości… + Nie udało się sprawdzić ostatnich wiadomości. Spróbuj ponownie. + Nie ma jeszcze ostatnich wiadomości do sprawdzenia. + Odebrane: ta reguła pasuje do %1$d z ostatnich %2$d wiadomości + Odebrane: brak wiadomości do sprawdzenia + Zablokowane: ta reguła pasuje do %1$d z ostatnich %2$d wiadomości + Zablokowane: brak wiadomości do sprawdzenia + Na przykład: %1$s + Usunąć ten zapisany tekst? + E-mail + Przytrzymaj, aby skopiować + Skopiowano + Reguły już na tym telefonie: %1$d, pominięto. + Reguły w pliku ponad limit: %1$d, pominięto. + Usunąć harmonogram i zapisaną zaplanowaną wiadomość? Tekst zostaje w polu. + Zadzwoń + Kopiuj numer + Dodaj kontakt + Szukanie starszych wiadomości… + + %d nowa wiadomość + %d nowe wiadomości + %d nowych wiadomości + %d nowej wiadomości + + Przeniesiono do kosza + Cofnij + diff --git a/app/src/main/res/values-pt-rBR/strings_carrier_report.xml b/app/src/main/res/values-pt-rBR/strings_carrier_report.xml index 35f49201..353e343b 100644 --- a/app/src/main/res/values-pt-rBR/strings_carrier_report.xml +++ b/app/src/main/res/values-pt-rBR/strings_carrier_report.xml @@ -8,7 +8,7 @@ Use de 3 a 8 dígitos Denuncie à operadora Enviar denúncia à sua operadora? - Isso envia a mensagem mais recente deste remetente para %1$s por SMS. Sua operadora pode cobrar pelo envio. + Isso envia a mensagem mais recente deste remetente, com o número do remetente embaixo, para %1$s por SMS. Sua operadora pode cobrar pelo envio. Envie Denúncia enviada à sua operadora Não foi possível enviar a denúncia diff --git a/app/src/main/res/values-pt-rBR/strings_review2_blocked_rules.xml b/app/src/main/res/values-pt-rBR/strings_review2_blocked_rules.xml index 229a3216..b049a91f 100644 --- a/app/src/main/res/values-pt-rBR/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-pt-rBR/strings_review2_blocked_rules.xml @@ -11,6 +11,17 @@ As mensagens que você mover para a caixa de entrada a partir de agora ficam aqui por 30 dias. Movida para a caixa de entrada em %1$s Abra a conversa com %1$s + %1$s agora é sempre permitido nos dois chips + + %d remetente agora é sempre permitido nos dois chips + %d remetentes agora são sempre permitidos nos dois chips + + %1$s agora é sempre permitido + + %d remetente agora é sempre permitido + %d remetentes agora são sempre permitidos + + Veja a regra Regras Backup e restauração Bloqueado por você @@ -25,6 +36,8 @@ Bloqueie mensagens que contenham لغو۱۱ Bloqueie números de anúncios que começam com 3000 Permita sempre um número, como o dos Correios + Remetente + Texto da mensagem Número de telefone O número começa com Nome do remetente diff --git a/app/src/main/res/values-pt-rBR/strings_review_nov11.xml b/app/src/main/res/values-pt-rBR/strings_review_nov11.xml new file mode 100644 index 00000000..108240dd --- /dev/null +++ b/app/src/main/res/values-pt-rBR/strings_review_nov11.xml @@ -0,0 +1,63 @@ + + + Algumas fotos e arquivos foram enviados, o resto não. Envie de novo para enviar só o que faltou. + Parte da mensagem programada para \'%s\' foi enviada, o resto não. Abra a conversa e toque em Tentar de novo para enviar só o que faltou. + Mover os códigos lidos? + + %d mensagem de código lida é mais antiga que isso e vai para a lixeira agora. Mensagens com estrela ficam. + %d mensagens de código lidas são mais antigas que isso e vão para a lixeira agora. Mensagens com estrela ficam. + + Nenhum código lido é tão antigo ainda. Os mais antigos vão para a lixeira sozinhos. + + Excluir %d conversa? + Excluir %d conversas? + + + A conversa e todas as suas mensagens serão excluídas deste celular. Você pode desfazer por alguns segundos depois. + As conversas e todas as suas mensagens serão excluídas deste celular. Você pode desfazer por alguns segundos depois. + + %1$s está nos seus contatos. Bloquear este remetente? As novas mensagens dele irão para Bloqueados, e não para a caixa de entrada. Você pode desfazer logo em seguida. + Vermelho + Laranja + Amarelo + Verde + Verde-azulado + Azul + Roxo + Marrom + Foto %1$d de %2$d, %3$s. Toque para abrir. + Agora não + Limpar lista + PIN: de %1$d a %2$d dígitos + Desfaça + + %d código lido foi para a lixeira + %d códigos lidos foram para a lixeira + + Testar nas mensagens recentes + Verificando as mensagens recentes… + Não foi possível verificar as mensagens recentes. Tente de novo. + Ainda não há mensagens recentes para verificar. + Caixa de entrada: esta regra corresponde a %1$d das últimas %2$d mensagens + Caixa de entrada: nenhuma mensagem para verificar + Bloqueados: esta regra corresponde a %1$d das últimas %2$d mensagens + Bloqueados: nenhuma mensagem para verificar + Por exemplo: %1$s + Excluir este texto salvo? + E-mail + Segure para copiar + Copiado + Regras que já estão neste celular: %1$d, ignoradas. + Regras do arquivo acima do limite: %1$d, ignoradas. + Remover o agendamento e excluir a mensagem programada salva? O texto continua na caixa. + Ligar + Copiar número + Adicionar contato + Buscando mensagens mais antigas… + + %d nova mensagem + %d novas mensagens + + Movida para a lixeira + Desfaça + diff --git a/app/src/main/res/values-ru/strings_carrier_report.xml b/app/src/main/res/values-ru/strings_carrier_report.xml index 60769676..e80a4e6c 100644 --- a/app/src/main/res/values-ru/strings_carrier_report.xml +++ b/app/src/main/res/values-ru/strings_carrier_report.xml @@ -8,7 +8,7 @@ Введите от 3 до 8 цифр Пожаловаться оператору Пожаловаться оператору? - Последнее сообщение от этого отправителя будет отправлено по SMS на номер %1$s. Оператор может взимать за это плату. + Последнее сообщение от этого отправителя и номер отправителя под ним будут отправлены по SMS на номер %1$s. Оператор может взимать за это плату. Отправить Жалоба отправлена оператору Не удалось отправить жалобу diff --git a/app/src/main/res/values-ru/strings_review2_blocked_rules.xml b/app/src/main/res/values-ru/strings_review2_blocked_rules.xml index 594345e9..7de00fbd 100644 --- a/app/src/main/res/values-ru/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-ru/strings_review2_blocked_rules.xml @@ -13,6 +13,21 @@ Сообщения, которые вы перенесете во входящие, будут отображаться здесь 30 дней. Перенесено во входящие %1$s Открыть чат с %1$s + %1$s теперь всегда разрешен на обеих SIM-картах + + %d отправитель теперь всегда разрешен на обеих SIM-картах + %d отправителя теперь всегда разрешены на обеих SIM-картах + %d отправителей теперь всегда разрешены на обеих SIM-картах + Теперь всегда разрешено %d отправителя на обеих SIM-картах + + %1$s теперь всегда разрешен + + %d отправитель теперь всегда разрешен + %d отправителя теперь всегда разрешены + %d отправителей теперь всегда разрешены + Теперь всегда разрешено %d отправителя + + Посмотреть правило Правила Резервное копирование и восстановление Заблокирован вами @@ -27,6 +42,8 @@ Заблокировать сообщения с لغو۱۱ Заблокировать рекламные номера, начинающиеся с 3000 Всегда разрешать номер, например вашей почты + Отправитель + Текст сообщения Номер телефона Номер начинается с Имя отправителя diff --git a/app/src/main/res/values-ru/strings_review_nov11.xml b/app/src/main/res/values-ru/strings_review_nov11.xml new file mode 100644 index 00000000..97ef8ec7 --- /dev/null +++ b/app/src/main/res/values-ru/strings_review_nov11.xml @@ -0,0 +1,73 @@ + + + Часть фото и файлов отправлена, остальные нет. Отправьте снова, чтобы отправить только остальные. + Часть запланированного сообщения для \'%s\' отправлена, остальное нет. Откройте чат и нажмите «Повторить», чтобы отправить только остальное. + Переместить прочитанные коды? + + %d прочитанное сообщение с кодом старше этого срока и сейчас переместится в корзину. Избранные сообщения останутся. + %d прочитанных сообщения с кодом старше этого срока и сейчас переместятся в корзину. Избранные сообщения останутся. + %d прочитанных сообщений с кодом старше этого срока и сейчас переместятся в корзину. Избранные сообщения останутся. + %d прочитанных сообщения с кодом старше этого срока и сейчас переместятся в корзину. Избранные сообщения останутся. + + Прочитанных кодов такого возраста пока нет. Более старые переместятся в корзину сами. + + Удалить %d чат? + Удалить %d чата? + Удалить %d чатов? + Удалить %d чата? + + + Чат и все его сообщения будут удалены с этого телефона. Сразу после этого удаление можно отменить на несколько секунд. + Чаты и все их сообщения будут удалены с этого телефона. Сразу после этого удаление можно отменить на несколько секунд. + Чаты и все их сообщения будут удалены с этого телефона. Сразу после этого удаление можно отменить на несколько секунд. + Чаты и все их сообщения будут удалены с этого телефона. Сразу после этого удаление можно отменить на несколько секунд. + + %1$s есть в ваших контактах. Заблокировать этого отправителя? Новые сообщения от него будут попадать в «Заблокированные сообщения», а не во входящие. Сразу после этого блокировку можно отменить. + Красный + Оранжевый + Желтый + Зеленый + Бирюзовый + Синий + Фиолетовый + Коричневый + Фото %1$d из %2$d, %3$s. Нажмите, чтобы открыть. + Не сейчас + Очистить список + PIN-код: от %1$d до %2$d цифр + Отменить + + %d прочитанный код перемещен в корзину + %d прочитанных кода перемещено в корзину + %d прочитанных кодов перемещено в корзину + %d прочитанных кода перемещено в корзину + + Проверить на последних сообщениях + Проверяем последние сообщения… + Не удалось проверить последние сообщения. Попробуйте еще раз. + Пока нет последних сообщений для проверки. + Входящие: правилу соответствуют %1$d из последних %2$d сообщений + Входящие: нет сообщений для проверки + Заблокированные: правилу соответствуют %1$d из последних %2$d сообщений + Заблокированные: нет сообщений для проверки + Например: %1$s + Удалить этот сохраненный текст? + Эл. почта + Удерживайте, чтобы скопировать + Скопировано + Правил, которые уже есть на этом телефоне: %1$d, пропущено. + Правил в файле сверх лимита: %1$d, пропущено. + Убрать расписание и удалить сохраненное запланированное сообщение? Текст останется в поле ввода. + Позвонить + Копировать номер + Добавить контакт + Ищем в старых сообщениях… + + %d новое сообщение + %d новых сообщения + %d новых сообщений + %d новых сообщения + + Перемещено в корзину + Отменить + diff --git a/app/src/main/res/values-th/strings_carrier_report.xml b/app/src/main/res/values-th/strings_carrier_report.xml index 3a62bb06..536fbd15 100644 --- a/app/src/main/res/values-th/strings_carrier_report.xml +++ b/app/src/main/res/values-th/strings_carrier_report.xml @@ -8,7 +8,7 @@ ใช้ตัวเลข 3 ถึง 8 หลัก รายงานให้ผู้ให้บริการเครือข่าย รายงานให้ผู้ให้บริการเครือข่ายไหม? - จะส่งข้อความล่าสุดจากผู้ส่งรายนี้ไปยัง %1$s เป็น SMS ผู้ให้บริการเครือข่ายอาจคิดค่าบริการ + จะส่งข้อความล่าสุดจากผู้ส่งรายนี้ พร้อมหมายเลขของผู้ส่งไว้ด้านล่าง ไปยัง %1$s เป็น SMS ผู้ให้บริการเครือข่ายอาจคิดค่าบริการ ส่ง ส่งรายงานให้ผู้ให้บริการเครือข่ายแล้ว ส่งรายงานไม่ได้ diff --git a/app/src/main/res/values-th/strings_review2_blocked_rules.xml b/app/src/main/res/values-th/strings_review2_blocked_rules.xml index 15f3e3d3..9f95b6bd 100644 --- a/app/src/main/res/values-th/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-th/strings_review2_blocked_rules.xml @@ -10,6 +10,15 @@ ข้อความที่ย้ายไปยังกล่องข้อความเข้านับจากนี้จะแสดงที่นี่เป็นเวลา 30 วัน ย้ายไปกล่องข้อความเข้าเมื่อ %1$s เปิดการสนทนากับ %1$s + อนุญาต %1$s เสมอแล้วทั้ง 2 SIM + + อนุญาตผู้ส่ง %d รายเสมอแล้วทั้ง 2 SIM + + อนุญาต %1$s เสมอแล้ว + + อนุญาตผู้ส่ง %d รายเสมอแล้ว + + ดูกฎ กฎ สำรองข้อมูลและกู้คืน คุณบล็อกแล้ว @@ -24,6 +33,8 @@ บล็อกข้อความที่มี لغو۱۱ บล็อกหมายเลขโฆษณาที่ขึ้นต้นด้วย 3000 อนุญาตหมายเลขเสมอ เช่น ที่ทำการไปรษณีย์ + ผู้ส่ง + เนื้อหาข้อความ หมายเลขโทรศัพท์ หมายเลขขึ้นต้นด้วย ชื่อผู้ส่ง diff --git a/app/src/main/res/values-th/strings_review_nov11.xml b/app/src/main/res/values-th/strings_review_nov11.xml new file mode 100644 index 00000000..47080833 --- /dev/null +++ b/app/src/main/res/values-th/strings_review_nov11.xml @@ -0,0 +1,58 @@ + + + ส่งรูปภาพและไฟล์บางส่วนแล้ว ส่วนที่เหลือยังไม่ได้ส่ง ส่งอีกครั้งเพื่อส่งเฉพาะส่วนที่เหลือ + ส่งข้อความที่ตั้งเวลาไว้ถึง \'%s\' ไปบางส่วนแล้ว ส่วนที่เหลือยังไม่ได้ส่ง เปิดการสนทนาแล้วแตะ “ลองอีกครั้ง” เพื่อส่งเฉพาะส่วนที่เหลือ + ย้ายรหัสที่อ่านแล้วหรือไม่ + + ข้อความรหัสที่อ่านแล้ว %d ข้อความเก่ากว่านั้นและจะย้ายไปถังขยะทันที ข้อความที่ติดดาวจะยังอยู่ + + ยังไม่มีรหัสที่อ่านแล้วที่เก่าขนาดนั้น รหัสที่เก่ากว่านั้นจะย้ายไปถังขยะเอง + + ลบ %d การสนทนาหรือไม่ + + + การสนทนาและข้อความทั้งหมดจะถูกลบออกจากโทรศัพท์เครื่องนี้ คุณเลิกทำได้ภายในไม่กี่วินาทีหลังจากนั้น + + %1$s อยู่ในรายชื่อติดต่อของคุณ บล็อกผู้ส่งรายนี้หรือไม่ ข้อความใหม่จากผู้ส่งจะไปอยู่ที่ข้อความที่บล็อกแทนกล่องข้อความ คุณเลิกทำได้ทันทีหลังจากนั้น + แดง + ส้ม + เหลือง + เขียว + เขียวอมฟ้า + น้ำเงิน + ม่วง + น้ำตาล + รูปภาพ %1$d จาก %2$d, %3$s แตะเพื่อเปิด + ไว้ภายหลัง + ล้างรายการ + PIN: %1$d ถึง %2$d หลัก + เลิกทำ + + ย้ายรหัสที่อ่านแล้ว %d รายการไปถังขยะแล้ว + + ทดสอบกับข้อความล่าสุด + กำลังตรวจสอบข้อความล่าสุด… + ตรวจสอบข้อความล่าสุดไม่ได้ ลองอีกครั้ง + ยังไม่มีข้อความล่าสุดให้ตรวจสอบ + กล่องข้อความ: กฎนี้ตรงกับ %1$d จาก %2$d ข้อความล่าสุด + กล่องข้อความ: ไม่มีข้อความให้ตรวจสอบ + ที่บล็อก: กฎนี้ตรงกับ %1$d จาก %2$d ข้อความล่าสุด + ที่บล็อก: ไม่มีข้อความให้ตรวจสอบ + เช่น %1$s + ลบข้อความที่บันทึกไว้นี้หรือไม่ + อีเมล + กดค้างเพื่อคัดลอก + คัดลอกแล้ว + กฎที่มีอยู่ในโทรศัพท์เครื่องนี้แล้ว: %1$d ข้ามแล้ว + กฎในไฟล์ที่เกินขีดจำกัด: %1$d ข้ามแล้ว + ลบการตั้งเวลาและลบข้อความที่ตั้งเวลาไว้ที่บันทึกไว้หรือไม่ ข้อความจะยังอยู่ในช่องพิมพ์ + โทร + คัดลอกหมายเลข + เพิ่มรายชื่อติดต่อ + กำลังค้นหาข้อความเก่า… + + %d ข้อความใหม่ + + ย้ายไปถังขยะแล้ว + เลิกทำ + diff --git a/app/src/main/res/values-tr/strings_carrier_report.xml b/app/src/main/res/values-tr/strings_carrier_report.xml index 2b664be0..f13c5c93 100644 --- a/app/src/main/res/values-tr/strings_carrier_report.xml +++ b/app/src/main/res/values-tr/strings_carrier_report.xml @@ -8,7 +8,7 @@ 3 ila 8 rakam kullanın Operatöre bildirin Operatörünüze bildirilsin mi? - Bu gönderenden gelen son mesaj, %1$s numarasına SMS olarak gönderilir. Operatörünüz bunun için ücret alabilir. + Bu gönderenden gelen son mesaj, altına gönderenin numarası eklenerek %1$s numarasına SMS olarak gönderilir. Operatörünüz bunun için ücret alabilir. Gönderin Operatörünüze bildirim gönderildi Bildirim gönderilemedi diff --git a/app/src/main/res/values-tr/strings_review2_blocked_rules.xml b/app/src/main/res/values-tr/strings_review2_blocked_rules.xml index cfbe1490..0179606e 100644 --- a/app/src/main/res/values-tr/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-tr/strings_review2_blocked_rules.xml @@ -11,6 +11,17 @@ Bundan sonra gelen kutusuna taşıdığınız mesajlar burada 30 gün boyunca listelenir. Gelen kutusuna taşınma zamanı: %1$s %1$s ile görüşmeyi açın + %1$s için artık her iki SIM\'de de her zaman izin verildi + + %d gönderen için artık her iki SIM\'de de her zaman izin verildi + %d gönderen için artık her iki SIM\'de de her zaman izin verildi + + %1$s için artık her zaman izin verildi + + %d gönderen için artık her zaman izin verildi + %d gönderen için artık her zaman izin verildi + + Kuralı görüntüleyin Kurallar Yedekleyin ve geri yükleyin Sizin tarafınızdan engellendi @@ -25,6 +36,8 @@ لغو۱۱ içeren mesajları engelleyin 3000 ile başlayan reklam numaralarını engelleyin Postaneniz gibi bir numaraya her zaman izin verin + Gönderen + Mesaj metni Telefon numarası Numaranın başlangıcı Gönderen adı diff --git a/app/src/main/res/values-tr/strings_review_nov11.xml b/app/src/main/res/values-tr/strings_review_nov11.xml new file mode 100644 index 00000000..075894a6 --- /dev/null +++ b/app/src/main/res/values-tr/strings_review_nov11.xml @@ -0,0 +1,63 @@ + + + Bazı fotoğraflar ve dosyalar gönderildi, geri kalanı gönderilemedi. Yalnızca kalanını göndermek için yeniden gönderin. + \'%s\' kişisine zamanladığınız mesajın bir kısmı gönderildi, kalanı gönderilemedi. Yalnızca kalanını göndermek için görüşmeyi açıp “Yeniden deneyin” düğmesine dokunun. + Okunmuş kodlar taşınsın mı? + + Bu süreden eski %d okunmuş kodlu mesaj şimdi çöp kutusuna taşınır. Yıldızlı mesajlar kalır. + Bu süreden eski %d okunmuş kodlu mesaj şimdi çöp kutusuna taşınır. Yıldızlı mesajlar kalır. + + Henüz o kadar eski okunmuş kod yok. Daha eskileri kendiliğinden çöp kutusuna taşınır. + + %d görüşme silinsin mi? + %d görüşme silinsin mi? + + + Görüşme ve tüm mesajları bu telefondan silinir. Hemen ardından birkaç saniye boyunca geri alabilirsiniz. + Görüşmeler ve tüm mesajları bu telefondan silinir. Hemen ardından birkaç saniye boyunca geri alabilirsiniz. + + %1$s kişilerinizde kayıtlı. Bu gönderen engellensin mi? Ondan gelen yeni mesajlar gelen kutusu yerine Engellenen mesajlar bölümüne düşer. Hemen ardından geri alabilirsiniz. + Kırmızı + Turuncu + Sarı + Yeşil + Turkuaz + Mavi + Mor + Kahverengi + Fotoğraf %1$d / %2$d, %3$s. Açmak için dokunun. + Şimdi değil + Listeyi temizleyin + PIN: %1$d - %2$d hane + Geri alın + + %d okunmuş kod çöp kutusuna taşındı + %d okunmuş kod çöp kutusuna taşındı + + Son mesajlarda deneyin + Son mesajlar kontrol ediliyor… + Son mesajlar kontrol edilemedi. Yeniden deneyin. + Kontrol edilecek son mesaj henüz yok. + Gelen kutusu: bu kural son %2$d mesajın %1$d tanesiyle eşleşiyor + Gelen kutusu: kontrol edilecek mesaj yok + Engellenenler: bu kural son %2$d mesajın %1$d tanesiyle eşleşiyor + Engellenenler: kontrol edilecek mesaj yok + Örneğin: %1$s + Bu kayıtlı metin silinsin mi? + E-posta + Kopyalamak için basılı tutun + Kopyalandı + Bu telefonda zaten olan kurallar: %1$d, atlandı. + Dosyada sınırı aşan kurallar: %1$d, atlandı. + Zamanlama kaldırılsın ve kayıtlı zamanlanmış mesaj silinsin mi? Metin kutuda kalır. + Arayın + Numarayı kopyalayın + Kişi ekleyin + Eski mesajlar aranıyor… + + %d yeni mesaj + %d yeni mesaj + + Çöp kutusuna taşındı + Geri alın + diff --git a/app/src/main/res/values-uk/strings_carrier_report.xml b/app/src/main/res/values-uk/strings_carrier_report.xml index 6ee7f540..db796275 100644 --- a/app/src/main/res/values-uk/strings_carrier_report.xml +++ b/app/src/main/res/values-uk/strings_carrier_report.xml @@ -8,7 +8,7 @@ Введіть від 3 до 8 цифр Повідомити оператору Повідомити вашому оператору? - Останнє повідомлення від цього відправника буде надіслано на номер %1$s як SMS. Ваш оператор може стягнути за це плату. + Останнє повідомлення від цього відправника та його номер під ним буде надіслано на номер %1$s як SMS. Ваш оператор може стягнути за це плату. Надіслати Скаргу надіслано вашому оператору Не вдалося надіслати скаргу diff --git a/app/src/main/res/values-uk/strings_review2_blocked_rules.xml b/app/src/main/res/values-uk/strings_review2_blocked_rules.xml index 06a8608b..0a8998d4 100644 --- a/app/src/main/res/values-uk/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-uk/strings_review2_blocked_rules.xml @@ -13,6 +13,21 @@ Повідомлення, які ви відтепер переміщуватимете у «Вхідні», будуть у цьому списку протягом 30 днів. Переміщено у «Вхідні» %1$s Відкрити чат із %1$s + %1$s тепер завжди дозволено на обох SIM + + Тепер завжди дозволено %d відправника на обох SIM + Тепер завжди дозволено %d відправників на обох SIM + Тепер завжди дозволено %d відправників на обох SIM + Тепер завжди дозволено %d відправника на обох SIM + + %1$s тепер завжди дозволено + + Тепер завжди дозволено %d відправника + Тепер завжди дозволено %d відправників + Тепер завжди дозволено %d відправників + Тепер завжди дозволено %d відправника + + Переглянути правило Правила Резервне копіювання та відновлення Заблоковано вами @@ -27,6 +42,8 @@ Заблокувати повідомлення з لغو۱۱ Заблокувати рекламні номери, що починаються з 3000 Завжди дозволяти номер, наприклад вашої пошти + Відправник + Текст повідомлення Номер телефону Номер починається з Ім’я відправника diff --git a/app/src/main/res/values-uk/strings_review_nov11.xml b/app/src/main/res/values-uk/strings_review_nov11.xml new file mode 100644 index 00000000..4b1485f7 --- /dev/null +++ b/app/src/main/res/values-uk/strings_review_nov11.xml @@ -0,0 +1,73 @@ + + + Частину фото й файлів надіслано, решту — ні. Надішліть ще раз, щоб надіслати лише решту. + Частину запланованого повідомлення для \'%s\' надіслано, решту — ні. Відкрийте чат і торкніться «Повторити», щоб надіслати лише решту. + Перемістити прочитані коди? + + %d прочитане повідомлення з кодом старше за цей термін і зараз переміститься до кошика. Повідомлення із зірочкою залишаться. + %d прочитані повідомлення з кодом старші за цей термін і зараз перемістяться до кошика. Повідомлення із зірочкою залишаться. + %d прочитаних повідомлень з кодом старші за цей термін і зараз перемістяться до кошика. Повідомлення із зірочкою залишаться. + %d прочитаного повідомлення з кодом старші за цей термін і зараз перемістяться до кошика. Повідомлення із зірочкою залишаться. + + Прочитаних кодів такого віку ще немає. Старіші самі перемістяться до кошика. + + Видалити %d чат? + Видалити %d чати? + Видалити %d чатів? + Видалити %d чату? + + + Чат і всі його повідомлення буде видалено з цього телефона. Одразу після цього видалення можна скасувати на кілька секунд. + Чати й усі їхні повідомлення буде видалено з цього телефона. Одразу після цього видалення можна скасувати на кілька секунд. + Чати й усі їхні повідомлення буде видалено з цього телефона. Одразу після цього видалення можна скасувати на кілька секунд. + Чати й усі їхні повідомлення буде видалено з цього телефона. Одразу після цього видалення можна скасувати на кілька секунд. + + %1$s є у ваших контактах. Заблокувати цього відправника? Нові повідомлення від нього потраплятимуть до «Заблоковані повідомлення», а не до вхідних. Одразу після цього блокування можна скасувати. + Червоний + Помаранчевий + Жовтий + Зелений + Бірюзовий + Синій + Фіолетовий + Коричневий + Фото %1$d з %2$d, %3$s. Торкніться, щоб відкрити. + Не зараз + Очистити список + PIN-код: від %1$d до %2$d цифр + Скасувати + + %d прочитаний код переміщено до кошика + %d прочитані коди переміщено до кошика + %d прочитаних кодів переміщено до кошика + %d прочитаного коду переміщено до кошика + + Перевірити на останніх повідомленнях + Перевіряємо останні повідомлення… + Не вдалося перевірити останні повідомлення. Спробуйте ще раз. + Поки немає останніх повідомлень для перевірки. + Вхідні: правилу відповідають %1$d з останніх %2$d повідомлень + Вхідні: немає повідомлень для перевірки + Заблоковані: правилу відповідають %1$d з останніх %2$d повідомлень + Заблоковані: немає повідомлень для перевірки + Наприклад: %1$s + Видалити цей збережений текст? + Ел. пошта + Утримуйте, щоб скопіювати + Скопійовано + Правил, що вже є на цьому телефоні: %1$d, пропущено. + Правил у файлі понад ліміт: %1$d, пропущено. + Прибрати розклад і видалити збережене заплановане повідомлення? Текст залишиться в полі. + Зателефонувати + Копіювати номер + Додати контакт + Шукаємо в старих повідомленнях… + + %d нове повідомлення + %d нові повідомлення + %d нових повідомлень + %d нового повідомлення + + Переміщено до кошика + Скасувати + diff --git a/app/src/main/res/values-vi/strings_carrier_report.xml b/app/src/main/res/values-vi/strings_carrier_report.xml index fdff737c..12ad9eb7 100644 --- a/app/src/main/res/values-vi/strings_carrier_report.xml +++ b/app/src/main/res/values-vi/strings_carrier_report.xml @@ -8,7 +8,7 @@ Dùng từ 3 đến 8 chữ số Báo cáo cho nhà mạng Báo cáo cho nhà mạng của bạn? - Tin nhắn mới nhất từ người gửi này sẽ được gửi đến %1$s qua SMS. Nhà mạng có thể tính phí. + Tin nhắn mới nhất từ người gửi này, kèm số của người gửi bên dưới, sẽ được gửi đến %1$s qua SMS. Nhà mạng có thể tính phí. Gửi Đã gửi báo cáo cho nhà mạng của bạn Không thể gửi báo cáo diff --git a/app/src/main/res/values-vi/strings_review2_blocked_rules.xml b/app/src/main/res/values-vi/strings_review2_blocked_rules.xml index 0bcddc66..d31e1150 100644 --- a/app/src/main/res/values-vi/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-vi/strings_review2_blocked_rules.xml @@ -10,6 +10,15 @@ Từ giờ, tin nhắn bạn chuyển vào hộp thư đến sẽ được liệt kê ở đây trong 30 ngày. Đã chuyển vào hộp thư đến %1$s Mở cuộc trò chuyện với %1$s + Đã luôn cho phép %1$s trên cả hai SIM + + Đã luôn cho phép %d người gửi trên cả hai SIM + + Đã luôn cho phép %1$s + + Đã luôn cho phép %d người gửi + + Xem quy tắc Quy tắc Sao lưu và khôi phục Đã chặn theo lựa chọn của bạn @@ -24,6 +33,8 @@ Chặn tin nhắn chứa لغو۱۱ Chặn số quảng cáo bắt đầu bằng 3000 Luôn cho phép một số, như số bưu điện của bạn + Người gửi + Nội dung tin nhắn Số điện thoại Số bắt đầu bằng Tên người gửi diff --git a/app/src/main/res/values-vi/strings_review_nov11.xml b/app/src/main/res/values-vi/strings_review_nov11.xml new file mode 100644 index 00000000..6461dccd --- /dev/null +++ b/app/src/main/res/values-vi/strings_review_nov11.xml @@ -0,0 +1,58 @@ + + + Một số ảnh và tệp đã được gửi, phần còn lại thì chưa. Gửi lại để chỉ gửi phần còn lại. + Một phần tin nhắn đã hẹn giờ gửi đến \'%s\' đã được gửi, phần còn lại thì chưa. Mở cuộc trò chuyện và nhấn Thử lại để chỉ gửi phần còn lại. + Chuyển mã đã đọc? + + %d tin nhắn mã đã đọc cũ hơn mức đó và sẽ được chuyển vào thùng rác ngay bây giờ. Tin nhắn gắn sao sẽ được giữ lại. + + Chưa có mã đã đọc nào cũ đến vậy. Mã cũ hơn sẽ tự chuyển vào thùng rác. + + Xóa %d cuộc trò chuyện? + + + Cuộc trò chuyện và toàn bộ tin nhắn sẽ bị xóa khỏi điện thoại này. Bạn có thể hoàn tác trong vài giây sau đó. + + %1$s có trong danh bạ của bạn. Chặn người gửi này? Tin nhắn mới từ họ sẽ vào Tin nhắn đã chặn thay vì hộp thư đến. Bạn có thể hoàn tác ngay sau đó. + Đỏ + Cam + Vàng + Xanh lá + Xanh ngọc + Xanh dương + Tím + Nâu + Ảnh %1$d/%2$d, %3$s. Nhấn để mở. + Để sau + Xóa danh sách + PIN: %1$d đến %2$d chữ số + Hoàn tác + + Đã chuyển %d mã đã đọc vào thùng rác + + Thử trên tin nhắn gần đây + Đang kiểm tra tin nhắn gần đây… + Không kiểm tra được tin nhắn gần đây. Hãy thử lại. + Chưa có tin nhắn gần đây để kiểm tra. + Hộp thư đến: quy tắc này khớp %1$d trong %2$d tin nhắn gần nhất + Hộp thư đến: không có tin nhắn để kiểm tra + Đã chặn: quy tắc này khớp %1$d trong %2$d tin nhắn gần nhất + Đã chặn: không có tin nhắn để kiểm tra + Ví dụ: %1$s + Xóa văn bản đã lưu này? + Email + Nhấn giữ để sao chép + Đã sao chép + Quy tắc đã có trên điện thoại này: %1$d, đã bỏ qua. + Quy tắc trong tệp vượt giới hạn: %1$d, đã bỏ qua. + Bỏ lịch hẹn và xóa tin nhắn hẹn giờ đã lưu? Văn bản vẫn ở trong khung soạn. + Gọi + Sao chép số + Thêm liên hệ + Đang tìm trong tin nhắn cũ… + + %d tin nhắn mới + + Đã chuyển vào thùng rác + Hoàn tác + diff --git a/app/src/main/res/values-zh-rCN/strings_carrier_report.xml b/app/src/main/res/values-zh-rCN/strings_carrier_report.xml index 81d929c3..146eb805 100644 --- a/app/src/main/res/values-zh-rCN/strings_carrier_report.xml +++ b/app/src/main/res/values-zh-rCN/strings_carrier_report.xml @@ -8,7 +8,7 @@ 请输入3至8位数字 向运营商举报 向运营商举报? - 将把此发件人的最新一条消息以短信形式发送至%1$s。运营商可能会收取费用。 + 将把此发件人的最新一条消息及其下方的发件人号码,以短信形式发送至%1$s。运营商可能会收取费用。 发送 已向运营商发送举报 举报发送失败 diff --git a/app/src/main/res/values-zh-rCN/strings_review2_blocked_rules.xml b/app/src/main/res/values-zh-rCN/strings_review2_blocked_rules.xml index 65d3210a..a824b436 100644 --- a/app/src/main/res/values-zh-rCN/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values-zh-rCN/strings_review2_blocked_rules.xml @@ -10,6 +10,15 @@ 从现在起,移至收件箱的消息会在这里显示30天。 移至收件箱的时间:%1$s 打开与%1$s的会话 + 已在两张SIM卡上始终允许%1$s + + 已在两张SIM卡上始终允许%d个发件人 + + 已始终允许%1$s + + 已始终允许%d个发件人 + + 查看规则 规则 备份与恢复 你已屏蔽 @@ -24,6 +33,8 @@ 屏蔽包含لغو۱۱的消息 屏蔽以3000开头的广告号码 始终允许某个号码,例如邮局号码 + 发件人 + 消息正文 电话号码 号码开头 发件人名称 diff --git a/app/src/main/res/values-zh-rCN/strings_review_nov11.xml b/app/src/main/res/values-zh-rCN/strings_review_nov11.xml new file mode 100644 index 00000000..5a6cc055 --- /dev/null +++ b/app/src/main/res/values-zh-rCN/strings_review_nov11.xml @@ -0,0 +1,58 @@ + + + 部分图片和文件已发送,其余未发送。再次发送即可只发送其余部分。 + 发给\'%s\'的定时消息已发送一部分,其余未发送。打开会话并点按“重试”,即可只发送其余部分。 + 移动已读验证码? + + 有%d条已读验证码消息早于该期限,现在将移至回收站。已加星标的消息会保留。 + + 还没有这么久的已读验证码。更早的验证码会自动移至回收站。 + + 删除%d个会话? + + + 这些会话及其所有消息将从此手机中删除。删除后的几秒内可以撤销。 + + %1$s在联系人中。要屏蔽此发件人吗?其新消息将进入“已屏蔽消息”,而不是收件箱。屏蔽后可立即撤销。 + 红色 + 橙色 + 黄色 + 绿色 + 青色 + 蓝色 + 紫色 + 棕色 + 第%1$d张图片,共%2$d张,%3$s。点按即可打开。 + 暂不 + 清空列表 + PIN码:%1$d至%2$d位数字 + 撤销 + + 已将%d条已读验证码移至回收站 + + 在最近的消息上测试 + 正在检查最近的消息… + 无法检查最近的消息。请重试。 + 暂时没有可检查的最近消息。 + 收件箱:此规则匹配最近%2$d条消息中的%1$d条 + 收件箱:没有可检查的消息 + 已屏蔽:此规则匹配最近%2$d条消息中的%1$d条 + 已屏蔽:没有可检查的消息 + 例如:%1$s + 删除此已保存的文本? + 电子邮件 + 长按可复制 + 已复制 + 此手机上已有的规则:%1$d条,已跳过。 + 文件中超出上限的规则:%1$d条,已跳过。 + 移除定时并删除已保存的定时消息?文本会保留在输入框中。 + 拨打电话 + 复制号码 + 添加联系人 + 正在搜索更早的消息… + + %d条新消息 + + 已移至回收站 + 撤销 + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index eda53e19..f1dc9121 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -6,6 +6,8 @@ Not sent. Touch to retry. Your message to \'%s\' has not been sent Your scheduled message to \'%s\' was not sent: its attachment can no longer be opened. Open the chat to add it again. + Some pictures and files were sent, the rest were not. Send again to send only the rest. + Part of your scheduled message to \'%s\' was sent, the rest was not. Open the chat and tap Retry to send only the rest. Add Person Attachment Reply diff --git a/app/src/main/res/values/strings_auto_delete.xml b/app/src/main/res/values/strings_auto_delete.xml index d5275517..8a4afcb9 100644 --- a/app/src/main/res/values/strings_auto_delete.xml +++ b/app/src/main/res/values/strings_auto_delete.xml @@ -15,4 +15,10 @@ No message is that old yet. Older ones will move to the recycle bin by themselves. Starred and unread messages and pinned chats stay. Move + Move read codes? + + %d read code message is older than that and moves to the recycle bin now. Starred messages stay. + %d read code messages are older than that and move to the recycle bin now. Starred messages stay. + + No read code is that old yet. Older ones will move to the recycle bin by themselves. diff --git a/app/src/main/res/values/strings_carrier_report.xml b/app/src/main/res/values/strings_carrier_report.xml index ad90d217..099802ab 100644 --- a/app/src/main/res/values/strings_carrier_report.xml +++ b/app/src/main/res/values/strings_carrier_report.xml @@ -1,16 +1,16 @@ - - - - Report spam - Carrier spam number - Report spam to your carrier by SMS - Not set - Your carrier\'s spam report number. Reports go out as an SMS and may cost money. - Use 3 to 8 digits - Report to carrier - Report to your carrier? - This sends the latest message from this sender to %1$s as an SMS. Your carrier may charge you for it. - Send - Report sent to your carrier - The report could not be sent - + + + + Report spam + Carrier spam number + Report spam to your carrier by SMS + Not set + Your carrier\'s spam report number. Reports go out as an SMS and may cost money. + Use 3 to 8 digits + Report to carrier + Report to your carrier? + This sends the latest message from this sender, with the sender\'s number under it, to %1$s as an SMS. Your carrier may charge you for it. + Send + Report sent to your carrier + The report could not be sent + diff --git a/app/src/main/res/values/strings_conversations.xml b/app/src/main/res/values/strings_conversations.xml index f7f3751f..446440a0 100644 --- a/app/src/main/res/values/strings_conversations.xml +++ b/app/src/main/res/values/strings_conversations.xml @@ -48,6 +48,15 @@ %d conversation deleted %d conversations deleted + + Delete %d conversation? + Delete %d conversations? + + + The conversation and all its messages will be deleted from this phone. You can undo it for a few seconds afterwards. + The conversations and all their messages will be deleted from this phone. You can undo it for a few seconds afterwards. + + %1$s is in your contacts. Block this sender? New messages from them will go to Blocked messages instead of your inbox. You can undo it right afterwards. %d conversation archived %d conversations archived diff --git a/app/src/main/res/values/strings_labels.xml b/app/src/main/res/values/strings_labels.xml index 92fcb2d9..e06b15b6 100644 --- a/app/src/main/res/values/strings_labels.xml +++ b/app/src/main/res/values/strings_labels.xml @@ -17,6 +17,14 @@ Edit label Label name Save + Red + Orange + Yellow + Green + Teal + Blue + Purple + Brown Color %1$d You already have a label with this name. You can have up to %1$d labels. diff --git a/app/src/main/res/values/strings_media_links.xml b/app/src/main/res/values/strings_media_links.xml index c56703a1..04eeb476 100644 --- a/app/src/main/res/values/strings_media_links.xml +++ b/app/src/main/res/values/strings_media_links.xml @@ -8,6 +8,7 @@ No links in this chat. Show in chat Show more + Picture %1$d of %2$d, %3$s. Tap to open. Picture. Tap to open. %d picture diff --git a/app/src/main/res/values/strings_notify.xml b/app/src/main/res/values/strings_notify.xml index 4139fdda..3c3eec8c 100644 --- a/app/src/main/res/values/strings_notify.xml +++ b/app/src/main/res/values/strings_notify.xml @@ -10,4 +10,5 @@ Notifications are off You won\'t be told about new messages. Turn on + Not now diff --git a/app/src/main/res/values/strings_review2_blocked_rules.xml b/app/src/main/res/values/strings_review2_blocked_rules.xml index 6c02b31b..485ba251 100644 --- a/app/src/main/res/values/strings_review2_blocked_rules.xml +++ b/app/src/main/res/values/strings_review2_blocked_rules.xml @@ -13,9 +13,21 @@ Restored recently Messages you moved to the inbox in the last 30 days. Tap one to open the conversation. + Clear list Messages you move to the inbox from now on are listed here for 30 days. Moved to the inbox %1$s Open the conversation with %1$s + %1$s is now always allowed, on both SIMs + + %d sender is now always allowed, on both SIMs + %d senders are now always allowed, on both SIMs + + %1$s is now always allowed + + %d sender is now always allowed + %d senders are now always allowed + + View rule @@ -37,6 +49,8 @@ Block messages containing لغو۱۱ Block ad numbers starting with 3000 Always allow a number, like your post office + Sender + Message text Phone number diff --git a/app/src/main/res/values/strings_round2x.xml b/app/src/main/res/values/strings_round2x.xml new file mode 100644 index 00000000..638fe05a --- /dev/null +++ b/app/src/main/res/values/strings_round2x.xml @@ -0,0 +1,9 @@ + + + PIN: %1$d to %2$d digits + Undo + + %d read code moved to the recycle bin + %d read codes moved to the recycle bin + + diff --git a/app/src/main/res/values/strings_rule_preview.xml b/app/src/main/res/values/strings_rule_preview.xml new file mode 100644 index 00000000..6403795e --- /dev/null +++ b/app/src/main/res/values/strings_rule_preview.xml @@ -0,0 +1,12 @@ + + + Test on recent messages + Checking recent messages… + Could not check recent messages. Try again. + There are no recent messages to check yet. + Inbox: this rule matches %1$d of the last %2$d messages + Inbox: no messages to check + Blocked: this rule matches %1$d of the last %2$d messages + Blocked: no messages to check + For example: %1$s + diff --git a/app/src/main/res/values/strings_saved_texts.xml b/app/src/main/res/values/strings_saved_texts.xml index f7eabd3c..fdadd6a9 100644 --- a/app/src/main/res/values/strings_saved_texts.xml +++ b/app/src/main/res/values/strings_saved_texts.xml @@ -1,17 +1,18 @@ - - - Saved text - Saved texts - For example: your address or card number. Tap one to put it in your message. - Add saved text - Change saved text - Title (optional) - Text - Save - Delete - Kept only on this phone, not encrypted. Do not save passwords or PINs. - Save to saved texts - Saved - The list is full. Delete one first. - Already saved - + + + Saved text + Saved texts + For example: your address or card number. Tap one to put it in your message. + Add saved text + Change saved text + Title (optional) + Text + Save + Delete + Delete this saved text? + Kept only on this phone, not encrypted. Do not save passwords or PINs. + Save to saved texts + Saved + The list is full. Delete one first. + Already saved + diff --git a/app/src/main/res/values/strings_screens.xml b/app/src/main/res/values/strings_screens.xml index bfdc6213..3bea89c6 100644 --- a/app/src/main/res/values/strings_screens.xml +++ b/app/src/main/res/values/strings_screens.xml @@ -63,6 +63,9 @@ Add to contacts Show details Hide details + Email + Hold to copy + Copied No contact found in this file diff --git a/app/src/main/res/values/strings_settings_f.xml b/app/src/main/res/values/strings_settings_f.xml index f02ea757..83efbf49 100644 --- a/app/src/main/res/values/strings_settings_f.xml +++ b/app/src/main/res/values/strings_settings_f.xml @@ -6,6 +6,8 @@ Restore from this file? Allow rules: %1$d · Block rules: %2$d. Rules you already have are skipped. + Rules already on this phone: %1$d, skipped. + Rules in the file over the limit: %1$d, skipped. Forward rules to add: %1$d, switched off. Turn them on in Rules › Forwarding. Forward rules skipped: %1$d (already here, or no number that can receive them). Settings that change: %1$s diff --git a/app/src/main/res/values/strings_thread_composer.xml b/app/src/main/res/values/strings_thread_composer.xml index 115bb914..f67a725a 100644 --- a/app/src/main/res/values/strings_thread_composer.xml +++ b/app/src/main/res/values/strings_thread_composer.xml @@ -5,6 +5,7 @@ Emoji Show keyboard Scheduled message not sent + Remove the schedule and delete the saved scheduled message? The text stays in the box. Editing the scheduled message replaces what you are typing. Continue? diff --git a/app/src/main/res/values/strings_thread_phone.xml b/app/src/main/res/values/strings_thread_phone.xml new file mode 100644 index 00000000..73a027a7 --- /dev/null +++ b/app/src/main/res/values/strings_thread_phone.xml @@ -0,0 +1,7 @@ + + + + Call + Copy number + Add contact + diff --git a/app/src/main/res/values/strings_thread_round2.xml b/app/src/main/res/values/strings_thread_round2.xml new file mode 100644 index 00000000..d13e8573 --- /dev/null +++ b/app/src/main/res/values/strings_thread_round2.xml @@ -0,0 +1,12 @@ + + + + Searching older messages… + + + %d new message + %d new messages + + Moved to the recycle bin + Undo + diff --git a/app/src/test/kotlin/com/glooboo/umessage/backup/BackupRuleCountsTest.kt b/app/src/test/kotlin/com/glooboo/umessage/backup/BackupRuleCountsTest.kt new file mode 100644 index 00000000..736317bf --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/backup/BackupRuleCountsTest.kt @@ -0,0 +1,39 @@ +package com.glooboo.umessage.backup + +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 + +class BackupRuleCountsTest { + private fun keyword(pattern: String, kind: ListKind = ListKind.BLOCK) = + SpamRule(kind = kind, type = RuleType.KEYWORD, pattern = pattern, createdAt = 1) + + @Test fun rulesAlreadyOnThePhoneAreCountedAsPresent() { + val (fresh, present) = SettingsBackupFormat.newRules( + incoming = listOf(keyword("sale"), keyword("win"), keyword("sale ")), + existing = listOf(keyword("sale")), + ) + assertThat(fresh.map { it.pattern }).containsExactly("win") + assertThat(present).isEqualTo(2) + } + + @Test fun sameTextWithAnotherKindIsNew() { + val (fresh, present) = SettingsBackupFormat.newRules( + incoming = listOf(keyword("sale", ListKind.ALLOW)), + existing = listOf(keyword("sale")), + ) + assertThat(fresh).hasSize(1) + assertThat(present).isEqualTo(0) + } + + @Test fun rulesOverTheLimitAreCounted() { + val many = List(SettingsBackupFormat.MAX_RULES + 3) { keyword("k$it") } + val text = SettingsBackupFormat.encode(BackupContent(many, emptyList(), BackupSettings()), 1) + val back = SettingsBackupFormat.decode(text) + assertThat(back.rules).hasSize(SettingsBackupFormat.MAX_RULES) + assertThat(back.droppedRules).isEqualTo(3) + assertThat(back.droppedForwardRules).isEqualTo(0) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/dialogs/AppLockLogicTest.kt b/app/src/test/kotlin/com/glooboo/umessage/dialogs/AppLockLogicTest.kt index b107e591..661db95e 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/dialogs/AppLockLogicTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/dialogs/AppLockLogicTest.kt @@ -189,4 +189,10 @@ class PatternGeometryTest { org.junit.Assert.assertNull(PatternGeometry.cellAt(310f, 50f, 300f, 300f)) org.junit.Assert.assertNull(PatternGeometry.cellAt(10f, 10f, 0f, 0f)) } + + @Test + fun pinLengthHintRangeIsConsistent() { + assertTrue(AppLockLogic.MIN_PIN_LENGTH <= AppLockLogic.SUGGESTED_PIN_LENGTH) + assertTrue(AppLockLogic.SUGGESTED_PIN_LENGTH <= AppLockLogic.MAX_PIN_LENGTH) + } } diff --git a/app/src/test/kotlin/com/glooboo/umessage/export/ExportFileTitleTest.kt b/app/src/test/kotlin/com/glooboo/umessage/export/ExportFileTitleTest.kt new file mode 100644 index 00000000..78b4b3cd --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/export/ExportFileTitleTest.kt @@ -0,0 +1,22 @@ +package com.glooboo.umessage.export + +import org.junit.Assert.assertEquals +import org.junit.Test + +class ExportFileTitleTest { + @Test fun keepsLettersAndDigitsJoinedByDashes() { + assertEquals("Sara-Smith-2", exportFileTitle("Sara Smith / 2")) + } + + @Test fun removesPathCharactersAndEdgeDashes() { + assertEquals("a-b", exportFileTitle("../a:b?*")) + } + + @Test fun emptyWhenNothingUsable() { + assertEquals("", exportFileTitle("+-- //")) + } + + @Test fun isShortened() { + assertEquals(30, exportFileTitle("x".repeat(100)).length) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/helpers/CacheCleanupTest.kt b/app/src/test/kotlin/com/glooboo/umessage/helpers/CacheCleanupTest.kt new file mode 100644 index 00000000..8f8aebad --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/helpers/CacheCleanupTest.kt @@ -0,0 +1,43 @@ +package com.glooboo.umessage.helpers + +import java.io.File +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class CacheCleanupTest { + @get:Rule + val tmp = TemporaryFolder() + + @Test + fun deletesOnlyFilesOlderThanTheLimit() { + val dir = tmp.newFolder("attachments") + val old = File(dir, "old.jpg").apply { writeText("x"); setLastModified(1_000L) } + val fresh = File(dir, "fresh.jpg").apply { writeText("x"); setLastModified(9_500L) } + assertEquals(1, CacheCleanup.deleteOlderThan(dir, 1_000L, now = 10_000L)) + assertFalse(old.exists()) + assertTrue(fresh.exists()) + } + + @Test + fun missingFolderIsFine() { + assertEquals(0, CacheCleanup.deleteOlderThan(File(tmp.root, "none"), 1_000L, now = 10_000L)) + } + + @Test + fun deleteQuietlyRemovesTheFileAndToleratesAMissingOne() { + val file = tmp.newFile("export.csv") + assertTrue(CacheCleanup.deleteQuietly(file)) + assertFalse(file.exists()) + assertTrue(CacheCleanup.deleteQuietly(file)) + } + + @Test + fun shareCopiesLiveLongerThanASlowUploadButNotAnHour() { + assertTrue(CacheCleanup.SHARE_COPY_LIFETIME_MS >= 10 * 60 * 1000L) + assertTrue(CacheCleanup.SHARE_COPY_LIFETIME_MS < 60 * 60 * 1000L) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/helpers/SavedTextsTest.kt b/app/src/test/kotlin/com/glooboo/umessage/helpers/SavedTextsTest.kt index 5cb09076..e2a75e8a 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/helpers/SavedTextsTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/helpers/SavedTextsTest.kt @@ -83,6 +83,14 @@ class SavedTextsTest { assertThat(replies).doesNotContain("Card 4000123456789010") } + @Test + fun groupedDigitsCountAsALongNumber() { + assertThat(SavedTexts.hasLongNumber("6037 9975 1234 5678")).isTrue() + assertThat(SavedTexts.hasLongNumber("6037-9975-12")).isTrue() + assertThat(SavedTexts.hasLongNumber("Call me at 5")).isFalse() + assertThat(SavedTexts.hasLongNumber("See you at 10.30")).isFalse() + } + @Test fun notificationChoicesAreAbsentWithoutSavedTextsAndPresentWithThem() { assertThat(NotificationQuickReplies.choices(app)).isNull() diff --git a/app/src/test/kotlin/com/glooboo/umessage/messaging/PartialSendTest.kt b/app/src/test/kotlin/com/glooboo/umessage/messaging/PartialSendTest.kt new file mode 100644 index 00000000..4b65fcfb --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/messaging/PartialSendTest.kt @@ -0,0 +1,74 @@ +package com.glooboo.umessage.messaging + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.glooboo.umessage.models.Attachment +import com.glooboo.umessage.ui.thread.ThreadRecipients +import com.glooboo.umessage.ui.thread.buildScheduledMessage +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith + +/** A message with several pictures that went out in part must resend only what is left (core-1). */ +@RunWith(AndroidJUnit4::class) +class PartialSendTest { + + private fun picture(n: Int) = Attachment(null, 5L, "content://x/$n", "image/jpeg", 0, 0, "p$n.jpg") + + private fun scheduled(vararg pictures: Attachment) = buildScheduledMessage( + text = "caption", recipients = ThreadRecipients.fromNumbers(listOf("111")), subscriptionId = 1, messageId = 5L, + millis = 5_000_000L, threadId = 12L, threadHasMessages = true, isMms = true, attachments = pictures.toList(), + ) + + @Test + fun aPartlySentOutcomeNeedsSomeSentAndSomeLeft() { + assertThat(SendOutcome(handedOff = true, sentCount = 3, textSent = true).partlySent).isFalse() + assertThat(SendOutcome(handedOff = false, remainingAttachments = listOf(picture(1))).partlySent).isFalse() + assertThat(SendOutcome(false, listOf(picture(3)), sentCount = 2, textSent = true).partlySent).isTrue() + } + + @Test + fun theHeldMessageKeepsOnlyTheUnsentPicturesAndDropsTheTextThatWent() { + val message = scheduled(picture(1), picture(2), picture(3)) + val outcome = SendOutcome(false, listOf(picture(2)), sentCount = 2, textSent = true) + + val left = message.withUnsentOnly(outcome) + + assertThat(left.attachment!!.attachments.map { it.uriString }).containsExactly("content://x/2") + assertThat(left.body).isEmpty() + } + + @Test + fun theTextStaysWhenItsPictureDidNotGoOut() { + val message = scheduled(picture(1), picture(2)) + val outcome = SendOutcome(false, listOf(picture(2)), sentCount = 1, textSent = false) + + val left = message.withUnsentOnly(outcome) + + assertThat(left.body).isEqualTo("caption") + assertThat(left.attachment!!.attachments).hasSize(1) + } + + @Test + fun aRetryOfABundledRowSkipsPicturesAnEarlierRetryDelivered() { + val all = listOf(picture(1), picture(2), picture(3)) + val ledger = ResendLedger().plus(listOf("content://x/1", "content://x/3"), textNowSent = false) + + assertThat(ledger.undelivered(all).map { it.uriString }).containsExactly("content://x/2") + assertThat(ResendLedger().undelivered(all)).hasSize(3) + } + + @Test + fun theTextIsSentOnlyUntilItWent() { + assertThat(ResendLedger().textToSend("hi")).isEqualTo("hi") + assertThat(ResendLedger().plus(emptyList(), textNowSent = true).textToSend("hi")).isEmpty() + } + + @Test + fun aLedgerSurvivesBeingStoredAndRead() { + val ledger = ResendLedger(setOf("content://x/1", "content://x/2"), textSent = true) + + assertThat(ResendLedger.decode(ledger.encode())).isEqualTo(ledger) + assertThat(ResendLedger.decode(null)).isEqualTo(ResendLedger()) + assertThat(ResendLedger.decode(ResendLedger().encode())).isEqualTo(ResendLedger()) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/receivers/SmsReceiverTest.kt b/app/src/test/kotlin/com/glooboo/umessage/receivers/SmsReceiverTest.kt index 64950593..7d3976c9 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/receivers/SmsReceiverTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/receivers/SmsReceiverTest.kt @@ -64,6 +64,19 @@ class SmsReceiverTest { assertThat(pendingRows()).isEmpty() } + @Test + fun carrierSendTime_isWrittenAsDateSentWhileDateStaysTheArrivalTime() { + val before = System.currentTimeMillis() + receive("+15551234567", "Hello there") + + // The test PDU says it was sent 2026-01-01 12:34:56 UTC. + val sentAt = java.time.LocalDateTime.of(2026, 1, 1, 12, 34, 56) + .toInstant(java.time.ZoneOffset.UTC).toEpochMilli() + val row = inbox().single() + assertThat(row["date_sent"]).isEqualTo(sentAt) + assertThat(row["date"] as Long).isAtLeast(before) + } + @Test fun multipartSms_isJoinedIntoOneMessage() { receive("+15551234567", "Part one, ", "part two") diff --git a/app/src/test/kotlin/com/glooboo/umessage/spam/TextNormalizerObfuscationTest.kt b/app/src/test/kotlin/com/glooboo/umessage/spam/TextNormalizerObfuscationTest.kt new file mode 100644 index 00000000..d1f509cc --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/spam/TextNormalizerObfuscationTest.kt @@ -0,0 +1,29 @@ +package com.glooboo.umessage.spam + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class TextNormalizerObfuscationTest { + + @Test fun invisibleMarksAreDropped() { + assertEquals("free", TextNormalizer.deobfuscate("f‎r‪e⁢e͏️")) + } + + @Test fun fancyLettersMatchKeyword() { + assertTrue(TextNormalizer.containsObfuscated("FREE gift", "free")) // fullwidth + assertTrue(TextNormalizer.containsObfuscated("𝐟𝐫𝐞𝐞 prize", "free")) // math bold + assertTrue(TextNormalizer.containsObfuscated("f̶r̶e̶e̶ prize", "free")) // strike-through + assertTrue(TextNormalizer.containsObfuscated("f́ree", "free")) // accent + } + + @Test fun mathBoldDigitsAreAscii() { + assertEquals("1234", TextNormalizer.deobfuscate("𝟏𝟐𝟑𝟒")) + } + + @Test fun plainTextIsUnchanged() { + assertFalse(TextNormalizer.containsObfuscated("Your parcel is on the way", "free")) + assertEquals("hello world 2025", TextNormalizer.deobfuscate("Hello World 2025")) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/spam/data/PendingSmsDateSentMigrationTest.kt b/app/src/test/kotlin/com/glooboo/umessage/spam/data/PendingSmsDateSentMigrationTest.kt new file mode 100644 index 00000000..d032a3b9 --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/spam/data/PendingSmsDateSentMigrationTest.kt @@ -0,0 +1,73 @@ +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.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 7 adds the carrier send time to the pending SMS queue; queued rows keep everything and get 0 (unknown). */ +@RunWith(AndroidJUnit4::class) +class PendingSmsDateSentMigrationTest { + + @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 migratesFromVersionSixKeepingQueuedRowsWithAnUnknownSendTime() { + helper.createDatabase(TEST_DB, 6).use { db -> + db.execSQL( + "INSERT INTO pending_sms (address, subject, body, date, subscriptionId, status, createdAt) " + + "VALUES ('Shop', '', 'queued', 5000, 1, 0, 6000)" + ) + } + + helper.runMigrationsAndValidate(TEST_DB, 7, true, *SpamDatabase.ALL_MIGRATIONS).use { db -> + db.query("SELECT body, date, dateSent FROM pending_sms").use { + assertThat(it.moveToFirst()).isTrue() + assertThat(it.getString(0)).isEqualTo("queued") + assertThat(it.getLong(1)).isEqualTo(5000L) + assertThat(it.getLong(2)).isEqualTo(0L) + } + } + } + + @Test + fun theSendTimeIsStoredAndReadBack(): Unit = offMainThread { + val db = SpamDatabase.build(context, TEST_DB) + try { + val dao = db.spamDao() + dao.insertPending( + PendingSmsEntity( + address = "Shop", subject = "", body = "hi", date = 9_000L, subscriptionId = 1, status = 0, + createdAt = 9_000L, dateSent = 4_000L, + ) + ) + val row = dao.getPending().single() + assertThat(row.date).isEqualTo(9_000L) + assertThat(row.dateSent).isEqualTo(4_000L) + } finally { + db.close() + } + } + + private companion object { + const val TEST_DB = "pending-date-sent-migration-test.db" + } +} 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 6b9cdbbb..3fcccffb 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 = 6 + const val LATEST = 7 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/engine/OtpGroupedCodeTest.kt b/app/src/test/kotlin/com/glooboo/umessage/spam/engine/OtpGroupedCodeTest.kt new file mode 100644 index 00000000..517f83b9 --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/spam/engine/OtpGroupedCodeTest.kt @@ -0,0 +1,31 @@ +package com.glooboo.umessage.spam.engine + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class OtpGroupedCodeTest { + + private fun otp(body: String) = OtpDetector.looksLikeOtp(body) + + @Test fun hyphenatedAndSpacedSixDigitCodes() { + assertTrue(otp("Your WhatsApp code: 123-456")) + assertTrue(otp("Your verification code is 123 456")) + assertTrue(otp("123 456 is your login code")) + } + + @Test fun phoneNumbersAreNotCodes() { + assertFalse(otp("Call 555-123-456 to verify")) + assertFalse(otp("Call 1 555 123 456 7 to verify")) + } + + @Test fun groupedAmountsAreNotCodes() { + assertFalse(otp("Your password costs 123 456 rials")) + assertFalse(otp("Promo code 123-456, 20% off")) + } + + @Test fun plainCodesStillWork() { + assertTrue(otp("Your OTP is 4821")) + assertTrue(otp("otp 1234 5678")) + } +} 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 f6bfeea8..337a9dd9 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 @@ -115,6 +115,7 @@ class ConversationsViewModelTest { awaitUntil { rowIds().size == 2 } vm.deleteOne(dad.threadId) + vm.confirmDelete() awaitUntil { events.any { it is ConversationsEvent.Deleted } } val token = (events.single { it is ConversationsEvent.Deleted } as ConversationsEvent.Deleted).token // The event is sent before the background rebuild has dropped the chat from the rows: wait for the rows too. @@ -124,12 +125,33 @@ class ConversationsViewModelTest { vm.replayPendingUndo() awaitUntil { events.count { it is ConversationsEvent.Deleted } == 2 } assertThat(events.filterIsInstance().map { it.token }).containsExactly(token, token) - assertThat(rowIds()).containsExactly(mom.threadId) + awaitUntil { rowIds() == listOf(mom.threadId) } vm.undoDelete(token) awaitUntil { rowIds().size == 2 } } + /** main-1: Delete only asks; the chat stays until the user confirms, and Cancel changes nothing. */ + @Test + fun deleteWaitsForConfirmation() { + vm.submit(listOf(dad, mom), cached = false, firstRun = false) + awaitUntil { rowIds().size == 2 } + + vm.deleteOne(dad.threadId) + awaitUntil { vm.state.value.confirmDeleteCount == 1 } + assertThat(rowIds()).containsExactly(dad.threadId, mom.threadId) + assertThat(events.filterIsInstance()).isEmpty() + + vm.cancelDelete() + awaitUntil { vm.state.value.confirmDeleteCount == 0 } + assertThat(rowIds().size).isEqualTo(2) + + vm.deleteOne(dad.threadId) + awaitUntil { vm.state.value.confirmDeleteCount == 1 } + vm.confirmDelete() + awaitUntil { rowIds() == listOf(mom.threadId) && vm.state.value.confirmDeleteCount == 0 } + } + /** MC-37: Report spam blocks the sender with a uMessage rule and archives the chat; Undo takes both back. */ @Test fun reportSpamBlocksTheSenderAndArchivesTheChat() { diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/conversations/RowCacheTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/conversations/RowCacheTest.kt new file mode 100644 index 00000000..eb0f4e14 --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/conversations/RowCacheTest.kt @@ -0,0 +1,36 @@ +package com.glooboo.umessage.ui.conversations + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** main-3: a row is derived again only when its input changed. */ +class RowCacheTest { + + @Test + fun sameInputIsNotComputedAgain() { + val cache = RowCache() + var calls = 0 + repeat(3) { cache.get(1L, "a") { calls++; "row-a" } } + assertEquals(1, calls) + } + + @Test + fun changedInputIsComputedAgain() { + val cache = RowCache() + assertEquals("one", cache.get(1L, "a") { "one" }) + assertEquals("two", cache.get(1L, "b") { "two" }) + assertEquals("two", cache.get(1L, "b") { "never" }) + } + + @Test + fun retainOnlyForgetsGoneKeys() { + val cache = RowCache() + cache.get(1L, "a") { "x" } + cache.get(2L, "a") { "y" } + cache.retainOnly(setOf(2L)) + assertNull(cache.lookup(1L, "a")) + assertEquals("y", cache.lookup(2L, "a")) + assertEquals(1, cache.size) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/lock/LockScreenTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/lock/LockScreenTest.kt index 2ba1042f..39d30b4a 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/lock/LockScreenTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/lock/LockScreenTest.kt @@ -168,6 +168,7 @@ class LockScreenTest { compose.onNodeWithText("Forgot it?", substring = true).assertDoesNotExist() } + @Config(qualifiers = "w411dp-h1200dp") @Test fun `right-to-left keeps the keypad and pattern dots left to right`() { compose.setContent { diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/main/MainSearchTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/main/MainSearchTest.kt index e865f5cc..155bf948 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/main/MainSearchTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/main/MainSearchTest.kt @@ -26,6 +26,8 @@ class MainSearchTest { assertFalse(isSearchable("")) assertFalse(isSearchable("a")) assertTrue(isSearchable("ab")) + assertFalse(isSearchable(" ")) + assertFalse(isSearchable(" a ")) } @Test diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/main/SearchNumberHitsTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/main/SearchNumberHitsTest.kt index 53974f80..80751bb8 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/main/SearchNumberHitsTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/main/SearchNumberHitsTest.kt @@ -69,3 +69,16 @@ class SearchNumberHitsTest { assertTrue(highlightRanges("a-b", "ab").isEmpty()) } } + +/** main-7: which queries need a number lookup at all. */ +class NumberQueryTest { + @Test + fun onlyDigitQueriesOfThreeOrMoreDigitsLookUpNumbers() { + assertTrue(isNumberQuery("555")) + assertTrue(isNumberQuery("0555 345")) + assertTrue(isNumberQuery("۷۱۲۱۲۳")) + assertTrue(!isNumberQuery("55")) + assertTrue(!isNumberQuery("Sara 555")) + assertTrue(!isNumberQuery("سارا")) + } +} 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 new file mode 100644 index 00000000..bfb147e5 --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/BlockedRound2S1Test.kt @@ -0,0 +1,234 @@ +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.DecisionReason +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.launch +import org.junit.After +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Shadows.shadowOf + +/** + * spamui-11 (choosing several messages in the sender thread) and spamui-15 (the restored list goes with the blocked + * messages). Only fake data and a fake repository: nothing real is read, sent or stored. + */ +@RunWith(AndroidJUnit4::class) +class BlockedRound2S1Test { + + private val app: Application = ApplicationProvider.getApplicationContext() + private val scope = CoroutineScope(Job() + Dispatchers.Main) + + @After + fun tearDown() = scope.cancel() + + private fun msg(id: Long, address: String = "AD-SHOP", at: Long = id, body: String = "text $id") = + BlockedMessage(id, address, body, 1, false, at, DecisionReason.UNKNOWN_SENDER) + + private fun entry(restoredAt: Long, address: String = "AD-SHOP") = + RestoredEntry(address, restoredAt - 10, restoredAt) + + // region spamui-11: selection helpers + + @Test + fun aTapTogglesAMessageInAndOutOfTheSelection() { + val one = toggleMessageSelection(emptySet(), 5) + assertThat(one).containsExactly(5L) + assertThat(toggleMessageSelection(one, 6)).containsExactly(5L, 6L) + assertThat(toggleMessageSelection(one, 5)).isEmpty() + } + + @Test + fun aMessageThatLeftDropsOutOfTheSelection() { + val messages = listOf(msg(1), msg(2)) + assertThat(presentSelection(messages, setOf(1L, 9L))).containsExactly(1L) + assertThat(presentSelection(messages, emptySet())).isEmpty() + assertThat(presentSelection(emptyList(), setOf(1L))).isEmpty() + } + + @Test + fun onlyMessagesWithContentAreMovedToTheInbox() { + val empty = BlockedMessage(3, "AD-SHOP", "", 1, true, 3, DecisionReason.UNKNOWN_SENDER) + val messages = listOf(msg(1), msg(2), empty) + val chosen = setOf(1L, 3L) + val releasable = releasableSelection(messages, chosen) + assertThat(releasable).contains(1L) + assertThat(releasable).doesNotContain(2L) + assertThat(releasable.all { id -> messages.first { it.id == id }.canRestoreContent }).isTrue() + } + + // endregion + + // region spamui-11: several messages through the view model + + @Test + fun severalChosenMessagesGoToTheInboxTogetherWithOneUndo() { + val repo = FakeSpamRepository(initialBlocked = listOf(msg(1), msg(2), msg(3)), initialRules = emptyList()) + val vm = BlockedViewModel(app, repo, RestoredLog(prefs = null), ignoreFilter = true) + val events = mutableListOf() + scope.launch { vm.state.collect { } } + scope.launch { vm.eventFlow.collect { events += it } } + awaitUntil { !vm.state.value.loading } + + vm.releaseMessages(setOf(1L, 3L)) + + 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) + + vm.undoRestore(restored.token) + awaitUntil { vm.state.value.groups.singleOrNull()?.messages?.size == 3 } + assertThat(vm.state.value.restored).isEmpty() + } + + @Test + fun severalChosenMessagesAreDeletedTogetherAndUndoBringsThemBack() { + val repo = FakeSpamRepository(initialBlocked = listOf(msg(1), msg(2), msg(3)), initialRules = emptyList()) + val vm = BlockedViewModel(app, repo, RestoredLog(prefs = null), ignoreFilter = true) + val events = mutableListOf() + scope.launch { vm.state.collect { } } + scope.launch { vm.eventFlow.collect { events += it } } + awaitUntil { !vm.state.value.loading } + + vm.deleteMessages(setOf(1L, 2L)) + + awaitUntil { events.any { it is BlockedEvent.Deleted } } + val deleted = events.filterIsInstance().single() + assertThat(deleted.count).isEqualTo(2) + assertThat(vm.state.value.groups.single().messages.map { it.id }).containsExactly(3L) + vm.undoDelete(deleted.token) + awaitUntil { vm.state.value.groups.single().messages.size == 3 } + } + + // endregion + + // region spamui-15: the restored list + + @Test + fun entriesOlderThanTheLimitAreDroppedOnLoad() { + val now = 100L * DAY + val fresh = entry(now - 2 * DAY) + val old = entry(now - RestoredLog.KEEP_MS - 1) + val prefs = app.getSharedPreferences("round2_s1_test", android.content.Context.MODE_PRIVATE) + prefs.edit().putString("entries", RestoredLogCodec.encode(listOf(fresh, old))).commit() + + val log = RestoredLog(prefs, now = { now }) + + assertThat(log.entries.value).containsExactly(fresh) + } + + @Test + fun theLogDropsEntriesOlderThanThePurgeDays() { + val now = 100L * DAY + val recent = entry(now - 2 * DAY, "A") + val older = entry(now - 10 * DAY, "B") + val log = RestoredLog(prefs = null, now = { now }) + log.record(listOf(recent, older)) + + log.dropOlderThan(days = 7) + + assertThat(log.entries.value).containsExactly(recent) + assertThat(RestoredLogCodec.dropOlderThan(listOf(recent, older), 30, now)) + .containsExactly(recent, older).inOrder() + } + + @Test + fun clearEmptiesTheLog() { + val now = 100L * DAY + val log = RestoredLog(prefs = null, now = { now }) + log.record(listOf(entry(now - DAY))) + + log.clear() + + assertThat(log.entries.value).isEmpty() + } + + @Test + fun deleteAllClearsTheRestoredListOnceTheDeletionIsFinal() { + val log = RestoredLog(prefs = null) + log.record(listOf(RestoredEntry("AD-SHOP", 1L, System.currentTimeMillis()))) + val repo = FakeSpamRepository(initialBlocked = listOf(msg(1), msg(2, "OTHER")), initialRules = emptyList()) + val vm = BlockedViewModel(app, repo, log) + val events = mutableListOf() + scope.launch { vm.state.collect { } } + scope.launch { vm.eventFlow.collect { events += it } } + awaitUntil { !vm.state.value.loading } + + vm.deleteAll() + awaitUntil { events.any { it is BlockedEvent.Deleted } } + // Not final yet: the Undo window is open, and Undo keeps the list. + assertThat(log.entries.value).hasSize(1) + + vm.commitDelete(events.filterIsInstance().single().token) + awaitUntil { log.entries.value.isEmpty() } + assertThat(vm.state.value.groups).isEmpty() + } + + @Test + fun undoOfDeleteAllKeepsTheRestoredList() { + val log = RestoredLog(prefs = null) + log.record(listOf(RestoredEntry("AD-SHOP", 1L, System.currentTimeMillis()))) + val repo = FakeSpamRepository(initialBlocked = listOf(msg(1)), initialRules = emptyList()) + val vm = BlockedViewModel(app, repo, log) + val events = mutableListOf() + scope.launch { vm.state.collect { } } + scope.launch { vm.eventFlow.collect { events += it } } + awaitUntil { !vm.state.value.loading } + + vm.deleteAll() + awaitUntil { events.any { it is BlockedEvent.Deleted } } + val token = events.filterIsInstance().single().token + vm.undoDelete(token) + vm.commitDelete(token) + idleMain() + + assertThat(log.entries.value).hasSize(1) + awaitUntil { vm.state.value.groups.size == 1 } + } + + @Test + fun deletingOneSenderLeavesTheRestoredListAlone() { + val log = RestoredLog(prefs = null) + log.record(listOf(RestoredEntry("AD-SHOP", 1L, System.currentTimeMillis()))) + val repo = FakeSpamRepository(initialBlocked = listOf(msg(1), msg(2, "OTHER")), initialRules = emptyList()) + val vm = BlockedViewModel(app, repo, log) + val events = mutableListOf() + scope.launch { vm.state.collect { } } + scope.launch { vm.eventFlow.collect { events += it } } + awaitUntil { !vm.state.value.loading } + + vm.delete(setOf("OTHER")) + awaitUntil { events.any { it is BlockedEvent.Deleted } } + vm.commitDelete(events.filterIsInstance().single().token) + awaitUntil { vm.state.value.groups.size == 1 } + + assertThat(log.entries.value).hasSize(1) + } + + // endregion + + 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" } + Thread.sleep(10) + } + } + + private companion object { + const val DAY = 24L * 60 * 60 * 1000 + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/CarrierReportTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/CarrierReportTest.kt index 284e6c33..4d31c394 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/CarrierReportTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/CarrierReportTest.kt @@ -1,108 +1,115 @@ -package com.glooboo.umessage.ui.spam - -import android.content.Context -import androidx.compose.ui.test.junit4.createComposeRule -import androidx.compose.ui.test.onNodeWithText -import androidx.compose.ui.test.performClick -import androidx.test.core.app.ApplicationProvider -import androidx.test.ext.junit.runners.AndroidJUnit4 -import com.glooboo.umessage.R -import com.glooboo.umessage.spam.BlockedMessage -import com.glooboo.umessage.spam.DecisionReason -import com.glooboo.umessage.spam.MMS_PLACEHOLDER_BODY -import com.glooboo.umessage.testing.ShadowRecordingSmsManager -import com.glooboo.umessage.ui.theme.UMessageTheme -import com.google.common.truth.Truth.assertThat -import org.junit.Before -import org.junit.Rule -import org.junit.Test -import org.junit.runner.RunWith - -/** - * I32: the carrier report. Every sender here is a fake that records the call: no test sends an SMS, and the recording - * SmsManager of the test setup is checked to have seen nothing either. - */ -@RunWith(AndroidJUnit4::class) -class CarrierReportTest { - - @get:Rule - val compose = createComposeRule() - - private val context: Context = ApplicationProvider.getApplicationContext() - private val sent = mutableListOf>() - private val report = CarrierReport(context) { _, text, number, subId -> sent += Triple(text, number, subId) } - - @Before - fun setUp() { - ShadowRecordingSmsManager.reset() - report.number = "" - } - - private fun spam(id: Long, body: String, address: String = "AD-SHOP", at: Long = id, subId: Int = 2) = - BlockedMessage(id, address, body, subId, false, at, DecisionReason.UNKNOWN_SENDER) - - @Test - fun nothingIsSentWhileNoNumberIsSet() { - assertThat(report.send(spam(1, "Win a prize"))).isFalse() - assertThat(sent).isEmpty() - } - - @Test - fun onlyAShortNumberOfDigitsIsAccepted() { - assertThat(CarrierReport.isValidNumber("7726")).isTrue() - assertThat(CarrierReport.isValidNumber("12")).isFalse() - assertThat(CarrierReport.isValidNumber("123456789")).isFalse() - assertThat(CarrierReport.isValidNumber("77a6")).isFalse() - assertThat(CarrierReport.isValidNumber("+7726")).isFalse() - report.number = "77a6" - assertThat(report.send(spam(1, "Win a prize"))).isFalse() - assertThat(sent).isEmpty() - } - - @Test - fun withANumberTheMessageTextGoesOutOnceFromTheSimItCameOn() { - report.number = " 7726 " - - assertThat(report.send(spam(1, "Win a prize", subId = 2))).isTrue() - - assertThat(sent).containsExactly(Triple("Win a prize", "7726", 2)) - } - - @Test - fun aPictureMessageWithoutTextIsNotReported() { - report.number = "7726" - - assertThat(report.send(spam(1, MMS_PLACEHOLDER_BODY))).isFalse() - assertThat(report.send(spam(2, " "))).isFalse() - assertThat(sent).isEmpty() - } - - @Test - fun theReportIsTheNewestMessageOfExactlyOneSelectedSender() { - val groups = groupBySender( - listOf(spam(1, "old ad", at = 100), spam(2, "new ad", at = 200), spam(3, "other", address = "X", at = 50)), - ) - - assertThat(CarrierReport.pick(groups, setOf("AD-SHOP"))?.body).isEqualTo("new ad") - assertThat(CarrierReport.pick(groups, setOf("AD-SHOP", "X"))).isNull() - assertThat(CarrierReport.pick(groups, emptySet())).isNull() - assertThat(CarrierReport.pick(groups, setOf("nobody"))).isNull() - } - - @Test - fun theDialogSendsNothingUntilConfirmedAndNamesTheCost() { - var confirmed = 0 - compose.setContent { - UMessageTheme { CarrierReportDialog(number = "7726", onConfirm = { confirmed++ }, onDismiss = {}) } - } - - compose.onNodeWithText(context.getString(R.string.carrier_report_body, "7726")).assertExists() - assertThat(context.getString(R.string.carrier_report_body, "7726")).contains("charge") - assertThat(confirmed).isEqualTo(0) - - compose.onNodeWithText(context.getString(R.string.carrier_report_send)).performClick() - - assertThat(confirmed).isEqualTo(1) - assertThat(ShadowRecordingSmsManager.textSends).isEmpty() - } -} +package com.glooboo.umessage.ui.spam + +import android.content.Context +import androidx.compose.ui.test.junit4.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.glooboo.umessage.R +import com.glooboo.umessage.spam.BlockedMessage +import com.glooboo.umessage.spam.DecisionReason +import com.glooboo.umessage.spam.MMS_PLACEHOLDER_BODY +import com.glooboo.umessage.testing.ShadowRecordingSmsManager +import com.glooboo.umessage.ui.theme.UMessageTheme +import com.google.common.truth.Truth.assertThat +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +/** + * I32: the carrier report. Every sender here is a fake that records the call: no test sends an SMS, and the recording + * SmsManager of the test setup is checked to have seen nothing either. + */ +@RunWith(AndroidJUnit4::class) +class CarrierReportTest { + + @get:Rule + val compose = createComposeRule() + + private val context: Context = ApplicationProvider.getApplicationContext() + private val sent = mutableListOf>() + private val report = CarrierReport(context) { _, text, number, subId -> sent += Triple(text, number, subId) } + + @Before + fun setUp() { + ShadowRecordingSmsManager.reset() + report.number = "" + } + + private fun spam(id: Long, body: String, address: String = "AD-SHOP", at: Long = id, subId: Int = 2) = + BlockedMessage(id, address, body, subId, false, at, DecisionReason.UNKNOWN_SENDER) + + @Test + fun nothingIsSentWhileNoNumberIsSet() { + assertThat(report.send(spam(1, "Win a prize"))).isFalse() + assertThat(sent).isEmpty() + } + + @Test + fun onlyAShortNumberOfDigitsIsAccepted() { + assertThat(CarrierReport.isValidNumber("7726")).isTrue() + assertThat(CarrierReport.isValidNumber("12")).isFalse() + assertThat(CarrierReport.isValidNumber("123456789")).isFalse() + assertThat(CarrierReport.isValidNumber("77a6")).isFalse() + assertThat(CarrierReport.isValidNumber("+7726")).isFalse() + report.number = "77a6" + assertThat(report.send(spam(1, "Win a prize"))).isFalse() + assertThat(sent).isEmpty() + } + + @Test + fun withANumberTheMessageTextGoesOutOnceFromTheSimItCameOn() { + report.number = " 7726 " + + assertThat(report.send(spam(1, "Win a prize", subId = 2))).isTrue() + + assertThat(sent).containsExactly(Triple("Win a prize\nAD-SHOP", "7726", 2)) + } + + @Test + fun theReportTextEndsWithTheSenderNumberOnItsOwnLine() { + assertThat(CarrierReport.reportText(spam(1, "Win a prize \n", address = "+15551234"))) + .isEqualTo("Win a prize\n+15551234") + assertThat(CarrierReport.reportText(spam(2, "Win", address = " "))).isEqualTo("Win") + } + + @Test + fun aPictureMessageWithoutTextIsNotReported() { + report.number = "7726" + + assertThat(report.send(spam(1, MMS_PLACEHOLDER_BODY))).isFalse() + assertThat(report.send(spam(2, " "))).isFalse() + assertThat(sent).isEmpty() + } + + @Test + fun theReportIsTheNewestMessageOfExactlyOneSelectedSender() { + val groups = groupBySender( + listOf(spam(1, "old ad", at = 100), spam(2, "new ad", at = 200), spam(3, "other", address = "X", at = 50)), + ) + + assertThat(CarrierReport.pick(groups, setOf("AD-SHOP"))?.body).isEqualTo("new ad") + assertThat(CarrierReport.pick(groups, setOf("AD-SHOP", "X"))).isNull() + assertThat(CarrierReport.pick(groups, emptySet())).isNull() + assertThat(CarrierReport.pick(groups, setOf("nobody"))).isNull() + } + + @Test + fun theDialogSendsNothingUntilConfirmedAndNamesTheCost() { + var confirmed = 0 + compose.setContent { + UMessageTheme { CarrierReportDialog(number = "7726", onConfirm = { confirmed++ }, onDismiss = {}) } + } + + compose.onNodeWithText(context.getString(R.string.carrier_report_body, "7726")).assertExists() + assertThat(context.getString(R.string.carrier_report_body, "7726")).contains("charge") + assertThat(confirmed).isEqualTo(0) + + compose.onNodeWithText(context.getString(R.string.carrier_report_send)).performClick() + + assertThat(confirmed).isEqualTo(1) + assertThat(ShadowRecordingSmsManager.textSends).isEmpty() + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/spam/RuleDryRunTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/RuleDryRunTest.kt new file mode 100644 index 00000000..2450dc85 --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/spam/RuleDryRunTest.kt @@ -0,0 +1,91 @@ +package com.glooboo.umessage.ui.spam + +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 com.glooboo.umessage.spam.engine.RuleMatcher +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class RuleDryRunTest { + private val matcher = RuleMatcher(NumberNormalizer { "GB" }) + + private fun msg(address: String, body: String, sub: Int = 1) = DryRunMessage(address, body, sub) + private fun keyword(word: String, sub: Int? = null, kind: ListKind = ListKind.BLOCK) = + SpamRule(kind = kind, type = RuleType.KEYWORD, pattern = word, subscriptionId = sub) + + @Test + fun countsMatchesAndListsDistinctSenders() { + val messages = listOf( + msg("AD-SHOP", "Big sale today"), msg("AD-SHOP", "sale again"), msg("+447700900001", "SALE!"), + msg("Mum", "dinner?"), + ) + val part = RuleDryRun.scan(matcher, keyword("sale"), messages) + assertEquals(4, part.scanned) + assertEquals(3, part.matched) + assertEquals(listOf("AD-SHOP", "+447700900001"), part.senders) + } + + @Test + fun capsTheScanAndTheExamples() { + val messages = (1..10).map { msg("S$it", "free prize") } + val part = RuleDryRun.scan(matcher, keyword("free"), messages, cap = 5) + assertEquals(5, part.scanned) + assertEquals(5, part.matched) + assertEquals(RuleDryRun.MAX_EXAMPLES, part.senders.size) + } + + @Test + fun hidesSendersWhenAskedButKeepsTheCount() { + val part = RuleDryRun.scan(matcher, keyword("sale"), listOf(msg("AD-SHOP", "sale")), showSenders = false) + assertEquals(1, part.matched) + assertTrue(part.senders.isEmpty()) + } + + @Test + fun ruleForOneSimOnlySeesThatSim() { + val messages = listOf(msg("A", "sale", sub = 1), msg("B", "sale", sub = 2)) + val part = RuleDryRun.scan(matcher, keyword("sale", sub = 2), messages) + assertEquals(2, part.scanned) + assertEquals(1, part.matched) + assertEquals(listOf("B"), part.senders) + } + + @Test + fun emptyInputGivesZeroes() { + assertEquals(DryRunPart(), RuleDryRun.scan(matcher, keyword("sale"), emptyList())) + assertTrue(RuleDryRunResult().isEmpty) + } + + @Test + fun regexRuleMatchesAndBadPatternMatchesNothing() { + val rule = SpamRule(kind = ListKind.BLOCK, type = RuleType.REGEX, pattern = "win \\d+") + assertEquals(1, RuleDryRun.scan(matcher, rule, listOf(msg("X", "you win 100 now"), msg("Y", "hello"))).matched) + val bad = rule.copy(pattern = "(") + assertEquals(0, RuleDryRun.scan(matcher, bad, listOf(msg("X", "(((" ))).matched) + } + + @Test + fun stopsWhenToldTo() { + var calls = 0 + val part = RuleDryRun.scan(matcher, keyword("a"), List(10) { msg("S", "a") }, keepGoing = { ++calls <= 3 }) + assertEquals(3, part.scanned) + } + + @Test + fun blockedMessagesAreNewestFirstCappedAndTextOnly() { + fun blocked(id: Long, at: Long, body: String) = BlockedMessage( + id = id, address = "S$id", body = body, subscriptionId = 1, isMms = false, receivedAt = at, + reason = DecisionReason.BLOCK_RULE, + ) + val list = RuleDryRun.blockedMessages( + listOf(blocked(1, 10, "old"), blocked(2, 30, "new"), blocked(3, 20, " "), blocked(4, 25, "mid")), + cap = 2, + ) + assertEquals(listOf("S2", "S4"), list.map { it.address }) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/thread/MediaSizesTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/MediaSizesTest.kt index cd5a4219..31f2b65f 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/thread/MediaSizesTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/MediaSizesTest.kt @@ -52,4 +52,15 @@ class MediaSizesTest { fun theLoadedPictureWins() { assertEquals(2f, mediaAspect(800, 400, 0.5f), 0.001f) } + + @Test + fun evictionDropsOnlyTheOldestAndOnlyWhenFull() { + assertEquals(emptyList(), evictionBatch(listOf("a", "b", "c"), 3)) + val keys = (1..101).map { "k$it" } + val dropped = evictionBatch(keys, 100) + assertEquals(keys.take(dropped.size), dropped) + // Leaves room for new pictures instead of evicting again on the next one. + assertEquals(true, keys.size - dropped.size <= 90) + assertEquals(false, "k101" in dropped) + } } diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/thread/PhoneLinksTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/PhoneLinksTest.kt new file mode 100644 index 00000000..fa860d0b --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/PhoneLinksTest.kt @@ -0,0 +1,81 @@ +package com.glooboo.umessage.ui.thread + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class PhoneLinksTest { + private fun numbers(text: String) = findPhoneNumbers(text).map { it.number } + + @Test + fun internationalAndLocalNumbersAreFound() { + assertEquals(listOf("+14155550123"), numbers("Call +1 (415) 555-0123 today")) + assertEquals(listOf("09121234567"), numbers("زنگ بزن 09121234567 لطفا")) + assertEquals(listOf("+989121234567"), numbers("00989121234567")) + assertEquals(listOf("02112345678"), numbers("021-1234 5678")) + assertEquals(listOf("5551234567"), numbers("call 5551234567.")) + } + + @Test + fun persianDigitsAreFound() { + assertEquals(listOf("09121234567"), numbers("شماره ۰۹۱۲۱۲۳۴۵۶۷ است")) + } + + @Test + fun rangeCoversTheWrittenNumber() { + val text = "Ring +44 20 7946 0958 now" + val match = findPhoneNumbers(text).single() + assertEquals("+44 20 7946 0958", text.substring(match.range)) + assertEquals("+442079460958", match.number) + } + + @Test + fun verificationCodesAreNotNumbers() { + assertTrue(numbers("Your code is 123456").isEmpty()) + assertTrue(numbers("Code: 1234567 expires soon").isEmpty()) + assertTrue(numbers("code 12345678").isEmpty()) + assertTrue(numbers("G-123456 is your code").isEmpty()) + assertTrue(numbers("123 456").isEmpty()) + } + + @Test + fun pricesAreNotNumbers() { + assertTrue(numbers("Total $1234567 due").isEmpty()) + assertTrue(numbers("Paid 1.234.567 today").isEmpty()) + assertTrue(numbers("Sum 1234567.50 EUR").isEmpty()) + assertTrue(numbers("Sum 1,234,567 IRR").isEmpty()) + assertTrue(numbers("50% off 12345678%").isEmpty()) + } + + @Test + fun datesAndTimesAreNotNumbers() { + assertTrue(numbers("On 2026-11-11 at 12:30").isEmpty()) + assertTrue(numbers("Due 11.11.2026").isEmpty()) + assertTrue(numbers("Due 11/11/2026").isEmpty()) + assertTrue(numbers("2026/11/11 10:20:30").isEmpty()) + } + + @Test + fun cardsIdsAndPartsOfWordsAreNotNumbers() { + assertTrue(numbers("Card 6037 9912 3456 7890").isEmpty()) + assertTrue(numbers("Order AB12345678 shipped").isEmpty()) + assertTrue(numbers("ref #12345678").isEmpty()) + assertTrue(numbers("see example.com/12345678901").isEmpty()) + assertTrue(numbers("me@12345678901.test").isEmpty()) + assertTrue(numbers("version 10.0.0.1234567").isEmpty()) + } + + @Test + fun severalNumbersAreAllFound() { + assertEquals(listOf("09121234567", "+14155550123"), numbers("09121234567 or +1-415-555-0123")) + } + + @Test + fun phoneLinkRoundTrip() { + assertEquals("tel:+14155550123", phoneLink("+14155550123")) + assertEquals("+14155550123", phoneOf("tel:+14155550123")) + assertNull(phoneOf("https://example.com")) + assertEquals("+14155550123", linkCopyText("tel:+14155550123")) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/thread/SecureUrlTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/SecureUrlTest.kt new file mode 100644 index 00000000..fe4a930f --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/SecureUrlTest.kt @@ -0,0 +1,22 @@ +package com.glooboo.umessage.ui.thread + +import org.junit.Assert.assertEquals +import org.junit.Test + +class SecureUrlTest { + @Test + fun linkWrittenWithoutSchemeOpensOnHttps() { + assertEquals("https://example.com/a", secureUrl("http://example.com/a", "example.com/a")) + } + + @Test + fun writtenHttpStaysHttp() { + assertEquals("http://example.com", secureUrl("http://example.com", "http://example.com")) + } + + @Test + fun mailAndHttpsAreUntouched() { + assertEquals("mailto:a@b.test", secureUrl("mailto:a@b.test", "a@b.test")) + assertEquals("https://x.test", secureUrl("https://x.test", "https://x.test")) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/thread/ThreadRound2Test.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/ThreadRound2Test.kt new file mode 100644 index 00000000..e954b4af --- /dev/null +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/ThreadRound2Test.kt @@ -0,0 +1,93 @@ +package com.glooboo.umessage.ui.thread + +import android.provider.Telephony +import com.glooboo.umessage.models.Message +import com.glooboo.umessage.models.MessageKey +import com.google.common.truth.Truth.assertThat +import org.junit.Test + +/** Search over older messages, the lookup cache and the new-message count of the chat screen. */ +class ThreadRound2Test { + + private fun hit(id: Long, date: Int) = SearchHit(MessageKey(id, false), date) + + @Test + fun olderMatchesJoinTheLoadedOnesNewestFirstWithoutDuplicates() { + val loaded = listOf(hit(9, 90), hit(8, 80)) + val older = listOf(hit(8, 80), hit(3, 30), hit(1, 10)) + assertThat(mergeSearchHits(loaded, older)) + .containsExactly(MessageKey(9, false), MessageKey(8, false), MessageKey(3, false), MessageKey(1, false)) + .inOrder() + assertThat(mergeSearchHits(loaded, emptyList())) + .containsExactly(MessageKey(9, false), MessageKey(8, false)).inOrder() + assertThat(mergeSearchHits(emptyList(), older)).hasSize(3) + } + + @Test + fun smsAndMmsWithTheSameIdAreDifferentMatches() { + val merged = mergeSearchHits(listOf(hit(5, 50)), listOf(SearchHit(MessageKey(5, true), 40))) + assertThat(merged).containsExactly(MessageKey(5, false), MessageKey(5, true)).inOrder() + } + + @Test + fun lookupsRunOnceUntilInvalidated() { + val cache = ThreadLookupCache() + var calls = 0 + repeat(3) { cache.isSaved("+100") { calls++; true } } + assertThat(calls).isEqualTo(1) + cache.isSaved("+200") { calls++; false } + assertThat(calls).isEqualTo(2) + cache.invalidateContacts() + cache.isSaved("+200") { calls++; false } + assertThat(calls).isEqualTo(3) + } + + @Test + fun strangerIsAskedAgainOnceTheUserWritesToThem() { + val cache = ThreadLookupCache() + var calls = 0 + assertThat(cache.isStranger("+1", false, false) { calls++; true }).isTrue() + assertThat(cache.isStranger("+1", false, false) { calls++; true }).isTrue() + assertThat(calls).isEqualTo(1) + assertThat(cache.isStranger("+1", false, true) { calls++; false }).isFalse() + assertThat(calls).isEqualTo(2) + } + + @Test + fun simResultIsKeptUntilTheSimsChange() { + val cache = ThreadLookupCache() + var calls = 0 + repeat(2) { cache.sims { calls++; "labels" } } + assertThat(calls).isEqualTo(1) + cache.invalidateSims() + cache.sims { calls++; "labels" } + assertThat(calls).isEqualTo(2) + } + + private fun message(id: Long, body: String = "x") = Message( + id = id, body = body, type = Telephony.Sms.MESSAGE_TYPE_INBOX, status = 0, participants = ArrayList(), + date = id.toInt(), read = true, threadId = 1L, isMMS = false, attachment = null, + senderPhoneNumber = "1", senderName = "1", senderPhotoUri = "", subscriptionId = -1, + ) + + @Test + fun onlyNewOrChangedMessagesAreWrittenBack() { + val cached = listOf(message(1), message(2)) + val fresh = listOf(message(1), message(2, "edited"), message(3)) + assertThat(messagesToCache(fresh, cached).map { it.id }).containsExactly(2L, 3L) + assertThat(messagesToCache(fresh, emptyList())).hasSize(3) + assertThat(messagesToCache(cached, cached)).isEmpty() + } + + @Test + fun newMessageCountCountsRowsAboveTheOnesSeenWhileScrolledUp() { + val keys = listOf("c", "b", "a") + assertThat(newRowsSince(keys, "b")).isEqualTo(1) + assertThat(newRowsSince(keys, "c")).isEqualTo(0) + assertThat(newRowsSince(keys, "gone")).isEqualTo(0) + assertThat(newRowsSince(emptyList(), "b")).isEqualTo(0) + assertThat(newRowsSince(keys, null)).isEqualTo(0) + // Only counted rows (received messages) add up: a date header or the user's own message does not. + assertThat(newRowsSince(listOf("d", "h", "m"), "m") { it != "h" }).isEqualTo(1) + } +} diff --git a/app/src/test/kotlin/com/glooboo/umessage/ui/thread/ThreadSendControllerTest.kt b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/ThreadSendControllerTest.kt index 7e3adb00..250c7db6 100644 --- a/app/src/test/kotlin/com/glooboo/umessage/ui/thread/ThreadSendControllerTest.kt +++ b/app/src/test/kotlin/com/glooboo/umessage/ui/thread/ThreadSendControllerTest.kt @@ -1,6 +1,7 @@ package com.glooboo.umessage.ui.thread import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.glooboo.umessage.messaging.SendOutcome import com.glooboo.umessage.models.Attachment import com.glooboo.umessage.models.MessageKey import com.google.common.truth.Truth.assertThat @@ -17,7 +18,7 @@ class ThreadSendControllerTest { private val errors = mutableListOf() private fun controller(answer: (OutgoingMessage) -> Boolean) = - ThreadSendController({ sent += it; answer(it) }) { errors += it } + ThreadSendController({ sent += it; SendOutcome(handedOff = answer(it)) }) { errors += it } @Test fun aHandedOffComposerMessageEmptiesTheComposer() { @@ -59,6 +60,26 @@ class ThreadSendControllerTest { assertThat(sent.single().resendOf).isEqualTo(MessageKey(9, true)) } + @Test + fun aPartlySentMessageReportsWhatIsLeftAndKeepsTheComposer() { + val a = Attachment(null, -1L, "content://x/1", "image/jpeg", 0, 0, "a.jpg") + val c = Attachment(null, -1L, "content://x/3", "image/jpeg", 0, 0, "c.jpg") + val outcome = SendOutcome(handedOff = false, remainingAttachments = listOf(c), sentCount = 2, textSent = true) + val result = ThreadSendController({ outcome }) { errors += it } + .send(OutgoingMessage("hi", listOf("111"), 1, listOf(a, c)), fromComposer = true) + assertThat(result.clearComposer).isFalse() + assertThat(result.partial!!.remainingAttachments).containsExactly(c) + assertThat(result.partial!!.textSent).isTrue() + } + + @Test + fun aSendThatSentNothingIsNotPartial() { + val a = Attachment(null, -1L, "content://x/1", "image/jpeg", 0, 0, "a.jpg") + val result = ThreadSendController({ SendOutcome(false, listOf(a), 0, false) }) { errors += it } + .send(OutgoingMessage("hi", listOf("111"), 1, listOf(a)), fromComposer = true) + assertThat(result.partial).isNull() + } + @Test fun retryTextKeepsTheResendTargetUntilTheUserEdits() { val tracker = ResendTracker() diff --git a/docs/PLAY_STORE.md b/docs/PLAY_STORE.md index 1bfda840..544c9e70 100644 --- a/docs/PLAY_STORE.md +++ b/docs/PLAY_STORE.md @@ -71,7 +71,7 @@ If a future version adds anything that sends data (crash reports, an online spam - [ ] Upload to **internal testing** first; check the pre-launch report (it cannot become the default SMS app, so expect limited coverage). - [ ] Play's new personal developer accounts must run a **closed test with at least 12 testers for 14 days** before production. **Owner:** plan for this. -- [ ] Check that Play Protect does not flag the bundle (see the warning below). +- [ ] Check that Play Protect does not flag the bundle (see the forwarding notes below). ## In-app rating card