Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions shared/src/commonMain/composeResources/values-en/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -800,6 +800,23 @@
<!-- Confirmation for restoring every excluded uploader -->
<string name="settings_feed_clear_excluded_message">The exclusion list is emptied and posts from these uploaders return to the feed.</string>

<!-- Search & keyword local filters (orthogonal to feed exclusion) -->
<string name="menu_block_up_in_search">Block creator in search</string>
<string name="search_block_up_added">Blocked %1$s in search results</string>
<string name="settings_feed_excluded_subtitle">Hidden only in the subscription feed; still visible in search and profiles</string>
<string name="settings_content_filter">Search &amp; keyword filters</string>
<string name="settings_content_filter_subtitle">Hide selected creators in search and filter keywords in search and feed</string>
<string name="settings_content_filter_count">%1$d rules</string>
<string name="settings_content_filter_keyword_section">Blocked keywords</string>
<string name="settings_content_filter_keyword_hint">Enter a keyword for titles or posts</string>
<string name="settings_content_filter_keyword_add">Add</string>
<string name="settings_content_filter_keyword_empty">No blocked keywords. Matching search results and subscription posts are hidden.</string>
<string name="settings_content_filter_search_ups_section">Blocked creators in search</string>
<string name="settings_content_filter_search_ups_empty">No creators blocked in search. Add one from any search result menu.</string>
<string name="settings_content_filter_remove">Remove</string>
<string name="settings_content_filter_clear">Clear all rules</string>
<string name="settings_content_filter_clear_message">All search-blocked creators and keywords will be removed, and hidden items will appear again.</string>

<!-- Live room connection notices -->
<string name="live_notice_disconnected">Disconnected</string>
<string name="live_notice_reconnected">Reconnected</string>
Expand Down
17 changes: 17 additions & 0 deletions shared/src/commonMain/composeResources/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -865,6 +865,23 @@
<!-- 排除名单全部恢复的确认 -->
<string name="settings_feed_clear_excluded_message">排除名单会清空,这些 UP 主的投稿重新出现在动态里。</string>

<!-- 搜索与关键词本地屏蔽(与订阅流排除名单正交) -->
<string name="menu_block_up_in_search">在搜索中屏蔽该 UP 主</string>
<string name="search_block_up_added">已在搜索结果中屏蔽 %1$s</string>
<string name="settings_feed_excluded_subtitle">仅在订阅动态流中隐藏,主动搜索与个人空间照常可见</string>
<string name="settings_content_filter">搜索与关键词屏蔽</string>
<string name="settings_content_filter_subtitle">隐藏搜索中的指定 UP 主,并按关键词过滤搜索与订阅动态</string>
<string name="settings_content_filter_count">%1$d 项</string>
<string name="settings_content_filter_keyword_section">屏蔽关键词</string>
<string name="settings_content_filter_keyword_hint">输入标题或动态正文关键词</string>
<string name="settings_content_filter_keyword_add">添加</string>
<string name="settings_content_filter_keyword_empty">未添加屏蔽关键词,命中关键词的搜索结果与订阅动态会被隐藏。</string>
<string name="settings_content_filter_search_ups_section">搜索屏蔽的 UP 主</string>
<string name="settings_content_filter_search_ups_empty">未在搜索中屏蔽任何 UP 主,可在搜索结果菜单中添加。</string>
<string name="settings_content_filter_remove">移除</string>
<string name="settings_content_filter_clear">清空全部规则</string>
<string name="settings_content_filter_clear_message">搜索屏蔽的 UP 主与关键词列表都会被清空,相关内容将重新显示。</string>

<!-- 直播间的连接状态提示 -->
<string name="live_notice_disconnected">连接已断开</string>
<string name="live_notice_reconnected">已重新连接</string>
Expand Down
2 changes: 2 additions & 0 deletions shared/src/commonMain/kotlin/dev/bilby/api/dto/SearchDto.kt
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ data class SearchSuggestDto(
data class SearchArticleItemDto(
/** cv 号。 */
val id: Long = 0,
/** 作者 mid。专栏搜索接口不返回作者名,只返回 mid。 */
val mid: Long = 0,
/** 带 `<em>` 高亮与 HTML 实体,同视频标题。 */
val title: String = "",
val desc: String = "",
Expand Down
183 changes: 183 additions & 0 deletions shared/src/commonMain/kotlin/dev/bilby/data/ContentFilter.kt
Original file line number Diff line number Diff line change
@@ -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<BlockedSearchUp> = emptyList(),
val keywords: List<String> = emptyList(),
) {
@Transient
private val blockedMidSet: Set<Long> = if (blockedSearchUps.isEmpty()) {
emptySet()
} else {
blockedSearchUps.mapTo(HashSet(blockedSearchUps.size)) { it.mid }
}

@Transient
private val effectiveKeywords: List<String> = 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<RichSpan>): 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
}
}
24 changes: 20 additions & 4 deletions shared/src/commonMain/kotlin/dev/bilby/data/DynamicFeedStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,28 @@ class DynamicFeedStore(
private val _other = MutableStateFlow<List<DynamicCard>>(emptyList())
private val _status = MutableStateFlow(DynamicFeedStatus())

val home: Flow<List<FeedEntry>> = combine(_home, settings.excludedFeedMids) { items, excluded ->
items.filterNot { it.upMid in excluded }
val home: Flow<List<FeedEntry>> = 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<List<DynamicCard>> = combine(_other, settings.excludedFeedMids) { cards, excluded ->
cards.filterNot { it.author.mid in excluded }
val other: Flow<List<DynamicCard>> = 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<DynamicFeedStatus> = _status.asStateFlow()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ data class SearchArticle(
val publishedAtEpochSeconds: Long,
val categoryName: String,
val titleHighlights: List<IntRange> = emptyList(),
val authorMid: Long = 0L,
)

data class SearchVideoPage(val items: List<SearchVideo>, val hasMore: Boolean)
Expand Down Expand Up @@ -220,6 +221,7 @@ class SearchRepository(private val client: BiliClient) {
replyCount = reply,
publishedAtEpochSeconds = pubTime,
categoryName = categoryName,
authorMid = mid,
)
}

Expand Down
78 changes: 78 additions & 0 deletions shared/src/commonMain/kotlin/dev/bilby/data/SettingsStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,70 @@ class SettingsStore(private val store: DataStore<Preferences>) {
store.edit { p -> p.remove(KEY_EXCLUDED_FEED_MIDS) }
}

/**
* 搜索与关键词本地过滤偏好,与 [excludedFeedMids] 严格正交。
* 见 [ContentFilterPrefs]。
*/
val contentFilterPrefs: Flow<ContentFilterPrefs> = 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)
}
}

/**
* 普通搜索的历史,最近的在前。
*
Expand Down Expand Up @@ -822,6 +886,7 @@ class SettingsStore(private val store: DataStore<Preferences>) {
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")

Expand Down Expand Up @@ -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<WhitelistedUp> {
if (raw.isNullOrBlank()) return emptyList()
Expand Down
Loading
Loading