From 560652a7371ed211ae9c0134a934ce6241b618a6 Mon Sep 17 00:00:00 2001
From: The-R0 <2861295907@qq.com>
Date: Wed, 25 Nov 2026 19:25:22 +0800
Subject: [PATCH 1/2] feat(privacy,feed,search): add local UP and keyword
content block rules
---
.../composeResources/values-en/strings.xml | 13 ++
.../composeResources/values/strings.xml | 13 ++
.../kotlin/dev/bilby/data/ContentBlockRule.kt | 69 ++++++++++
.../kotlin/dev/bilby/data/DynamicFeedStore.kt | 32 ++++-
.../kotlin/dev/bilby/data/SettingsStore.kt | 63 +++++++++
.../kotlin/dev/bilby/ui/BilbyApp.kt | 44 +++++-
.../dev/bilby/ui/components/ContextMenuBox.kt | 27 ++++
.../dev/bilby/ui/search/SearchResults.kt | 59 +++++---
.../dev/bilby/ui/settings/SettingsPages.kt | 129 ++++++++++++++++++
.../bilby/ui/settings/SettingsViewModel.kt | 20 +++
.../dev/bilby/data/ContentBlockMatcherTest.kt | 34 +++++
11 files changed, 482 insertions(+), 21 deletions(-)
create mode 100644 shared/src/commonMain/kotlin/dev/bilby/data/ContentBlockRule.kt
create mode 100644 shared/src/commonTest/kotlin/dev/bilby/data/ContentBlockMatcherTest.kt
diff --git a/shared/src/commonMain/composeResources/values-en/strings.xml b/shared/src/commonMain/composeResources/values-en/strings.xml
index a569f448..2d52f6ff 100644
--- a/shared/src/commonMain/composeResources/values-en/strings.xml
+++ b/shared/src/commonMain/composeResources/values-en/strings.xml
@@ -799,6 +799,19 @@
The exclusion list is emptied and posts from these uploaders return to the feed.
+ Block this creator
+ Blocked %1$s in feed and search
+ Unblocked %1$s
+ Local content filters
+ Hide matching creators and title keywords locally in feed and search
+ %1$d rules
+ Keyword to block in titles or creator names
+ Add
+ Creator
+ Remove
+ No filter rules yet. Long-press any video to block a creator or add keywords here.
+ Clear filter rules
+ All blocked creator and keyword rules will be cleared.
Disconnected
diff --git a/shared/src/commonMain/composeResources/values/strings.xml b/shared/src/commonMain/composeResources/values/strings.xml
index 6e3b5277..2c711bdf 100644
--- a/shared/src/commonMain/composeResources/values/strings.xml
+++ b/shared/src/commonMain/composeResources/values/strings.xml
@@ -864,6 +864,19 @@
排除名单会清空,这些 UP 主的投稿重新出现在动态里。
+ 屏蔽这位 UP 主
+ 已屏蔽 %1$s,动态与搜索将自动过滤
+ 已取消屏蔽 %1$s
+ 本地内容屏蔽
+ 按 UP 主或标题关键词在动态与搜索中本地过滤
+ %1$d 条规则
+ 输入要屏蔽的标题或 UP 主关键词
+ 添加
+ UP
+ 移除
+ 暂无屏蔽规则,可长按视频屏蔽 UP 主或在此添加关键词
+ 清空屏蔽规则
+ 已添加的 UP 主与关键词屏蔽规则都会被清除。
连接已断开
diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/ContentBlockRule.kt b/shared/src/commonMain/kotlin/dev/bilby/data/ContentBlockRule.kt
new file mode 100644
index 00000000..f5d70dfd
--- /dev/null
+++ b/shared/src/commonMain/kotlin/dev/bilby/data/ContentBlockRule.kt
@@ -0,0 +1,69 @@
+package dev.bilby.data
+
+import kotlinx.serialization.Serializable
+
+/**
+ * 本地内容屏蔽规则:按 UP 主 mid 或标题/UP 名关键词(忽略大小写)在动态流与搜索结果中实时过滤。
+ */
+@Serializable
+data class ContentBlockRule(
+ val kind: Kind,
+ val value: String,
+ val label: String,
+) {
+ @Serializable
+ enum class Kind { Up, Keyword }
+}
+
+/**
+ * 由 [ContentBlockRule] 列表编译出的不可变匹配器。
+ */
+data class ContentBlockMatcher(
+ val blockedUpMids: Set = emptySet(),
+ val blockedKeywords: List = emptyList(),
+) {
+ val isEmpty: Boolean get() = blockedUpMids.isEmpty() && blockedKeywords.isEmpty()
+
+ fun matchesVideo(
+ upMid: Long = 0L,
+ upName: String = "",
+ title: String = "",
+ ): Boolean {
+ if (upMid != 0L && upMid in blockedUpMids) return true
+ if (blockedKeywords.isNotEmpty()) {
+ for (kw in blockedKeywords) {
+ if (title.contains(kw, ignoreCase = true) || upName.contains(kw, ignoreCase = true)) {
+ return true
+ }
+ }
+ }
+ return false
+ }
+
+ fun matchesUser(mid: Long, name: String): Boolean {
+ if (mid != 0L && mid in blockedUpMids) return true
+ if (blockedKeywords.isNotEmpty()) {
+ for (kw in blockedKeywords) {
+ if (name.contains(kw, ignoreCase = true)) return true
+ }
+ }
+ return false
+ }
+
+ companion object {
+ val EMPTY = ContentBlockMatcher()
+
+ fun fromRules(rules: List): ContentBlockMatcher {
+ if (rules.isEmpty()) return EMPTY
+ val mids = mutableSetOf()
+ val keywords = mutableListOf()
+ for (rule in rules) {
+ when (rule.kind) {
+ ContentBlockRule.Kind.Up -> rule.value.toLongOrNull()?.takeIf { it > 0L }?.let { mids += it }
+ ContentBlockRule.Kind.Keyword -> rule.value.trim().takeIf { it.isNotEmpty() }?.let { keywords += it }
+ }
+ }
+ return ContentBlockMatcher(blockedUpMids = mids, blockedKeywords = keywords)
+ }
+ }
+}
diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/DynamicFeedStore.kt b/shared/src/commonMain/kotlin/dev/bilby/data/DynamicFeedStore.kt
index 04770bf0..5a62fbc2 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/data/DynamicFeedStore.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/data/DynamicFeedStore.kt
@@ -6,6 +6,7 @@ import dev.bilby.api.BiliResult
import dev.bilby.data.db.FeedCacheRepository
import dev.bilby.data.model.DynamicCard
import dev.bilby.data.model.FeedEntry
+import dev.bilby.data.model.plainText
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -50,12 +51,35 @@ class DynamicFeedStore(
private val _other = MutableStateFlow>(emptyList())
private val _status = MutableStateFlow(DynamicFeedStatus())
- val home: Flow> = combine(_home, settings.excludedFeedMids) { items, excluded ->
- items.filterNot { it.upMid in excluded }
+ val home: Flow> = combine(
+ _home,
+ settings.excludedFeedMids,
+ settings.contentBlockMatcher,
+ ) { items, excluded, matcher ->
+ items.filterNot { entry ->
+ if (entry.upMid in excluded) return@filterNot true
+ if (matcher.isEmpty) return@filterNot false
+ val title = when (entry) {
+ is FeedEntry.Video -> entry.title
+ is FeedEntry.Article -> entry.title
+ }
+ matcher.matchesVideo(upMid = entry.upMid, upName = entry.upName, title = title)
+ }
}
- val other: Flow> = combine(_other, settings.excludedFeedMids) { cards, excluded ->
- cards.filterNot { it.author.mid in excluded }
+ val other: Flow> = combine(
+ _other,
+ settings.excludedFeedMids,
+ settings.contentBlockMatcher,
+ ) { cards, excluded, matcher ->
+ cards.filterNot { card ->
+ card.author.mid in excluded ||
+ (!matcher.isEmpty && matcher.matchesVideo(
+ upMid = card.author.mid,
+ upName = card.author.name,
+ title = card.text.plainText(),
+ ))
+ }
}
val status: StateFlow = _status.asStateFlow()
diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/SettingsStore.kt b/shared/src/commonMain/kotlin/dev/bilby/data/SettingsStore.kt
index e26d735d..4c0263f3 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/data/SettingsStore.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/data/SettingsStore.kt
@@ -496,6 +496,67 @@ class SettingsStore(private val store: DataStore) {
store.edit { p -> p.remove(KEY_EXCLUDED_FEED_MIDS) }
}
+ /** 本地内容屏蔽规则(UP 主与标题/UP 名关键词),用于动态与搜索实时过滤。 */
+ val contentBlockRules: Flow> = store.data.map { p ->
+ decodeContentBlockRules(p[KEY_CONTENT_BLOCK_RULES])
+ }
+
+ val contentBlockMatcher: Flow = contentBlockRules.map(ContentBlockMatcher::fromRules)
+
+ suspend fun addBlockedUp(mid: Long, name: String) {
+ if (mid <= 0L) return
+ val value = mid.toString()
+ val label = name.ifBlank { "UID $mid" }
+ store.edit { p ->
+ val current = decodeContentBlockRules(p[KEY_CONTENT_BLOCK_RULES])
+ .filterNot { it.kind == ContentBlockRule.Kind.Up && it.value == value }
+ val updated = listOf(ContentBlockRule(ContentBlockRule.Kind.Up, value, label)) + current
+ p[KEY_CONTENT_BLOCK_RULES] = encodeContentBlockRules(updated)
+ }
+ }
+
+ suspend fun removeBlockedUp(mid: Long) {
+ removeContentBlockRule(ContentBlockRule.Kind.Up, mid.toString())
+ }
+
+ suspend fun addBlockedKeyword(keyword: String): Boolean {
+ val trimmed = keyword.trim()
+ if (trimmed.isEmpty()) return false
+ val normalized = trimmed.lowercase()
+ store.edit { p ->
+ val current = decodeContentBlockRules(p[KEY_CONTENT_BLOCK_RULES])
+ .filterNot { it.kind == ContentBlockRule.Kind.Keyword && it.value == normalized }
+ val updated = listOf(ContentBlockRule(ContentBlockRule.Kind.Keyword, normalized, trimmed)) + current
+ p[KEY_CONTENT_BLOCK_RULES] = encodeContentBlockRules(updated)
+ }
+ return true
+ }
+
+ suspend fun removeContentBlockRule(kind: ContentBlockRule.Kind, value: String) {
+ store.edit { p ->
+ val updated = decodeContentBlockRules(p[KEY_CONTENT_BLOCK_RULES])
+ .filterNot { it.kind == kind && it.value == value }
+ if (updated.isEmpty()) p.remove(KEY_CONTENT_BLOCK_RULES)
+ else p[KEY_CONTENT_BLOCK_RULES] = encodeContentBlockRules(updated)
+ }
+ }
+
+ suspend fun clearContentBlockRules() {
+ store.edit { p -> p.remove(KEY_CONTENT_BLOCK_RULES) }
+ }
+
+ private fun decodeContentBlockRules(raw: String?): List {
+ if (raw.isNullOrBlank()) return emptyList()
+ return runCatching {
+ ContentBlockRulesJson.decodeFromString(ListSerializer(ContentBlockRule.serializer()), raw)
+ }.onFailure { cause ->
+ BiliLog.w("解析本地屏蔽规则失败: ${cause.message}", cause)
+ }.getOrDefault(emptyList())
+ }
+
+ private fun encodeContentBlockRules(rules: List): String =
+ ContentBlockRulesJson.encodeToString(ListSerializer(ContentBlockRule.serializer()), rules)
+
/**
* 普通搜索的历史,最近的在前。
*
@@ -822,6 +883,7 @@ class SettingsStore(private val store: DataStore) {
private val KEY_DANMAKU_IN_PIP = booleanPreferencesKey("danmaku_in_pip")
private val KEY_DANMAKU_FONT_SCALE = floatPreferencesKey("danmaku_font_scale")
private val KEY_EXCLUDED_FEED_MIDS = stringSetPreferencesKey("excluded_feed_mids")
+ private val KEY_CONTENT_BLOCK_RULES = stringPreferencesKey("content_block_rules")
private val KEY_DANMAKUS_ARCHIVE = booleanPreferencesKey("danmakus_archive_enabled")
@@ -1165,6 +1227,7 @@ private data class ScheduleRuleDto(
)
private val NightUpsJson = Json { ignoreUnknownKeys = true }
+private val ContentBlockRulesJson = Json { ignoreUnknownKeys = true }
private val NightUpsSerializer = ListSerializer(WhitelistedUpDto.serializer())
private val ScheduleRulesJson = Json { ignoreUnknownKeys = true; encodeDefaults = true }
private val ScheduleRulesSerializer = ListSerializer(ScheduleRuleDto.serializer())
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt
index 1f92a6fd..1b8c99f1 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt
@@ -2,7 +2,10 @@ package dev.bilby.ui
import dev.bilby.ui.components.BilbySearchTopBar
import dev.bilby.ui.components.EditableFocusTracker
+import dev.bilby.ui.components.LocalContentBlockMatcher
import dev.bilby.ui.components.LocalCopyNotice
+import dev.bilby.ui.components.LocalVideoBlockActions
+import dev.bilby.ui.components.VideoBlockActions
import dev.bilby.ui.components.LocalEditableFocusTracker
import dev.bilby.ui.components.LocalPageRefreshRegistry
import dev.bilby.ui.components.LocalPageSearchRegistry
@@ -289,6 +292,7 @@ import dev.bilby.ui.settings.PlayerCustomizationPage
import dev.bilby.ui.settings.PlaybackSettingsPage
import dev.bilby.data.model.ArticleRef
import dev.bilby.data.model.FeedEntry
+import dev.bilby.ui.settings.BlockRulesPage
import dev.bilby.ui.settings.ExcludedFeedPage
import dev.bilby.ui.settings.PrivacySettingsPage
import dev.bilby.ui.settings.SettingsScreen
@@ -1155,7 +1159,36 @@ private fun BilbyApp(
}
}
- CompositionLocalProvider(LocalQueueActions provides queueMenuActions) {
+ val contentBlockMatcher by remember(container) {
+ container.settings.contentBlockMatcher
+ }.collectAsStateWithLifecycle(initialValue = dev.bilby.data.ContentBlockMatcher.EMPTY)
+ val undoLabel = stringResource(Res.string.action_undo)
+ val videoBlockActions = remember(container, snackbarHostState, snackbarScope, undoLabel) {
+ VideoBlockActions { upMid, upName ->
+ snackbarScope.launch {
+ val label = upName.ifBlank { "UID $upMid" }
+ container.settings.addBlockedUp(mid = upMid, name = label)
+ val res = snackbarHostState.showSnackbar(
+ message = dev.bilby.getString(Res.string.block_up_added, label),
+ actionLabel = undoLabel,
+ duration = SnackbarDuration.Short,
+ )
+ if (res == SnackbarResult.ActionPerformed) {
+ container.settings.removeBlockedUp(upMid)
+ snackbarHostState.showSnackbar(
+ dev.bilby.getString(Res.string.block_up_undone, label),
+ duration = SnackbarDuration.Short,
+ )
+ }
+ }
+ }
+ }
+
+ CompositionLocalProvider(
+ LocalQueueActions provides queueMenuActions,
+ LocalVideoBlockActions provides videoBlockActions,
+ LocalContentBlockMatcher provides contentBlockMatcher,
+ ) {
Box(
modifier = Modifier
.fillMaxSize()
@@ -3350,6 +3383,7 @@ private fun SettingsPageRoute(
onRetryHistoryPause = vm::loadHistoryPause,
onOpenBlacklist = onOpenBlacklist,
onOpenExcludedFeed = { onOpenSection(SettingsSection.ExcludedFeed) },
+ onOpenBlockRules = { onOpenSection(SettingsSection.BlockRules) },
onDanmakusArchiveChange = vm::setDanmakusArchive,
onBack = onBack,
)
@@ -3362,6 +3396,14 @@ private fun SettingsPageRoute(
onBack = onBack,
)
+ SettingsSection.BlockRules -> BlockRulesPage(
+ state = state,
+ onAddKeyword = vm::addBlockedKeyword,
+ onRemoveRule = vm::removeContentBlockRule,
+ onClearAll = vm::clearContentBlockRules,
+ onBack = onBack,
+ )
+
SettingsSection.About -> AboutSettingsPage(
updater = container.platform.updater,
onOpenGithub = { system.openInBrowser(PROJECT_GITHUB_URL) },
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/components/ContextMenuBox.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/components/ContextMenuBox.kt
index cc814f9e..3fc74287 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/components/ContextMenuBox.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/components/ContextMenuBox.kt
@@ -13,6 +13,7 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.PlaylistAdd
import androidx.compose.material.icons.automirrored.outlined.PlaylistPlay
+import androidx.compose.material.icons.outlined.Block
import androidx.compose.material.icons.outlined.ContentCopy
import androidx.compose.material.icons.outlined.Link
import androidx.compose.material.icons.outlined.Person
@@ -61,11 +62,13 @@ import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.round
+import dev.bilby.data.ContentBlockMatcher
import dev.bilby.player.QueueItem
import dev.bilby.resources.Res
import dev.bilby.resources.action_copy_title
import dev.bilby.resources.action_share
import dev.bilby.resources.comment_copied
+import dev.bilby.resources.menu_block_up
import dev.bilby.resources.menu_copy_link
import dev.bilby.resources.menu_open_space
import dev.bilby.resources.queue_add
@@ -94,6 +97,16 @@ data class QueueMenuActions(
val LocalQueueActions = staticCompositionLocalOf { null }
+/** 视频列表项右键/长按本地屏蔽 UP 主动作,由根部 [dev.bilby.ui.BilbyApp] 提供。 */
+data class VideoBlockActions(
+ val blockUp: (upMid: Long, upName: String) -> Unit,
+)
+
+val LocalVideoBlockActions = staticCompositionLocalOf { null }
+
+/** 本地内容屏蔽匹配器,供搜索结果等列表实时过滤。 */
+val LocalContentBlockMatcher = staticCompositionLocalOf { ContentBlockMatcher.EMPTY }
+
/**
* 桌面右键菜单的动效方案:去掉移动端 `DropdownMenu` 默认的 `0.8 -> 1.0` 缩放弹簧,保留极短的
* 80ms 淡入淡出,让指针所指之处即点即出。
@@ -316,6 +329,7 @@ fun videoCommonMenuItemCount(
if (includeQueueActions && LocalQueueActions.current != null) count += 2
if (title == null || title.isNotBlank()) count += 1
count += 2
+ if (upMid != 0L && LocalVideoBlockActions.current != null) count += 1
}
if (upMid != 0L && onOpenUpSpace != null) count += 1
return count
@@ -341,6 +355,7 @@ fun VideoCommonMenuItems(
) {
val system = LocalSystemActions.current
val queueActions = LocalQueueActions.current.takeIf { includeQueueActions }
+ val blockActions = LocalVideoBlockActions.current
val copyTitle = rememberCopyAction()
val copyBvid = rememberCopyAction(
clipLabel = stringResource(Res.string.video_bvid_clip_label),
@@ -416,6 +431,18 @@ fun VideoCommonMenuItems(
},
shape = menuItemShape(shareIndex, totalCount),
)
+ if (upMid != 0L && blockActions != null) {
+ val blockUpIndex = cursor++
+ DropdownMenuItem(
+ onClick = {
+ close()
+ blockActions.blockUp(upMid, upName)
+ },
+ text = { Text(stringResource(Res.string.menu_block_up)) },
+ leadingIcon = { Icon(Icons.Outlined.Block, contentDescription = null) },
+ shape = menuItemShape(blockUpIndex, totalCount),
+ )
+ }
}
if (upMid != 0L && onOpenUpSpace != null) {
val spaceIndex = cursor
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchResults.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchResults.kt
index dd173190..33a27c4c 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchResults.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchResults.kt
@@ -78,6 +78,7 @@ import dev.bilby.ui.BilbyWindowSize
import dev.bilby.ui.components.Avatar
import dev.bilby.ui.components.ContextMenuBox
import dev.bilby.ui.components.CoverAspectRatio
+import dev.bilby.ui.components.LocalContentBlockMatcher
import dev.bilby.ui.components.LocalPointerSource
import dev.bilby.ui.components.PagedColumn
import dev.bilby.ui.components.PagedLayout
@@ -475,21 +476,33 @@ private fun ResultPage(
bottomPadding = bottomPadding,
)
- SearchTab.User -> PagedColumn(
- layout = layout,
- items = state.users.items,
- key = { it.mid },
- skeletonRow = { PersonRowSkeleton() },
- loading = state.users.loading && state.users.items.isEmpty(),
- appending = state.users.appending,
- hasMore = state.users.hasMore,
- error = state.users.error.takeIf { state.users.items.isEmpty() },
- emptyText = stringResource(Res.string.search_no_results),
- onLoadMore = actions.onLoadMore,
- onRetry = actions.onRetry,
- contentPadding = listPadding,
- ) { user ->
- UserResultRow(user, onClick = { actions.onUserClick(user.mid) })
+ SearchTab.User -> {
+ val blockMatcher = LocalContentBlockMatcher.current
+ val visibleUsers = remember(state.users.items, blockMatcher) {
+ if (blockMatcher.isEmpty) {
+ state.users.items
+ } else {
+ state.users.items.filterNot { user ->
+ blockMatcher.matchesUser(mid = user.mid, name = user.name)
+ }
+ }
+ }
+ PagedColumn(
+ layout = layout,
+ items = visibleUsers,
+ key = { it.mid },
+ skeletonRow = { PersonRowSkeleton() },
+ loading = state.users.loading && state.users.items.isEmpty(),
+ appending = state.users.appending,
+ hasMore = state.users.hasMore,
+ error = state.users.error.takeIf { state.users.items.isEmpty() },
+ emptyText = stringResource(Res.string.search_no_results),
+ onLoadMore = actions.onLoadMore,
+ onRetry = actions.onRetry,
+ contentPadding = listPadding,
+ ) { user ->
+ UserResultRow(user, onClick = { actions.onUserClick(user.mid) })
+ }
}
SearchTab.Article -> PagedColumn(
@@ -531,6 +544,20 @@ private fun VideoResults(
bottomPadding: Dp,
) {
val videos = state.videos
+ val blockMatcher = LocalContentBlockMatcher.current
+ val visibleVideos = remember(videos.items, blockMatcher) {
+ if (blockMatcher.isEmpty) {
+ videos.items
+ } else {
+ videos.items.filterNot { video ->
+ blockMatcher.matchesVideo(
+ upMid = video.upMid,
+ upName = video.upName,
+ title = video.title,
+ )
+ }
+ }
+ }
val wideWindow = rememberBilbyWindowSize().isAtLeast(BilbyWindowSize.Expanded)
val density = LocalDensity.current
var containerWidth by remember { mutableStateOf(0.dp) }
@@ -566,7 +593,7 @@ private fun VideoResults(
) {
PagedColumn(
layout = effectiveLayout,
- items = videos.items,
+ items = visibleVideos,
key = { it.bvid },
loading = videos.loading && videos.items.isEmpty(),
appending = videos.appending,
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsPages.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsPages.kt
index 9501ff6e..13950dbf 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsPages.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsPages.kt
@@ -117,6 +117,7 @@ import dev.bilby.resources.*
import dev.bilby.ui.navigationBarsBottom
import dev.bilby.ui.padScaffoldExceptBottom
import dev.bilby.data.CodecPreference
+import dev.bilby.data.ContentBlockRule
import dev.bilby.data.DEFAULT_NIGHT_END_MINUTE
import dev.bilby.data.DEFAULT_NIGHT_START_MINUTE
import dev.bilby.data.LlmConfig
@@ -228,6 +229,8 @@ enum class SettingsSection {
/** 排除的 UP 主名单。从隐私页再降一层,理由见 [ExcludedFeedPage]。 */
ExcludedFeed,
+ /** 本地内容屏蔽规则(UP 主与关键词)。从隐私页再降一层。 */
+ BlockRules,
Agent,
Privacy,
NightMode,
@@ -1195,6 +1198,7 @@ fun PrivacySettingsPage(
onRetryHistoryPause: () -> Unit,
onOpenBlacklist: () -> Unit,
onOpenExcludedFeed: () -> Unit,
+ onOpenBlockRules: () -> Unit,
onDanmakusArchiveChange: (Boolean) -> Unit,
onBack: (() -> Unit)?,
) {
@@ -1255,6 +1259,19 @@ fun PrivacySettingsPage(
onCheckedChange = onDanmakusArchiveChange,
)
}
+ row { position ->
+ SettingRow(
+ position = position,
+ icon = Icons.Outlined.Block,
+ title = stringResource(Res.string.settings_block_rules),
+ subtitle = stringResource(Res.string.settings_block_rules_subtitle),
+ value = state.contentBlockRules.size.takeIf { it > 0 }?.let {
+ stringResource(Res.string.settings_block_rules_count, it)
+ },
+ target = RowTarget.Page,
+ onClick = onOpenBlockRules,
+ )
+ }
// 一个都没排除过的人不需要看见这个概念。
if (state.excludedFeedUps.isNotEmpty()) {
row { position ->
@@ -1345,6 +1362,118 @@ fun ExcludedFeedPage(
}
}
+/**
+ * 本地内容屏蔽规则:按 UP 主或关键词(匹配标题与 UP 名)在关注动态与搜索结果中实时过滤。
+ */
+@Composable
+fun BlockRulesPage(
+ state: SettingsUiState,
+ onAddKeyword: (String) -> Unit,
+ onRemoveRule: (ContentBlockRule.Kind, String) -> Unit,
+ onClearAll: () -> Unit,
+ onBack: (() -> Unit)?,
+) {
+ var keywordInput by rememberSaveable { mutableStateOf("") }
+ var confirmingClearAll by rememberSaveable { mutableStateOf(false) }
+ val upPrefix = stringResource(Res.string.settings_block_rule_up_prefix)
+ SettingsSubPage(stringResource(Res.string.settings_block_rules), onBack, state.loaded) {
+ androidx.compose.foundation.layout.Row(
+ verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
+ horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(Spacing.Tight),
+ modifier = Modifier.padding(horizontal = Spacing.Comfortable, vertical = Spacing.Tight),
+ ) {
+ OutlinedTextField(
+ value = keywordInput,
+ onValueChange = { keywordInput = it },
+ singleLine = true,
+ placeholder = { Text(stringResource(Res.string.settings_block_keyword_hint)) },
+ modifier = Modifier.weight(1f),
+ )
+ Button(
+ enabled = keywordInput.isNotBlank(),
+ onClick = {
+ val kw = keywordInput.trim()
+ if (kw.isNotEmpty()) {
+ onAddKeyword(kw)
+ keywordInput = ""
+ }
+ },
+ ) {
+ Text(stringResource(Res.string.settings_block_keyword_add))
+ }
+ }
+ if (state.contentBlockRules.isEmpty()) {
+ Text(
+ text = stringResource(Res.string.settings_block_rules_empty),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ modifier = Modifier.padding(horizontal = Spacing.Comfortable, vertical = Spacing.Cozy),
+ )
+ } else {
+ SettingsGroup {
+ state.contentBlockRules.forEach { rule ->
+ val title = if (rule.kind == ContentBlockRule.Kind.Up) {
+ "$upPrefix ${rule.label}"
+ } else {
+ rule.label
+ }
+ val icon = if (rule.kind == ContentBlockRule.Kind.Up) {
+ Icons.Outlined.Person
+ } else {
+ Icons.Outlined.Search
+ }
+ row { position ->
+ StaticSettingRow(
+ position = position,
+ icon = icon,
+ title = title,
+ trailing = {
+ TextButton(onClick = { onRemoveRule(rule.kind, rule.value) }) {
+ Text(stringResource(Res.string.settings_block_rule_remove))
+ }
+ },
+ )
+ }
+ }
+ if (state.contentBlockRules.size > 1) {
+ row { position ->
+ SettingRow(
+ position = position,
+ icon = Icons.Outlined.Restore,
+ title = stringResource(Res.string.settings_block_rules_clear),
+ onClick = { confirmingClearAll = true },
+ )
+ }
+ }
+ }
+ }
+ }
+ if (confirmingClearAll) {
+ AlertDialog(
+ onDismissRequest = { confirmingClearAll = false },
+ title = { Text(stringResource(Res.string.settings_block_rules_clear)) },
+ text = { Text(stringResource(Res.string.settings_block_rules_clear_message)) },
+ confirmButton = {
+ Button(
+ colors = ButtonDefaults.buttonColors(
+ containerColor = MaterialTheme.colorScheme.error,
+ contentColor = MaterialTheme.colorScheme.onError,
+ ),
+ onClick = {
+ confirmingClearAll = false
+ onClearAll()
+ },
+ ) { Text(stringResource(Res.string.settings_block_rules_clear)) }
+ },
+ dismissButton = {
+ TextButton(onClick = { confirmingClearAll = false }) {
+ Text(stringResource(Res.string.action_cancel))
+ }
+ },
+ )
+ }
+}
+
/**
* @param updater 应用内更新,不做的平台为 null。状态归它,不归这一页:在这里开始的下载,
* 离开设置页再回来还是那一份,开屏弹窗读的也是它。
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt
index 4a52f8b4..f42d61a5 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt
@@ -22,6 +22,7 @@ import androidx.lifecycle.viewModelScope
import dev.bilby.data.CodecPreference
import dev.bilby.agent.LlmClient
import dev.bilby.agent.LlmModelInfo
+import dev.bilby.data.ContentBlockRule
import dev.bilby.data.ExcludedUp
import dev.bilby.data.LlmConfig
import dev.bilby.data.NavigationPrefs
@@ -85,6 +86,8 @@ data class SettingsUiState(
val pbpOutroCompletion: Boolean = true,
/** 排除的 UP 主,名字已经带上。为空时那一行不显示 —— 没排除过的人不需要看见这个概念。 */
val excludedFeedUps: List = emptyList(),
+ /** 本地内容屏蔽规则(UP 主与关键词)。 */
+ val contentBlockRules: List = emptyList(),
/** 直播间要不要去 danmakus.com 补本场早前的醒目留言。见 SettingsStore.danmakusArchiveEnabled。 */
val danmakusArchive: Boolean = true,
val offlineConcurrency: Int = SettingsStore.DEFAULT_OFFLINE_CONCURRENCY,
@@ -294,6 +297,11 @@ class SettingsViewModel(
_state.update { it.copy(excludedFeedUps = ups) }
}
}
+ viewModelScope.launch {
+ settings.contentBlockRules.collect { rules ->
+ _state.update { it.copy(contentBlockRules = rules) }
+ }
+ }
viewModelScope.launch {
settings.danmakusArchiveEnabled.collect { enabled ->
_state.update { it.copy(danmakusArchive = enabled) }
@@ -319,6 +327,18 @@ class SettingsViewModel(
persist { settings.restoreFeedMid(mid) }
}
+ fun addBlockedKeyword(keyword: String) {
+ persist { settings.addBlockedKeyword(keyword) }
+ }
+
+ fun removeContentBlockRule(kind: ContentBlockRule.Kind, value: String) {
+ persist { settings.removeContentBlockRule(kind, value) }
+ }
+
+ fun clearContentBlockRules() {
+ persist { settings.clearContentBlockRules() }
+ }
+
fun setDanmakusArchive(enabled: Boolean) {
persist { settings.setDanmakusArchiveEnabled(enabled) }
}
diff --git a/shared/src/commonTest/kotlin/dev/bilby/data/ContentBlockMatcherTest.kt b/shared/src/commonTest/kotlin/dev/bilby/data/ContentBlockMatcherTest.kt
new file mode 100644
index 00000000..e3bbcecb
--- /dev/null
+++ b/shared/src/commonTest/kotlin/dev/bilby/data/ContentBlockMatcherTest.kt
@@ -0,0 +1,34 @@
+package dev.bilby.data
+
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ContentBlockMatcherTest {
+
+ @Test
+ fun `匹配器按 UP 主 mid 与大小写不敏感关键词过滤视频与用户`() {
+ val rules = listOf(
+ ContentBlockRule(ContentBlockRule.Kind.Up, "42", "某营销号"),
+ ContentBlockRule(ContentBlockRule.Kind.Keyword, "震惊", "震惊"),
+ ContentBlockRule(ContentBlockRule.Kind.Keyword, "clickbait", "ClickBait"),
+ )
+ val matcher = ContentBlockMatcher.fromRules(rules)
+
+ assertTrue(matcher.matchesVideo(upMid = 42L, upName = "某营销号", title = "正常标题"))
+ assertTrue(matcher.matchesVideo(upMid = 99L, upName = "路人", title = "太震惊了!必看"))
+ assertTrue(matcher.matchesVideo(upMid = 99L, upName = "ClickBait Studio", title = "普通视频"))
+ assertFalse(matcher.matchesVideo(upMid = 99L, upName = "科普君", title = "Compose 源码解析"))
+ assertTrue(matcher.matchesUser(mid = 42L, name = "改名后的号"))
+ assertTrue(matcher.matchesUser(mid = 77L, name = "震惊部"))
+ assertFalse(matcher.matchesUser(mid = 77L, name = "科普君"))
+ }
+
+ @Test
+ fun `空规则不命中任何条目`() {
+ val matcher = ContentBlockMatcher.fromRules(emptyList())
+ assertTrue(matcher.isEmpty)
+ assertFalse(matcher.matchesVideo(upMid = 1L, upName = "任意", title = "任意标题"))
+ assertFalse(matcher.matchesUser(mid = 1L, name = "任意"))
+ }
+}
From 00a20930e42820635bfded6a2b9f26977894c2c3 Mon Sep 17 00:00:00 2001
From: NihilDigit
Date: Mon, 30 Nov 2026 00:54:26 +0800
Subject: [PATCH 2/2] refactor(filter): decouple search creator block and
keyword filters from feed exclusions
---
.../composeResources/values-en/strings.xml | 30 +-
.../composeResources/values/strings.xml | 30 +-
.../kotlin/dev/bilby/api/dto/SearchDto.kt | 2 +
.../kotlin/dev/bilby/data/ContentBlockRule.kt | 69 ---
.../kotlin/dev/bilby/data/ContentFilter.kt | 183 ++++++++
.../kotlin/dev/bilby/data/DynamicFeedStore.kt | 32 +-
.../kotlin/dev/bilby/data/SearchRepository.kt | 2 +
.../kotlin/dev/bilby/data/SettingsStore.kt | 99 ++--
.../kotlin/dev/bilby/ui/BilbyApp.kt | 87 ++--
.../dev/bilby/ui/components/ContextMenuBox.kt | 27 --
.../bilby/ui/search/NormalSearchController.kt | 214 +++++++--
.../bilby/ui/search/SearchChatViewModel.kt | 2 +-
.../dev/bilby/ui/search/SearchResultScreen.kt | 6 +-
.../dev/bilby/ui/search/SearchResults.kt | 103 +++--
.../dev/bilby/ui/settings/SettingsPages.kt | 250 ++++++----
.../bilby/ui/settings/SettingsViewModel.kt | 22 +-
.../dev/bilby/data/ContentBlockMatcherTest.kt | 34 --
.../dev/bilby/data/ContentFilterTest.kt | 428 ++++++++++++++++++
18 files changed, 1194 insertions(+), 426 deletions(-)
delete mode 100644 shared/src/commonMain/kotlin/dev/bilby/data/ContentBlockRule.kt
create mode 100644 shared/src/commonMain/kotlin/dev/bilby/data/ContentFilter.kt
delete mode 100644 shared/src/commonTest/kotlin/dev/bilby/data/ContentBlockMatcherTest.kt
create mode 100644 shared/src/commonTest/kotlin/dev/bilby/data/ContentFilterTest.kt
diff --git a/shared/src/commonMain/composeResources/values-en/strings.xml b/shared/src/commonMain/composeResources/values-en/strings.xml
index 2d52f6ff..91e6a6b5 100644
--- a/shared/src/commonMain/composeResources/values-en/strings.xml
+++ b/shared/src/commonMain/composeResources/values-en/strings.xml
@@ -799,19 +799,23 @@
The exclusion list is emptied and posts from these uploaders return to the feed.
- Block this creator
- Blocked %1$s in feed and search
- Unblocked %1$s
- Local content filters
- Hide matching creators and title keywords locally in feed and search
- %1$d rules
- Keyword to block in titles or creator names
- Add
- Creator
- Remove
- No filter rules yet. Long-press any video to block a creator or add keywords here.
- Clear filter rules
- All blocked creator and keyword rules will be cleared.
+
+
+ Block creator in search
+ Blocked %1$s in search results
+ Hidden only in the subscription feed; still visible in search and profiles
+ Search & keyword filters
+ Hide selected creators in search and filter keywords in search and feed
+ %1$d rules
+ Blocked keywords
+ Enter a keyword for titles or posts
+ Add
+ No blocked keywords. Matching search results and subscription posts are hidden.
+ Blocked creators in search
+ No creators blocked in search. Add one from any search result menu.
+ Remove
+ Clear all rules
+ All search-blocked creators and keywords will be removed, and hidden items will appear again.
Disconnected
diff --git a/shared/src/commonMain/composeResources/values/strings.xml b/shared/src/commonMain/composeResources/values/strings.xml
index 2c711bdf..e03e4be7 100644
--- a/shared/src/commonMain/composeResources/values/strings.xml
+++ b/shared/src/commonMain/composeResources/values/strings.xml
@@ -864,19 +864,23 @@
排除名单会清空,这些 UP 主的投稿重新出现在动态里。
- 屏蔽这位 UP 主
- 已屏蔽 %1$s,动态与搜索将自动过滤
- 已取消屏蔽 %1$s
- 本地内容屏蔽
- 按 UP 主或标题关键词在动态与搜索中本地过滤
- %1$d 条规则
- 输入要屏蔽的标题或 UP 主关键词
- 添加
- UP
- 移除
- 暂无屏蔽规则,可长按视频屏蔽 UP 主或在此添加关键词
- 清空屏蔽规则
- 已添加的 UP 主与关键词屏蔽规则都会被清除。
+
+
+ 在搜索中屏蔽该 UP 主
+ 已在搜索结果中屏蔽 %1$s
+ 仅在订阅动态流中隐藏,主动搜索与个人空间照常可见
+ 搜索与关键词屏蔽
+ 隐藏搜索中的指定 UP 主,并按关键词过滤搜索与订阅动态
+ %1$d 项
+ 屏蔽关键词
+ 输入标题或动态正文关键词
+ 添加
+ 未添加屏蔽关键词,命中关键词的搜索结果与订阅动态会被隐藏。
+ 搜索屏蔽的 UP 主
+ 未在搜索中屏蔽任何 UP 主,可在搜索结果菜单中添加。
+ 移除
+ 清空全部规则
+ 搜索屏蔽的 UP 主与关键词列表都会被清空,相关内容将重新显示。
连接已断开
diff --git a/shared/src/commonMain/kotlin/dev/bilby/api/dto/SearchDto.kt b/shared/src/commonMain/kotlin/dev/bilby/api/dto/SearchDto.kt
index c92bb77c..1735a6b1 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/api/dto/SearchDto.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/api/dto/SearchDto.kt
@@ -80,6 +80,8 @@ data class SearchSuggestDto(
data class SearchArticleItemDto(
/** cv 号。 */
val id: Long = 0,
+ /** 作者 mid。专栏搜索接口不返回作者名,只返回 mid。 */
+ val mid: Long = 0,
/** 带 `` 高亮与 HTML 实体,同视频标题。 */
val title: String = "",
val desc: String = "",
diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/ContentBlockRule.kt b/shared/src/commonMain/kotlin/dev/bilby/data/ContentBlockRule.kt
deleted file mode 100644
index f5d70dfd..00000000
--- a/shared/src/commonMain/kotlin/dev/bilby/data/ContentBlockRule.kt
+++ /dev/null
@@ -1,69 +0,0 @@
-package dev.bilby.data
-
-import kotlinx.serialization.Serializable
-
-/**
- * 本地内容屏蔽规则:按 UP 主 mid 或标题/UP 名关键词(忽略大小写)在动态流与搜索结果中实时过滤。
- */
-@Serializable
-data class ContentBlockRule(
- val kind: Kind,
- val value: String,
- val label: String,
-) {
- @Serializable
- enum class Kind { Up, Keyword }
-}
-
-/**
- * 由 [ContentBlockRule] 列表编译出的不可变匹配器。
- */
-data class ContentBlockMatcher(
- val blockedUpMids: Set = emptySet(),
- val blockedKeywords: List = emptyList(),
-) {
- val isEmpty: Boolean get() = blockedUpMids.isEmpty() && blockedKeywords.isEmpty()
-
- fun matchesVideo(
- upMid: Long = 0L,
- upName: String = "",
- title: String = "",
- ): Boolean {
- if (upMid != 0L && upMid in blockedUpMids) return true
- if (blockedKeywords.isNotEmpty()) {
- for (kw in blockedKeywords) {
- if (title.contains(kw, ignoreCase = true) || upName.contains(kw, ignoreCase = true)) {
- return true
- }
- }
- }
- return false
- }
-
- fun matchesUser(mid: Long, name: String): Boolean {
- if (mid != 0L && mid in blockedUpMids) return true
- if (blockedKeywords.isNotEmpty()) {
- for (kw in blockedKeywords) {
- if (name.contains(kw, ignoreCase = true)) return true
- }
- }
- return false
- }
-
- companion object {
- val EMPTY = ContentBlockMatcher()
-
- fun fromRules(rules: List): ContentBlockMatcher {
- if (rules.isEmpty()) return EMPTY
- val mids = mutableSetOf()
- val keywords = mutableListOf()
- for (rule in rules) {
- when (rule.kind) {
- ContentBlockRule.Kind.Up -> rule.value.toLongOrNull()?.takeIf { it > 0L }?.let { mids += it }
- ContentBlockRule.Kind.Keyword -> rule.value.trim().takeIf { it.isNotEmpty() }?.let { keywords += it }
- }
- }
- return ContentBlockMatcher(blockedUpMids = mids, blockedKeywords = keywords)
- }
- }
-}
diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/ContentFilter.kt b/shared/src/commonMain/kotlin/dev/bilby/data/ContentFilter.kt
new file mode 100644
index 00000000..7361df5d
--- /dev/null
+++ b/shared/src/commonMain/kotlin/dev/bilby/data/ContentFilter.kt
@@ -0,0 +1,183 @@
+package dev.bilby.data
+
+import androidx.compose.runtime.Immutable
+import dev.bilby.data.model.DynamicAdditional
+import dev.bilby.data.model.DynamicCard
+import dev.bilby.data.model.DynamicContent
+import dev.bilby.data.model.FeedEntry
+import dev.bilby.data.model.RichSpan
+import dev.bilby.data.model.plainText
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.Transient
+
+/**
+ * 在搜索结果中被屏蔽的 UP 主。
+ *
+ * 与订阅流的 [ExcludedUp] 严格正交:这里只过滤搜索结果里的视频与专栏,不影响订阅动态流、
+ * 个人空间、合集、收藏夹、历史记录、稍后再看与离线缓存。
+ */
+@Immutable
+@Serializable
+data class BlockedSearchUp(
+ val mid: Long,
+ val name: String,
+)
+
+/**
+ * 搜索与关键词本地过滤偏好。
+ *
+ * - [blockedSearchUps]:仅作用于搜索结果(视频与专栏),不侵入订阅动态流与其他页面。
+ * - [keywords]:纯文本大小写不敏感子串匹配(不用正则防回溯),作用于搜索结果(视频标题、
+ * 专栏标题与摘要)与主页订阅动态流(视频标题、专栏标题与摘要、动态正文与转发原帖正文/标题)。
+ */
+@Immutable
+@Serializable
+data class ContentFilterPrefs(
+ val blockedSearchUps: List = emptyList(),
+ val keywords: List = emptyList(),
+) {
+ @Transient
+ private val blockedMidSet: Set = if (blockedSearchUps.isEmpty()) {
+ emptySet()
+ } else {
+ blockedSearchUps.mapTo(HashSet(blockedSearchUps.size)) { it.mid }
+ }
+
+ @Transient
+ private val effectiveKeywords: List = if (keywords.isEmpty()) {
+ emptyList()
+ } else {
+ keywords.mapNotNull { it.trim().takeIf(String::isNotEmpty) }
+ }
+
+ val isEmpty: Boolean
+ get() = blockedSearchUps.isEmpty() && effectiveKeywords.isEmpty()
+
+ val hasKeywordFilters: Boolean
+ get() = effectiveKeywords.isNotEmpty()
+
+ val hasSearchFilters: Boolean
+ get() = blockedMidSet.isNotEmpty() || effectiveKeywords.isNotEmpty()
+
+ val totalRuleCount: Int
+ get() = blockedSearchUps.size + effectiveKeywords.size
+
+ fun sanitized(): ContentFilterPrefs {
+ val cleanedUps = blockedSearchUps
+ .asSequence()
+ .filter { it.mid != 0L }
+ .distinctBy { it.mid }
+ .map { up -> up.copy(name = up.name.trim().ifBlank { up.mid.toString() }) }
+ .toList()
+ val cleanedKeywords = keywords
+ .asSequence()
+ .map(String::trim)
+ .filter(String::isNotEmpty)
+ .distinctBy(String::lowercase)
+ .toList()
+ return ContentFilterPrefs(
+ blockedSearchUps = cleanedUps,
+ keywords = cleanedKeywords,
+ )
+ }
+
+ fun matchesSearchVideo(video: SearchVideo): Boolean =
+ matchesSearchVideo(upMid = video.upMid, title = video.title)
+
+ fun matchesSearchVideo(upMid: Long, title: String): Boolean {
+ if (upMid != 0L && upMid in blockedMidSet) return true
+ return containsAnyKeyword(title)
+ }
+
+ fun matchesSearchArticle(article: SearchArticle): Boolean =
+ matchesSearchArticle(
+ authorMid = article.authorMid,
+ title = article.title,
+ summary = article.summary,
+ )
+
+ fun matchesSearchArticle(authorMid: Long, title: String, summary: String): Boolean {
+ if (authorMid != 0L && authorMid in blockedMidSet) return true
+ return containsAnyKeyword(title) || containsAnyKeyword(summary)
+ }
+
+ /**
+ * 首页订阅流(投稿视频与专栏)过滤:**仅应用关键词**,不应用 [blockedSearchUps]。
+ */
+ fun matchesFeedEntry(entry: FeedEntry): Boolean {
+ if (effectiveKeywords.isEmpty()) return false
+ return when (entry) {
+ is FeedEntry.Video -> containsAnyKeyword(entry.title)
+ is FeedEntry.Article -> containsAnyKeyword(entry.title) || containsAnyKeyword(entry.summary)
+ }
+ }
+
+ /**
+ * 订阅动态流(图文、纯文字、转发动态等)过滤:**仅应用关键词**,覆盖正文、内嵌内容标题
+ * 与转发原帖正文/标题,不应用 [blockedSearchUps]。
+ */
+ fun matchesFeedEntry(card: DynamicCard): Boolean = matchesDynamicCard(card)
+
+ fun matchesDynamicCard(card: DynamicCard): Boolean {
+ if (effectiveKeywords.isEmpty()) return false
+ return matchesDynamicCard(card, depth = 0)
+ }
+
+ private fun matchesDynamicCard(card: DynamicCard, depth: Int): Boolean {
+ if (matchesRichText(card.text)) return true
+ if (card.topic != null && containsAnyKeyword(card.topic)) return true
+ if (matchesDynamicContent(card.content)) return true
+ if (matchesDynamicAdditional(card.additional)) return true
+ val forwarded = card.forwarded
+ if (forwarded != null && depth < MAX_FORWARD_DEPTH) {
+ return matchesDynamicCard(forwarded, depth + 1)
+ }
+ return false
+ }
+
+ private fun matchesRichText(spans: List): Boolean {
+ when (spans.size) {
+ 0 -> return false
+ 1 -> return containsAnyKeyword(spans[0].plainText)
+ else -> {
+ for (i in spans.indices) {
+ if (containsAnyKeyword(spans[i].plainText)) return true
+ }
+ return containsAnyKeyword(spans.plainText())
+ }
+ }
+ }
+
+ private fun matchesDynamicContent(content: DynamicContent?): Boolean = when (content) {
+ null -> false
+ is DynamicContent.Video -> containsAnyKeyword(content.title)
+ is DynamicContent.Season -> containsAnyKeyword(content.title)
+ is DynamicContent.Live -> containsAnyKeyword(content.title)
+ is DynamicContent.Music -> containsAnyKeyword(content.title)
+ is DynamicContent.Medialist -> containsAnyKeyword(content.title) || containsAnyKeyword(content.subTitle)
+ is DynamicContent.Common -> containsAnyKeyword(content.title) || containsAnyKeyword(content.description)
+ is DynamicContent.Images,
+ is DynamicContent.Gone,
+ -> false
+ }
+
+ private fun matchesDynamicAdditional(additional: DynamicAdditional?): Boolean = when (additional) {
+ null -> false
+ is DynamicAdditional.Vote -> containsAnyKeyword(additional.title)
+ is DynamicAdditional.Reserve -> containsAnyKeyword(additional.title) || containsAnyKeyword(additional.description)
+ is DynamicAdditional.Video -> containsAnyKeyword(additional.title) || containsAnyKeyword(additional.description)
+ is DynamicAdditional.Common -> containsAnyKeyword(additional.title) || containsAnyKeyword(additional.description)
+ }
+
+ private fun containsAnyKeyword(text: String): Boolean {
+ if (text.isEmpty() || effectiveKeywords.isEmpty()) return false
+ for (i in effectiveKeywords.indices) {
+ if (text.contains(effectiveKeywords[i], ignoreCase = true)) return true
+ }
+ return false
+ }
+
+ companion object {
+ private const val MAX_FORWARD_DEPTH = 4
+ }
+}
diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/DynamicFeedStore.kt b/shared/src/commonMain/kotlin/dev/bilby/data/DynamicFeedStore.kt
index 5a62fbc2..6d855c01 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/data/DynamicFeedStore.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/data/DynamicFeedStore.kt
@@ -6,7 +6,6 @@ import dev.bilby.api.BiliResult
import dev.bilby.data.db.FeedCacheRepository
import dev.bilby.data.model.DynamicCard
import dev.bilby.data.model.FeedEntry
-import dev.bilby.data.model.plainText
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -54,31 +53,24 @@ class DynamicFeedStore(
val home: Flow> = combine(
_home,
settings.excludedFeedMids,
- settings.contentBlockMatcher,
- ) { items, excluded, matcher ->
- items.filterNot { entry ->
- if (entry.upMid in excluded) return@filterNot true
- if (matcher.isEmpty) return@filterNot false
- val title = when (entry) {
- is FeedEntry.Video -> entry.title
- is FeedEntry.Article -> entry.title
- }
- matcher.matchesVideo(upMid = entry.upMid, upName = entry.upName, title = title)
+ settings.contentFilterPrefs,
+ ) { items, excluded, filter ->
+ if (excluded.isEmpty() && !filter.hasKeywordFilters) {
+ items
+ } else {
+ items.filterNot { it.upMid in excluded || filter.matchesFeedEntry(it) }
}
}
val other: Flow> = combine(
_other,
settings.excludedFeedMids,
- settings.contentBlockMatcher,
- ) { cards, excluded, matcher ->
- cards.filterNot { card ->
- card.author.mid in excluded ||
- (!matcher.isEmpty && matcher.matchesVideo(
- upMid = card.author.mid,
- upName = card.author.name,
- title = card.text.plainText(),
- ))
+ settings.contentFilterPrefs,
+ ) { cards, excluded, filter ->
+ if (excluded.isEmpty() && !filter.hasKeywordFilters) {
+ cards
+ } else {
+ cards.filterNot { it.author.mid in excluded || filter.matchesDynamicCard(it) }
}
}
diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/SearchRepository.kt b/shared/src/commonMain/kotlin/dev/bilby/data/SearchRepository.kt
index 4210062c..21ade566 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/data/SearchRepository.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/data/SearchRepository.kt
@@ -57,6 +57,7 @@ data class SearchArticle(
val publishedAtEpochSeconds: Long,
val categoryName: String,
val titleHighlights: List = emptyList(),
+ val authorMid: Long = 0L,
)
data class SearchVideoPage(val items: List, val hasMore: Boolean)
@@ -220,6 +221,7 @@ class SearchRepository(private val client: BiliClient) {
replyCount = reply,
publishedAtEpochSeconds = pubTime,
categoryName = categoryName,
+ authorMid = mid,
)
}
diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/SettingsStore.kt b/shared/src/commonMain/kotlin/dev/bilby/data/SettingsStore.kt
index 4c0263f3..2a522697 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/data/SettingsStore.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/data/SettingsStore.kt
@@ -496,67 +496,70 @@ class SettingsStore(private val store: DataStore) {
store.edit { p -> p.remove(KEY_EXCLUDED_FEED_MIDS) }
}
- /** 本地内容屏蔽规则(UP 主与标题/UP 名关键词),用于动态与搜索实时过滤。 */
- val contentBlockRules: Flow> = store.data.map { p ->
- decodeContentBlockRules(p[KEY_CONTENT_BLOCK_RULES])
+ /**
+ * 搜索与关键词本地过滤偏好,与 [excludedFeedMids] 严格正交。
+ * 见 [ContentFilterPrefs]。
+ */
+ val contentFilterPrefs: Flow = store.data.map { p ->
+ decodeContentFilterPrefs(p[KEY_CONTENT_FILTER_JSON])
}
- val contentBlockMatcher: Flow = contentBlockRules.map(ContentBlockMatcher::fromRules)
-
- suspend fun addBlockedUp(mid: Long, name: String) {
- if (mid <= 0L) return
- val value = mid.toString()
- val label = name.ifBlank { "UID $mid" }
+ suspend fun addBlockedSearchUp(mid: Long, name: String) {
+ if (mid == 0L) return
+ val label = name.trim().ifBlank { mid.toString() }
store.edit { p ->
- val current = decodeContentBlockRules(p[KEY_CONTENT_BLOCK_RULES])
- .filterNot { it.kind == ContentBlockRule.Kind.Up && it.value == value }
- val updated = listOf(ContentBlockRule(ContentBlockRule.Kind.Up, value, label)) + current
- p[KEY_CONTENT_BLOCK_RULES] = encodeContentBlockRules(updated)
+ val current = decodeContentFilterPrefs(p[KEY_CONTENT_FILTER_JSON])
+ val nextUps = listOf(BlockedSearchUp(mid = mid, name = label)) +
+ current.blockedSearchUps.filterNot { it.mid == mid }
+ writeContentFilterPrefs(p, current.copy(blockedSearchUps = nextUps))
}
}
- suspend fun removeBlockedUp(mid: Long) {
- removeContentBlockRule(ContentBlockRule.Kind.Up, mid.toString())
+ suspend fun removeBlockedSearchUp(mid: Long) {
+ store.edit { p ->
+ val current = decodeContentFilterPrefs(p[KEY_CONTENT_FILTER_JSON])
+ val nextUps = current.blockedSearchUps.filterNot { it.mid == mid }
+ writeContentFilterPrefs(p, current.copy(blockedSearchUps = nextUps))
+ }
}
- suspend fun addBlockedKeyword(keyword: String): Boolean {
+ suspend fun addBlockedKeyword(keyword: String) {
val trimmed = keyword.trim()
- if (trimmed.isEmpty()) return false
- val normalized = trimmed.lowercase()
+ if (trimmed.isEmpty()) return
store.edit { p ->
- val current = decodeContentBlockRules(p[KEY_CONTENT_BLOCK_RULES])
- .filterNot { it.kind == ContentBlockRule.Kind.Keyword && it.value == normalized }
- val updated = listOf(ContentBlockRule(ContentBlockRule.Kind.Keyword, normalized, trimmed)) + current
- p[KEY_CONTENT_BLOCK_RULES] = encodeContentBlockRules(updated)
+ val current = decodeContentFilterPrefs(p[KEY_CONTENT_FILTER_JSON])
+ val nextKeywords = listOf(trimmed) +
+ current.keywords.filterNot { it.equals(trimmed, ignoreCase = true) }
+ writeContentFilterPrefs(p, current.copy(keywords = nextKeywords))
}
- return true
}
- suspend fun removeContentBlockRule(kind: ContentBlockRule.Kind, value: String) {
+ suspend fun removeBlockedKeyword(keyword: String) {
+ val trimmed = keyword.trim()
+ if (trimmed.isEmpty()) return
store.edit { p ->
- val updated = decodeContentBlockRules(p[KEY_CONTENT_BLOCK_RULES])
- .filterNot { it.kind == kind && it.value == value }
- if (updated.isEmpty()) p.remove(KEY_CONTENT_BLOCK_RULES)
- else p[KEY_CONTENT_BLOCK_RULES] = encodeContentBlockRules(updated)
+ val current = decodeContentFilterPrefs(p[KEY_CONTENT_FILTER_JSON])
+ val nextKeywords = current.keywords.filterNot { it.equals(trimmed, ignoreCase = true) }
+ writeContentFilterPrefs(p, current.copy(keywords = nextKeywords))
}
}
- suspend fun clearContentBlockRules() {
- store.edit { p -> p.remove(KEY_CONTENT_BLOCK_RULES) }
+ suspend fun clearContentFilters() {
+ store.edit { p -> p.remove(KEY_CONTENT_FILTER_JSON) }
}
- private fun decodeContentBlockRules(raw: String?): List {
- if (raw.isNullOrBlank()) return emptyList()
- return runCatching {
- ContentBlockRulesJson.decodeFromString(ListSerializer(ContentBlockRule.serializer()), raw)
- }.onFailure { cause ->
- BiliLog.w("解析本地屏蔽规则失败: ${cause.message}", cause)
- }.getOrDefault(emptyList())
+ private fun writeContentFilterPrefs(
+ prefs: androidx.datastore.preferences.core.MutablePreferences,
+ value: ContentFilterPrefs,
+ ) {
+ val sanitized = value.sanitized()
+ if (sanitized.isEmpty) {
+ prefs.remove(KEY_CONTENT_FILTER_JSON)
+ } else {
+ prefs[KEY_CONTENT_FILTER_JSON] = encodeContentFilterPrefs(sanitized)
+ }
}
- private fun encodeContentBlockRules(rules: List): String =
- ContentBlockRulesJson.encodeToString(ListSerializer(ContentBlockRule.serializer()), rules)
-
/**
* 普通搜索的历史,最近的在前。
*
@@ -883,7 +886,7 @@ class SettingsStore(private val store: DataStore) {
private val KEY_DANMAKU_IN_PIP = booleanPreferencesKey("danmaku_in_pip")
private val KEY_DANMAKU_FONT_SCALE = floatPreferencesKey("danmaku_font_scale")
private val KEY_EXCLUDED_FEED_MIDS = stringSetPreferencesKey("excluded_feed_mids")
- private val KEY_CONTENT_BLOCK_RULES = stringPreferencesKey("content_block_rules")
+ private val KEY_CONTENT_FILTER_JSON = stringPreferencesKey("content_filter_json")
private val KEY_DANMAKUS_ARCHIVE = booleanPreferencesKey("danmakus_archive_enabled")
@@ -1227,10 +1230,22 @@ private data class ScheduleRuleDto(
)
private val NightUpsJson = Json { ignoreUnknownKeys = true }
-private val ContentBlockRulesJson = Json { ignoreUnknownKeys = true }
private val NightUpsSerializer = ListSerializer(WhitelistedUpDto.serializer())
private val ScheduleRulesJson = Json { ignoreUnknownKeys = true; encodeDefaults = true }
private val ScheduleRulesSerializer = ListSerializer(ScheduleRuleDto.serializer())
+private val ContentFilterJson = Json { ignoreUnknownKeys = true; encodeDefaults = true }
+
+private fun encodeContentFilterPrefs(prefs: ContentFilterPrefs): String =
+ ContentFilterJson.encodeToString(ContentFilterPrefs.serializer(), prefs.sanitized())
+
+private fun decodeContentFilterPrefs(raw: String?): ContentFilterPrefs {
+ if (raw.isNullOrBlank()) return ContentFilterPrefs()
+ return runCatching {
+ ContentFilterJson.decodeFromString(ContentFilterPrefs.serializer(), raw).sanitized()
+ }.onFailure {
+ BiliLog.w("内容屏蔽规则解析失败: ${it.message}")
+ }.getOrDefault(ContentFilterPrefs())
+}
private fun decodeNightUps(raw: String?): List {
if (raw.isNullOrBlank()) return emptyList()
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt
index 1b8c99f1..c7b011e8 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt
@@ -2,10 +2,7 @@ package dev.bilby.ui
import dev.bilby.ui.components.BilbySearchTopBar
import dev.bilby.ui.components.EditableFocusTracker
-import dev.bilby.ui.components.LocalContentBlockMatcher
import dev.bilby.ui.components.LocalCopyNotice
-import dev.bilby.ui.components.LocalVideoBlockActions
-import dev.bilby.ui.components.VideoBlockActions
import dev.bilby.ui.components.LocalEditableFocusTracker
import dev.bilby.ui.components.LocalPageRefreshRegistry
import dev.bilby.ui.components.LocalPageSearchRegistry
@@ -154,6 +151,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
+import dev.bilby.getString
import dev.bilby.stringResource
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.lifecycle.compose.collectAsStateWithLifecycle
@@ -292,7 +290,7 @@ import dev.bilby.ui.settings.PlayerCustomizationPage
import dev.bilby.ui.settings.PlaybackSettingsPage
import dev.bilby.data.model.ArticleRef
import dev.bilby.data.model.FeedEntry
-import dev.bilby.ui.settings.BlockRulesPage
+import dev.bilby.ui.settings.ContentFilterSettingsPage
import dev.bilby.ui.settings.ExcludedFeedPage
import dev.bilby.ui.settings.PrivacySettingsPage
import dev.bilby.ui.settings.SettingsScreen
@@ -1041,6 +1039,28 @@ private fun BilbyApp(
}
}
}
+ val blockUpInSearch: (Long, String) -> Unit = remember(container, snackbarHostState, snackbarScope) {
+ { mid, name ->
+ if (mid != 0L) {
+ val displayName = name.trim().ifBlank { "UID $mid" }
+ container.persistScope.launch {
+ container.settings.addBlockedSearchUp(mid, displayName)
+ }
+ snackbarScope.launch {
+ val result = snackbarHostState.showSnackbar(
+ message = getString(Res.string.search_block_up_added, displayName),
+ actionLabel = getString(Res.string.action_undo),
+ duration = SnackbarDuration.Short,
+ )
+ if (result == SnackbarResult.ActionPerformed) {
+ container.persistScope.launch {
+ container.settings.removeBlockedSearchUp(mid)
+ }
+ }
+ }
+ }
+ }
+ }
val playDraftQueue: (String?) -> Unit = { chosenBvid ->
val taken = container.customQueueDraft.consumeAll()
if (taken.isNotEmpty()) {
@@ -1159,36 +1179,7 @@ private fun BilbyApp(
}
}
- val contentBlockMatcher by remember(container) {
- container.settings.contentBlockMatcher
- }.collectAsStateWithLifecycle(initialValue = dev.bilby.data.ContentBlockMatcher.EMPTY)
- val undoLabel = stringResource(Res.string.action_undo)
- val videoBlockActions = remember(container, snackbarHostState, snackbarScope, undoLabel) {
- VideoBlockActions { upMid, upName ->
- snackbarScope.launch {
- val label = upName.ifBlank { "UID $upMid" }
- container.settings.addBlockedUp(mid = upMid, name = label)
- val res = snackbarHostState.showSnackbar(
- message = dev.bilby.getString(Res.string.block_up_added, label),
- actionLabel = undoLabel,
- duration = SnackbarDuration.Short,
- )
- if (res == SnackbarResult.ActionPerformed) {
- container.settings.removeBlockedUp(upMid)
- snackbarHostState.showSnackbar(
- dev.bilby.getString(Res.string.block_up_undone, label),
- duration = SnackbarDuration.Short,
- )
- }
- }
- }
- }
-
- CompositionLocalProvider(
- LocalQueueActions provides queueMenuActions,
- LocalVideoBlockActions provides videoBlockActions,
- LocalContentBlockMatcher provides contentBlockMatcher,
- ) {
+ CompositionLocalProvider(LocalQueueActions provides queueMenuActions) {
Box(
modifier = Modifier
.fillMaxSize()
@@ -1444,6 +1435,7 @@ private fun BilbyApp(
onOpenFavFolders = { push(FavFolders) },
onOpenMessages = { push(Messages) },
onOpen = { push(it) },
+ onBlockUpInSearch = blockUpInSearch,
)
}
}
@@ -1578,6 +1570,7 @@ private fun BilbyApp(
onVideoClick = { push(Video(it)) },
onUserClick = { push(Space(it)) },
onArticleClick = { cv -> push(ArticlePage(cv.toString(), isRead = true)) },
+ onBlockUpInSearch = blockUpInSearch,
onBack = { backStack.removeLastOrNull() },
)
}
@@ -2121,6 +2114,7 @@ private fun RootTabs(
onOpenMessages: () -> Unit,
/** 搜索框里的编号或链接直接打开的那一页,可以是任何一种目的地。 */
onOpen: (NavKey) -> Unit,
+ onBlockUpInSearch: (Long, String) -> Unit,
) {
val cleanNavPrefs = remember(navigationPrefs) { navigationPrefs.sanitize() }
val visibleTabs = remember(cleanNavPrefs.primaryTabs) {
@@ -2217,6 +2211,7 @@ private fun RootTabs(
onOpenFavFolders = onOpenFavFolders,
onOpenMessages = onOpenMessages,
onOpen = onOpen,
+ onBlockUpInSearch = onBlockUpInSearch,
)
}
}
@@ -2257,6 +2252,7 @@ private fun RootTabs(
onOpenFavFolders = onOpenFavFolders,
onOpenMessages = onOpenMessages,
onOpen = onOpen,
+ onBlockUpInSearch = onBlockUpInSearch,
)
}
}
@@ -2753,6 +2749,7 @@ private fun RootTabsContent(
onOpenFavFolders: () -> Unit,
onOpenMessages: () -> Unit,
onOpen: (NavKey) -> Unit,
+ onBlockUpInSearch: (Long, String) -> Unit,
) {
val bottom = PaddingValues(bottom = insets.calculateBottomPadding())
Box(
@@ -2794,6 +2791,7 @@ private fun RootTabsContent(
onUserClick = onUserClick,
onOpenArticle = onOpenArticle,
onOpen = onOpen,
+ onBlockUpInSearch = onBlockUpInSearch,
)
RootTab.Profile -> ProfilePane(
@@ -3052,6 +3050,7 @@ private fun SearchPane(
onUserClick: (Long) -> Unit,
onOpenArticle: (ArticleRef) -> Unit,
onOpen: (NavKey) -> Unit,
+ onBlockUpInSearch: (Long, String) -> Unit,
) {
val vm: SearchChatViewModel = viewModel(
key = "root-search",
@@ -3132,6 +3131,7 @@ private fun SearchPane(
onArticleClick = { cv -> onOpenArticle(ArticleRef(cv.toString(), isRead = true)) },
onLoadMore = vm::loadMore,
onRetry = vm::refresh,
+ onBlockUpInSearch = onBlockUpInSearch,
),
)
}
@@ -3143,12 +3143,19 @@ private fun SearchResultRoute(
onVideoClick: (String) -> Unit,
onUserClick: (Long) -> Unit,
onArticleClick: (Long) -> Unit,
+ onBlockUpInSearch: (Long, String) -> Unit,
onBack: () -> Unit,
) {
// keyword 是这个目的地的身份,同一个词压两次由 pushUnique 挡住,不需要 switchTo。
val vm: SearchResultViewModel = viewModel(
factory = viewModelFactory {
- initializer { SearchResultViewModel(keyword, container.searchRepository) }
+ initializer {
+ SearchResultViewModel(
+ keyword = keyword,
+ searchRepository = container.searchRepository,
+ contentFilter = container.settings.contentFilterPrefs,
+ )
+ }
},
)
val state by vm.state.collectAsStateWithLifecycle()
@@ -3193,6 +3200,7 @@ private fun SearchResultRoute(
onArticleClick = onArticleClick,
onLoadMore = vm::loadMore,
onRetry = vm::retry,
+ onBlockUpInSearch = onBlockUpInSearch,
),
modifier = Modifier.padScaffoldExceptBottom(insets),
)
@@ -3383,7 +3391,7 @@ private fun SettingsPageRoute(
onRetryHistoryPause = vm::loadHistoryPause,
onOpenBlacklist = onOpenBlacklist,
onOpenExcludedFeed = { onOpenSection(SettingsSection.ExcludedFeed) },
- onOpenBlockRules = { onOpenSection(SettingsSection.BlockRules) },
+ onOpenContentFilter = { onOpenSection(SettingsSection.ContentFilter) },
onDanmakusArchiveChange = vm::setDanmakusArchive,
onBack = onBack,
)
@@ -3396,11 +3404,12 @@ private fun SettingsPageRoute(
onBack = onBack,
)
- SettingsSection.BlockRules -> BlockRulesPage(
+ SettingsSection.ContentFilter -> ContentFilterSettingsPage(
state = state,
onAddKeyword = vm::addBlockedKeyword,
- onRemoveRule = vm::removeContentBlockRule,
- onClearAll = vm::clearContentBlockRules,
+ onRemoveKeyword = vm::removeBlockedKeyword,
+ onRemoveSearchUp = vm::removeBlockedSearchUp,
+ onClearAll = vm::clearContentFilters,
onBack = onBack,
)
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/components/ContextMenuBox.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/components/ContextMenuBox.kt
index 3fc74287..cc814f9e 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/components/ContextMenuBox.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/components/ContextMenuBox.kt
@@ -13,7 +13,6 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.PlaylistAdd
import androidx.compose.material.icons.automirrored.outlined.PlaylistPlay
-import androidx.compose.material.icons.outlined.Block
import androidx.compose.material.icons.outlined.ContentCopy
import androidx.compose.material.icons.outlined.Link
import androidx.compose.material.icons.outlined.Person
@@ -62,13 +61,11 @@ import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.round
-import dev.bilby.data.ContentBlockMatcher
import dev.bilby.player.QueueItem
import dev.bilby.resources.Res
import dev.bilby.resources.action_copy_title
import dev.bilby.resources.action_share
import dev.bilby.resources.comment_copied
-import dev.bilby.resources.menu_block_up
import dev.bilby.resources.menu_copy_link
import dev.bilby.resources.menu_open_space
import dev.bilby.resources.queue_add
@@ -97,16 +94,6 @@ data class QueueMenuActions(
val LocalQueueActions = staticCompositionLocalOf { null }
-/** 视频列表项右键/长按本地屏蔽 UP 主动作,由根部 [dev.bilby.ui.BilbyApp] 提供。 */
-data class VideoBlockActions(
- val blockUp: (upMid: Long, upName: String) -> Unit,
-)
-
-val LocalVideoBlockActions = staticCompositionLocalOf { null }
-
-/** 本地内容屏蔽匹配器,供搜索结果等列表实时过滤。 */
-val LocalContentBlockMatcher = staticCompositionLocalOf { ContentBlockMatcher.EMPTY }
-
/**
* 桌面右键菜单的动效方案:去掉移动端 `DropdownMenu` 默认的 `0.8 -> 1.0` 缩放弹簧,保留极短的
* 80ms 淡入淡出,让指针所指之处即点即出。
@@ -329,7 +316,6 @@ fun videoCommonMenuItemCount(
if (includeQueueActions && LocalQueueActions.current != null) count += 2
if (title == null || title.isNotBlank()) count += 1
count += 2
- if (upMid != 0L && LocalVideoBlockActions.current != null) count += 1
}
if (upMid != 0L && onOpenUpSpace != null) count += 1
return count
@@ -355,7 +341,6 @@ fun VideoCommonMenuItems(
) {
val system = LocalSystemActions.current
val queueActions = LocalQueueActions.current.takeIf { includeQueueActions }
- val blockActions = LocalVideoBlockActions.current
val copyTitle = rememberCopyAction()
val copyBvid = rememberCopyAction(
clipLabel = stringResource(Res.string.video_bvid_clip_label),
@@ -431,18 +416,6 @@ fun VideoCommonMenuItems(
},
shape = menuItemShape(shareIndex, totalCount),
)
- if (upMid != 0L && blockActions != null) {
- val blockUpIndex = cursor++
- DropdownMenuItem(
- onClick = {
- close()
- blockActions.blockUp(upMid, upName)
- },
- text = { Text(stringResource(Res.string.menu_block_up)) },
- leadingIcon = { Icon(Icons.Outlined.Block, contentDescription = null) },
- shape = menuItemShape(blockUpIndex, totalCount),
- )
- }
}
if (upMid != 0L && onOpenUpSpace != null) {
val spaceIndex = cursor
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/search/NormalSearchController.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/search/NormalSearchController.kt
index 866ed41f..bad598a9 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/search/NormalSearchController.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/search/NormalSearchController.kt
@@ -10,17 +10,21 @@ import dev.bilby.api.CODE_RISK_CHALLENGE
import java.time.LocalDate
import java.time.ZoneId
import dev.bilby.api.map
+import dev.bilby.data.ContentFilterPrefs
import dev.bilby.data.SearchArticle
import dev.bilby.data.SearchPage
import dev.bilby.data.SearchRepository
import dev.bilby.data.SearchUser
import dev.bilby.data.SearchVideo
import java.io.IOException
+import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
+import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
@@ -138,30 +142,80 @@ data class NormalSearchState(
*
* 生命周期跟着 [scope] 走,宿主用自己的 viewModelScope 传进来即可,不需要另行清理。
*/
-class NormalSearchController(
+class NormalSearchController internal constructor(
private val scope: CoroutineScope,
- private val searchRepository: SearchRepository,
+ private val contentFilter: Flow,
+ private val fetchVideos: suspend (
+ query: String,
+ page: Int,
+ order: SearchOrder,
+ duration: SearchDuration,
+ pubTime: SearchPubTime,
+ zone: SearchZone,
+ ) -> BiliResult>,
+ private val fetchUsers: suspend (
+ query: String,
+ page: Int,
+ order: SearchUserOrder,
+ ) -> BiliResult>,
+ private val fetchArticles: suspend (
+ query: String,
+ page: Int,
+ order: SearchOrder,
+ ) -> BiliResult>,
) {
+ constructor(
+ scope: CoroutineScope,
+ searchRepository: SearchRepository,
+ contentFilter: Flow = flowOf(ContentFilterPrefs()),
+ ) : this(
+ scope = scope,
+ contentFilter = contentFilter,
+ fetchVideos = { query, page, order, duration, pubTime, zone ->
+ searchRepository.searchVideos(
+ keyword = query,
+ page = page,
+ order = order.apiValue,
+ duration = duration.apiValue.takeIf { it != 0 },
+ tids = zone.tids,
+ pubTime = pubTime.window(),
+ ).map { SearchPage(it.items, it.hasMore) }
+ },
+ fetchUsers = { query, page, order ->
+ searchRepository.searchUserPage(query, page, order.apiValue, order.ascending)
+ },
+ fetchArticles = { query, page, order ->
+ searchRepository.searchArticles(query, page, order.apiValue)
+ },
+ )
+
private val _state = MutableStateFlow(NormalSearchState())
val state: StateFlow = _state.asStateFlow()
+ private var currentFilter: ContentFilterPrefs =
+ (contentFilter as? StateFlow)?.value ?: ContentFilterPrefs()
+ private val filterReady = CompletableDeferred().apply {
+ if (contentFilter is StateFlow<*>) complete(Unit)
+ }
+
+ private suspend fun awaitCurrentFilter(): ContentFilterPrefs {
+ filterReady.await()
+ return currentFilter
+ }
+
private val videoPager = Pager(
scope = scope,
key = { it.bvid },
fetch = { query, page ->
val s = _state.value
- searchRepository.searchVideos(
- keyword = query,
- page = page,
- order = s.order.apiValue,
- duration = s.duration.apiValue.takeIf { it != 0 },
- tids = s.zone.tids,
- pubTime = s.pubTime.window(),
- ).map { SearchPage(it.items, it.hasMore) }
+ fetchVideos(query, page, s.order, s.duration, s.pubTime, s.zone)
},
read = { it.videos },
write = { s, list -> s.copy(videos = list) },
state = _state,
+ shouldFilter = { video, filter -> filter.matchesSearchVideo(video) },
+ awaitFilter = ::awaitCurrentFilter,
+ activeFilter = { currentFilter },
)
private val userPager = Pager(
@@ -169,7 +223,7 @@ class NormalSearchController(
key = { it.mid },
fetch = { query, page ->
val order = _state.value.userOrder
- searchRepository.searchUserPage(query, page, order.apiValue, order.ascending)
+ fetchUsers(query, page, order)
},
read = { it.users },
write = { s, list -> s.copy(users = list) },
@@ -179,12 +233,31 @@ class NormalSearchController(
private val articlePager = Pager(
scope = scope,
key = { it.id },
- fetch = { query, page -> searchRepository.searchArticles(query, page, _state.value.articleOrder.apiValue) },
+ fetch = { query, page -> fetchArticles(query, page, _state.value.articleOrder) },
read = { it.articles },
write = { s, list -> s.copy(articles = list) },
state = _state,
+ shouldFilter = { article, filter -> filter.matchesSearchArticle(article) },
+ awaitFilter = ::awaitCurrentFilter,
+ activeFilter = { currentFilter },
)
+ init {
+ scope.launch {
+ try {
+ contentFilter.collect { filter ->
+ currentFilter = filter
+ filterReady.complete(Unit)
+ val query = _state.value.query
+ videoPager.onFilterChanged(filter, query)
+ articlePager.onFilterChanged(filter, query)
+ }
+ } finally {
+ filterReady.complete(Unit)
+ }
+ }
+ }
+
private fun pagerFor(tab: SearchTab): Pager<*> = when (tab) {
SearchTab.Video -> videoPager
SearchTab.User -> userPager
@@ -278,6 +351,11 @@ class NormalSearchController(
pager.reset(keepVisible = false)
if (query.isNotEmpty()) pager.start(query)
}
+
+ internal companion object {
+ /** 单次触发(首屏或翻页)整页被过滤为空时,最多连续自动补拉的下一页次数。 */
+ const val MAX_AUTO_BACKFILL_PAGES = 3
+ }
}
/**
@@ -288,6 +366,9 @@ class NormalSearchController(
* - **分页游标在请求发出时归位**,不等响应回来:留到响应落地才写的话,首页在途期间 page 还是
* 上一次搜索的值,任何一次续页都会从一个与本次查询无关的偏移开始。
* - **跨页去重**:分页边界上同一条会重出,而 UI 拿它当 LazyColumn 的 key,重复即崩溃。
+ * - **受控补页**:当某页服务端返回非空新条目但过滤后新增可见条数为 0 且 `hasMore == true` 时,
+ * 自动续拉下一页(单次触发最多连续自动补拉 [NormalSearchController.MAX_AUTO_BACKFILL_PAGES] 页),
+ * 避免误显空态或触底预取死锁。
*/
private class Pager(
private val scope: CoroutineScope,
@@ -296,9 +377,13 @@ private class Pager(
private val read: (NormalSearchState) -> SearchListState,
private val write: (NormalSearchState, SearchListState) -> NormalSearchState,
private val state: MutableStateFlow,
+ private val shouldFilter: (T, ContentFilterPrefs) -> Boolean = { _, _ -> false },
+ private val awaitFilter: suspend () -> ContentFilterPrefs = { ContentFilterPrefs() },
+ private val activeFilter: () -> ContentFilterPrefs = { ContentFilterPrefs() },
) {
private var page = 1
private val seen = mutableSetOf()
+ private val rawItems = mutableListOf()
private var generation = 0
private var job: Job? = null
@@ -313,12 +398,13 @@ private class Pager(
job?.cancel()
page = 1
seen.clear()
+ rawItems.clear()
update { if (keepVisible) it.copy(started = false, error = null) else SearchListState() }
}
fun start(query: String) {
update { it.copy(started = true, loading = true, appending = false, error = null, hasMore = true) }
- run(query, page = 1)
+ run(query, startPage = 1)
}
/**
@@ -328,35 +414,99 @@ private class Pager(
fun loadMore(query: String) {
val current = read(state.value)
if (!current.started || current.loading || current.error != null) return
- if (current.appending || !current.hasMore || current.items.isEmpty()) return
+ if (current.appending || !current.hasMore || (current.items.isEmpty() && rawItems.isEmpty())) return
update { it.copy(appending = true) }
- run(query, page = page + 1)
+ run(query, startPage = page + 1)
+ }
+
+ /**
+ * 屏蔽规则变化时就地重筛已拉取的原始条目(取消屏蔽可无请求恢复)。
+ * 若当前可见结果被全部滤空且服务端仍有下一页,自动补拉下一页避免停在假空态。
+ */
+ fun onFilterChanged(filter: ContentFilterPrefs, query: String) {
+ val current = read(state.value)
+ if (!current.started || rawItems.isEmpty()) return
+ val visible = rawItems.filterNot { shouldFilter(it, filter) }
+ update { it.copy(items = visible) }
+ if (visible.isEmpty() && !current.loading && !current.appending && current.error == null && current.hasMore && query.isNotEmpty()) {
+ update { it.copy(appending = true) }
+ run(query, startPage = page + 1)
+ }
}
- private fun run(query: String, page: Int) {
+ private fun run(query: String, startPage: Int) {
val gen = ++generation
- if (page == 1) this.page = 1
+ if (startPage == 1) this.page = 1
job?.cancel()
job = scope.launch {
try {
- val result = fetch(query, page)
+ awaitFilter()
if (gen != generation) return@launch
- when (result) {
- is BiliResult.Ok -> {
- this@Pager.page = page
- if (page == 1) seen.clear()
- val fresh = result.value.items.filter { seen.add(key(it)) }
- update {
- it.copy(
- items = if (page == 1) fresh else it.items + fresh,
- hasMore = result.value.hasMore,
- error = null,
- )
+ var currentPage = startPage
+ var autoBackfills = 0
+ var hasPublishedFirstPage = startPage != 1
+ var lastHasMore = read(state.value).hasMore
+ while (true) {
+ val result = fetch(query, currentPage)
+ if (gen != generation) return@launch
+ when (result) {
+ is BiliResult.Ok -> {
+ this@Pager.page = currentPage
+ if (currentPage == 1) {
+ seen.clear()
+ rawItems.clear()
+ }
+ val freshRaw = result.value.items.filter { seen.add(key(it)) }
+ rawItems.addAll(freshRaw)
+ val filter = activeFilter()
+ val freshVisible = freshRaw.filterNot { shouldFilter(it, filter) }
+ val serverHasMore = result.value.hasMore
+ lastHasMore = serverHasMore
+ val needBackfill = freshRaw.isNotEmpty() &&
+ freshVisible.isEmpty() &&
+ serverHasMore &&
+ autoBackfills < NormalSearchController.MAX_AUTO_BACKFILL_PAGES
+ if (needBackfill) {
+ autoBackfills++
+ currentPage++
+ continue
+ }
+ val visible = rawItems.filterNot { shouldFilter(it, filter) }
+ hasPublishedFirstPage = true
+ update {
+ it.copy(
+ items = visible,
+ hasMore = serverHasMore,
+ error = null,
+ )
+ }
+ break
+ }
+
+ is BiliResult.ApiError -> {
+ val errorText = apiErrorText(result)
+ if (!hasPublishedFirstPage && currentPage > 1) {
+ val filter = activeFilter()
+ val visible = rawItems.filterNot { shouldFilter(it, filter) }
+ update { it.copy(items = visible, hasMore = lastHasMore, error = errorText) }
+ } else {
+ update { it.copy(error = errorText) }
+ }
+ break
}
- }
- is BiliResult.ApiError -> update { it.copy(error = apiErrorText(result)) }
- is BiliResult.Failure -> update { it.copy(error = failureText(result.cause)) }
+ is BiliResult.Failure -> {
+ val errorText = failureText(result.cause)
+ if (!hasPublishedFirstPage && currentPage > 1) {
+ val filter = activeFilter()
+ val visible = rawItems.filterNot { shouldFilter(it, filter) }
+ update { it.copy(items = visible, hasMore = lastHasMore, error = errorText) }
+ } else {
+ update { it.copy(error = errorText) }
+ }
+ break
+ }
+ }
}
} finally {
// 按当前 generation 释放:被取消的旧一代不该把新一代刚置上的 loading 又扒下来。
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchChatViewModel.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchChatViewModel.kt
index a9f5116f..1f06cc1e 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchChatViewModel.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchChatViewModel.kt
@@ -140,7 +140,7 @@ class SearchChatViewModel(
* 普通搜索整套状态机在 [NormalSearchController] 里(标签结果页共用同一套)。它是
* `normal` 那一格的唯一写入方,这边只镜像进 [SearchChatUiState] —— UI 仍然只看一份状态。
*/
- private val normal = NormalSearchController(viewModelScope, searchRepository)
+ private val normal = NormalSearchController(viewModelScope, searchRepository, settings.contentFilterPrefs)
init {
viewModelScope.launch {
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchResultScreen.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchResultScreen.kt
index 3864f501..587f4d57 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchResultScreen.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchResultScreen.kt
@@ -5,10 +5,13 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import dev.bilby.data.ContentFilterPrefs
import dev.bilby.data.SearchRepository
import dev.bilby.ui.AdaptiveListContent
import dev.bilby.ui.components.RefreshBox
+import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.flowOf
/**
* 标签结果页的 ViewModel:一个关键词、一份 [NormalSearchController]。关键词是路由身份
@@ -21,8 +24,9 @@ import kotlinx.coroutines.flow.StateFlow
class SearchResultViewModel(
keyword: String,
searchRepository: SearchRepository,
+ contentFilter: Flow = flowOf(ContentFilterPrefs()),
) : ViewModel() {
- private val controller = NormalSearchController(viewModelScope, searchRepository)
+ private val controller = NormalSearchController(viewModelScope, searchRepository, contentFilter)
val state: StateFlow = controller.state
init {
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchResults.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchResults.kt
index 33a27c4c..7d77d4f8 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchResults.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/search/SearchResults.kt
@@ -31,6 +31,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.outlined.ContentCopy
import androidx.compose.material.icons.outlined.MoreVert
+import androidx.compose.material.icons.outlined.PersonOff
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
@@ -78,7 +79,6 @@ import dev.bilby.ui.BilbyWindowSize
import dev.bilby.ui.components.Avatar
import dev.bilby.ui.components.ContextMenuBox
import dev.bilby.ui.components.CoverAspectRatio
-import dev.bilby.ui.components.LocalContentBlockMatcher
import dev.bilby.ui.components.LocalPointerSource
import dev.bilby.ui.components.PagedColumn
import dev.bilby.ui.components.PagedLayout
@@ -98,6 +98,7 @@ import dev.bilby.ui.components.selectedSemantics
import dev.bilby.ui.components.skeleton
import dev.bilby.ui.components.touchOnlyPaging
import dev.bilby.ui.components.verticalWheelScrollsRow
+import dev.bilby.ui.components.videoCommonMenuItemCount
import dev.bilby.ui.isAtLeast
import dev.bilby.ui.navigationBarsBottom
import dev.bilby.ui.rememberBilbyWindowSize
@@ -129,6 +130,8 @@ class SearchResultActions(
val onArticleClick: (id: Long) -> Unit,
val onLoadMore: () -> Unit,
val onRetry: () -> Unit,
+ /** 仅在搜索结果页生效:屏蔽洗稿/营销号 UP 主,不触碰订阅流的「不看动态」名单。 */
+ val onBlockUpInSearch: ((mid: Long, name: String) -> Unit)? = null,
)
/** 视频的六档,顺序照 B 站搜索页本身(notes 2.4 的 ArchiveFilterType)。 */
@@ -476,33 +479,21 @@ private fun ResultPage(
bottomPadding = bottomPadding,
)
- SearchTab.User -> {
- val blockMatcher = LocalContentBlockMatcher.current
- val visibleUsers = remember(state.users.items, blockMatcher) {
- if (blockMatcher.isEmpty) {
- state.users.items
- } else {
- state.users.items.filterNot { user ->
- blockMatcher.matchesUser(mid = user.mid, name = user.name)
- }
- }
- }
- PagedColumn(
- layout = layout,
- items = visibleUsers,
- key = { it.mid },
- skeletonRow = { PersonRowSkeleton() },
- loading = state.users.loading && state.users.items.isEmpty(),
- appending = state.users.appending,
- hasMore = state.users.hasMore,
- error = state.users.error.takeIf { state.users.items.isEmpty() },
- emptyText = stringResource(Res.string.search_no_results),
- onLoadMore = actions.onLoadMore,
- onRetry = actions.onRetry,
- contentPadding = listPadding,
- ) { user ->
- UserResultRow(user, onClick = { actions.onUserClick(user.mid) })
- }
+ SearchTab.User -> PagedColumn(
+ layout = layout,
+ items = state.users.items,
+ key = { it.mid },
+ skeletonRow = { PersonRowSkeleton() },
+ loading = state.users.loading && state.users.items.isEmpty(),
+ appending = state.users.appending,
+ hasMore = state.users.hasMore,
+ error = state.users.error.takeIf { state.users.items.isEmpty() },
+ emptyText = stringResource(Res.string.search_no_results),
+ onLoadMore = actions.onLoadMore,
+ onRetry = actions.onRetry,
+ contentPadding = listPadding,
+ ) { user ->
+ UserResultRow(user, onClick = { actions.onUserClick(user.mid) })
}
SearchTab.Article -> PagedColumn(
@@ -521,6 +512,7 @@ private fun ResultPage(
ArticleResultRow(
article = article,
onClick = { actions.onArticleClick(article.id) },
+ onBlockUpInSearch = actions.onBlockUpInSearch,
)
}
}
@@ -544,20 +536,6 @@ private fun VideoResults(
bottomPadding: Dp,
) {
val videos = state.videos
- val blockMatcher = LocalContentBlockMatcher.current
- val visibleVideos = remember(videos.items, blockMatcher) {
- if (blockMatcher.isEmpty) {
- videos.items
- } else {
- videos.items.filterNot { video ->
- blockMatcher.matchesVideo(
- upMid = video.upMid,
- upName = video.upName,
- title = video.title,
- )
- }
- }
- }
val wideWindow = rememberBilbyWindowSize().isAtLeast(BilbyWindowSize.Expanded)
val density = LocalDensity.current
var containerWidth by remember { mutableStateOf(0.dp) }
@@ -593,7 +571,7 @@ private fun VideoResults(
) {
PagedColumn(
layout = effectiveLayout,
- items = visibleVideos,
+ items = videos.items,
key = { it.bvid },
loading = videos.loading && videos.items.isEmpty(),
appending = videos.appending,
@@ -629,7 +607,15 @@ private fun VideoResults(
val rowUi = remember(video, dateText, playText, danmakuText) {
video.toRowUi(dateText = dateText, playText = playText, danmakuText = danmakuText)
}
+ val blockUp = actions.onBlockUpInSearch?.takeIf { video.upMid != 0L }
val menu: @Composable ColumnScope.(close: () -> Unit) -> Unit = { close ->
+ val baseCount = videoCommonMenuItemCount(
+ bvid = video.bvid,
+ upMid = video.upMid,
+ onOpenUpSpace = actions.onUserClick,
+ title = video.title,
+ )
+ val totalCount = baseCount + if (blockUp != null) 1 else 0
VideoCommonMenuItems(
bvid = video.bvid,
title = video.title,
@@ -639,7 +625,19 @@ private fun VideoResults(
coverUrl = video.coverUrl,
upName = video.upName,
durationSeconds = parseDurationSeconds(video.durationText),
+ totalCount = totalCount,
)
+ if (blockUp != null) {
+ DropdownMenuItem(
+ onClick = {
+ close()
+ blockUp(video.upMid, video.upName)
+ },
+ text = { Text(stringResource(Res.string.menu_block_up_in_search)) },
+ leadingIcon = { Icon(Icons.Outlined.PersonOff, contentDescription = null) },
+ shape = menuItemShape(baseCount, totalCount),
+ )
+ }
}
ContextMenuBox(
onClick = null,
@@ -716,10 +714,14 @@ private fun VideoGridCardSkeleton(modifier: Modifier = Modifier) {
private fun ArticleResultRow(
article: SearchArticle,
onClick: () -> Unit,
+ onBlockUpInSearch: ((mid: Long, name: String) -> Unit)? = null,
) {
val copy = rememberCopyAction()
val copyTitleLabel = stringResource(Res.string.action_copy_title)
val copyArticleIdLabel = stringResource(Res.string.action_copy_article_id)
+ val blockUpLabel = stringResource(Res.string.menu_block_up_in_search)
+ val blockUp = onBlockUpInSearch?.takeIf { article.authorMid != 0L }
+ val totalCount = if (blockUp != null) 3 else 2
ContextMenuBox(
onClick = null,
@@ -732,7 +734,7 @@ private fun ArticleResultRow(
},
text = { Text(copyTitleLabel) },
leadingIcon = { Icon(Icons.Outlined.ContentCopy, contentDescription = null) },
- shape = menuItemShape(0, 2),
+ shape = menuItemShape(0, totalCount),
)
DropdownMenuItem(
onClick = {
@@ -741,8 +743,19 @@ private fun ArticleResultRow(
},
text = { Text(copyArticleIdLabel) },
leadingIcon = { Icon(Icons.Outlined.ContentCopy, contentDescription = null) },
- shape = menuItemShape(1, 2),
+ shape = menuItemShape(1, totalCount),
)
+ if (blockUp != null) {
+ DropdownMenuItem(
+ onClick = {
+ close()
+ blockUp(article.authorMid, "UID ${article.authorMid}")
+ },
+ text = { Text(blockUpLabel) },
+ leadingIcon = { Icon(Icons.Outlined.PersonOff, contentDescription = null) },
+ shape = menuItemShape(2, totalCount),
+ )
+ }
},
) { openMenu ->
val articleBadge = stringResource(Res.string.feed_article_badge)
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsPages.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsPages.kt
index 13950dbf..8a85929c 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsPages.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsPages.kt
@@ -19,6 +19,8 @@ import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.material.icons.automirrored.outlined.AltRoute
@@ -36,6 +38,7 @@ import androidx.compose.material.icons.outlined.DarkMode
import androidx.compose.material.icons.outlined.Dns
import androidx.compose.material.icons.outlined.DownloadForOffline
import androidx.compose.material.icons.outlined.FastForward
+import androidx.compose.material.icons.outlined.FilterList
import androidx.compose.material.icons.outlined.Flag
import androidx.compose.material.icons.outlined.Forum
import androidx.compose.material.icons.outlined.Gesture
@@ -117,7 +120,6 @@ import dev.bilby.resources.*
import dev.bilby.ui.navigationBarsBottom
import dev.bilby.ui.padScaffoldExceptBottom
import dev.bilby.data.CodecPreference
-import dev.bilby.data.ContentBlockRule
import dev.bilby.data.DEFAULT_NIGHT_END_MINUTE
import dev.bilby.data.DEFAULT_NIGHT_START_MINUTE
import dev.bilby.data.LlmConfig
@@ -173,6 +175,7 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import org.jetbrains.compose.resources.StringResource
+import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
@@ -229,8 +232,9 @@ enum class SettingsSection {
/** 排除的 UP 主名单。从隐私页再降一层,理由见 [ExcludedFeedPage]。 */
ExcludedFeed,
- /** 本地内容屏蔽规则(UP 主与关键词)。从隐私页再降一层。 */
- BlockRules,
+
+ /** 搜索屏蔽的 UP 主与关键词过滤。从隐私页再降一层,与 [ExcludedFeed] 正交。 */
+ ContentFilter,
Agent,
Privacy,
NightMode,
@@ -1198,7 +1202,7 @@ fun PrivacySettingsPage(
onRetryHistoryPause: () -> Unit,
onOpenBlacklist: () -> Unit,
onOpenExcludedFeed: () -> Unit,
- onOpenBlockRules: () -> Unit,
+ onOpenContentFilter: () -> Unit,
onDanmakusArchiveChange: (Boolean) -> Unit,
onBack: (() -> Unit)?,
) {
@@ -1259,19 +1263,6 @@ fun PrivacySettingsPage(
onCheckedChange = onDanmakusArchiveChange,
)
}
- row { position ->
- SettingRow(
- position = position,
- icon = Icons.Outlined.Block,
- title = stringResource(Res.string.settings_block_rules),
- subtitle = stringResource(Res.string.settings_block_rules_subtitle),
- value = state.contentBlockRules.size.takeIf { it > 0 }?.let {
- stringResource(Res.string.settings_block_rules_count, it)
- },
- target = RowTarget.Page,
- onClick = onOpenBlockRules,
- )
- }
// 一个都没排除过的人不需要看见这个概念。
if (state.excludedFeedUps.isNotEmpty()) {
row { position ->
@@ -1279,12 +1270,28 @@ fun PrivacySettingsPage(
position = position,
icon = Icons.Outlined.PersonOff,
title = stringResource(Res.string.settings_feed_excluded),
+ subtitle = stringResource(Res.string.settings_feed_excluded_subtitle),
value = stringResource(Res.string.settings_feed_excluded_count, state.excludedFeedUps.size),
+ valueAtEnd = true,
target = RowTarget.Page,
onClick = onOpenExcludedFeed,
)
}
}
+ row { position ->
+ SettingRow(
+ position = position,
+ icon = Icons.Outlined.FilterList,
+ title = stringResource(Res.string.settings_content_filter),
+ subtitle = stringResource(Res.string.settings_content_filter_subtitle),
+ value = state.contentFilter.totalRuleCount.takeIf { it > 0 }?.let {
+ stringResource(Res.string.settings_content_filter_count, it)
+ },
+ valueAtEnd = true,
+ target = RowTarget.Page,
+ onClick = onOpenContentFilter,
+ )
+ }
}
}
}
@@ -1363,107 +1370,188 @@ fun ExcludedFeedPage(
}
/**
- * 本地内容屏蔽规则:按 UP 主或关键词(匹配标题与 UP 名)在关注动态与搜索结果中实时过滤。
+ * 搜索与关键词屏蔽管理页,与 [ExcludedFeedPage] 正交:
+ * - 关键词作用于搜索结果与主页订阅动态流(含转发原帖);
+ * - 搜索屏蔽 UP 主仅作用于搜索结果中的视频与专栏。
*/
@Composable
-fun BlockRulesPage(
+fun ContentFilterSettingsPage(
state: SettingsUiState,
onAddKeyword: (String) -> Unit,
- onRemoveRule: (ContentBlockRule.Kind, String) -> Unit,
+ onRemoveKeyword: (String) -> Unit,
+ onRemoveSearchUp: (Long) -> Unit,
onClearAll: () -> Unit,
onBack: (() -> Unit)?,
) {
var keywordInput by rememberSaveable { mutableStateOf("") }
var confirmingClearAll by rememberSaveable { mutableStateOf(false) }
- val upPrefix = stringResource(Res.string.settings_block_rule_up_prefix)
- SettingsSubPage(stringResource(Res.string.settings_block_rules), onBack, state.loaded) {
- androidx.compose.foundation.layout.Row(
- verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,
- horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(Spacing.Tight),
- modifier = Modifier.padding(horizontal = Spacing.Comfortable, vertical = Spacing.Tight),
- ) {
- OutlinedTextField(
- value = keywordInput,
- onValueChange = { keywordInput = it },
- singleLine = true,
- placeholder = { Text(stringResource(Res.string.settings_block_keyword_hint)) },
- modifier = Modifier.weight(1f),
- )
- Button(
- enabled = keywordInput.isNotBlank(),
- onClick = {
- val kw = keywordInput.trim()
- if (kw.isNotEmpty()) {
- onAddKeyword(kw)
- keywordInput = ""
- }
- },
- ) {
- Text(stringResource(Res.string.settings_block_keyword_add))
- }
+ val filter = state.contentFilter
+
+ val submitKeyword = {
+ val trimmed = keywordInput.trim()
+ if (trimmed.isNotEmpty()) {
+ onAddKeyword(trimmed)
+ keywordInput = ""
}
- if (state.contentBlockRules.isEmpty()) {
- Text(
- text = stringResource(Res.string.settings_block_rules_empty),
- style = MaterialTheme.typography.bodyMedium,
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- modifier = Modifier.padding(horizontal = Spacing.Comfortable, vertical = Spacing.Cozy),
- )
- } else {
- SettingsGroup {
- state.contentBlockRules.forEach { rule ->
- val title = if (rule.kind == ContentBlockRule.Kind.Up) {
- "$upPrefix ${rule.label}"
- } else {
- rule.label
+ }
+
+ SettingsSubPage(stringResource(Res.string.settings_content_filter), onBack, state.loaded) {
+ SettingsGroup(title = stringResource(Res.string.settings_content_filter_keyword_section)) {
+ row { position ->
+ Surface(
+ shape = segmentedRowShape(position),
+ color = MaterialTheme.colorScheme.surfaceContainer,
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(ListItemDefaults.ContentPadding),
+ horizontalArrangement = Arrangement.spacedBy(Spacing.Tight),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ OutlinedTextField(
+ value = keywordInput,
+ onValueChange = { keywordInput = it },
+ singleLine = true,
+ placeholder = {
+ Text(
+ text = stringResource(Res.string.settings_content_filter_keyword_hint),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ },
+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
+ keyboardActions = KeyboardActions(onDone = { submitKeyword() }),
+ modifier = Modifier.weight(1f),
+ )
+ Button(
+ onClick = submitKeyword,
+ enabled = keywordInput.isNotBlank(),
+ modifier = Modifier.heightIn(min = 48.dp),
+ ) {
+ Text(stringResource(Res.string.settings_content_filter_keyword_add))
+ }
}
- val icon = if (rule.kind == ContentBlockRule.Kind.Up) {
- Icons.Outlined.Person
- } else {
- Icons.Outlined.Search
+ }
+ }
+ if (filter.keywords.isEmpty()) {
+ row { position ->
+ Surface(
+ shape = segmentedRowShape(position),
+ color = MaterialTheme.colorScheme.surfaceContainer,
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .heightIn(min = 48.dp)
+ .padding(ListItemDefaults.ContentPadding),
+ contentAlignment = Alignment.CenterStart,
+ ) {
+ Text(
+ text = stringResource(Res.string.settings_content_filter_keyword_empty),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
}
+ }
+ } else {
+ filter.keywords.forEach { keyword ->
row { position ->
StaticSettingRow(
position = position,
- icon = icon,
- title = title,
+ icon = Icons.Outlined.Search,
+ title = keyword,
trailing = {
- TextButton(onClick = { onRemoveRule(rule.kind, rule.value) }) {
- Text(stringResource(Res.string.settings_block_rule_remove))
+ TextButton(
+ onClick = { onRemoveKeyword(keyword) },
+ modifier = Modifier.heightIn(min = 48.dp),
+ ) {
+ Text(stringResource(Res.string.settings_content_filter_remove))
}
},
)
}
}
- if (state.contentBlockRules.size > 1) {
+ }
+ }
+
+ SettingsGroup(title = stringResource(Res.string.settings_content_filter_search_ups_section)) {
+ if (filter.blockedSearchUps.isEmpty()) {
+ row { position ->
+ Surface(
+ shape = segmentedRowShape(position),
+ color = MaterialTheme.colorScheme.surfaceContainer,
+ modifier = Modifier.fillMaxWidth(),
+ ) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .heightIn(min = 48.dp)
+ .padding(ListItemDefaults.ContentPadding),
+ contentAlignment = Alignment.CenterStart,
+ ) {
+ Text(
+ text = stringResource(Res.string.settings_content_filter_search_ups_empty),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
+ }
+ }
+ } else {
+ filter.blockedSearchUps.forEach { up ->
row { position ->
- SettingRow(
+ val uidLabel = "UID ${up.mid}"
+ val subtitle = if (up.name != up.mid.toString() && up.name != uidLabel) uidLabel else null
+ StaticSettingRow(
position = position,
- icon = Icons.Outlined.Restore,
- title = stringResource(Res.string.settings_block_rules_clear),
- onClick = { confirmingClearAll = true },
+ icon = Icons.Outlined.PersonOff,
+ title = up.name,
+ subtitle = subtitle,
+ trailing = {
+ TextButton(
+ onClick = { onRemoveSearchUp(up.mid) },
+ modifier = Modifier.heightIn(min = 48.dp),
+ ) {
+ Text(stringResource(Res.string.settings_content_filter_remove))
+ }
+ },
)
}
}
}
}
+
+ if (!filter.isEmpty) {
+ SettingsGroup {
+ row { position ->
+ SettingRow(
+ position = position,
+ icon = Icons.Outlined.Restore,
+ title = stringResource(Res.string.settings_content_filter_clear),
+ onClick = { confirmingClearAll = true },
+ )
+ }
+ }
+ }
}
+
if (confirmingClearAll) {
AlertDialog(
onDismissRequest = { confirmingClearAll = false },
- title = { Text(stringResource(Res.string.settings_block_rules_clear)) },
- text = { Text(stringResource(Res.string.settings_block_rules_clear_message)) },
+ title = { Text(stringResource(Res.string.settings_content_filter_clear)) },
+ text = { Text(stringResource(Res.string.settings_content_filter_clear_message)) },
confirmButton = {
- Button(
- colors = ButtonDefaults.buttonColors(
- containerColor = MaterialTheme.colorScheme.error,
- contentColor = MaterialTheme.colorScheme.onError,
- ),
+ DestructiveConfirmButton(
+ text = stringResource(Res.string.action_clear),
onClick = {
confirmingClearAll = false
onClearAll()
},
- ) { Text(stringResource(Res.string.settings_block_rules_clear)) }
+ )
},
dismissButton = {
TextButton(onClick = { confirmingClearAll = false }) {
diff --git a/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt
index f42d61a5..7e61f286 100644
--- a/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt
+++ b/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt
@@ -20,9 +20,9 @@ import androidx.compose.runtime.Stable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dev.bilby.data.CodecPreference
+import dev.bilby.data.ContentFilterPrefs
import dev.bilby.agent.LlmClient
import dev.bilby.agent.LlmModelInfo
-import dev.bilby.data.ContentBlockRule
import dev.bilby.data.ExcludedUp
import dev.bilby.data.LlmConfig
import dev.bilby.data.NavigationPrefs
@@ -86,8 +86,8 @@ data class SettingsUiState(
val pbpOutroCompletion: Boolean = true,
/** 排除的 UP 主,名字已经带上。为空时那一行不显示 —— 没排除过的人不需要看见这个概念。 */
val excludedFeedUps: List = emptyList(),
- /** 本地内容屏蔽规则(UP 主与关键词)。 */
- val contentBlockRules: List = emptyList(),
+ /** 搜索屏蔽的 UP 主与关键词过滤规则,与 [excludedFeedUps] 正交。 */
+ val contentFilter: ContentFilterPrefs = ContentFilterPrefs(),
/** 直播间要不要去 danmakus.com 补本场早前的醒目留言。见 SettingsStore.danmakusArchiveEnabled。 */
val danmakusArchive: Boolean = true,
val offlineConcurrency: Int = SettingsStore.DEFAULT_OFFLINE_CONCURRENCY,
@@ -298,8 +298,8 @@ class SettingsViewModel(
}
}
viewModelScope.launch {
- settings.contentBlockRules.collect { rules ->
- _state.update { it.copy(contentBlockRules = rules) }
+ settings.contentFilterPrefs.collect { filter ->
+ _state.update { it.copy(contentFilter = filter) }
}
}
viewModelScope.launch {
@@ -331,12 +331,16 @@ class SettingsViewModel(
persist { settings.addBlockedKeyword(keyword) }
}
- fun removeContentBlockRule(kind: ContentBlockRule.Kind, value: String) {
- persist { settings.removeContentBlockRule(kind, value) }
+ fun removeBlockedKeyword(keyword: String) {
+ persist { settings.removeBlockedKeyword(keyword) }
}
- fun clearContentBlockRules() {
- persist { settings.clearContentBlockRules() }
+ fun removeBlockedSearchUp(mid: Long) {
+ persist { settings.removeBlockedSearchUp(mid) }
+ }
+
+ fun clearContentFilters() {
+ persist { settings.clearContentFilters() }
}
fun setDanmakusArchive(enabled: Boolean) {
diff --git a/shared/src/commonTest/kotlin/dev/bilby/data/ContentBlockMatcherTest.kt b/shared/src/commonTest/kotlin/dev/bilby/data/ContentBlockMatcherTest.kt
deleted file mode 100644
index e3bbcecb..00000000
--- a/shared/src/commonTest/kotlin/dev/bilby/data/ContentBlockMatcherTest.kt
+++ /dev/null
@@ -1,34 +0,0 @@
-package dev.bilby.data
-
-import org.junit.Assert.assertFalse
-import org.junit.Assert.assertTrue
-import org.junit.Test
-
-class ContentBlockMatcherTest {
-
- @Test
- fun `匹配器按 UP 主 mid 与大小写不敏感关键词过滤视频与用户`() {
- val rules = listOf(
- ContentBlockRule(ContentBlockRule.Kind.Up, "42", "某营销号"),
- ContentBlockRule(ContentBlockRule.Kind.Keyword, "震惊", "震惊"),
- ContentBlockRule(ContentBlockRule.Kind.Keyword, "clickbait", "ClickBait"),
- )
- val matcher = ContentBlockMatcher.fromRules(rules)
-
- assertTrue(matcher.matchesVideo(upMid = 42L, upName = "某营销号", title = "正常标题"))
- assertTrue(matcher.matchesVideo(upMid = 99L, upName = "路人", title = "太震惊了!必看"))
- assertTrue(matcher.matchesVideo(upMid = 99L, upName = "ClickBait Studio", title = "普通视频"))
- assertFalse(matcher.matchesVideo(upMid = 99L, upName = "科普君", title = "Compose 源码解析"))
- assertTrue(matcher.matchesUser(mid = 42L, name = "改名后的号"))
- assertTrue(matcher.matchesUser(mid = 77L, name = "震惊部"))
- assertFalse(matcher.matchesUser(mid = 77L, name = "科普君"))
- }
-
- @Test
- fun `空规则不命中任何条目`() {
- val matcher = ContentBlockMatcher.fromRules(emptyList())
- assertTrue(matcher.isEmpty)
- assertFalse(matcher.matchesVideo(upMid = 1L, upName = "任意", title = "任意标题"))
- assertFalse(matcher.matchesUser(mid = 1L, name = "任意"))
- }
-}
diff --git a/shared/src/commonTest/kotlin/dev/bilby/data/ContentFilterTest.kt b/shared/src/commonTest/kotlin/dev/bilby/data/ContentFilterTest.kt
new file mode 100644
index 00000000..c3b84b97
--- /dev/null
+++ b/shared/src/commonTest/kotlin/dev/bilby/data/ContentFilterTest.kt
@@ -0,0 +1,428 @@
+package dev.bilby.data
+
+import androidx.datastore.core.DataStore
+import androidx.datastore.preferences.core.Preferences
+import androidx.datastore.preferences.core.emptyPreferences
+import dev.bilby.api.BiliResult
+import dev.bilby.data.model.ArticleRef
+import dev.bilby.data.model.DynamicAdditional
+import dev.bilby.data.model.DynamicAuthor
+import dev.bilby.data.model.DynamicCard
+import dev.bilby.data.model.DynamicContent
+import dev.bilby.data.model.FeedEntry
+import dev.bilby.data.model.RichSpan
+import dev.bilby.ui.search.NormalSearchController
+import dev.bilby.ui.search.SearchTab
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.test.advanceUntilIdle
+import kotlinx.coroutines.test.runTest
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+@OptIn(ExperimentalCoroutinesApi::class)
+class ContentFilterTest {
+
+ @Test
+ fun `keywords match case-insensitively, trim blanks, and treat regex metacharacters literally`() {
+ val prefs = ContentFilterPrefs(
+ keywords = listOf(" ", "", " Spoiler ", "[剧透]", "a+b*"),
+ )
+ assertTrue(prefs.hasKeywordFilters)
+
+ // 大小写不敏感匹配视频标题
+ assertTrue(prefs.matchesSearchVideo(video(bvid = "BV1", upMid = 10L, title = "最终章 SPOILER 解析")))
+ assertTrue(prefs.matchesSearchVideo(video(bvid = "BV2", upMid = 10L, title = "正片[剧透]慎入")))
+ assertTrue(prefs.matchesSearchVideo(video(bvid = "BV3", upMid = 10L, title = "表达式 a+b* 的写法")))
+ // 正则元字符按字面匹配,不会把 "a+b*" 解释成正则去命中 "aaab"
+ assertFalse(prefs.matchesSearchVideo(video(bvid = "BV4", upMid = 10L, title = "aaab 测试")))
+ assertFalse(prefs.matchesSearchVideo(video(bvid = "BV5", upMid = 10L, title = "普通技术分享")))
+
+ // 专栏匹配标题与摘要
+ assertTrue(prefs.matchesSearchArticle(article(id = 1L, title = "spoiler 汇总", summary = "无")))
+ assertTrue(prefs.matchesSearchArticle(article(id = 2L, title = "普通标题", summary = "含 [剧透] 片段")))
+ assertFalse(prefs.matchesSearchArticle(article(id = 3L, title = "普通标题", summary = "普通摘要")))
+ }
+
+ @Test
+ fun `empty or blank-only keywords match nothing`() {
+ val prefs = ContentFilterPrefs(keywords = listOf("", " ", "\t"))
+ assertTrue(prefs.isEmpty)
+ assertFalse(prefs.hasKeywordFilters)
+ assertFalse(prefs.matchesSearchVideo(video(bvid = "BV1", upMid = 1L, title = "任意标题")))
+ assertFalse(prefs.matchesFeedEntry(feedVideo(bvid = "BV1", upMid = 1L, title = "任意标题")))
+ }
+
+ @Test
+ fun `feed keyword filter covers video, article, dynamic body, and forwarded original post`() {
+ val prefs = ContentFilterPrefs(
+ blockedSearchUps = listOf(BlockedSearchUp(mid = 777L, name = "营销号")),
+ keywords = listOf("剧透", "引战"),
+ )
+
+ // 首页投稿:匹配视频标题与专栏标题/摘要
+ assertTrue(prefs.matchesFeedEntry(feedVideo(bvid = "BV1", upMid = 1L, title = "大结局剧透解读")))
+ assertFalse(prefs.matchesFeedEntry(feedVideo(bvid = "BV2", upMid = 1L, title = "正常实况")))
+ assertTrue(prefs.matchesFeedEntry(feedArticle(id = "10", upMid = 1L, title = "普通", summary = "这段内容很引战")))
+
+ // 转发动态:外层正文无关键词,命中原帖正文
+ val forwardedBodyHit = dynamicCard(
+ id = "dyn-1",
+ authorMid = 1L,
+ text = listOf(RichSpan.Text("转发看看")),
+ forwarded = dynamicCard(
+ id = "orig-1",
+ authorMid = 2L,
+ text = listOf(RichSpan.Text("前方高能"), RichSpan.Text("剧透警告")),
+ ),
+ )
+ assertTrue(prefs.matchesFeedEntry(forwardedBodyHit))
+
+ // 转发动态:外层与原帖正文均无关键词,命中原帖内嵌视频标题
+ val forwardedVideoTitleHit = dynamicCard(
+ id = "dyn-2",
+ authorMid = 1L,
+ text = listOf(RichSpan.Text("推荐这个视频")),
+ forwarded = dynamicCard(
+ id = "orig-2",
+ authorMid = 2L,
+ text = listOf(RichSpan.Text("新视频发啦")),
+ content = DynamicContent.Video(
+ bvid = "BV99",
+ title = "刻意引战的标题",
+ coverUrl = "",
+ durationText = "05:00",
+ playCountText = "1万",
+ danmakuCountText = "100",
+ ),
+ ),
+ )
+ assertTrue(prefs.matchesFeedEntry(forwardedVideoTitleHit))
+
+ // 转发动态:命中原帖附加视频标题
+ val forwardedAdditionalHit = dynamicCard(
+ id = "dyn-3",
+ authorMid = 1L,
+ text = listOf(RichSpan.Text("转")),
+ forwarded = dynamicCard(
+ id = "orig-3",
+ authorMid = 2L,
+ additional = DynamicAdditional.Video(
+ title = "最终话剧透",
+ coverUrl = "",
+ description = "",
+ webUrl = "",
+ durationText = "03:00",
+ ),
+ ),
+ )
+ assertTrue(prefs.matchesFeedEntry(forwardedAdditionalHit))
+
+ // 跨 RichSpan 拼接后的关键词也能命中
+ val crossSpanHit = dynamicCard(
+ id = "dyn-4",
+ authorMid = 1L,
+ text = listOf(RichSpan.Text("前面有剧"), RichSpan.Text("透请绕行")),
+ )
+ assertTrue(prefs.matchesFeedEntry(crossSpanHit))
+ }
+
+ @Test
+ fun `blockedSearchUps and excludedFeedMids are strictly orthogonal`() = runTest {
+ val settings = SettingsStore(inMemoryPreferencesStore())
+ // UP 100 仅在订阅流「不看动态」里;UP 200 仅在搜索结果里被屏蔽
+ settings.excludeFeedMid(100L, "高频更新UP")
+ settings.addBlockedSearchUp(200L, "洗稿营销号")
+
+ val excludedMids = settings.excludedFeedMids.first()
+ val filterPrefs = settings.contentFilterPrefs.first()
+
+ // 订阅流只按 excludedFeedMids + keywords 过滤,绝不屏蔽 blockedSearchUps(200)
+ assertTrue(100L in excludedMids)
+ assertFalse(200L in excludedMids)
+ assertFalse(filterPrefs.matchesFeedEntry(feedVideo(bvid = "BV200", upMid = 200L, title = "普通视频")))
+ assertFalse(filterPrefs.matchesDynamicCard(dynamicCard(id = "d200", authorMid = 200L, text = listOf(RichSpan.Text("普通动态")))))
+
+ // 搜索结果只按 blockedSearchUps + keywords 过滤,绝不屏蔽 excludedFeedMids(100)
+ assertFalse(filterPrefs.matchesSearchVideo(video(bvid = "BV100", upMid = 100L, title = "高频UP的教程")))
+ assertTrue(filterPrefs.matchesSearchVideo(video(bvid = "BV200", upMid = 200L, title = "营销号搬运")))
+ assertFalse(filterPrefs.matchesSearchArticle(article(id = 100L, authorMid = 100L, title = "专栏")))
+ assertTrue(filterPrefs.matchesSearchArticle(article(id = 200L, authorMid = 200L, title = "营销号专栏")))
+
+ // 清空内容屏蔽不影响 excludedFeedMids,反之亦然
+ settings.clearContentFilters()
+ assertEquals(setOf(100L), settings.excludedFeedMids.first())
+ assertTrue(settings.contentFilterPrefs.first().isEmpty)
+
+ settings.addBlockedSearchUp(200L, "洗稿营销号")
+ settings.clearExcludedFeedMids()
+ assertTrue(settings.excludedFeedMids.first().isEmpty())
+ assertEquals(listOf(BlockedSearchUp(200L, "洗稿营销号")), settings.contentFilterPrefs.first().blockedSearchUps)
+ }
+
+ @Test
+ fun `SettingsStore persists blocked search ups and keywords with dedup and trim`() = runTest {
+ val settings = SettingsStore(inMemoryPreferencesStore())
+ settings.addBlockedSearchUp(0L, "无效")
+ settings.addBlockedSearchUp(42L, " 营销号A ")
+ settings.addBlockedSearchUp(42L, "营销号A新名")
+ settings.addBlockedKeyword(" ")
+ settings.addBlockedKeyword(" ClickBait ")
+ settings.addBlockedKeyword("clickbait")
+ settings.addBlockedKeyword("剧透")
+
+ val stored = settings.contentFilterPrefs.first()
+ assertEquals(listOf(BlockedSearchUp(42L, "营销号A新名")), stored.blockedSearchUps)
+ assertEquals(listOf("剧透", "clickbait"), stored.keywords)
+
+ settings.removeBlockedKeyword("CLICKBAIT")
+ settings.removeBlockedSearchUp(42L)
+ val afterRemove = settings.contentFilterPrefs.first()
+ assertTrue(afterRemove.blockedSearchUps.isEmpty())
+ assertEquals(listOf("剧透"), afterRemove.keywords)
+
+ settings.clearContentFilters()
+ assertTrue(settings.contentFilterPrefs.first().isEmpty)
+ }
+
+ @Test
+ fun `search auto-backfills when a full page is filtered out and stops after 3 consecutive backfills`() = runTest {
+ val filterFlow = MutableStateFlow(
+ ContentFilterPrefs(blockedSearchUps = listOf(BlockedSearchUp(mid = 999L, name = "营销号"))),
+ )
+ val requestedPages = mutableListOf()
+ val controllerScope = CoroutineScope(coroutineContext + Job())
+ try {
+ val controller = NormalSearchController(
+ scope = controllerScope,
+ contentFilter = filterFlow,
+ fetchVideos = { _, page, _, _, _, _ ->
+ requestedPages += page
+ val items = when (page) {
+ 1, 2 -> listOf(video(bvid = "BV_SPAM_$page", upMid = 999L, title = "搬运 $page"))
+ 3 -> listOf(
+ video(bvid = "BV_SPAM_3", upMid = 999L, title = "搬运 3"),
+ video(bvid = "BV_GOOD_3", upMid = 101L, title = "真正教程"),
+ )
+ else -> listOf(video(bvid = "BV_SPAM_$page", upMid = 999L, title = "搬运 $page"))
+ }
+ BiliResult.Ok(SearchPage(items = items, hasMore = true))
+ },
+ fetchUsers = { _, _, _ -> BiliResult.Ok(SearchPage(emptyList(), hasMore = false)) },
+ fetchArticles = { _, _, _ -> BiliResult.Ok(SearchPage(emptyList(), hasMore = false)) },
+ )
+
+ // 第 1、2 页全被过滤,自动补拉到第 3 页拿到有效结果后立即停止
+ controller.search("教程")
+ advanceUntilIdle()
+ assertEquals(listOf(1, 2, 3), requestedPages)
+ assertEquals(listOf("BV_GOOD_3"), controller.state.value.videos.items.map { it.bvid })
+ assertTrue(controller.state.value.videos.hasMore)
+ assertFalse(controller.state.value.videos.loading)
+
+ // 触发翻页:第 4、5、6、7 页全被过滤,单次触发最多连续自动补拉 3 页(共请求 4 页)后停止
+ requestedPages.clear()
+ controller.loadMore()
+ advanceUntilIdle()
+ assertEquals(listOf(4, 5, 6, 7), requestedPages)
+ assertEquals(listOf("BV_GOOD_3"), controller.state.value.videos.items.map { it.bvid })
+ assertFalse(controller.state.value.videos.appending)
+ assertTrue(controller.state.value.videos.hasMore)
+ } finally {
+ controllerScope.cancel()
+ }
+ }
+
+ @Test
+ fun `search stops initial auto-backfill at cap when every page is filtered out`() = runTest {
+ val filterFlow = MutableStateFlow(
+ ContentFilterPrefs(keywords = listOf("广告")),
+ )
+ val requestedPages = mutableListOf()
+ val controllerScope = CoroutineScope(coroutineContext + Job())
+ try {
+ val controller = NormalSearchController(
+ scope = controllerScope,
+ contentFilter = filterFlow,
+ fetchVideos = { _, page, _, _, _, _ ->
+ requestedPages += page
+ BiliResult.Ok(
+ SearchPage(
+ items = listOf(video(bvid = "BV_AD_$page", upMid = page.toLong(), title = "全是广告 $page")),
+ hasMore = true,
+ ),
+ )
+ },
+ fetchUsers = { _, _, _ -> BiliResult.Ok(SearchPage(emptyList(), hasMore = false)) },
+ fetchArticles = { _, _, _ -> BiliResult.Ok(SearchPage(emptyList(), hasMore = false)) },
+ )
+
+ controller.search("手机")
+ advanceUntilIdle()
+ // 第 1 页 + 连续自动补拉 3 页 = 共 4 页
+ assertEquals(listOf(1, 2, 3, 4), requestedPages)
+ assertTrue(controller.state.value.videos.items.isEmpty())
+ assertFalse(controller.state.value.videos.loading)
+ assertTrue(controller.state.value.videos.hasMore)
+ } finally {
+ controllerScope.cancel()
+ }
+ }
+
+ @Test
+ fun `search does not backfill on genuinely empty server page and reacts to live block and undo`() = runTest {
+ val filterFlow = MutableStateFlow(ContentFilterPrefs())
+ val requestedVideoPages = mutableListOf()
+ val requestedArticlePages = mutableListOf()
+ val controllerScope = CoroutineScope(coroutineContext + Job())
+ try {
+ val controller = NormalSearchController(
+ scope = controllerScope,
+ contentFilter = filterFlow,
+ fetchVideos = { _, page, _, _, _, _ ->
+ requestedVideoPages += page
+ when (page) {
+ 1 -> BiliResult.Ok(
+ SearchPage(
+ items = listOf(
+ video(bvid = "BV_A", upMid = 10L, title = "UP A 视频"),
+ video(bvid = "BV_B", upMid = 20L, title = "UP B 视频"),
+ ),
+ hasMore = true,
+ ),
+ )
+ else -> BiliResult.Ok(SearchPage(items = emptyList(), hasMore = false))
+ }
+ },
+ fetchUsers = { _, _, _ ->
+ BiliResult.Ok(
+ SearchPage(
+ items = listOf(SearchUser(mid = 10L, name = "UP A", avatarUrl = "", fansCount = 1, signature = "")),
+ hasMore = false,
+ ),
+ )
+ },
+ fetchArticles = { _, page, _ ->
+ requestedArticlePages += page
+ BiliResult.Ok(SearchPage(items = emptyList(), hasMore = true))
+ },
+ )
+
+ controller.search("测试")
+ advanceUntilIdle()
+ assertEquals(listOf("BV_A", "BV_B"), controller.state.value.videos.items.map { it.bvid })
+
+ // 实时屏蔽 UP A:视频列表立刻移除 BV_A,不额外发网络请求
+ filterFlow.value = ContentFilterPrefs(blockedSearchUps = listOf(BlockedSearchUp(10L, "UP A")))
+ advanceUntilIdle()
+ assertEquals(listOf(1), requestedVideoPages)
+ assertEquals(listOf("BV_B"), controller.state.value.videos.items.map { it.bvid })
+
+ // 用户栏不受 blockedSearchUps 影响(用户主动搜 UP 时仍可找到)
+ controller.selectTab(SearchTab.User)
+ advanceUntilIdle()
+ assertEquals(listOf(10L), controller.state.value.users.items.map { it.mid })
+
+ // 撤销屏蔽:BV_A 无请求恢复
+ filterFlow.value = ContentFilterPrefs()
+ advanceUntilIdle()
+ assertEquals(listOf(1), requestedVideoPages)
+ assertEquals(listOf("BV_A", "BV_B"), controller.state.value.videos.items.map { it.bvid })
+
+ // 专栏页服务端返回真空气页(即使 hasMore=true)也不触发自动补拉
+ controller.selectTab(SearchTab.Article)
+ advanceUntilIdle()
+ assertEquals(listOf(1), requestedArticlePages)
+ } finally {
+ controllerScope.cancel()
+ }
+ }
+
+ private fun video(bvid: String, upMid: Long, title: String) = SearchVideo(
+ bvid = bvid,
+ title = title,
+ coverUrl = "",
+ durationText = "01:00",
+ upName = "UP$upMid",
+ upMid = upMid,
+ publishedAtEpochSeconds = 1_700_000_000L,
+ playCount = 100L,
+ danmakuCount = 10L,
+ )
+
+ private fun article(id: Long, title: String, summary: String = "", authorMid: Long = 0L) = SearchArticle(
+ id = id,
+ title = title,
+ summary = summary,
+ coverUrl = "",
+ viewCount = 100L,
+ replyCount = 5L,
+ publishedAtEpochSeconds = 1_700_000_000L,
+ categoryName = "科技",
+ authorMid = authorMid,
+ )
+
+ private fun feedVideo(bvid: String, upMid: Long, title: String) = FeedEntry.Video(
+ bvid = bvid,
+ title = title,
+ coverUrl = "",
+ durationText = "02:00",
+ upName = "UP$upMid",
+ upMid = upMid,
+ upFaceUrl = "",
+ publishedAtEpochSeconds = 1_700_000_000L,
+ playCount = "100",
+ danmakuCount = "10",
+ )
+
+ private fun feedArticle(id: String, upMid: Long, title: String, summary: String) = FeedEntry.Article(
+ ref = ArticleRef(id = id, isRead = false),
+ title = title,
+ summary = summary,
+ coverUrl = "",
+ upName = "UP$upMid",
+ upMid = upMid,
+ upFaceUrl = "",
+ publishedAtEpochSeconds = 1_700_000_000L,
+ )
+
+ private fun dynamicCard(
+ id: String,
+ authorMid: Long,
+ text: List = emptyList(),
+ content: DynamicContent? = null,
+ additional: DynamicAdditional? = null,
+ forwarded: DynamicCard? = null,
+ ) = DynamicCard(
+ id = id,
+ type = "DYNAMIC_TYPE_WORD",
+ author = DynamicAuthor(mid = authorMid, name = "UP$authorMid", faceUrl = ""),
+ publishedAtEpochSeconds = 1_700_000_000L,
+ text = text,
+ content = content,
+ additional = additional,
+ forwarded = forwarded,
+ )
+
+ private fun inMemoryPreferencesStore(initial: Preferences = emptyPreferences()): DataStore =
+ object : DataStore {
+ private val mutex = Mutex()
+ private val state = MutableStateFlow(initial)
+ override val data: Flow = state
+ override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences): Preferences =
+ mutex.withLock {
+ val updated = transform(state.value)
+ state.value = updated
+ updated
+ }
+ }
+}