diff --git a/shared/src/commonMain/composeResources/values-en/strings.xml b/shared/src/commonMain/composeResources/values-en/strings.xml index a569f44..91e6a6b 100644 --- a/shared/src/commonMain/composeResources/values-en/strings.xml +++ b/shared/src/commonMain/composeResources/values-en/strings.xml @@ -800,6 +800,23 @@ The exclusion list is emptied and posts from these uploaders return to the feed. + + 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 Reconnected diff --git a/shared/src/commonMain/composeResources/values/strings.xml b/shared/src/commonMain/composeResources/values/strings.xml index 6e3b527..e03e4be 100644 --- a/shared/src/commonMain/composeResources/values/strings.xml +++ b/shared/src/commonMain/composeResources/values/strings.xml @@ -865,6 +865,23 @@ 排除名单会清空,这些 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 c92bb77..1735a6b 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/ContentFilter.kt b/shared/src/commonMain/kotlin/dev/bilby/data/ContentFilter.kt new file mode 100644 index 0000000..7361df5 --- /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 04770bf..6d855c0 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/data/DynamicFeedStore.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/data/DynamicFeedStore.kt @@ -50,12 +50,28 @@ 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.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) { cards, excluded -> - cards.filterNot { it.author.mid in excluded } + val other: Flow> = combine( + _other, + settings.excludedFeedMids, + settings.contentFilterPrefs, + ) { cards, excluded, filter -> + if (excluded.isEmpty() && !filter.hasKeywordFilters) { + cards + } else { + cards.filterNot { it.author.mid in excluded || filter.matchesDynamicCard(it) } + } } val status: StateFlow = _status.asStateFlow() diff --git a/shared/src/commonMain/kotlin/dev/bilby/data/SearchRepository.kt b/shared/src/commonMain/kotlin/dev/bilby/data/SearchRepository.kt index 4210062..21ade56 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 e26d735..2a52269 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/data/SettingsStore.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/data/SettingsStore.kt @@ -496,6 +496,70 @@ class SettingsStore(private val store: DataStore) { store.edit { p -> p.remove(KEY_EXCLUDED_FEED_MIDS) } } + /** + * 搜索与关键词本地过滤偏好,与 [excludedFeedMids] 严格正交。 + * 见 [ContentFilterPrefs]。 + */ + val contentFilterPrefs: Flow = store.data.map { p -> + decodeContentFilterPrefs(p[KEY_CONTENT_FILTER_JSON]) + } + + suspend fun addBlockedSearchUp(mid: Long, name: String) { + if (mid == 0L) return + val label = name.trim().ifBlank { mid.toString() } + store.edit { p -> + 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 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) { + val trimmed = keyword.trim() + if (trimmed.isEmpty()) return + store.edit { p -> + 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)) + } + } + + suspend fun removeBlockedKeyword(keyword: String) { + val trimmed = keyword.trim() + if (trimmed.isEmpty()) return + store.edit { p -> + 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 clearContentFilters() { + store.edit { p -> p.remove(KEY_CONTENT_FILTER_JSON) } + } + + 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) + } + } + /** * 普通搜索的历史,最近的在前。 * @@ -822,6 +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_FILTER_JSON = stringPreferencesKey("content_filter_json") private val KEY_DANMAKUS_ARCHIVE = booleanPreferencesKey("danmakus_archive_enabled") @@ -1168,6 +1233,19 @@ private val NightUpsJson = 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 1f92a6f..c7b011e 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/ui/BilbyApp.kt @@ -151,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 @@ -289,6 +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.ContentFilterSettingsPage import dev.bilby.ui.settings.ExcludedFeedPage import dev.bilby.ui.settings.PrivacySettingsPage import dev.bilby.ui.settings.SettingsScreen @@ -1037,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()) { @@ -1411,6 +1435,7 @@ private fun BilbyApp( onOpenFavFolders = { push(FavFolders) }, onOpenMessages = { push(Messages) }, onOpen = { push(it) }, + onBlockUpInSearch = blockUpInSearch, ) } } @@ -1545,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() }, ) } @@ -2088,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) { @@ -2184,6 +2211,7 @@ private fun RootTabs( onOpenFavFolders = onOpenFavFolders, onOpenMessages = onOpenMessages, onOpen = onOpen, + onBlockUpInSearch = onBlockUpInSearch, ) } } @@ -2224,6 +2252,7 @@ private fun RootTabs( onOpenFavFolders = onOpenFavFolders, onOpenMessages = onOpenMessages, onOpen = onOpen, + onBlockUpInSearch = onBlockUpInSearch, ) } } @@ -2720,6 +2749,7 @@ private fun RootTabsContent( onOpenFavFolders: () -> Unit, onOpenMessages: () -> Unit, onOpen: (NavKey) -> Unit, + onBlockUpInSearch: (Long, String) -> Unit, ) { val bottom = PaddingValues(bottom = insets.calculateBottomPadding()) Box( @@ -2761,6 +2791,7 @@ private fun RootTabsContent( onUserClick = onUserClick, onOpenArticle = onOpenArticle, onOpen = onOpen, + onBlockUpInSearch = onBlockUpInSearch, ) RootTab.Profile -> ProfilePane( @@ -3019,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", @@ -3099,6 +3131,7 @@ private fun SearchPane( onArticleClick = { cv -> onOpenArticle(ArticleRef(cv.toString(), isRead = true)) }, onLoadMore = vm::loadMore, onRetry = vm::refresh, + onBlockUpInSearch = onBlockUpInSearch, ), ) } @@ -3110,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() @@ -3160,6 +3200,7 @@ private fun SearchResultRoute( onArticleClick = onArticleClick, onLoadMore = vm::loadMore, onRetry = vm::retry, + onBlockUpInSearch = onBlockUpInSearch, ), modifier = Modifier.padScaffoldExceptBottom(insets), ) @@ -3350,6 +3391,7 @@ private fun SettingsPageRoute( onRetryHistoryPause = vm::loadHistoryPause, onOpenBlacklist = onOpenBlacklist, onOpenExcludedFeed = { onOpenSection(SettingsSection.ExcludedFeed) }, + onOpenContentFilter = { onOpenSection(SettingsSection.ContentFilter) }, onDanmakusArchiveChange = vm::setDanmakusArchive, onBack = onBack, ) @@ -3362,6 +3404,15 @@ private fun SettingsPageRoute( onBack = onBack, ) + SettingsSection.ContentFilter -> ContentFilterSettingsPage( + state = state, + onAddKeyword = vm::addBlockedKeyword, + onRemoveKeyword = vm::removeBlockedKeyword, + onRemoveSearchUp = vm::removeBlockedSearchUp, + onClearAll = vm::clearContentFilters, + 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/search/NormalSearchController.kt b/shared/src/commonMain/kotlin/dev/bilby/ui/search/NormalSearchController.kt index 866ed41..bad598a 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 a9f5116..1f06cc1 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 3864f50..587f4d5 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 dd17319..7d77d4f 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 @@ -97,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 @@ -128,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)。 */ @@ -508,6 +512,7 @@ private fun ResultPage( ArticleResultRow( article = article, onClick = { actions.onArticleClick(article.id) }, + onBlockUpInSearch = actions.onBlockUpInSearch, ) } } @@ -602,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, @@ -612,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, @@ -689,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, @@ -705,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 = { @@ -714,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 9501ff6..8a85929 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 @@ -172,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 @@ -228,6 +232,9 @@ enum class SettingsSection { /** 排除的 UP 主名单。从隐私页再降一层,理由见 [ExcludedFeedPage]。 */ ExcludedFeed, + + /** 搜索屏蔽的 UP 主与关键词过滤。从隐私页再降一层,与 [ExcludedFeed] 正交。 */ + ContentFilter, Agent, Privacy, NightMode, @@ -1195,6 +1202,7 @@ fun PrivacySettingsPage( onRetryHistoryPause: () -> Unit, onOpenBlacklist: () -> Unit, onOpenExcludedFeed: () -> Unit, + onOpenContentFilter: () -> Unit, onDanmakusArchiveChange: (Boolean) -> Unit, onBack: (() -> Unit)?, ) { @@ -1262,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, + ) + } } } } @@ -1345,6 +1369,199 @@ fun ExcludedFeedPage( } } +/** + * 搜索与关键词屏蔽管理页,与 [ExcludedFeedPage] 正交: + * - 关键词作用于搜索结果与主页订阅动态流(含转发原帖); + * - 搜索屏蔽 UP 主仅作用于搜索结果中的视频与专栏。 + */ +@Composable +fun ContentFilterSettingsPage( + state: SettingsUiState, + onAddKeyword: (String) -> Unit, + onRemoveKeyword: (String) -> Unit, + onRemoveSearchUp: (Long) -> Unit, + onClearAll: () -> Unit, + onBack: (() -> Unit)?, +) { + var keywordInput by rememberSaveable { mutableStateOf("") } + var confirmingClearAll by rememberSaveable { mutableStateOf(false) } + val filter = state.contentFilter + + val submitKeyword = { + val trimmed = keywordInput.trim() + if (trimmed.isNotEmpty()) { + onAddKeyword(trimmed) + keywordInput = "" + } + } + + 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)) + } + } + } + } + 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 = Icons.Outlined.Search, + title = keyword, + trailing = { + TextButton( + onClick = { onRemoveKeyword(keyword) }, + modifier = Modifier.heightIn(min = 48.dp), + ) { + Text(stringResource(Res.string.settings_content_filter_remove)) + } + }, + ) + } + } + } + } + + 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 -> + 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.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_content_filter_clear)) }, + text = { Text(stringResource(Res.string.settings_content_filter_clear_message)) }, + confirmButton = { + DestructiveConfirmButton( + text = stringResource(Res.string.action_clear), + onClick = { + confirmingClearAll = false + onClearAll() + }, + ) + }, + 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 4a52f8b..7e61f28 100644 --- a/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt +++ b/shared/src/commonMain/kotlin/dev/bilby/ui/settings/SettingsViewModel.kt @@ -20,6 +20,7 @@ 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.ExcludedUp @@ -85,6 +86,8 @@ data class SettingsUiState( val pbpOutroCompletion: Boolean = true, /** 排除的 UP 主,名字已经带上。为空时那一行不显示 —— 没排除过的人不需要看见这个概念。 */ val excludedFeedUps: List = emptyList(), + /** 搜索屏蔽的 UP 主与关键词过滤规则,与 [excludedFeedUps] 正交。 */ + val contentFilter: ContentFilterPrefs = ContentFilterPrefs(), /** 直播间要不要去 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.contentFilterPrefs.collect { filter -> + _state.update { it.copy(contentFilter = filter) } + } + } viewModelScope.launch { settings.danmakusArchiveEnabled.collect { enabled -> _state.update { it.copy(danmakusArchive = enabled) } @@ -319,6 +327,22 @@ class SettingsViewModel( persist { settings.restoreFeedMid(mid) } } + fun addBlockedKeyword(keyword: String) { + persist { settings.addBlockedKeyword(keyword) } + } + + fun removeBlockedKeyword(keyword: String) { + persist { settings.removeBlockedKeyword(keyword) } + } + + fun removeBlockedSearchUp(mid: Long) { + persist { settings.removeBlockedSearchUp(mid) } + } + + fun clearContentFilters() { + persist { settings.clearContentFilters() } + } + fun setDanmakusArchive(enabled: Boolean) { persist { settings.setDanmakusArchiveEnabled(enabled) } } 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 0000000..c3b84b9 --- /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 + } + } +}