feat: release v0.1.3 with video favorites
This commit is contained in:
1 parent
e8cd96eb5e
commit
a9f38d7359
28 files changed
+1492
-50
No files matched your search
@@ -13,8 +13,8 @@ android {
|
||||
applicationId = "dev.bulubulu.tv"
|
||||
minSdk = 23
|
||||
targetSdk = 34
|
||||
versionCode = 3
|
||||
versionName = "0.1.2"
|
||||
versionCode = 4
|
||||
versionName = "0.1.3"
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
buildFeatures { compose = true; buildConfig = true }
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
@file:OptIn(androidx.compose.ui.test.ExperimentalTestApi::class)
|
||||
|
||||
package dev.bulubulu.tv.player
|
||||
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.semantics.SemanticsProperties
|
||||
import androidx.compose.ui.test.*
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import dev.bulubulu.tv.core.*
|
||||
import dev.bulubulu.tv.favorites.FavoriteActionState
|
||||
import dev.bulubulu.tv.ui.BulubuluTheme
|
||||
import dev.bulubulu.tv.ui.FavoriteDialog
|
||||
import java.net.ServerSocket
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
class PlayerFavoriteNavigationTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
|
||||
@Test fun remoteMovesBetweenPlayerActionsAndRestoresFocusAfterFavoriteMenu() {
|
||||
// A local socket keeps playback buffering; this test never accesses an external CDN.
|
||||
ServerSocket(0).use { socket ->
|
||||
val source = PlaybackSource("播放器收藏操作", PlaybackStream("https://127.0.0.1:" + socket.localPort + "/video"))
|
||||
val favorite = mutableStateOf(FavoriteActionState(
|
||||
aid = 100, loggedIn = true, folders = listOf(FavoriteFolder(11, "默认收藏夹", 0)), selectedIds = setOf(11),
|
||||
))
|
||||
compose.setContent { BulubuluTheme {
|
||||
PlayerScreen(source, {}, {}, favorite.value, { favorite.value = favorite.value.copy(visible = true) })
|
||||
if (favorite.value.visible) {
|
||||
FavoriteDialog(favorite.value, {}, {}, {}, { favorite.value = favorite.value.copy(visible = false) })
|
||||
}
|
||||
} }
|
||||
compose.mainClock.advanceTimeBy(350)
|
||||
compose.onNodeWithTag("quality_button").key(Key.DirectionUp)
|
||||
awaitFocus("quality_button")
|
||||
compose.onNodeWithTag("quality_button").key(Key.DirectionRight)
|
||||
awaitFocus("favorite_button")
|
||||
compose.onNodeWithTag("favorite_button").key(Key.DirectionLeft)
|
||||
awaitFocus("quality_button")
|
||||
compose.onNodeWithTag("quality_button").key(Key.DirectionRight).key(Key.DirectionCenter)
|
||||
compose.mainClock.advanceTimeBy(350)
|
||||
awaitFocus("favorite_option_11")
|
||||
InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK)
|
||||
compose.mainClock.advanceTimeBy(350)
|
||||
awaitFocus("favorite_button")
|
||||
}
|
||||
}
|
||||
|
||||
private fun SemanticsNodeInteraction.key(key: Key) = performKeyInput { keyDown(key); keyUp(key) }
|
||||
private fun awaitFocus(tag: String) = compose.waitUntil(5_000) {
|
||||
compose.onAllNodesWithTag(tag).fetchSemanticsNodes().any { it.config.getOrElse(SemanticsProperties.Focused) { false } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
@file:OptIn(androidx.compose.ui.test.ExperimentalTestApi::class)
|
||||
|
||||
package dev.bulubulu.tv.ui
|
||||
|
||||
import android.view.KeyEvent
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.semantics.SemanticsProperties
|
||||
import androidx.compose.ui.test.*
|
||||
import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import dev.bulubulu.tv.core.*
|
||||
import dev.bulubulu.tv.favorites.FavoriteActionState
|
||||
import dev.bulubulu.tv.favorites.FavoriteLibraryState
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
|
||||
class FavoriteNavigationTest {
|
||||
@get:Rule val compose = createComposeRule()
|
||||
private val folders = listOf(FavoriteFolder(11, "默认收藏夹", 2), FavoriteFolder(22, "教程", 1))
|
||||
|
||||
@Test fun favoritesTabOnlyAppearsAfterLoginAndIsRemoteReachable() {
|
||||
val state = mutableStateOf(HomeUiState(loading = false, hasMore = false))
|
||||
compose.setContent { BulubuluTheme {
|
||||
BulubuluHome(
|
||||
state = state.value, onTabSelected = { state.value = state.value.copy(selectedTab = it) },
|
||||
onItemSelected = {}, onLoadMore = {}, onRefresh = {}, onLogin = {}, onLogout = {},
|
||||
favorites = FavoriteLibraryState(folders = folders, selectedFolderId = 11),
|
||||
)
|
||||
} }
|
||||
compose.mainClock.advanceTimeBy(300)
|
||||
compose.onNodeWithTag("tab_FAVORITES").assertDoesNotExist()
|
||||
compose.runOnIdle { state.value = state.value.copy(account = Account(123, "测试用户")) }
|
||||
compose.onNodeWithTag("tab_RECOMMEND").key(Key.DirectionRight).key(Key.DirectionRight).key(Key.DirectionRight).key(Key.DirectionCenter)
|
||||
compose.runOnIdle { assertEquals(ContentTab.FAVORITES, state.value.selectedTab) }
|
||||
awaitFocus("tab_FAVORITES")
|
||||
compose.onNodeWithTag("tab_FAVORITES").key(Key.DirectionDown)
|
||||
awaitFocus("favorite_folder_11")
|
||||
}
|
||||
|
||||
@Test fun favoriteVideosOpenAndBackReturnsThroughFolderToTab() {
|
||||
val favorite = mutableStateOf(FavoriteLibraryState(
|
||||
folders = folders, selectedFolderId = 11,
|
||||
items = listOf(VideoItem("av1", "收藏视频 0", "", aid = 1)),
|
||||
))
|
||||
val state = mutableStateOf(HomeUiState(
|
||||
selectedTab = ContentTab.FAVORITES, account = Account(123, "测试用户"), loading = false,
|
||||
))
|
||||
var selected: VideoItem? = null
|
||||
compose.setContent { BulubuluTheme {
|
||||
BulubuluHome(
|
||||
state.value, {}, { selected = it }, {}, {}, {}, {},
|
||||
favorites = favorite.value,
|
||||
onFavoriteFolderSelected = { favorite.value = favorite.value.copy(selectedFolderId = it) },
|
||||
)
|
||||
} }
|
||||
compose.mainClock.advanceTimeBy(300)
|
||||
compose.onNodeWithTag("tab_FAVORITES").key(Key.DirectionDown)
|
||||
awaitFocus("favorite_folder_11")
|
||||
compose.onNodeWithTag("favorite_folder_11").key(Key.DirectionDown)
|
||||
compose.waitUntil(5_000) {
|
||||
compose.onAllNodesWithText("收藏视频 0").fetchSemanticsNodes().any { it.config.getOrElse(SemanticsProperties.Focused) { false } }
|
||||
}
|
||||
compose.onNodeWithText("收藏视频 0").key(Key.DirectionCenter)
|
||||
compose.runOnIdle { assertEquals("av1", selected?.id) }
|
||||
back(); awaitFocus("favorite_folder_11")
|
||||
back(); awaitFocus("tab_FAVORITES")
|
||||
}
|
||||
|
||||
@Test fun selectedFolderOutsideViewportScrollsIntoFocus() {
|
||||
compose.setContent { BulubuluTheme {
|
||||
BulubuluHome(
|
||||
HomeUiState(selectedTab = ContentTab.FAVORITES, account = Account(123, "测试用户"), loading = false),
|
||||
{}, {}, {}, {}, {}, {},
|
||||
favorites = FavoriteLibraryState(
|
||||
folders = (1L..20L).map { FavoriteFolder(it, "收藏夹 $it", 0) }, selectedFolderId = 20,
|
||||
),
|
||||
)
|
||||
} }
|
||||
compose.mainClock.advanceTimeBy(300)
|
||||
compose.onNodeWithTag("tab_FAVORITES").key(Key.DirectionDown)
|
||||
awaitFocus("favorite_folder_20")
|
||||
compose.onNodeWithTag("favorite_folder_20").assertIsDisplayed()
|
||||
back(); awaitFocus("tab_FAVORITES")
|
||||
}
|
||||
|
||||
@Test fun folderChoicesAreDraftsUntilRemoteConfirmsSave() {
|
||||
val state = mutableStateOf(FavoriteActionState(
|
||||
aid = 100, loggedIn = true, visible = true, folders = folders, selectedIds = setOf(11),
|
||||
))
|
||||
var saved = false
|
||||
compose.setContent { BulubuluTheme {
|
||||
FavoriteDialog(
|
||||
state.value,
|
||||
{ id -> state.value = state.value.copy(selectedIds = state.value.selectedIds.let { if (id in it) it - id else it + id }) },
|
||||
{ saved = true }, {}, {},
|
||||
)
|
||||
} }
|
||||
compose.mainClock.advanceTimeBy(400)
|
||||
awaitFocus("favorite_option_11")
|
||||
compose.onNodeWithTag("favorite_option_11").key(Key.DirectionCenter).key(Key.DirectionDown)
|
||||
awaitFocus("favorite_option_22")
|
||||
compose.onNodeWithTag("favorite_option_22").key(Key.DirectionCenter)
|
||||
compose.runOnIdle { assertFalse(saved); assertEquals(setOf(22L), state.value.selectedIds) }
|
||||
compose.onNodeWithTag("favorite_option_22").key(Key.DirectionDown)
|
||||
awaitFocus("favorite_save")
|
||||
compose.onNodeWithTag("favorite_save").key(Key.DirectionCenter)
|
||||
compose.runOnIdle { assertTrue(saved) }
|
||||
}
|
||||
|
||||
@Test fun savingPreventsDuplicateWritesButBackCanDismiss() {
|
||||
var dismissed = false
|
||||
compose.setContent { BulubuluTheme {
|
||||
FavoriteDialog(
|
||||
FavoriteActionState(visible = true, saving = true, folders = folders, selectedIds = setOf(11)),
|
||||
{}, {}, {}, { dismissed = true },
|
||||
)
|
||||
} }
|
||||
compose.mainClock.advanceTimeBy(350)
|
||||
awaitFocus("favorite_close")
|
||||
compose.onNodeWithTag("favorite_option_11").assertIsNotEnabled()
|
||||
compose.onNodeWithTag("favorite_save").assertIsNotEnabled()
|
||||
back()
|
||||
compose.runOnIdle { assertTrue(dismissed) }
|
||||
}
|
||||
|
||||
@Test fun longFolderListScrollsToSelectionAndUncertainResultRequiresReload() {
|
||||
val state = mutableStateOf(FavoriteActionState(
|
||||
visible = true, folders = (1L..15L).map { FavoriteFolder(it, "收藏夹 $it", 0) }, selectedIds = setOf(15),
|
||||
))
|
||||
var reloaded = false
|
||||
compose.setContent { BulubuluTheme {
|
||||
FavoriteDialog(state.value, {}, {}, { reloaded = true }, {})
|
||||
} }
|
||||
compose.mainClock.advanceTimeBy(450)
|
||||
awaitFocus("favorite_option_15")
|
||||
compose.onNodeWithTag("favorite_option_15").assertIsDisplayed()
|
||||
compose.runOnIdle { state.value = state.value.copy(needsReload = true, error = "结果尚未确认") }
|
||||
compose.mainClock.advanceTimeBy(250)
|
||||
awaitFocus("favorite_reload")
|
||||
compose.onNodeWithTag("favorite_save").assertDoesNotExist()
|
||||
compose.onNodeWithTag("favorite_reload").key(Key.DirectionCenter)
|
||||
compose.runOnIdle { assertTrue(reloaded) }
|
||||
}
|
||||
|
||||
private fun back() = InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK)
|
||||
private fun SemanticsNodeInteraction.key(key: Key) = performKeyInput { keyDown(key); keyUp(key) }
|
||||
private fun awaitFocus(tag: String) = compose.waitUntil(5_000) {
|
||||
compose.onAllNodesWithTag(tag).fetchSemanticsNodes().any { it.config.getOrElse(SemanticsProperties.Focused) { false } }
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,9 @@ import dev.bulubulu.tv.core.VideoDetails
|
||||
import dev.bulubulu.tv.core.VideoEpisode
|
||||
import dev.bulubulu.tv.core.VideoItem
|
||||
import dev.bulubulu.tv.core.SearchCategory
|
||||
import dev.bulubulu.tv.core.Account
|
||||
import dev.bulubulu.tv.favorites.FavoriteLibraryController
|
||||
import dev.bulubulu.tv.favorites.FavoriteActionController
|
||||
import dev.bulubulu.tv.search.SearchController
|
||||
import dev.bulubulu.tv.ui.HomeUiState
|
||||
import java.net.SocketTimeoutException
|
||||
@@ -55,6 +58,12 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
val notice = _notice.asStateFlow()
|
||||
private val searchController = SearchController(viewModelScope, graph.search)
|
||||
val search = searchController.state
|
||||
private val libraryController = FavoriteLibraryController(viewModelScope, graph.favorites)
|
||||
val favoriteLibrary = libraryController.state
|
||||
private val favoriteController = FavoriteActionController(
|
||||
viewModelScope, graph.favorites, libraryController::refreshIfOpened, ::showNotice,
|
||||
)
|
||||
val favoriteAction = favoriteController.state
|
||||
|
||||
private data class CachedFeed(val items: List<VideoItem>, val nextPage: Int?)
|
||||
private val feeds = mutableMapOf<ContentTab, CachedFeed>()
|
||||
@@ -65,12 +74,13 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
private var accountJob: Job? = null
|
||||
private var logoutJob: Job? = null
|
||||
private var selectedItem: VideoItem? = null
|
||||
private var feedGeneration = 0L
|
||||
|
||||
init {
|
||||
accountJob = viewModelScope.launch {
|
||||
try {
|
||||
val account = graph.auth.currentAccount()
|
||||
_home.update { it.copy(account = account) }
|
||||
applyAccount(account)
|
||||
} catch (error: Exception) {
|
||||
error.rethrowCancellation()
|
||||
showNotice("登录状态暂时无法验证,已保留本地登录信息")
|
||||
@@ -81,6 +91,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
fun selectTab(tab: ContentTab) {
|
||||
if (_home.value.authBusy) return
|
||||
if (tab == ContentTab.FAVORITES && _home.value.account == null) return
|
||||
if (tab == _home.value.selectedTab) return
|
||||
loadTab(tab)
|
||||
}
|
||||
@@ -91,6 +102,12 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
private fun loadTab(tab: ContentTab, force: Boolean = false) {
|
||||
feedJob?.cancel()
|
||||
val request = ++feedGeneration
|
||||
if (tab == ContentTab.FAVORITES) {
|
||||
_home.update { it.copy(selectedTab = tab, items = emptyList(), loading = false, loadingMore = false, error = null, hasMore = false) }
|
||||
libraryController.refresh()
|
||||
return
|
||||
}
|
||||
val cached = feeds[tab].takeUnless { force }
|
||||
_home.update {
|
||||
it.copy(
|
||||
@@ -106,12 +123,14 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
feedJob = viewModelScope.launch {
|
||||
try {
|
||||
val result = graph.content.loadFeed(tab)
|
||||
if (request != feedGeneration) return@launch
|
||||
feeds[tab] = CachedFeed(result.items.distinctBy(VideoItem::id), result.nextPage)
|
||||
_home.update {
|
||||
it.copy(items = feeds.getValue(tab).items, loading = false, hasMore = result.nextPage != null)
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
error.rethrowCancellation()
|
||||
if (request != feedGeneration) return@launch
|
||||
_home.update { it.copy(loading = false, error = userMessage(error)) }
|
||||
}
|
||||
}
|
||||
@@ -120,11 +139,14 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
fun loadMore() {
|
||||
val current = _home.value
|
||||
if (current.loading || current.loadingMore || current.authBusy) return
|
||||
if (current.selectedTab == ContentTab.FAVORITES) { libraryController.loadMore(); return }
|
||||
val nextPage = feeds[current.selectedTab]?.nextPage ?: return
|
||||
_home.update { it.copy(loadingMore = true, error = null) }
|
||||
val request = feedGeneration
|
||||
feedJob = viewModelScope.launch {
|
||||
try {
|
||||
val result = graph.content.loadFeed(current.selectedTab, nextPage)
|
||||
if (request != feedGeneration) return@launch
|
||||
val merged = (current.items + result.items).distinctBy(VideoItem::id)
|
||||
// A repeated backend page must not leave an endless "load more" loop.
|
||||
val following = result.nextPage.takeIf { merged.size > current.items.size }
|
||||
@@ -132,6 +154,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
_home.update { it.copy(items = merged, loadingMore = false, hasMore = following != null) }
|
||||
} catch (error: Exception) {
|
||||
error.rethrowCancellation()
|
||||
if (request != feedGeneration) return@launch
|
||||
_home.update { it.copy(loadingMore = false, error = userMessage(error)) }
|
||||
}
|
||||
}
|
||||
@@ -161,7 +184,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
_login.update { it.copy(status = status) }
|
||||
when (status) {
|
||||
is QrLoginStatus.Success -> {
|
||||
_home.update { it.copy(account = status.account) }
|
||||
applyAccount(status.account)
|
||||
feeds.clear()
|
||||
_login.value = LoginUiState()
|
||||
refresh()
|
||||
@@ -203,8 +226,10 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
closePlayer()
|
||||
closeSearch()
|
||||
feedJob?.cancel()
|
||||
feedGeneration++
|
||||
feeds.clear()
|
||||
_home.update { it.copy(account = null, items = emptyList(), loading = true, loadingMore = false, error = null, authBusy = true) }
|
||||
applyAccount(null)
|
||||
_home.update { it.copy(selectedTab = ContentTab.RECOMMEND, items = emptyList(), loading = true, loadingMore = false, error = null, authBusy = true) }
|
||||
logoutJob = viewModelScope.launch {
|
||||
try {
|
||||
graph.auth.logout()
|
||||
@@ -257,6 +282,7 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
detailsJob = viewModelScope.launch {
|
||||
try {
|
||||
val source = graph.content.resolvePlayback(episode)
|
||||
favoriteController.setVideo(episode.aid)
|
||||
val heading = _details.value.details?.title.orEmpty()
|
||||
_playback.value = if (heading.isNotBlank() && heading != source.title) {
|
||||
source.copy(title = "$heading · ${source.title}")
|
||||
@@ -269,7 +295,19 @@ class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
}
|
||||
|
||||
fun closePlayer() { _playback.value = null }
|
||||
fun closePlayer() { favoriteController.setVideo(null); _playback.value = null }
|
||||
|
||||
fun selectFavoriteFolder(id: Long) = libraryController.selectFolder(id)
|
||||
fun openFavorite() = favoriteController.open()
|
||||
fun closeFavorite() = favoriteController.close()
|
||||
fun toggleFavoriteFolder(id: Long) = favoriteController.toggle(id)
|
||||
fun saveFavorite() = favoriteController.save()
|
||||
|
||||
private fun applyAccount(account: Account?) {
|
||||
libraryController.setAccount(account?.uid)
|
||||
favoriteController.setAccount(account?.uid)
|
||||
_home.update { it.copy(account = account) }
|
||||
}
|
||||
|
||||
fun openSearch() {
|
||||
if (!_home.value.authBusy) searchController.open()
|
||||
|
||||
@@ -6,6 +6,7 @@ import dev.bulubulu.tv.data.BiliHttpClient
|
||||
import dev.bulubulu.tv.data.ContentRepository
|
||||
import dev.bulubulu.tv.data.SessionStore
|
||||
import dev.bulubulu.tv.data.SearchRepository
|
||||
import dev.bulubulu.tv.data.FavoriteRepository
|
||||
|
||||
class BulubuluApplication : Application() {
|
||||
val sessionStore by lazy { SessionStore(this) }
|
||||
@@ -13,4 +14,5 @@ class BulubuluApplication : Application() {
|
||||
val auth by lazy { AuthRepository(http, sessionStore) }
|
||||
val content by lazy { ContentRepository(http) }
|
||||
val search by lazy { SearchRepository(http) }
|
||||
val favorites by lazy { FavoriteRepository(http) }
|
||||
}
|
||||
@@ -29,6 +29,7 @@ import dev.bulubulu.tv.ui.BulubuluTheme
|
||||
import dev.bulubulu.tv.ui.DetailsDialog
|
||||
import dev.bulubulu.tv.ui.LoginDialog
|
||||
import dev.bulubulu.tv.ui.SearchScreen
|
||||
import dev.bulubulu.tv.ui.FavoriteDialog
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
private val model: AppViewModel by viewModels()
|
||||
@@ -47,6 +48,8 @@ class MainActivity : ComponentActivity() {
|
||||
val playback by model.playback.collectAsStateWithLifecycle()
|
||||
val notice by model.notice.collectAsStateWithLifecycle()
|
||||
val search by model.search.collectAsStateWithLifecycle()
|
||||
val favoriteLibrary by model.favoriteLibrary.collectAsStateWithLifecycle()
|
||||
val favoriteAction by model.favoriteAction.collectAsStateWithLifecycle()
|
||||
var focusRestoreKey by remember { mutableIntStateOf(0) }
|
||||
var hadOverlay by remember { mutableStateOf(false) }
|
||||
var searchFocusRestoreKey by remember { mutableIntStateOf(0) }
|
||||
@@ -73,6 +76,8 @@ class MainActivity : ComponentActivity() {
|
||||
focusRestoreKey = focusRestoreKey,
|
||||
active = !overlay,
|
||||
onSearch = model::openSearch,
|
||||
favorites = favoriteLibrary,
|
||||
onFavoriteFolderSelected = model::selectFavoriteFolder,
|
||||
)
|
||||
if (search.visible) {
|
||||
SearchScreen(
|
||||
@@ -95,7 +100,10 @@ class MainActivity : ComponentActivity() {
|
||||
if (details.visible) {
|
||||
DetailsDialog(details.details, details.loading, details.error, model::play, model::retryDetails, model::dismissDetails)
|
||||
}
|
||||
playback?.let { PlayerScreen(it, model::closePlayer, model::playbackError) }
|
||||
playback?.let { PlayerScreen(it, model::closePlayer, model::playbackError, favoriteAction, model::openFavorite) }
|
||||
if (favoriteAction.visible && playback != null) {
|
||||
FavoriteDialog(favoriteAction, model::toggleFavoriteFolder, model::saveFavorite, model::openFavorite, model::closeFavorite)
|
||||
}
|
||||
notice?.let { message ->
|
||||
Surface(
|
||||
modifier = Modifier.align(Alignment.BottomCenter).padding(24.dp),
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package dev.bulubulu.tv.core
|
||||
|
||||
data class FavoriteFolder(
|
||||
val id: Long,
|
||||
val title: String,
|
||||
val mediaCount: Int,
|
||||
val containsVideo: Boolean = false,
|
||||
)
|
||||
|
||||
data class FavoritePage(val items: List<VideoItem>, val nextPage: Int?)
|
||||
|
||||
interface FavoriteDataSource {
|
||||
suspend fun folders(uid: Long, aid: Long? = null): List<FavoriteFolder>
|
||||
suspend fun videos(uid: Long, folderId: Long, page: Int): FavoritePage
|
||||
suspend fun isFavorite(uid: Long, aid: Long): Boolean
|
||||
suspend fun update(uid: Long, aid: Long, add: Set<Long>, remove: Set<Long>)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package dev.bulubulu.tv.core
|
||||
|
||||
enum class ContentTab(val title: String) {
|
||||
RECOMMEND("推荐"), MOVIE("电影"), BANGUMI("番剧")
|
||||
RECOMMEND("推荐"), MOVIE("电影"), BANGUMI("番剧"), FAVORITES("我的收藏")
|
||||
}
|
||||
|
||||
data class Account(val uid: Long, val name: String, val avatarUrl: String = "")
|
||||
|
||||
@@ -22,6 +22,8 @@ import dev.bulubulu.tv.core.ClientException
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
internal data class AccountRequestSession(val epoch: Long, val csrf: String?)
|
||||
|
||||
/** Host/path/expiry checks are shared by persistence and actual network requests. */
|
||||
internal class BiliCookieJar(private val storage: SessionCookieStore) : CookieJar {
|
||||
private var epoch = 0L
|
||||
@@ -29,6 +31,27 @@ internal class BiliCookieJar(private val storage: SessionCookieStore) : CookieJa
|
||||
@Synchronized
|
||||
fun currentEpoch(): Long = epoch
|
||||
|
||||
@Synchronized
|
||||
fun requestSession(url: HttpUrl, expectedEpoch: Long? = null): Pair<Long, List<Cookie>> {
|
||||
if (expectedEpoch != null && expectedEpoch != epoch) {
|
||||
// OkHttp worker callbacks require IOException for interceptor failures.
|
||||
throw IOException("登录状态已变化,请重新操作")
|
||||
}
|
||||
return epoch to loadForRequest(url)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun accountSession(uid: Long, requireCsrf: Boolean): AccountRequestSession {
|
||||
val scoped = loadForRequest("https://api.bilibili.com/".toHttpUrlOrNull()!!)
|
||||
if (uid <= 0 || scoped.none { it.name == "DedeUserID" && it.value == uid.toString() } ||
|
||||
scoped.none { it.name == "SESSDATA" && it.value.isNotBlank() }) {
|
||||
throw ClientException("请重新扫码登录后使用收藏")
|
||||
}
|
||||
val csrf = scoped.firstOrNull { it.name == "bili_jct" }?.value?.takeIf { it.isNotBlank() }
|
||||
if (requireCsrf && csrf == null) throw ClientException("登录验证已失效,请重新扫码登录")
|
||||
return AccountRequestSession(epoch, csrf)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun clear() {
|
||||
epoch++
|
||||
@@ -100,8 +123,9 @@ class BiliHttpClient(storage: SessionCookieStore) {
|
||||
// The epoch also prevents an in-flight login response restoring cookies after logout.
|
||||
.addNetworkInterceptor { chain ->
|
||||
val request = chain.request()
|
||||
val epoch = cookies.currentEpoch()
|
||||
val scopedCookies = cookies.loadForRequest(request.url)
|
||||
val (epoch, scopedCookies) = cookies.requestSession(
|
||||
request.url, request.tag(AccountRequestSession::class.java)?.epoch,
|
||||
)
|
||||
val builder = request.newBuilder().removeHeader("Cookie")
|
||||
if (scopedCookies.isNotEmpty()) {
|
||||
builder.header("Cookie", scopedCookies.joinToString("; ") { "${it.name}=${it.value}" })
|
||||
@@ -125,18 +149,30 @@ class BiliHttpClient(storage: SessionCookieStore) {
|
||||
url: String,
|
||||
params: Map<String, String> = emptyMap(),
|
||||
allowedApiCodes: Set<Int> = emptySet(),
|
||||
): JSONObject = getJsonForSession(url, params, allowedApiCodes, null)
|
||||
|
||||
private suspend fun getJsonForSession(
|
||||
url: String, params: Map<String, String>, allowedApiCodes: Set<Int>, session: AccountRequestSession?,
|
||||
): JSONObject {
|
||||
val target = officialUrl(url).newBuilder().apply {
|
||||
params.forEach { (key, value) -> setQueryParameter(key, value) }
|
||||
}.build()
|
||||
return requestJson(Request.Builder().url(target).get().build(), allowedApiCodes)
|
||||
return requestJson(Request.Builder().url(target).tag(AccountRequestSession::class.java, session).get().build(), allowedApiCodes)
|
||||
}
|
||||
|
||||
suspend fun postFormJson(url: String, params: Map<String, String>): JSONObject {
|
||||
internal suspend fun getAccountJson(url: String, params: Map<String, String>, uid: Long): JSONObject =
|
||||
getJsonForSession(url, params, emptySet(), cookies.accountSession(uid, requireCsrf = false))
|
||||
|
||||
internal fun accountRequestSession(uid: Long): AccountRequestSession = cookies.accountSession(uid, requireCsrf = true)
|
||||
|
||||
suspend fun postFormJson(url: String, params: Map<String, String>): JSONObject =
|
||||
postFormJson(url, params, null)
|
||||
|
||||
internal suspend fun postFormJson(url: String, params: Map<String, String>, session: AccountRequestSession?): JSONObject {
|
||||
val body = FormBody.Builder().apply {
|
||||
params.forEach { (key, value) -> add(key, value) }
|
||||
}.build()
|
||||
return requestJson(Request.Builder().url(officialUrl(url)).post(body).build(), emptySet())
|
||||
return requestJson(Request.Builder().url(officialUrl(url)).tag(AccountRequestSession::class.java, session).post(body).build(), emptySet())
|
||||
}
|
||||
|
||||
/** Obtain the ordinary first-party browser cookie required by official search. */
|
||||
@@ -173,7 +209,11 @@ class BiliHttpClient(storage: SessionCookieStore) {
|
||||
|
||||
private suspend fun requestJson(request: Request, allowedApiCodes: Set<Int>): JSONObject =
|
||||
withContext(Dispatchers.IO) {
|
||||
client.newCall(request).awaitResponse().use { response ->
|
||||
// A form's CSRF value and account-specific requests must never follow a redirect.
|
||||
val transport = if (request.method == "POST" || request.tag(AccountRequestSession::class.java) != null) {
|
||||
client.newBuilder().followRedirects(false).retryOnConnectionFailure(false).build()
|
||||
} else client
|
||||
transport.newCall(request).awaitResponse().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
val message = when (response.code) {
|
||||
412 -> "请求被哔哩哔哩风控拦截,请稍后重试或切换正常网络"
|
||||
|
||||
@@ -25,6 +25,7 @@ class ContentRepository(private val http: BiliHttpClient) {
|
||||
ContentTab.RECOMMEND -> recommendations(page)
|
||||
ContentTab.MOVIE -> seasonIndex(seasonType = 2, page = page)
|
||||
ContentTab.BANGUMI -> seasonIndex(seasonType = 1, page = page)
|
||||
ContentTab.FAVORITES -> throw ClientException("请登录后打开我的收藏")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package dev.bulubulu.tv.data
|
||||
|
||||
import dev.bulubulu.tv.core.BiliApiException
|
||||
import dev.bulubulu.tv.core.ClientException
|
||||
import dev.bulubulu.tv.core.FavoriteDataSource
|
||||
import dev.bulubulu.tv.core.FavoriteFolder
|
||||
import dev.bulubulu.tv.core.FavoritePage
|
||||
import dev.bulubulu.tv.core.VideoItem
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
/** Account-bound official favorites; only an explicit Save issues a mutation. */
|
||||
class FavoriteRepository(private val http: BiliHttpClient) : FavoriteDataSource {
|
||||
override suspend fun folders(uid: Long, aid: Long?): List<FavoriteFolder> {
|
||||
val params = mutableMapOf("up_mid" to uid.toString(), "type" to "2", "web_location" to "333.1387")
|
||||
if (aid != null) {
|
||||
require(aid > 0)
|
||||
params += mapOf("rid" to aid.toString(), "type" to "2")
|
||||
}
|
||||
val response = http.getAccountJson("$API/x/v3/fav/folder/created/list-all", params, uid)
|
||||
if (response.has("data") && response.isNull("data")) {
|
||||
// The endpoint can return data:null to anonymous/expired sessions too.
|
||||
val nav = http.getAccountJson("$API/x/web-interface/nav", emptyMap(), uid).optJSONObject("data")
|
||||
if (nav?.optBoolean("isLogin") != true || nav.optLong("mid") != uid) {
|
||||
throw BiliApiException(-101, "登录已失效,请重新扫码登录后查看收藏")
|
||||
}
|
||||
}
|
||||
return FavoriteJson.folders(response, uid, aid != null)
|
||||
}
|
||||
|
||||
override suspend fun videos(uid: Long, folderId: Long, page: Int): FavoritePage {
|
||||
require(folderId > 0 && page in 1..FavoriteJson.MAX_PAGE)
|
||||
return FavoriteJson.videos(http.getAccountJson(
|
||||
"$API/x/v3/fav/resource/list",
|
||||
mapOf("media_id" to folderId.toString(), "pn" to page.toString(), "ps" to "20", "order" to "mtime", "platform" to "web", "type" to "0", "tid" to "0", "web_location" to "333.1387"),
|
||||
uid,
|
||||
), page)
|
||||
}
|
||||
|
||||
override suspend fun isFavorite(uid: Long, aid: Long): Boolean {
|
||||
require(aid > 0)
|
||||
return FavoriteJson.status(http.getAccountJson("$API/x/v2/fav/video/favoured", mapOf("aid" to aid.toString()), uid))
|
||||
}
|
||||
|
||||
override suspend fun update(uid: Long, aid: Long, add: Set<Long>, remove: Set<Long>) {
|
||||
require(aid > 0 && (add + remove).all { it > 0 } && add.intersect(remove).isEmpty())
|
||||
if (add.isEmpty() && remove.isEmpty()) return
|
||||
val session = http.accountRequestSession(uid)
|
||||
val response = http.postFormJson(
|
||||
"$API/x/v3/fav/resource/deal",
|
||||
mapOf(
|
||||
"rid" to aid.toString(), "type" to "2",
|
||||
"add_media_ids" to add.sorted().joinToString(","),
|
||||
"del_media_ids" to remove.sorted().joinToString(","),
|
||||
"csrf" to requireNotNull(session.csrf), "platform" to "web",
|
||||
),
|
||||
session,
|
||||
)
|
||||
FavoriteJson.requireSuccess(response)
|
||||
}
|
||||
|
||||
private companion object { const val API = "https://api.bilibili.com" }
|
||||
}
|
||||
|
||||
internal object FavoriteJson {
|
||||
const val MAX_PAGE = 1000
|
||||
|
||||
fun requireSuccess(root: JSONObject) {
|
||||
val code = root.longValue("code") ?: throw malformed()
|
||||
if (code != 0L) throw BiliApiException(code.toInt(), "收藏操作未成功,请稍后重试($code)")
|
||||
}
|
||||
|
||||
fun folders(root: JSONObject, uid: Long, membership: Boolean): List<FavoriteFolder> {
|
||||
requireSuccess(root)
|
||||
// The official API returns data:null for an account with no visible folders.
|
||||
if (root.has("data") && root.isNull("data")) return emptyList()
|
||||
val data = root.optJSONObject("data") ?: throw malformed()
|
||||
val raw = data.optJSONArray("list")
|
||||
if (raw == null && data.longValue("count") == 0L) return emptyList()
|
||||
if (raw == null) throw malformed()
|
||||
return raw.objects().map { folder ->
|
||||
val id = folder.longValue("id")?.takeIf { it > 0 } ?: throw malformed()
|
||||
val owner = folder.longValue("mid")
|
||||
if (owner != null && owner != uid) throw ClientException("收藏夹账号不匹配,请重新登录")
|
||||
val title = SearchJson.plainText(folder.optString("title")).takeIf { it.isNotBlank() } ?: throw malformed()
|
||||
val included = folder.flag("fav_state")
|
||||
if (membership && included == null) throw ClientException("收藏夹状态不完整,请重新打开后重试")
|
||||
FavoriteFolder(id, title, folder.optInt("media_count").coerceAtLeast(0), included == true)
|
||||
}.distinctBy { it.id }
|
||||
}
|
||||
|
||||
fun status(root: JSONObject): Boolean {
|
||||
requireSuccess(root)
|
||||
return root.optJSONObject("data")?.flag("favoured") ?: throw malformed()
|
||||
}
|
||||
|
||||
fun videos(root: JSONObject, page: Int): FavoritePage {
|
||||
require(page in 1..MAX_PAGE)
|
||||
requireSuccess(root)
|
||||
val data = root.optJSONObject("data") ?: throw malformed()
|
||||
val hasMore = data.flag("has_more") ?: throw malformed()
|
||||
val raw = data.optJSONArray("medias")
|
||||
if (raw == null && hasMore) throw malformed()
|
||||
if (raw == null && data.optJSONObject("info")?.longValue("media_count") != 0L) throw malformed()
|
||||
val items = raw.objects().mapNotNull { item ->
|
||||
if (item.optInt("type") != 2 || item.optInt("attr") and 9 != 0) return@mapNotNull null
|
||||
val aid = item.longValue("id")?.takeIf { it > 0 } ?: return@mapNotNull null
|
||||
val title = SearchJson.plainText(item.optString("title")).takeIf { it.isNotBlank() } ?: return@mapNotNull null
|
||||
val bvid = item.optString("bvid").takeIf { it.matches(Regex("BV[0-9A-Za-z]+")) }
|
||||
val owner = SearchJson.plainText(item.optJSONObject("upper")?.optString("name").orEmpty())
|
||||
val duration = item.longValue("duration")?.let { SearchJson.duration(it.toString()) }.orEmpty()
|
||||
VideoItem(
|
||||
id = "av$aid", title = title, coverUrl = ContentJson.secureUrl(item.optString("cover")),
|
||||
subtitle = listOf(owner, duration).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
aid = aid, bvid = bvid,
|
||||
)
|
||||
}.distinctBy { it.id }
|
||||
return FavoritePage(items, if (hasMore && raw != null && raw.length() > 0 && page < MAX_PAGE) page + 1 else null)
|
||||
}
|
||||
|
||||
private fun JSONArray?.objects(): List<JSONObject> =
|
||||
if (this == null) emptyList() else (0 until length()).map { optJSONObject(it) ?: throw malformed() }
|
||||
private fun JSONObject.longValue(key: String): Long? = when (val value = opt(key)) {
|
||||
is Byte, is Short, is Int, is Long -> (value as Number).toLong()
|
||||
is String -> value.toLongOrNull()
|
||||
else -> null
|
||||
}
|
||||
private fun JSONObject.flag(key: String): Boolean? = when (val value = opt(key)) {
|
||||
is Boolean -> value
|
||||
0, 0L, "0" -> false
|
||||
1, 1L, "1" -> true
|
||||
else -> null
|
||||
}
|
||||
private fun malformed() = ClientException("B 站收藏数据不完整,请稍后重试")
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package dev.bulubulu.tv.favorites
|
||||
|
||||
import dev.bulubulu.tv.core.FavoriteDataSource
|
||||
import dev.bulubulu.tv.core.FavoriteFolder
|
||||
import dev.bulubulu.tv.userMessage
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class FavoriteActionState(
|
||||
val aid: Long? = null,
|
||||
val loggedIn: Boolean = false,
|
||||
val favorited: Boolean? = null,
|
||||
val visible: Boolean = false,
|
||||
val folders: List<FavoriteFolder> = emptyList(),
|
||||
val selectedIds: Set<Long> = emptySet(),
|
||||
val loading: Boolean = false,
|
||||
val saving: Boolean = false,
|
||||
val needsReload: Boolean = false,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
class FavoriteActionController(
|
||||
private val scope: CoroutineScope,
|
||||
private val repository: FavoriteDataSource,
|
||||
private val onChanged: () -> Unit,
|
||||
private val notice: (String) -> Unit,
|
||||
) {
|
||||
private val _state = MutableStateFlow(FavoriteActionState())
|
||||
val state = _state.asStateFlow()
|
||||
private var uid: Long? = null
|
||||
private var generation = 0L
|
||||
private var job: Job? = null
|
||||
|
||||
fun setAccount(value: Long?) {
|
||||
if (uid == value) return
|
||||
uid = value
|
||||
reset(_state.value.aid)
|
||||
}
|
||||
|
||||
fun setVideo(aid: Long?) { reset(aid?.takeIf { it > 0 }) }
|
||||
|
||||
private fun reset(aid: Long?) {
|
||||
cancel()
|
||||
_state.value = FavoriteActionState(aid = aid, loggedIn = uid != null)
|
||||
readStatus()
|
||||
}
|
||||
|
||||
private fun readStatus() {
|
||||
val account = uid ?: return
|
||||
val aid = _state.value.aid ?: return
|
||||
val request = generation
|
||||
job = scope.launch {
|
||||
try {
|
||||
val value = repository.isFavorite(account, aid)
|
||||
if (request == generation) _state.update { it.copy(favorited = value) }
|
||||
} catch (error: Exception) {
|
||||
if (error is CancellationException) throw error
|
||||
// A failed background status read never pretends the video is uncollected.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun open() {
|
||||
val account = uid ?: run { notice("请先返回首页扫码登录后收藏"); return }
|
||||
val aid = _state.value.aid ?: run { notice("暂不支持收藏这类内容"); return }
|
||||
if (_state.value.saving || _state.value.loading) return
|
||||
cancel()
|
||||
val request = generation
|
||||
_state.update { it.copy(visible = true, loading = true, error = null, needsReload = false, folders = emptyList(), selectedIds = emptySet()) }
|
||||
job = scope.launch {
|
||||
try {
|
||||
val folders = repository.folders(account, aid)
|
||||
if (request != generation) return@launch
|
||||
val current = folders.filter { it.containsVideo }.map { it.id }.toSet()
|
||||
// Draft only: a new video defaults to the first folder; nothing is written until Save.
|
||||
val selected = current.ifEmpty { folders.firstOrNull()?.let { setOf(it.id) }.orEmpty() }
|
||||
_state.update { it.copy(folders = folders, selectedIds = selected, favorited = current.isNotEmpty(), loading = false) }
|
||||
} catch (error: Exception) {
|
||||
if (error is CancellationException) throw error
|
||||
if (request == generation) _state.update { it.copy(loading = false, needsReload = true, error = userMessage(error)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun toggle(id: Long) {
|
||||
val current = _state.value
|
||||
if (!current.visible || current.loading || current.saving || current.needsReload || current.folders.none { it.id == id }) return
|
||||
_state.update { it.copy(selectedIds = if (id in it.selectedIds) it.selectedIds - id else it.selectedIds + id) }
|
||||
}
|
||||
|
||||
fun save() {
|
||||
val account = uid ?: return
|
||||
val current = _state.value
|
||||
val aid = current.aid ?: return
|
||||
if (!current.visible || current.loading || current.saving || current.needsReload || current.folders.isEmpty()) return
|
||||
val original = current.folders.filter { it.containsVideo }.map { it.id }.toSet()
|
||||
val add = current.selectedIds - original
|
||||
val remove = original - current.selectedIds
|
||||
if (add.isEmpty() && remove.isEmpty()) { close(); return }
|
||||
val request = generation
|
||||
_state.update { it.copy(saving = true, error = null) }
|
||||
job = scope.launch {
|
||||
try {
|
||||
repository.update(account, aid, add, remove)
|
||||
if (request != generation) return@launch
|
||||
_state.update { it.copy(visible = false, saving = false, favorited = current.selectedIds.isNotEmpty()) }
|
||||
onChanged()
|
||||
notice(if (current.selectedIds.isEmpty()) "已取消收藏" else "已更新收藏")
|
||||
} catch (error: Exception) {
|
||||
if (error is CancellationException) throw error
|
||||
if (request == generation) {
|
||||
_state.update { it.copy(
|
||||
saving = false, needsReload = true, favorited = null,
|
||||
error = "未能确认收藏结果,请重新加载后重试。\n" + userMessage(error),
|
||||
) }
|
||||
onChanged()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun close() {
|
||||
val uncertain = _state.value.saving || _state.value.needsReload
|
||||
cancel()
|
||||
_state.update { it.copy(visible = false, loading = false, saving = false, needsReload = false, error = null) }
|
||||
if (uncertain) { _state.update { it.copy(favorited = null) }; onChanged(); readStatus() }
|
||||
}
|
||||
|
||||
private fun cancel() { generation++; job?.cancel(); job = null }
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package dev.bulubulu.tv.favorites
|
||||
|
||||
import dev.bulubulu.tv.core.FavoriteDataSource
|
||||
import dev.bulubulu.tv.core.FavoriteFolder
|
||||
import dev.bulubulu.tv.core.VideoItem
|
||||
import dev.bulubulu.tv.userMessage
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class FavoriteLibraryState(
|
||||
val folders: List<FavoriteFolder> = emptyList(),
|
||||
val selectedFolderId: Long? = null,
|
||||
val items: List<VideoItem> = emptyList(),
|
||||
val loading: Boolean = false,
|
||||
val loadingMore: Boolean = false,
|
||||
val hasMore: Boolean = false,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/** Account/folder generations isolate even non-cooperative late responses. */
|
||||
class FavoriteLibraryController(private val scope: CoroutineScope, private val repository: FavoriteDataSource) {
|
||||
private val _state = MutableStateFlow(FavoriteLibraryState())
|
||||
val state = _state.asStateFlow()
|
||||
private var uid: Long? = null
|
||||
private var job: Job? = null
|
||||
private var generation = 0L
|
||||
private var nextPage: Int? = null
|
||||
private var opened = false
|
||||
|
||||
fun setAccount(value: Long?) {
|
||||
if (uid == value) return
|
||||
cancel()
|
||||
uid = value
|
||||
opened = false
|
||||
nextPage = null
|
||||
_state.value = FavoriteLibraryState()
|
||||
}
|
||||
|
||||
fun refreshIfOpened() { if (opened) refresh() }
|
||||
|
||||
fun refresh() {
|
||||
val account = uid ?: return
|
||||
opened = true
|
||||
cancel()
|
||||
val request = generation
|
||||
val previousFolder = _state.value.selectedFolderId
|
||||
nextPage = null
|
||||
_state.update { it.copy(items = emptyList(), loading = true, loadingMore = false, hasMore = false, error = null) }
|
||||
job = scope.launch {
|
||||
try {
|
||||
val folders = repository.folders(account)
|
||||
if (generation != request) return@launch
|
||||
val selected = folders.firstOrNull { it.id == previousFolder } ?: folders.firstOrNull()
|
||||
_state.update { it.copy(folders = folders, selectedFolderId = selected?.id) }
|
||||
if (selected == null) {
|
||||
_state.update { it.copy(loading = false) }
|
||||
return@launch
|
||||
}
|
||||
val page = repository.videos(account, selected.id, 1)
|
||||
if (generation != request) return@launch
|
||||
nextPage = page.nextPage?.takeIf { it > 1 }
|
||||
_state.update { it.copy(items = page.items.distinctBy(VideoItem::id), loading = false, hasMore = nextPage != null) }
|
||||
} catch (error: Exception) { fail(error, request) }
|
||||
}
|
||||
}
|
||||
|
||||
fun selectFolder(id: Long) {
|
||||
val account = uid ?: return
|
||||
if (_state.value.folders.none { it.id == id } || (id == _state.value.selectedFolderId && _state.value.error == null)) return
|
||||
cancel()
|
||||
val request = generation
|
||||
nextPage = null
|
||||
_state.update { it.copy(selectedFolderId = id, items = emptyList(), loading = true, loadingMore = false, hasMore = false, error = null) }
|
||||
job = scope.launch {
|
||||
try {
|
||||
val page = repository.videos(account, id, 1)
|
||||
if (generation != request) return@launch
|
||||
nextPage = page.nextPage?.takeIf { it > 1 }
|
||||
_state.update { it.copy(items = page.items.distinctBy(VideoItem::id), loading = false, hasMore = nextPage != null) }
|
||||
} catch (error: Exception) { fail(error, request) }
|
||||
}
|
||||
}
|
||||
|
||||
fun loadMore() {
|
||||
val account = uid ?: return
|
||||
val current = _state.value
|
||||
val folder = current.selectedFolderId ?: return
|
||||
val number = nextPage ?: return
|
||||
if (current.loading || current.loadingMore) return
|
||||
val request = generation
|
||||
_state.update { it.copy(loadingMore = true, error = null) }
|
||||
job = scope.launch {
|
||||
try {
|
||||
val page = repository.videos(account, folder, number)
|
||||
if (generation != request) return@launch
|
||||
val merged = (current.items + page.items).distinctBy(VideoItem::id)
|
||||
// Filtered (invalid/unsupported) entries may occupy a whole page.
|
||||
nextPage = page.nextPage?.takeIf { it > number && (page.items.isEmpty() || merged.size > current.items.size) }
|
||||
_state.update { it.copy(items = merged, loadingMore = false, hasMore = nextPage != null) }
|
||||
} catch (error: Exception) { fail(error, request) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun fail(error: Exception, request: Long) {
|
||||
if (error is CancellationException) throw error
|
||||
if (generation == request) _state.update { it.copy(loading = false, loadingMore = false, error = userMessage(error)) }
|
||||
}
|
||||
|
||||
private fun cancel() { generation++; job?.cancel(); job = null }
|
||||
}
|
||||
@@ -60,6 +60,7 @@ import androidx.media3.exoplayer.DefaultRenderersFactory
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.ui.PlayerView
|
||||
import dev.bulubulu.tv.core.PlaybackSource
|
||||
import dev.bulubulu.tv.favorites.FavoriteActionState
|
||||
import dev.bulubulu.tv.ui.TvAccent
|
||||
import dev.bulubulu.tv.ui.TvAction
|
||||
import dev.bulubulu.tv.ui.TvMuted
|
||||
@@ -68,7 +69,10 @@ import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
|
||||
@Composable
|
||||
fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (String) -> Unit) {
|
||||
fun PlayerScreen(
|
||||
source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (String) -> Unit,
|
||||
favorite: FavoriteActionState = FavoriteActionState(), onFavorite: () -> Unit = {},
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
val windowFocused = LocalWindowInfo.current.isWindowFocused
|
||||
@@ -76,6 +80,10 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
val retryFocus = remember { FocusRequester() }
|
||||
val qualityFocus = remember { FocusRequester() }
|
||||
val favoriteFocus = remember { FocusRequester() }
|
||||
var favoriteButtonFocused by remember(source) { mutableStateOf(false) }
|
||||
var focusFavoriteRequested by remember(source) { mutableStateOf(false) }
|
||||
var hadFavoriteMenu by remember(source) { mutableStateOf(false) }
|
||||
var qualityMenuOpen by remember(source) { mutableStateOf(false) }
|
||||
var qualityButtonFocused by remember(source) { mutableStateOf(false) }
|
||||
var focusQualityRequested by remember(source) { mutableStateOf(false) }
|
||||
@@ -180,21 +188,36 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
delay(400)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(lastInteraction, isPlaying, error, qualityButtonFocused, qualityMenuOpen) {
|
||||
if (isPlaying && error == null && !qualityButtonFocused && !qualityMenuOpen) {
|
||||
LaunchedEffect(lastInteraction, isPlaying, error, qualityButtonFocused, qualityMenuOpen, favoriteButtonFocused, favorite.visible) {
|
||||
if (isPlaying && error == null && !qualityButtonFocused && !qualityMenuOpen && !favoriteButtonFocused && !favorite.visible) {
|
||||
delay(4_000)
|
||||
controlsVisible = false
|
||||
} else {
|
||||
controlsVisible = true
|
||||
}
|
||||
}
|
||||
LaunchedEffect(focusQualityRequested, controlsVisible, qualityMenuOpen, error, windowFocused) {
|
||||
if (focusQualityRequested && controlsVisible && !qualityMenuOpen && error == null && windowFocused) {
|
||||
LaunchedEffect(focusQualityRequested, controlsVisible, qualityMenuOpen, error, windowFocused, favorite.visible) {
|
||||
if (focusQualityRequested && controlsVisible && !qualityMenuOpen && !favorite.visible && error == null && windowFocused) {
|
||||
delay(100)
|
||||
qualityFocus.requestFocus()
|
||||
focusQualityRequested = false
|
||||
}
|
||||
}
|
||||
LaunchedEffect(favorite.visible) {
|
||||
if (hadFavoriteMenu && !favorite.visible) {
|
||||
controlsVisible = true
|
||||
lastInteraction = SystemClock.elapsedRealtime()
|
||||
focusFavoriteRequested = true
|
||||
}
|
||||
hadFavoriteMenu = favorite.visible
|
||||
}
|
||||
LaunchedEffect(focusFavoriteRequested, controlsVisible, windowFocused, favorite.visible, error) {
|
||||
if (focusFavoriteRequested && controlsVisible && windowFocused && !favorite.visible && error == null && favorite.aid != null) {
|
||||
delay(100)
|
||||
favoriteFocus.requestFocus()
|
||||
focusFavoriteRequested = false
|
||||
}
|
||||
}
|
||||
LaunchedEffect(error) {
|
||||
if (error != null) { delay(100); retryFocus.requestFocus() }
|
||||
}
|
||||
@@ -212,11 +235,14 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
modifier = Modifier.fillMaxSize().background(Color.Black)
|
||||
.focusRequester(focusRequester)
|
||||
.onPreviewKeyEvent { event ->
|
||||
if (error != null || qualityMenuOpen) return@onPreviewKeyEvent false
|
||||
if (error != null || qualityMenuOpen || favorite.visible) return@onPreviewKeyEvent false
|
||||
val native = event.nativeKeyEvent
|
||||
val key = native.keyCode
|
||||
// Let the focused action receive its own confirm events.
|
||||
if (qualityButtonFocused && key in setOf(KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER)) {
|
||||
if ((qualityButtonFocused || favoriteButtonFocused) && key in setOf(
|
||||
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER,
|
||||
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT,
|
||||
)) {
|
||||
return@onPreviewKeyEvent false
|
||||
}
|
||||
val supported = key in setOf(
|
||||
@@ -293,6 +319,13 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
}
|
||||
TvAction("清晰度", { qualityMenuOpen = true; interact() }, Modifier.focusRequester(qualityFocus)
|
||||
.onFocusChanged { qualityButtonFocused = it.isFocused }.testTag("quality_button"))
|
||||
if (favorite.aid != null) {
|
||||
TvAction(
|
||||
if (!favorite.loggedIn) "登录后收藏" else if (favorite.saving) "保存中…" else if (favorite.favorited == true) "已收藏" else "收藏",
|
||||
{ onFavorite(); interact() },
|
||||
Modifier.focusRequester(favoriteFocus).onFocusChanged { favoriteButtonFocused = it.isFocused }.testTag("favorite_button"),
|
||||
)
|
||||
}
|
||||
}
|
||||
Column(
|
||||
Modifier.align(Alignment.BottomCenter).fillMaxWidth()
|
||||
@@ -309,7 +342,7 @@ fun PlayerScreen(source: PlaybackSource, onBack: () -> Unit, onPlaybackError: (S
|
||||
drawLine(Color.White.copy(alpha = 0.25f), Offset.Zero, Offset(size.width, 0f), strokeWidth = size.height)
|
||||
drawLine(TvAccent, Offset.Zero, Offset(size.width * progress, 0f), strokeWidth = size.height)
|
||||
}
|
||||
Text("确认键 暂停 / 继续 左右键 快退 / 快进 10 秒 上键 清晰度 返回键 退出", color = TvMuted, fontSize = 12.sp)
|
||||
Text("确认键 暂停 / 继续 左右键 快退 / 快进 10 秒 上键 清晰度 / 收藏 返回键 退出", color = TvMuted, fontSize = 12.sp)
|
||||
}
|
||||
}
|
||||
error?.let { message ->
|
||||
|
||||
@@ -24,6 +24,9 @@ import androidx.compose.foundation.lazy.grid.GridItemSpan
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Text
|
||||
@@ -33,6 +36,7 @@ import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -41,11 +45,17 @@ import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.input.key.KeyEventType
|
||||
import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
@@ -55,7 +65,9 @@ import coil.compose.AsyncImage
|
||||
import coil.request.ImageRequest
|
||||
import dev.bulubulu.tv.core.ContentTab
|
||||
import dev.bulubulu.tv.core.VideoItem
|
||||
import dev.bulubulu.tv.favorites.FavoriteLibraryState
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@Composable
|
||||
fun BulubuluHome(
|
||||
@@ -69,22 +81,49 @@ fun BulubuluHome(
|
||||
focusRestoreKey: Int = 0,
|
||||
active: Boolean = true,
|
||||
onSearch: () -> Unit = {},
|
||||
favorites: FavoriteLibraryState = FavoriteLibraryState(),
|
||||
onFavoriteFolderSelected: (Long) -> Unit = {},
|
||||
) {
|
||||
val isFavorites = state.selectedTab == ContentTab.FAVORITES
|
||||
val content = if (isFavorites) state.copy(
|
||||
items = favorites.items, loading = favorites.loading, loadingMore = favorites.loadingMore,
|
||||
hasMore = favorites.hasMore, error = favorites.error,
|
||||
) else state
|
||||
val visibleTabs = ContentTab.entries.filter { it != ContentTab.FAVORITES || state.account != null }
|
||||
val portrait = state.selectedTab == ContentTab.MOVIE || state.selectedTab == ContentTab.BANGUMI
|
||||
val itemScope = state.selectedTab.name + if (isFavorites) ":${favorites.selectedFolderId}" else ""
|
||||
val tabFocus = remember { ContentTab.entries.associateWith { FocusRequester() } }
|
||||
val accountFocus = remember { FocusRequester() }
|
||||
val refreshFocus = remember { FocusRequester() }
|
||||
val searchFocus = remember { FocusRequester() }
|
||||
val cardFocus = remember { mutableMapOf<String, FocusRequester>() }
|
||||
val folderFocus = remember { mutableMapOf<Long, FocusRequester>() }
|
||||
val foldersScroll = rememberLazyListState()
|
||||
val focusScope = rememberCoroutineScope()
|
||||
fun focusSelectedFolder() {
|
||||
val index = favorites.folders.indexOfFirst { it.id == favorites.selectedFolderId }
|
||||
if (index < 0) return
|
||||
focusScope.launch {
|
||||
foldersScroll.scrollToItem(index)
|
||||
delay(100)
|
||||
folderFocus[favorites.folders[index].id]?.requestFocus()
|
||||
}
|
||||
}
|
||||
val footerFocus = remember { FocusRequester() }
|
||||
var folderHasFocus by remember { mutableStateOf(false) }
|
||||
var pageStart by remember { mutableStateOf<Int?>(null) }
|
||||
var lastFocusToken by remember { mutableStateOf("tab:${state.selectedTab.name}") }
|
||||
val recommendGrid = rememberLazyGridState()
|
||||
val movieGrid = rememberLazyGridState()
|
||||
val bangumiGrid = rememberLazyGridState()
|
||||
val favoritesGrid = rememberLazyGridState()
|
||||
val gridState = when (state.selectedTab) {
|
||||
ContentTab.RECOMMEND -> recommendGrid
|
||||
ContentTab.MOVIE -> movieGrid
|
||||
ContentTab.BANGUMI -> bangumiGrid
|
||||
ContentTab.FAVORITES -> favoritesGrid
|
||||
}
|
||||
val columns = if (state.selectedTab == ContentTab.RECOMMEND) 4 else 5
|
||||
val columns = if (portrait) 5 else 4
|
||||
var gridHasFocus by remember { mutableStateOf(false) }
|
||||
var logoutConfirmation by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(focusRestoreKey, active) {
|
||||
@@ -95,9 +134,18 @@ fun BulubuluHome(
|
||||
lastFocusToken == "account" -> accountFocus.requestFocus()
|
||||
lastFocusToken == "refresh" -> refreshFocus.requestFocus()
|
||||
lastFocusToken == "search" -> searchFocus.requestFocus()
|
||||
lastFocusToken == "more" && content.hasMore -> footerFocus.requestFocus()
|
||||
lastFocusToken.startsWith("folder:") && isFavorites -> {
|
||||
val index = favorites.folders.indexOfFirst { "folder:${it.id}" == lastFocusToken }
|
||||
if (index >= 0) {
|
||||
foldersScroll.scrollToItem(index)
|
||||
delay(100)
|
||||
folderFocus[favorites.folders[index].id]?.requestFocus()
|
||||
} else tabFocus.getValue(state.selectedTab).requestFocus()
|
||||
}
|
||||
lastFocusToken.startsWith("item:") -> {
|
||||
val prefix = "item:${state.selectedTab.name}:"
|
||||
val index = state.items.indexOfFirst { prefix + it.id == lastFocusToken }
|
||||
val prefix = "item:$itemScope:"
|
||||
val index = content.items.indexOfFirst { prefix + it.id == lastFocusToken }
|
||||
if (index >= 0) {
|
||||
gridState.scrollToItem(index)
|
||||
delay(100)
|
||||
@@ -107,7 +155,26 @@ fun BulubuluHome(
|
||||
else -> tabFocus.getValue(state.selectedTab).requestFocus()
|
||||
}
|
||||
}
|
||||
BackHandler(active && gridHasFocus) { tabFocus.getValue(state.selectedTab).requestFocus() }
|
||||
LaunchedEffect(favorites.selectedFolderId) { favoritesGrid.scrollToItem(0); pageStart = null }
|
||||
LaunchedEffect(content.loadingMore, content.items.size, active) {
|
||||
val start = pageStart ?: return@LaunchedEffect
|
||||
if (!active || content.loadingMore) return@LaunchedEffect
|
||||
pageStart = null
|
||||
if (content.error == null && content.items.size > start) {
|
||||
gridState.scrollToItem(start)
|
||||
delay(100)
|
||||
cardFocus["item:$itemScope:${content.items[start].id}"]?.requestFocus()
|
||||
} else if (!content.hasMore && content.items.isNotEmpty()) {
|
||||
gridState.scrollToItem(content.items.lastIndex)
|
||||
delay(100)
|
||||
cardFocus["item:$itemScope:${content.items.last().id}"]?.requestFocus()
|
||||
}
|
||||
}
|
||||
BackHandler(active && (gridHasFocus || folderHasFocus)) {
|
||||
if (gridHasFocus && isFavorites && favorites.selectedFolderId != null) {
|
||||
focusSelectedFolder()
|
||||
} else tabFocus.getValue(state.selectedTab).requestFocus()
|
||||
}
|
||||
|
||||
CompositionLocalProvider(LocalTvFocusEnabled provides active) {
|
||||
Column(
|
||||
@@ -117,10 +184,16 @@ fun BulubuluHome(
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("bulubulu", color = TvText, fontWeight = FontWeight.Bold, fontSize = 28.sp, letterSpacing = (-1).sp)
|
||||
Spacer(Modifier.width(26.dp))
|
||||
Spacer(Modifier.width(if (state.account == null) 26.dp else 18.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(9.dp), modifier = Modifier.focusGroup()) {
|
||||
ContentTab.entries.forEach { tab ->
|
||||
TvAction(tab.title, { onTabSelected(tab) }, Modifier.focusRequester(tabFocus.getValue(tab)).onFocusChanged { if (it.isFocused) lastFocusToken = "tab:${tab.name}" }, selected = tab == state.selectedTab)
|
||||
visibleTabs.forEach { tab ->
|
||||
TvAction(tab.title, { onTabSelected(tab) }, Modifier.focusRequester(tabFocus.getValue(tab))
|
||||
.onPreviewKeyEvent { event ->
|
||||
if (tab == ContentTab.FAVORITES && isFavorites && favorites.folders.isNotEmpty() && event.key == Key.DirectionDown) {
|
||||
if (event.type == KeyEventType.KeyDown) focusSelectedFolder()
|
||||
true
|
||||
} else false
|
||||
}.testTag("tab_${tab.name}").onFocusChanged { if (it.isFocused) lastFocusToken = "tab:${tab.name}" }, selected = tab == state.selectedTab)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.weight(1f))
|
||||
@@ -129,7 +202,7 @@ fun BulubuluHome(
|
||||
if (state.authBusy) {
|
||||
TvAction("正在退出…", {}, Modifier.focusRequester(accountFocus), enabled = false)
|
||||
} else if (state.account != null) {
|
||||
TvAction(state.account.name.take(10) + " · 退出", { logoutConfirmation = true }, Modifier.focusRequester(accountFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "account" })
|
||||
TvAction(state.account.name.take(6) + " · 退出", { logoutConfirmation = true }, Modifier.focusRequester(accountFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "account" })
|
||||
} else {
|
||||
TvAction("扫码登录", onLogin, Modifier.focusRequester(accountFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "account" })
|
||||
}
|
||||
@@ -142,16 +215,35 @@ fun BulubuluHome(
|
||||
ContentTab.RECOMMEND -> if (state.account == null) "发现好视频" else "为你推荐"
|
||||
ContentTab.MOVIE -> "电影"
|
||||
ContentTab.BANGUMI -> "番剧"
|
||||
ContentTab.FAVORITES -> favorites.folders.firstOrNull { it.id == favorites.selectedFolderId }?.title ?: "我的收藏"
|
||||
},
|
||||
color = TvText, fontSize = 21.sp, fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(if (state.account == null) "登录后可观看账号有权访问的内容" else "${state.items.size} 部内容", color = TvMuted, fontSize = 12.sp, modifier = Modifier.padding(top = 3.dp))
|
||||
Text(if (state.account == null) "登录后可观看账号有权访问的内容" else if (isFavorites) "已加载 ${content.items.size} 个视频" else "${content.items.size} 部内容", color = TvMuted, fontSize = 12.sp, modifier = Modifier.padding(top = 3.dp))
|
||||
}
|
||||
TvAction("刷新", onRefresh, Modifier.focusRequester(refreshFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "refresh" }, enabled = !content.loading)
|
||||
}
|
||||
if (isFavorites && favorites.folders.isNotEmpty()) {
|
||||
LazyRow(
|
||||
state = foldersScroll,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 12.dp).onFocusChanged { folderHasFocus = it.hasFocus }.focusGroup(),
|
||||
) {
|
||||
items(favorites.folders, key = { it.id }) { folder ->
|
||||
TvAction(
|
||||
"${folder.title.take(22)} · ${folder.mediaCount}",
|
||||
{ pageStart = null; onFavoriteFolderSelected(folder.id) },
|
||||
Modifier.focusRequester(folderFocus.getOrPut(folder.id) { FocusRequester() })
|
||||
.testTag("favorite_folder_${folder.id}").onFocusChanged { if (it.isFocused) lastFocusToken = "folder:${folder.id}" },
|
||||
selected = folder.id == favorites.selectedFolderId,
|
||||
)
|
||||
}
|
||||
}
|
||||
TvAction("刷新", onRefresh, Modifier.focusRequester(refreshFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "refresh" }, enabled = !state.loading)
|
||||
}
|
||||
Spacer(Modifier.height(10.dp))
|
||||
when {
|
||||
state.loading && state.items.isEmpty() -> {
|
||||
content.loading && content.items.isEmpty() -> {
|
||||
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||
CircularProgressIndicator(Modifier.size(30.dp), color = TvAccent, strokeWidth = 2.dp)
|
||||
@@ -159,11 +251,19 @@ fun BulubuluHome(
|
||||
}
|
||||
}
|
||||
}
|
||||
state.items.isEmpty() -> {
|
||||
content.items.isEmpty() -> {
|
||||
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||
Text(state.error ?: "暂时没有内容", color = TvText, fontSize = 18.sp)
|
||||
TvAction("重新加载", onRefresh)
|
||||
Text(content.error ?: if (isFavorites) {
|
||||
if (favorites.folders.isEmpty()) "还没有收藏夹,在哔哩哔哩创建后即可查看" else "这个收藏夹暂无可播放的视频"
|
||||
} else "暂时没有内容", color = TvText, fontSize = 18.sp)
|
||||
if (content.hasMore) {
|
||||
TvAction(
|
||||
if (content.loadingMore) "正在加载…" else "继续加载",
|
||||
{ if (!content.loadingMore) { pageStart = content.items.size; onLoadMore() } },
|
||||
Modifier.focusRequester(footerFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "more" },
|
||||
)
|
||||
} else TvAction("重新加载", onRefresh)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -176,11 +276,11 @@ fun BulubuluHome(
|
||||
contentPadding = PaddingValues(6.dp, 8.dp, 6.dp, 20.dp),
|
||||
modifier = Modifier.weight(1f).fillMaxWidth().onFocusChanged { gridHasFocus = it.hasFocus }.focusGroup(),
|
||||
) {
|
||||
items(state.items, key = { it.id }) { item ->
|
||||
val focusToken = "item:${state.selectedTab.name}:${item.id}"
|
||||
items(content.items, key = { it.id }) { item ->
|
||||
val focusToken = "item:$itemScope:${item.id}"
|
||||
VideoCard(
|
||||
item = item,
|
||||
portrait = state.selectedTab != ContentTab.RECOMMEND,
|
||||
portrait = portrait,
|
||||
focusRequester = cardFocus.getOrPut(focusToken) { FocusRequester() },
|
||||
onFocused = { lastFocusToken = focusToken },
|
||||
onClick = { onItemSelected(item) },
|
||||
@@ -188,10 +288,13 @@ fun BulubuluHome(
|
||||
}
|
||||
item(span = { GridItemSpan(columns) }, key = "load-more") {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
state.error?.let { Text(it, color = Color(0xFFFFB0A6), fontSize = 14.sp) }
|
||||
content.error?.let { Text(it, color = Color(0xFFFFB0A6), fontSize = 14.sp) }
|
||||
when {
|
||||
state.loadingMore -> CircularProgressIndicator(Modifier.size(26.dp), color = TvAccent, strokeWidth = 2.dp)
|
||||
state.hasMore -> TvAction(if (state.error == null) "加载更多" else "重试", onLoadMore)
|
||||
content.loadingMore || content.hasMore -> TvAction(
|
||||
if (content.loadingMore) "正在加载…" else if (content.error == null) "加载更多" else "重试",
|
||||
{ if (!content.loadingMore) { if (isFavorites) pageStart = content.items.size; onLoadMore() } },
|
||||
Modifier.focusRequester(footerFocus).onFocusChanged { if (it.isFocused) lastFocusToken = "more" },
|
||||
)
|
||||
else -> Text("已经到底了", color = TvMuted, fontSize = 13.sp)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package dev.bulubulu.tv.ui
|
||||
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.platform.LocalWindowInfo
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.compose.ui.window.DialogWindowProvider
|
||||
import androidx.core.view.WindowCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.core.view.WindowInsetsControllerCompat
|
||||
import dev.bulubulu.tv.favorites.FavoriteActionState
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
@Composable
|
||||
fun FavoriteDialog(
|
||||
state: FavoriteActionState,
|
||||
onToggle: (Long) -> Unit,
|
||||
onSave: () -> Unit,
|
||||
onReload: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val list = rememberLazyListState()
|
||||
val firstFocus = remember { FocusRequester() }
|
||||
val closeFocus = remember { FocusRequester() }
|
||||
val reloadFocus = remember { FocusRequester() }
|
||||
val saveFocus = remember { FocusRequester() }
|
||||
val firstIndex = state.folders.indexOfFirst { it.id in state.selectedIds }.coerceAtLeast(0)
|
||||
Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
|
||||
val view = LocalView.current
|
||||
val windowFocused = LocalWindowInfo.current.isWindowFocused
|
||||
LaunchedEffect(view) {
|
||||
(view.parent as? DialogWindowProvider)?.window?.let { window ->
|
||||
WindowCompat.getInsetsController(window, view).apply {
|
||||
hide(WindowInsetsCompat.Type.systemBars())
|
||||
systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(state.loading, state.saving, state.needsReload, windowFocused) {
|
||||
if (!windowFocused) return@LaunchedEffect
|
||||
if (!state.loading && !state.saving && !state.needsReload && state.folders.isNotEmpty()) {
|
||||
list.scrollToItem(firstIndex)
|
||||
delay(100)
|
||||
firstFocus.requestFocus()
|
||||
} else {
|
||||
delay(100)
|
||||
if (state.needsReload) reloadFocus.requestFocus() else closeFocus.requestFocus()
|
||||
}
|
||||
}
|
||||
Surface(
|
||||
modifier = Modifier.widthIn(max = 540.dp).fillMaxWidth(0.92f)
|
||||
.border(1.dp, Color.White.copy(alpha = 0.1f), RoundedCornerShape(22.dp)).testTag("favorite_menu"),
|
||||
color = TvPanel, contentColor = TvText, shape = RoundedCornerShape(22.dp),
|
||||
) {
|
||||
Column(Modifier.padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text("收藏到", fontSize = 23.sp, fontWeight = FontWeight.SemiBold)
|
||||
Text(
|
||||
if (state.saving) "正在保存…" else "选择收藏夹后保存;取消勾选可移出对应收藏夹",
|
||||
color = TvMuted, fontSize = 13.sp,
|
||||
)
|
||||
when {
|
||||
state.loading -> CircularProgressIndicator(Modifier.size(28.dp), color = TvAccent, strokeWidth = 2.dp)
|
||||
state.needsReload -> Text(state.error ?: "请重新加载收藏状态", color = Color(0xFFFFB0A6), fontSize = 14.sp)
|
||||
state.folders.isEmpty() -> Text("还没有收藏夹,请先在哔哩哔哩创建一个。", color = TvMuted, fontSize = 15.sp)
|
||||
else -> LazyColumn(
|
||||
state = list, modifier = Modifier.fillMaxWidth().heightIn(max = 200.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
items(state.folders, key = { it.id }) { folder ->
|
||||
val selected = folder.id in state.selectedIds
|
||||
TvAction(
|
||||
(if (selected) "✓ " else "○ ") + folder.title.take(26),
|
||||
{ onToggle(folder.id) },
|
||||
Modifier.fillMaxWidth().focusProperties {
|
||||
if (folder.id == state.folders.last().id) down = saveFocus
|
||||
}.testTag("favorite_option_${folder.id}").then(
|
||||
if (folder.id == state.folders[firstIndex].id) Modifier.focusRequester(firstFocus) else Modifier,
|
||||
),
|
||||
selected = selected, enabled = !state.saving,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
if (state.needsReload) {
|
||||
TvAction("重新加载", onReload, Modifier.focusRequester(reloadFocus).testTag("favorite_reload"))
|
||||
} else if (state.folders.isNotEmpty() && !state.loading) {
|
||||
TvAction(
|
||||
if (state.saving) "正在保存…" else if (state.selectedIds.isEmpty()) "保存(移出收藏)" else "保存",
|
||||
onSave, Modifier.focusRequester(saveFocus).testTag("favorite_save"), enabled = !state.saving,
|
||||
)
|
||||
}
|
||||
TvAction("关闭", onDismiss, Modifier.focusRequester(closeFocus).testTag("favorite_close"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package dev.bulubulu.tv
|
||||
|
||||
import dev.bulubulu.tv.core.ClientException
|
||||
import dev.bulubulu.tv.data.BiliCookieJar
|
||||
import dev.bulubulu.tv.data.InMemorySessionCookieStore
|
||||
import okhttp3.Cookie
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import java.io.IOException
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class AccountRequestSessionTest {
|
||||
private fun cookie(name: String, value: String, domain: String = "bilibili.com") =
|
||||
Cookie.Builder().name(name).value(value).domain(domain).path("/").secure().build()
|
||||
private fun session(uid: Long) = listOf(cookie("DedeUserID", uid.toString()), cookie("SESSDATA", "fake-session"), cookie("bili_jct", "fake-csrf"))
|
||||
|
||||
@Test fun accountIdentityAndCsrfAreReadFromTheSameSession() {
|
||||
val jar = BiliCookieJar(InMemorySessionCookieStore(session(123)))
|
||||
val captured = jar.accountSession(123, true)
|
||||
assertEquals("fake-csrf", captured.csrf)
|
||||
assertEquals(jar.currentEpoch(), captured.epoch)
|
||||
rejected { jar.accountSession(456, true) }
|
||||
}
|
||||
|
||||
@Test fun csrfMustExistAndMatchTheApiCookieScopeForWrites() {
|
||||
val cookies = session(123).filter { it.name != "bili_jct" } + cookie("bili_jct", "wrong-scope", "passport.bilibili.com")
|
||||
val jar = BiliCookieJar(InMemorySessionCookieStore(cookies))
|
||||
assertNull(jar.accountSession(123, false).csrf)
|
||||
rejected { jar.accountSession(123, true) }
|
||||
}
|
||||
|
||||
@Test fun logoutOrAccountReplacementRejectsQueuedOldAccountRequests() {
|
||||
for (logout in listOf(true, false)) {
|
||||
val jar = BiliCookieJar(InMemorySessionCookieStore(session(123)))
|
||||
val captured = jar.accountSession(123, true)
|
||||
if (logout) jar.clear() else jar.replaceSession(session(456))
|
||||
try {
|
||||
jar.requestSession("https://api.bilibili.com/".toHttpUrl(), captured.epoch)
|
||||
fail("Stale request accepted")
|
||||
} catch (_: IOException) {
|
||||
// A transport-safe failure must reach OkHttp's onFailure, not crash its worker.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun accountCookieChecksNeverForwardCredentialsToCdn() {
|
||||
val jar = BiliCookieJar(InMemorySessionCookieStore(session(123)))
|
||||
val captured = jar.accountSession(123, true)
|
||||
assertTrue(jar.requestSession("https://cdn.example/video".toHttpUrl(), captured.epoch).second.isEmpty())
|
||||
val anonymous = BiliCookieJar(InMemorySessionCookieStore(session(123).filter { it.name != "SESSDATA" }))
|
||||
rejected { anonymous.accountSession(123, true) }
|
||||
}
|
||||
|
||||
private fun rejected(block: () -> Unit) { try { block(); fail("Unbound account request accepted") } catch (_: ClientException) { } }
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package dev.bulubulu.tv
|
||||
|
||||
import dev.bulubulu.tv.core.BiliApiException
|
||||
import dev.bulubulu.tv.core.ClientException
|
||||
import dev.bulubulu.tv.data.FavoriteJson
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class FavoriteJsonTest {
|
||||
@Test fun foldersKeepAccountLongIdsAndMembership() {
|
||||
val folders = FavoriteJson.folders(json("""{"code":0,"data":{"list":[
|
||||
{"id":9007199254740993,"mid":123,"title":"教程 & 示例","media_count":31,"fav_state":1},
|
||||
{"id":8,"mid":123,"title":"稍后看","media_count":2,"fav_state":0}
|
||||
]}}"""), 123, true)
|
||||
assertEquals(9007199254740993L, folders[0].id)
|
||||
assertEquals("教程 & 示例", folders[0].title)
|
||||
assertEquals(31, folders[0].mediaCount)
|
||||
assertTrue(folders[0].containsVideo)
|
||||
assertFalse(folders[1].containsVideo)
|
||||
}
|
||||
|
||||
@Test fun emptyFolderResponseIsDifferentFromMalformedData() {
|
||||
assertTrue(FavoriteJson.folders(json("""{"code":0,"data":null}"""), 1, false).isEmpty())
|
||||
assertTrue(FavoriteJson.folders(json("""{"code":0,"data":{"count":0}}"""), 1, false).isEmpty())
|
||||
malformed { FavoriteJson.folders(json("""{"code":0}"""), 1, false) }
|
||||
malformed { FavoriteJson.folders(json("""{"code":0,"data":{}}"""), 1, false) }
|
||||
}
|
||||
|
||||
@Test fun anotherAccountFolderAndUnknownMembershipCannotBecomeEditable() {
|
||||
malformed { FavoriteJson.folders(json("""{"code":0,"data":{"list":[{"id":1,"mid":2,"title":"别的账号"}]}}"""), 1, false) }
|
||||
malformed { FavoriteJson.folders(json("""{"code":0,"data":{"list":[{"id":1,"mid":1,"title":"收藏夹"}]}}"""), 1, true) }
|
||||
}
|
||||
|
||||
@Test fun favoriteVideosFilterInvalidAndUnsupportedResourcesAndDeduplicate() {
|
||||
val valid = """{"id":9007199254740993,"type":2,"attr":0,"title":"视频","cover":"http://img.example/cover.jpg","bvid":"BV1test","duration":125,"upper":{"name":"作者"}}"""
|
||||
val page = FavoriteJson.videos(json("""{"code":0,"data":{"has_more":true,"medias":[
|
||||
$valid,$valid,{"id":2,"type":2,"attr":9,"title":"已失效视频"},{"id":3,"type":24,"title":"不支持的资源"}
|
||||
]}}"""), 1)
|
||||
assertEquals(1, page.items.size)
|
||||
assertEquals(9007199254740993L, page.items.single().aid)
|
||||
assertEquals("https://img.example/cover.jpg", page.items.single().coverUrl)
|
||||
assertEquals("作者 · 2:05", page.items.single().subtitle)
|
||||
assertEquals(2, page.nextPage)
|
||||
}
|
||||
|
||||
@Test fun filteredPageStillAllowsAccessToFollowingVideos() {
|
||||
val page = FavoriteJson.videos(json("""{"code":0,"data":{"has_more":true,"medias":[{"id":1,"type":2,"attr":9}]}}"""), 4)
|
||||
assertTrue(page.items.isEmpty())
|
||||
assertEquals(5, page.nextPage)
|
||||
}
|
||||
|
||||
@Test fun trueEmptyFolderStopsButMissingResourceDataDoesNotLookEmpty() {
|
||||
assertNull(FavoriteJson.videos(json("""{"code":0,"data":{"has_more":false,"info":{"media_count":0},"medias":null}}"""), 1).nextPage)
|
||||
malformed { FavoriteJson.videos(json("""{"code":0,"data":{"has_more":true}}"""), 1) }
|
||||
malformed { FavoriteJson.videos(json("""{"code":0,"data":{"medias":[]}}"""), 1) }
|
||||
}
|
||||
|
||||
@Test fun statusRequiresExplicitFavoriteFlag() {
|
||||
assertTrue(FavoriteJson.status(json("""{"code":0,"data":{"favoured":true}}""")))
|
||||
assertFalse(FavoriteJson.status(json("""{"code":0,"data":{"favoured":0}}""")))
|
||||
malformed { FavoriteJson.status(json("""{"code":0,"data":{}}""")) }
|
||||
}
|
||||
|
||||
@Test fun writeSuccessRequiresAnExplicitZeroCode() {
|
||||
FavoriteJson.requireSuccess(json("""{"code":0,"data":null}"""))
|
||||
malformed { FavoriteJson.requireSuccess(json("""{}""")) }
|
||||
try { FavoriteJson.requireSuccess(json("""{"code":-101}""")); fail() } catch (_: BiliApiException) { }
|
||||
}
|
||||
|
||||
private fun json(value: String) = JSONObject(value)
|
||||
private fun malformed(block: () -> Unit) { try { block(); fail("Incomplete favorite data accepted") } catch (_: ClientException) { } }
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package dev.bulubulu.tv.favorites
|
||||
|
||||
import dev.bulubulu.tv.core.*
|
||||
|
||||
internal data class FavoriteChange(val uid: Long, val aid: Long, val add: Set<Long>, val remove: Set<Long>)
|
||||
|
||||
internal class FakeFavorites : FavoriteDataSource {
|
||||
var onFolders: suspend (Long, Long?) -> List<FavoriteFolder> = { _, _ ->
|
||||
listOf(FavoriteFolder(11, "默认收藏夹", 2), FavoriteFolder(22, "教程", 1))
|
||||
}
|
||||
var onVideos: suspend (Long, Long, Int) -> FavoritePage = { _, folder, _ ->
|
||||
FavoritePage(listOf(VideoItem("av$folder", "视频", "", aid = folder)), null)
|
||||
}
|
||||
var onStatus: suspend (Long, Long) -> Boolean = { _, _ -> false }
|
||||
var onUpdate: suspend (FavoriteChange) -> Unit = {}
|
||||
val folderCalls = mutableListOf<Pair<Long, Long?>>()
|
||||
val videoCalls = mutableListOf<Triple<Long, Long, Int>>()
|
||||
val updates = mutableListOf<FavoriteChange>()
|
||||
override suspend fun folders(uid: Long, aid: Long?): List<FavoriteFolder> {
|
||||
folderCalls += uid to aid
|
||||
return onFolders(uid, aid)
|
||||
}
|
||||
override suspend fun videos(uid: Long, folderId: Long, page: Int): FavoritePage {
|
||||
videoCalls += Triple(uid, folderId, page)
|
||||
return onVideos(uid, folderId, page)
|
||||
}
|
||||
override suspend fun isFavorite(uid: Long, aid: Long) = onStatus(uid, aid)
|
||||
override suspend fun update(uid: Long, aid: Long, add: Set<Long>, remove: Set<Long>) {
|
||||
val change = FavoriteChange(uid, aid, add, remove)
|
||||
updates += change
|
||||
onUpdate(change)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package dev.bulubulu.tv.favorites
|
||||
|
||||
import dev.bulubulu.tv.core.ClientException
|
||||
import dev.bulubulu.tv.core.FavoriteFolder
|
||||
import kotlin.coroutines.Continuation
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.suspendCoroutine
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.test.runCurrent
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class FavoriteActionControllerTest {
|
||||
@Test fun anonymousPlaybackCannotReadOrWritePrivateFavorites() = runTest {
|
||||
val api = FakeFavorites()
|
||||
val messages = mutableListOf<String>()
|
||||
val controller = FavoriteActionController(this, api, {}, messages::add)
|
||||
controller.setVideo(100)
|
||||
controller.open()
|
||||
controller.save()
|
||||
runCurrent()
|
||||
assertFalse(controller.state.value.visible)
|
||||
assertTrue(api.folderCalls.isEmpty())
|
||||
assertTrue(api.updates.isEmpty())
|
||||
assertEquals(1, messages.size)
|
||||
}
|
||||
|
||||
@Test fun draftSelectionAndDismissNeverWrite() = runTest {
|
||||
val api = FakeFavorites()
|
||||
val controller = FavoriteActionController(this, api, {}, {})
|
||||
controller.setAccount(123); controller.setVideo(100); controller.open()
|
||||
runCurrent()
|
||||
assertEquals(setOf(11L), controller.state.value.selectedIds)
|
||||
controller.toggle(22)
|
||||
controller.toggle(999)
|
||||
controller.close()
|
||||
runCurrent()
|
||||
assertTrue(api.updates.isEmpty())
|
||||
assertFalse(controller.state.value.visible)
|
||||
}
|
||||
|
||||
@Test fun saveOnlyAppliesMembershipDifferencesToThePlayingArchive() = runTest {
|
||||
val api = FakeFavorites().apply {
|
||||
onFolders = { _, _ -> listOf(FavoriteFolder(11, "已有", 1, true), FavoriteFolder(22, "新增", 0)) }
|
||||
}
|
||||
var changes = 0
|
||||
val messages = mutableListOf<String>()
|
||||
val controller = FavoriteActionController(this, api, { changes++ }, messages::add)
|
||||
controller.setAccount(123); controller.setVideo(100); controller.open()
|
||||
runCurrent()
|
||||
controller.toggle(11); controller.toggle(22); controller.save()
|
||||
runCurrent()
|
||||
assertEquals(listOf(FavoriteChange(123, 100, setOf(22), setOf(11))), api.updates)
|
||||
assertTrue(controller.state.value.favorited == true)
|
||||
assertFalse(controller.state.value.visible)
|
||||
assertEquals(1, changes)
|
||||
assertEquals(listOf("已更新收藏"), messages)
|
||||
}
|
||||
|
||||
@Test fun unchangedSelectionDoesNotReloadOrSendAWriteAndRemovingAllIsExplicit() = runTest {
|
||||
val api = FakeFavorites().apply { onFolders = { _, _ -> listOf(FavoriteFolder(11, "已有", 1, true)) } }
|
||||
val controller = FavoriteActionController(this, api, {}, {})
|
||||
controller.setAccount(123); controller.setVideo(100); controller.open()
|
||||
runCurrent()
|
||||
controller.save()
|
||||
runCurrent()
|
||||
assertTrue(api.updates.isEmpty())
|
||||
controller.open(); runCurrent()
|
||||
controller.toggle(11); controller.save(); runCurrent()
|
||||
assertEquals(setOf(11L), api.updates.single().remove)
|
||||
assertEquals(false, controller.state.value.favorited)
|
||||
}
|
||||
|
||||
@Test fun duplicateSaveCannotStartConcurrentWrites() = runTest {
|
||||
val api = FakeFavorites()
|
||||
lateinit var pending: Continuation<Unit>
|
||||
api.onUpdate = { suspendCoroutine { pending = it } }
|
||||
val controller = FavoriteActionController(this, api, {}, {})
|
||||
controller.setAccount(123); controller.setVideo(100); controller.open()
|
||||
runCurrent()
|
||||
controller.save(); controller.save(); controller.toggle(22); runCurrent()
|
||||
assertTrue(controller.state.value.saving)
|
||||
assertEquals(1, api.updates.size)
|
||||
pending.resume(Unit); runCurrent()
|
||||
assertFalse(controller.state.value.saving)
|
||||
}
|
||||
|
||||
@Test fun uncertainWriteRequiresAnAuthoritativeReloadBeforeRetry() = runTest {
|
||||
val api = FakeFavorites().apply { onUpdate = { throw ClientException("连接中断") } }
|
||||
val messages = mutableListOf<String>()
|
||||
val controller = FavoriteActionController(this, api, {}, messages::add)
|
||||
controller.setAccount(123); controller.setVideo(100); controller.open(); runCurrent()
|
||||
controller.save(); runCurrent()
|
||||
assertTrue(controller.state.value.visible)
|
||||
assertTrue(controller.state.value.needsReload)
|
||||
assertNull(controller.state.value.favorited)
|
||||
assertTrue(messages.isEmpty())
|
||||
controller.save(); runCurrent()
|
||||
assertEquals(1, api.updates.size)
|
||||
api.onFolders = { _, _ -> listOf(FavoriteFolder(11, "已保存", 1, true)) }
|
||||
controller.open(); runCurrent()
|
||||
assertFalse(controller.state.value.needsReload)
|
||||
assertEquals(true, controller.state.value.favorited)
|
||||
controller.save(); runCurrent()
|
||||
assertEquals(1, api.updates.size)
|
||||
}
|
||||
|
||||
@Test fun accountSwitchRejectsLateFolderMembership() = runTest {
|
||||
val api = FakeFavorites()
|
||||
lateinit var pending: Continuation<List<FavoriteFolder>>
|
||||
api.onFolders = { _, _ -> suspendCoroutine { pending = it } }
|
||||
val controller = FavoriteActionController(this, api, {}, {})
|
||||
controller.setAccount(123); controller.setVideo(100); controller.open(); runCurrent()
|
||||
controller.setAccount(null)
|
||||
pending.resume(listOf(FavoriteFolder(11, "旧账号", 1, true))); runCurrent()
|
||||
assertFalse(controller.state.value.visible)
|
||||
assertFalse(controller.state.value.loggedIn)
|
||||
assertTrue(controller.state.value.folders.isEmpty())
|
||||
assertNull(controller.state.value.favorited)
|
||||
}
|
||||
|
||||
@Test fun newVideoAndClosedDialogRejectLateSuccessfulWrites() = runTest {
|
||||
for (newVideo in listOf(true, false)) {
|
||||
val api = FakeFavorites()
|
||||
lateinit var pending: Continuation<Unit>
|
||||
api.onUpdate = { suspendCoroutine { pending = it } }
|
||||
val messages = mutableListOf<String>()
|
||||
val controller = FavoriteActionController(this, api, {}, messages::add)
|
||||
controller.setAccount(123); controller.setVideo(100); controller.open(); runCurrent()
|
||||
controller.save(); runCurrent()
|
||||
if (newVideo) controller.setVideo(200) else controller.close()
|
||||
runCurrent()
|
||||
pending.resume(Unit); runCurrent()
|
||||
assertTrue(messages.isEmpty())
|
||||
assertFalse(controller.state.value.visible)
|
||||
assertEquals(if (newVideo) 200L else 100L, controller.state.value.aid)
|
||||
assertEquals(false, controller.state.value.favorited)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package dev.bulubulu.tv.favorites
|
||||
|
||||
import dev.bulubulu.tv.core.*
|
||||
import kotlin.coroutines.Continuation
|
||||
import kotlin.coroutines.resume
|
||||
import kotlin.coroutines.suspendCoroutine
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.test.runCurrent
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class FavoriteLibraryControllerTest {
|
||||
private fun item(id: String) = VideoItem(id, "视频 $id", "")
|
||||
|
||||
@Test fun privateLibraryRequiresLoginAndLogoutClearsEverything() = runTest {
|
||||
val api = FakeFavorites()
|
||||
val controller = FavoriteLibraryController(this, api)
|
||||
controller.refresh(); runCurrent()
|
||||
assertTrue(api.folderCalls.isEmpty())
|
||||
controller.setAccount(123); controller.refresh(); runCurrent()
|
||||
assertEquals(2, controller.state.value.folders.size)
|
||||
assertEquals(11L, controller.state.value.selectedFolderId)
|
||||
controller.setAccount(null)
|
||||
assertEquals(FavoriteLibraryState(), controller.state.value)
|
||||
}
|
||||
|
||||
@Test fun newFolderRejectsUncooperativeOldPage() = runTest {
|
||||
val api = FakeFavorites()
|
||||
val pending = mutableListOf<Continuation<FavoritePage>>()
|
||||
api.onVideos = { _, _, _ -> suspendCoroutine { pending += it } }
|
||||
val controller = FavoriteLibraryController(this, api)
|
||||
controller.setAccount(123); controller.refresh(); runCurrent()
|
||||
controller.selectFolder(22); runCurrent()
|
||||
pending[1].resume(FavoritePage(listOf(item("new")), null)); runCurrent()
|
||||
pending[0].resume(FavoritePage(listOf(item("old")), 2)); runCurrent()
|
||||
assertEquals(22L, controller.state.value.selectedFolderId)
|
||||
assertEquals(listOf("new"), controller.state.value.items.map { it.id })
|
||||
assertFalse(controller.state.value.hasMore)
|
||||
}
|
||||
|
||||
@Test fun newAccountRejectsOldFolderList() = runTest {
|
||||
val api = FakeFavorites()
|
||||
lateinit var pending: Continuation<List<FavoriteFolder>>
|
||||
api.onFolders = { _, _ -> suspendCoroutine { pending = it } }
|
||||
val controller = FavoriteLibraryController(this, api)
|
||||
controller.setAccount(123); controller.refresh(); runCurrent()
|
||||
controller.setAccount(456)
|
||||
pending.resume(listOf(FavoriteFolder(99, "旧账号", 1))); runCurrent()
|
||||
assertEquals(FavoriteLibraryState(), controller.state.value)
|
||||
assertTrue(api.videoCalls.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun emptyFolderListIsAValidEmptyLibrary() = runTest {
|
||||
val api = FakeFavorites().apply { onFolders = { _, _ -> emptyList() } }
|
||||
val controller = FavoriteLibraryController(this, api)
|
||||
controller.setAccount(123); controller.refresh(); runCurrent()
|
||||
assertFalse(controller.state.value.loading)
|
||||
assertNull(controller.state.value.error)
|
||||
assertNull(controller.state.value.selectedFolderId)
|
||||
assertTrue(api.videoCalls.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun paginationSkipsUnsupportedEntriesAndStopsRepeatedPlayablePages() = runTest {
|
||||
val api = FakeFavorites().apply {
|
||||
onVideos = { _, _, page -> when (page) {
|
||||
1 -> FavoritePage(emptyList(), 2)
|
||||
2 -> FavoritePage(listOf(item("a"), item("a")), 3)
|
||||
else -> FavoritePage(listOf(item("a")), 4)
|
||||
} }
|
||||
}
|
||||
val controller = FavoriteLibraryController(this, api)
|
||||
controller.setAccount(123); controller.refresh(); runCurrent()
|
||||
assertTrue(controller.state.value.hasMore)
|
||||
controller.loadMore(); controller.loadMore(); runCurrent()
|
||||
controller.loadMore(); runCurrent()
|
||||
controller.loadMore(); runCurrent()
|
||||
assertEquals(listOf(1, 2, 3), api.videoCalls.map { it.third })
|
||||
assertEquals(listOf("a"), controller.state.value.items.map { it.id })
|
||||
assertFalse(controller.state.value.hasMore)
|
||||
}
|
||||
|
||||
@Test fun pageFailureRetainsVideosAndRetryUsesTheSamePage() = runTest {
|
||||
var fail = true
|
||||
val api = FakeFavorites().apply {
|
||||
onVideos = { _, _, page ->
|
||||
if (page == 2 && fail) { fail = false; throw ClientException("请重试") }
|
||||
FavoritePage(listOf(item(page.toString())), if (page == 1) 2 else null)
|
||||
}
|
||||
}
|
||||
val controller = FavoriteLibraryController(this, api)
|
||||
controller.setAccount(123); controller.refresh(); runCurrent()
|
||||
controller.loadMore(); runCurrent()
|
||||
assertEquals("请重试", controller.state.value.error)
|
||||
assertEquals(listOf("1"), controller.state.value.items.map { it.id })
|
||||
controller.loadMore(); runCurrent()
|
||||
assertEquals(listOf(1, 2, 2), api.videoCalls.map { it.third })
|
||||
assertEquals(listOf("1", "2"), controller.state.value.items.map { it.id })
|
||||
}
|
||||
|
||||
@Test fun mutationRefreshesAnOpenedLibraryAndRetainsSelectedFolder() = runTest {
|
||||
val api = FakeFavorites()
|
||||
val controller = FavoriteLibraryController(this, api)
|
||||
controller.setAccount(123); controller.refreshIfOpened(); runCurrent()
|
||||
assertTrue(api.folderCalls.isEmpty())
|
||||
controller.refresh(); runCurrent()
|
||||
controller.selectFolder(22); runCurrent()
|
||||
controller.refreshIfOpened(); runCurrent()
|
||||
assertEquals(22L, controller.state.value.selectedFolderId)
|
||||
api.onFolders = { _, _ -> listOf(FavoriteFolder(11, "剩下的", 0)) }
|
||||
controller.refresh(); runCurrent()
|
||||
assertEquals(11L, controller.state.value.selectedFolderId)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user