Compare commits
19
Commits
6be024f86f
..
v0.9.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a3f3481f4f | ||
|
|
1b19513efb | ||
|
|
935de13343 | ||
|
|
01a3b0101e | ||
|
|
d6df5fbe5f | ||
|
|
929b7f72f8 | ||
|
|
e028ca40b1 | ||
|
|
d206465ee1 | ||
|
|
9117bf58b8 | ||
|
|
bd826a9236 | ||
|
|
a5dbae7fff | ||
|
|
00405d2e3b | ||
|
|
72dcb92aca | ||
|
|
8d511933df | ||
|
|
06a2f6d7c0 | ||
|
|
0d785bf1f8 | ||
|
|
4c3acb047c | ||
|
|
d3dbc9f8dc | ||
|
|
4b97f89c0b |
No files matched your search
@@ -4,6 +4,7 @@ package com.stormg.lumadrama
|
|||||||
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.app.PictureInPictureParams
|
import android.app.PictureInPictureParams
|
||||||
|
import android.content.Context
|
||||||
import android.content.res.Configuration
|
import android.content.res.Configuration
|
||||||
import android.graphics.Bitmap
|
import android.graphics.Bitmap
|
||||||
import android.media.MediaMetadataRetriever
|
import android.media.MediaMetadataRetriever
|
||||||
@@ -12,6 +13,8 @@ import android.os.Build
|
|||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
|
import android.provider.Settings
|
||||||
|
import android.telephony.TelephonyManager
|
||||||
import android.util.Rational
|
import android.util.Rational
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.view.WindowManager
|
import android.view.WindowManager
|
||||||
@@ -21,6 +24,7 @@ import io.flutter.embedding.android.FlutterActivity
|
|||||||
import io.flutter.embedding.engine.FlutterEngine
|
import io.flutter.embedding.engine.FlutterEngine
|
||||||
import io.flutter.plugin.common.MethodChannel
|
import io.flutter.plugin.common.MethodChannel
|
||||||
import java.io.ByteArrayOutputStream
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.util.Locale
|
||||||
import java.util.concurrent.ExecutorService
|
import java.util.concurrent.ExecutorService
|
||||||
import java.util.concurrent.Executors
|
import java.util.concurrent.Executors
|
||||||
import java.util.concurrent.atomic.AtomicBoolean
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
@@ -65,6 +69,23 @@ class MainActivity : FlutterActivity() {
|
|||||||
result.success(false)
|
result.success(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 设备标识:SSAID 免权限,卸载重装不变,避免客户端自己生成的 id 每次重装都变
|
||||||
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.stormg.lumadrama/device")
|
||||||
|
.setMethodCallHandler { call, result ->
|
||||||
|
when (call.method) {
|
||||||
|
"ssaid" -> {
|
||||||
|
val value = try {
|
||||||
|
Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
result.success(value)
|
||||||
|
}
|
||||||
|
// 设备区域:注册时作为服务端 IP 解析失败后的兜底
|
||||||
|
"region" -> result.success(currentRegion())
|
||||||
|
else -> result.notImplemented()
|
||||||
|
}
|
||||||
|
}
|
||||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.stormg.lumadrama/share")
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.stormg.lumadrama/share")
|
||||||
.setMethodCallHandler { call, result ->
|
.setMethodCallHandler { call, result ->
|
||||||
if (call.method != "shareText") {
|
if (call.method != "shareText") {
|
||||||
@@ -156,6 +177,28 @@ class MainActivity : FlutterActivity() {
|
|||||||
?.bottom
|
?.bottom
|
||||||
?: 0
|
?: 0
|
||||||
|
|
||||||
|
/** 网络运营商国家优先,其次 SIM 卡,最后系统语言;都拿不到返回空串。 */
|
||||||
|
private fun currentRegion(): String {
|
||||||
|
return try {
|
||||||
|
val telephony = getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager
|
||||||
|
val localeCountry = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||||
|
resources.configuration.locales.get(0).country
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
resources.configuration.locale.country
|
||||||
|
}
|
||||||
|
val candidates = listOfNotNull(
|
||||||
|
telephony?.networkCountryIso,
|
||||||
|
telephony?.simCountryIso,
|
||||||
|
localeCountry
|
||||||
|
)
|
||||||
|
candidates.firstOrNull { it.isNotBlank() }?.uppercase(Locale.ROOT) ?: ""
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// 个别 ROM 读运营商信息会抛 SecurityException,别让注册流程卡住
|
||||||
|
""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun emitImeInset(value: Int) {
|
private fun emitImeInset(value: Int) {
|
||||||
if (value == imeInset) return
|
if (value == imeInset) return
|
||||||
imeInset = value
|
imeInset = value
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ final class RunnerFlutterViewController: FlutterViewController {
|
|||||||
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
|
func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
|
||||||
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
|
GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
|
||||||
registerWirelessDataChannel(engineBridge)
|
registerWirelessDataChannel(engineBridge)
|
||||||
|
registerDeviceIdChannel(engineBridge)
|
||||||
let channel = FlutterMethodChannel(
|
let channel = FlutterMethodChannel(
|
||||||
name: "com.stormg.lumadrama/share",
|
name: "com.stormg.lumadrama/share",
|
||||||
binaryMessenger: engineBridge.applicationRegistrar.messenger()
|
binaryMessenger: engineBridge.applicationRegistrar.messenger()
|
||||||
@@ -144,6 +145,29 @@ final class RunnerFlutterViewController: FlutterViewController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 设备标识:IDFV 免权限,卸载本 App 不变,避免客户端自生成的 id 每次重装都变。
|
||||||
|
/// 同通道顺带提供设备区域(ISO-2),注册时作为服务端 IP 解析失败后的兜底。
|
||||||
|
private func registerDeviceIdChannel(_ engineBridge: FlutterImplicitEngineBridge) {
|
||||||
|
let channel = FlutterMethodChannel(
|
||||||
|
name: "com.stormg.lumadrama/device",
|
||||||
|
binaryMessenger: engineBridge.applicationRegistrar.messenger()
|
||||||
|
)
|
||||||
|
channel.setMethodCallHandler { call, result in
|
||||||
|
switch call.method {
|
||||||
|
case "idfv":
|
||||||
|
result(UIDevice.current.identifierForVendor?.uuidString)
|
||||||
|
case "region":
|
||||||
|
if #available(iOS 16.0, *) {
|
||||||
|
result(Locale.current.region?.identifier)
|
||||||
|
} else {
|
||||||
|
result(Locale.current.regionCode)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
result(FlutterMethodNotImplemented)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private func registerWirelessDataChannel(_ engineBridge: FlutterImplicitEngineBridge) {
|
private func registerWirelessDataChannel(_ engineBridge: FlutterImplicitEngineBridge) {
|
||||||
let channel = FlutterMethodChannel(
|
let channel = FlutterMethodChannel(
|
||||||
name: WirelessDataPrompt.channelName,
|
name: WirelessDataPrompt.channelName,
|
||||||
|
|||||||
@@ -48,7 +48,7 @@
|
|||||||
<key>NSIncludesSubdomains</key>
|
<key>NSIncludesSubdomains</key>
|
||||||
<true/>
|
<true/>
|
||||||
</dict>
|
</dict>
|
||||||
<key>10.43.47.1</key>
|
<key>192.168.31.243</key>
|
||||||
<dict>
|
<dict>
|
||||||
<key>NSExceptionAllowsInsecureHTTPLoads</key>
|
<key>NSExceptionAllowsInsecureHTTPLoads</key>
|
||||||
<true/>
|
<true/>
|
||||||
|
|||||||
+8
-13
@@ -14,6 +14,7 @@ import 'core/data/remote/catalog_api.dart';
|
|||||||
import 'core/data/remote/category_api.dart';
|
import 'core/data/remote/category_api.dart';
|
||||||
import 'core/data/remote/comment_api.dart';
|
import 'core/data/remote/comment_api.dart';
|
||||||
import 'core/data/remote/commerce_api.dart';
|
import 'core/data/remote/commerce_api.dart';
|
||||||
|
import 'core/data/remote/device_profile.dart';
|
||||||
import 'core/data/remote/download_api.dart';
|
import 'core/data/remote/download_api.dart';
|
||||||
import 'core/data/remote/interaction_api.dart';
|
import 'core/data/remote/interaction_api.dart';
|
||||||
import 'core/data/remote/library_api.dart';
|
import 'core/data/remote/library_api.dart';
|
||||||
@@ -117,12 +118,13 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
|||||||
late final AuthSessionStore _sessionStore = AuthSessionStore();
|
late final AuthSessionStore _sessionStore = AuthSessionStore();
|
||||||
|
|
||||||
/// 全 App 共用一个 ApiClient:这样目录、账号、后续的互动/进度请求
|
/// 全 App 共用一个 ApiClient:这样目录、账号、后续的互动/进度请求
|
||||||
/// 都自动带 `Authorization` 与 `X-Device-Id`,401 的刷新重试也只有一处实现。
|
/// 都自动带 `Authorization`、`X-Device-Id` 与平台头,401 的刷新重试也只有一处实现。
|
||||||
late final ApiClient _apiClient = ApiClient(
|
late final ApiClient _apiClient = ApiClient(
|
||||||
accessTokenReader: () => _auth.accessToken,
|
accessTokenReader: () => _auth.accessToken,
|
||||||
tokenRefresher: () => _auth.refresh(),
|
tokenRefresher: () => _auth.refresh(),
|
||||||
onUnauthorized: () => _auth.clear(),
|
onUnauthorized: () => _auth.clear(),
|
||||||
deviceIdReader: _sessionStore.deviceId,
|
deviceIdReader: _sessionStore.deviceId,
|
||||||
|
platformReader: clientPlatform,
|
||||||
);
|
);
|
||||||
|
|
||||||
late final AuthController _auth = AuthController(
|
late final AuthController _auth = AuthController(
|
||||||
@@ -141,17 +143,11 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
|||||||
|
|
||||||
late final WatchHistoryRepository _watchHistory =
|
late final WatchHistoryRepository _watchHistory =
|
||||||
widget.watchHistoryRepository ??
|
widget.watchHistoryRepository ??
|
||||||
HttpWatchHistoryRepository(
|
HttpWatchHistoryRepository(WatchApi(_apiClient));
|
||||||
WatchApi(_apiClient),
|
|
||||||
isSignedIn: () => _auth.isSignedIn,
|
|
||||||
);
|
|
||||||
|
|
||||||
late final FavoriteRepository _favorites =
|
late final FavoriteRepository _favorites =
|
||||||
widget.favoriteRepository ??
|
widget.favoriteRepository ??
|
||||||
HttpFavoriteRepository(
|
HttpFavoriteRepository(LibraryApi(_apiClient));
|
||||||
LibraryApi(_apiClient),
|
|
||||||
isSignedIn: () => _auth.isSignedIn,
|
|
||||||
);
|
|
||||||
|
|
||||||
late final PlaybackRepository _playback =
|
late final PlaybackRepository _playback =
|
||||||
widget.playbackRepository ??
|
widget.playbackRepository ??
|
||||||
@@ -219,7 +215,7 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
|||||||
unawaited(_localeController.load());
|
unawaited(_localeController.load());
|
||||||
// 登录/登出时同步收藏状态:收藏属于账号,不能跨账号串联
|
// 登录/登出时同步收藏状态:收藏属于账号,不能跨账号串联
|
||||||
_auth.addListener(_onAuthChanged);
|
_auth.addListener(_onAuthChanged);
|
||||||
if (_auth.isSignedIn) unawaited(_favoriteController.load());
|
unawaited(_favoriteController.load());
|
||||||
if (_auth.isSignedIn) unawaited(_walletController.load());
|
if (_auth.isSignedIn) unawaited(_walletController.load());
|
||||||
unawaited(_downloadController.restore());
|
unawaited(_downloadController.restore());
|
||||||
}
|
}
|
||||||
@@ -235,6 +231,7 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
|||||||
unawaited(_walletController.load());
|
unawaited(_walletController.load());
|
||||||
} else {
|
} else {
|
||||||
_favoriteController.clear();
|
_favoriteController.clear();
|
||||||
|
unawaited(_favoriteController.load());
|
||||||
_downloadController.reset();
|
_downloadController.reset();
|
||||||
_walletController.reset();
|
_walletController.reset();
|
||||||
}
|
}
|
||||||
@@ -293,9 +290,7 @@ class _LumaDramaAppState extends State<LumaDramaApp> {
|
|||||||
),
|
),
|
||||||
ChangeNotifierProvider(create: (_) => _createCategories()),
|
ChangeNotifierProvider(create: (_) => _createCategories()),
|
||||||
if (playlists != null)
|
if (playlists != null)
|
||||||
ChangeNotifierProvider(
|
ChangeNotifierProvider(create: (_) => PlaylistController(playlists)),
|
||||||
create: (_) => PlaylistController(playlists),
|
|
||||||
),
|
|
||||||
ChangeNotifierProvider.value(value: _favoriteController),
|
ChangeNotifierProvider.value(value: _favoriteController),
|
||||||
ChangeNotifierProvider.value(value: _downloadController),
|
ChangeNotifierProvider.value(value: _downloadController),
|
||||||
ChangeNotifierProvider.value(value: _walletController),
|
ChangeNotifierProvider.value(value: _walletController),
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ class AppConfig {
|
|||||||
/// 开发调试默认服务地址,当前指向本机局域网 IP。
|
/// 开发调试默认服务地址,当前指向本机局域网 IP。
|
||||||
///
|
///
|
||||||
/// 换网络时只改这一行,地址不要带结尾斜杠。
|
/// 换网络时只改这一行,地址不要带结尾斜杠。
|
||||||
static const String devHostBaseUrl = 'http://10.43.47.1:8081';
|
static const String devHostBaseUrl = 'http://192.168.31.243:8081';
|
||||||
|
|
||||||
/// 本机后端地址:通过 `adb reverse tcp:8081 tcp:8081` 映射到开发机,
|
/// 本机后端地址:通过 `adb reverse tcp:8081 tcp:8081` 映射到开发机,
|
||||||
/// 探测可达时 App 直连本机服务;不可达时回落到公网地址。
|
/// 探测可达时 App 直连本机服务;不可达时回落到公网地址。
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ class ApiClient {
|
|||||||
this.tokenRefresher,
|
this.tokenRefresher,
|
||||||
this.onUnauthorized,
|
this.onUnauthorized,
|
||||||
this.deviceIdReader,
|
this.deviceIdReader,
|
||||||
|
this.platformReader,
|
||||||
}) : _fixedBaseUrl = baseUrl {
|
}) : _fixedBaseUrl = baseUrl {
|
||||||
_dio = Dio(
|
_dio = Dio(
|
||||||
BaseOptions(
|
BaseOptions(
|
||||||
@@ -40,6 +41,7 @@ class ApiClient {
|
|||||||
AuthHeaderInterceptor(
|
AuthHeaderInterceptor(
|
||||||
accessTokenReader: accessTokenReader,
|
accessTokenReader: accessTokenReader,
|
||||||
deviceIdReader: deviceIdReader,
|
deviceIdReader: deviceIdReader,
|
||||||
|
platformReader: platformReader,
|
||||||
),
|
),
|
||||||
const EnvelopeInterceptor(),
|
const EnvelopeInterceptor(),
|
||||||
NetworkLogInterceptor(),
|
NetworkLogInterceptor(),
|
||||||
@@ -67,6 +69,9 @@ class ApiClient {
|
|||||||
/// 设备号(`X-Device-Id`):注册风控、后续下载绑定都要用
|
/// 设备号(`X-Device-Id`):注册风控、后续下载绑定都要用
|
||||||
final Future<String> Function()? deviceIdReader;
|
final Future<String> Function()? deviceIdReader;
|
||||||
|
|
||||||
|
/// 客户端平台(`X-Client-Platform`):后台区分 iOS / Android
|
||||||
|
final String Function()? platformReader;
|
||||||
|
|
||||||
Future<Object?> get(String path, {Map<String, String>? query}) {
|
Future<Object?> get(String path, {Map<String, String>? query}) {
|
||||||
return _request('GET', path, query: query);
|
return _request('GET', path, query: query);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,11 @@ class TokenExpiredException implements Exception {
|
|||||||
///
|
///
|
||||||
/// 每个请求都重新取一次令牌,所以刷新成功后重发的那次会自动带上新令牌。
|
/// 每个请求都重新取一次令牌,所以刷新成功后重发的那次会自动带上新令牌。
|
||||||
class AuthHeaderInterceptor extends Interceptor {
|
class AuthHeaderInterceptor extends Interceptor {
|
||||||
AuthHeaderInterceptor({this.accessTokenReader, this.deviceIdReader});
|
AuthHeaderInterceptor({
|
||||||
|
this.accessTokenReader,
|
||||||
|
this.deviceIdReader,
|
||||||
|
this.platformReader,
|
||||||
|
});
|
||||||
|
|
||||||
/// 当前 access token;未登录返回 null 或空串。
|
/// 当前 access token;未登录返回 null 或空串。
|
||||||
final String? Function()? accessTokenReader;
|
final String? Function()? accessTokenReader;
|
||||||
@@ -40,6 +44,9 @@ class AuthHeaderInterceptor extends Interceptor {
|
|||||||
/// 设备号(`X-Device-Id`):注册风控、下载绑定都用它。
|
/// 设备号(`X-Device-Id`):注册风控、下载绑定都用它。
|
||||||
final Future<String> Function()? deviceIdReader;
|
final Future<String> Function()? deviceIdReader;
|
||||||
|
|
||||||
|
/// 客户端平台(`X-Client-Platform`):后台区分 iOS / Android,匿名请求同样要带。
|
||||||
|
final String Function()? platformReader;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<void> onRequest(
|
Future<void> onRequest(
|
||||||
RequestOptions options,
|
RequestOptions options,
|
||||||
@@ -54,6 +61,10 @@ class AuthHeaderInterceptor extends Interceptor {
|
|||||||
if (deviceId != null && deviceId.isNotEmpty) {
|
if (deviceId != null && deviceId.isNotEmpty) {
|
||||||
options.headers['X-Device-Id'] = deviceId;
|
options.headers['X-Device-Id'] = deviceId;
|
||||||
}
|
}
|
||||||
|
final platform = platformReader?.call() ?? '';
|
||||||
|
if (platform.isNotEmpty) {
|
||||||
|
options.headers['X-Client-Platform'] = platform;
|
||||||
|
}
|
||||||
handler.next(options);
|
handler.next(options);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,6 +56,7 @@ class AuthApi {
|
|||||||
required String target,
|
required String target,
|
||||||
required String code,
|
required String code,
|
||||||
required String deviceId,
|
required String deviceId,
|
||||||
|
String countryCode = '',
|
||||||
String platform = '',
|
String platform = '',
|
||||||
String osVersion = '',
|
String osVersion = '',
|
||||||
String appVersion = '',
|
String appVersion = '',
|
||||||
@@ -66,6 +67,7 @@ class AuthApi {
|
|||||||
'targetType': 'PHONE',
|
'targetType': 'PHONE',
|
||||||
'target': target,
|
'target': target,
|
||||||
'code': code,
|
'code': code,
|
||||||
|
'countryCode': countryCode,
|
||||||
'deviceId': deviceId,
|
'deviceId': deviceId,
|
||||||
'platform': platform,
|
'platform': platform,
|
||||||
'osVersion': osVersion,
|
'osVersion': osVersion,
|
||||||
@@ -79,6 +81,7 @@ class AuthApi {
|
|||||||
required String email,
|
required String email,
|
||||||
required String password,
|
required String password,
|
||||||
required String deviceId,
|
required String deviceId,
|
||||||
|
String countryCode = '',
|
||||||
String platform = '',
|
String platform = '',
|
||||||
String osVersion = '',
|
String osVersion = '',
|
||||||
String appVersion = '',
|
String appVersion = '',
|
||||||
@@ -89,7 +92,7 @@ class AuthApi {
|
|||||||
'targetType': 'EMAIL',
|
'targetType': 'EMAIL',
|
||||||
'target': email,
|
'target': email,
|
||||||
'password': password,
|
'password': password,
|
||||||
'countryCode': 'ID',
|
'countryCode': countryCode,
|
||||||
'deviceId': deviceId,
|
'deviceId': deviceId,
|
||||||
'platform': platform,
|
'platform': platform,
|
||||||
'osVersion': osVersion,
|
'osVersion': osVersion,
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
import 'dart:io' show Platform;
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
|
/// 客户端平台,后台只用来区分 iOS / Android。
|
||||||
|
///
|
||||||
|
/// 系统版本、机型一律不上报:后台列表需要的只是「这台设备是安卓还是苹果」。
|
||||||
|
String clientPlatform() {
|
||||||
|
if (kIsWeb) return 'WEB';
|
||||||
|
if (Platform.isAndroid) return 'ANDROID';
|
||||||
|
if (Platform.isIOS) return 'IOS';
|
||||||
|
return '';
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ import '../models/page_result.dart';
|
|||||||
import '../models/watch_progress.dart';
|
import '../models/watch_progress.dart';
|
||||||
import 'api_client.dart';
|
import 'api_client.dart';
|
||||||
|
|
||||||
/// 观看进度接口:`/app/watch/*`(契约 §1.5)。全部需要登录态。
|
/// 观看进度接口:`/app/watch/*`(契约 §1.5)。支持账号或设备身份。
|
||||||
class WatchApi {
|
class WatchApi {
|
||||||
const WatchApi(this._client);
|
const WatchApi(this._client);
|
||||||
|
|
||||||
|
|||||||
@@ -19,21 +19,15 @@ abstract interface class FavoriteRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class HttpFavoriteRepository implements FavoriteRepository {
|
class HttpFavoriteRepository implements FavoriteRepository {
|
||||||
const HttpFavoriteRepository(this._api, {this.isSignedIn});
|
const HttpFavoriteRepository(this._api);
|
||||||
|
|
||||||
final LibraryApi _api;
|
final LibraryApi _api;
|
||||||
|
|
||||||
/// 未登录时不请求:收藏属于账号,匿名浏览时列表按空处理(点收藏按钮会先引导登录)。
|
|
||||||
final bool Function()? isSignedIn;
|
|
||||||
|
|
||||||
bool get _signedIn => isSignedIn?.call() ?? true;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<bool> toggle(String dramaId) => _api.toggleFavorite(dramaId);
|
Future<bool> toggle(String dramaId) => _api.toggleFavorite(dramaId);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<PageResult<Drama>> page({int pageIndex = 1, int pageSize = 20}) async {
|
Future<PageResult<Drama>> page({int pageIndex = 1, int pageSize = 20}) async {
|
||||||
if (!_signedIn) return const PageResult();
|
|
||||||
return _api.favorites(pageIndex: pageIndex, pageSize: pageSize);
|
return _api.favorites(pageIndex: pageIndex, pageSize: pageSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,18 +35,12 @@ abstract interface class WatchHistoryRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class HttpWatchHistoryRepository implements WatchHistoryRepository {
|
class HttpWatchHistoryRepository implements WatchHistoryRepository {
|
||||||
const HttpWatchHistoryRepository(this._api, {this.isSignedIn});
|
const HttpWatchHistoryRepository(this._api);
|
||||||
|
|
||||||
final WatchApi _api;
|
final WatchApi _api;
|
||||||
|
|
||||||
/// 未登录时这些接口必然 401:直接短路成"没有记录",让浏览/试看保持匿名可用。
|
|
||||||
final bool Function()? isSignedIn;
|
|
||||||
|
|
||||||
bool get _signedIn => isSignedIn?.call() ?? true;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<WatchProgress?> progressFor(String dramaId) async {
|
Future<WatchProgress?> progressFor(String dramaId) async {
|
||||||
if (!_signedIn) return null;
|
|
||||||
return _api.progressOfDrama(dramaId);
|
return _api.progressOfDrama(dramaId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,7 +51,6 @@ class HttpWatchHistoryRepository implements WatchHistoryRepository {
|
|||||||
Duration? duration,
|
Duration? duration,
|
||||||
bool finished = false,
|
bool finished = false,
|
||||||
}) async {
|
}) async {
|
||||||
if (!_signedIn) return null;
|
|
||||||
return _api.saveProgress(
|
return _api.saveProgress(
|
||||||
episodeId: episodeId,
|
episodeId: episodeId,
|
||||||
position: position,
|
position: position,
|
||||||
@@ -71,19 +64,16 @@ class HttpWatchHistoryRepository implements WatchHistoryRepository {
|
|||||||
int pageIndex = 1,
|
int pageIndex = 1,
|
||||||
int pageSize = 20,
|
int pageSize = 20,
|
||||||
}) async {
|
}) async {
|
||||||
if (!_signedIn) return const PageResult();
|
|
||||||
return _api.recent(pageIndex: pageIndex, pageSize: pageSize);
|
return _api.recent(pageIndex: pageIndex, pageSize: pageSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<void> remove(String dramaId) async {
|
Future<void> remove(String dramaId) async {
|
||||||
if (!_signedIn) return;
|
|
||||||
await _api.removeProgress(dramaId);
|
await _api.removeProgress(dramaId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<void> clear() async {
|
Future<void> clear() async {
|
||||||
if (!_signedIn) return;
|
|
||||||
await _api.clearProgress();
|
await _api.clearProgress();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ class AuthController extends ChangeNotifier {
|
|||||||
email: email,
|
email: email,
|
||||||
password: password,
|
password: password,
|
||||||
deviceId: await _store.deviceId(),
|
deviceId: await _store.deviceId(),
|
||||||
|
countryCode: await _store.deviceRegion(),
|
||||||
platform: _platform,
|
platform: _platform,
|
||||||
osVersion: _osVersion,
|
osVersion: _osVersion,
|
||||||
);
|
);
|
||||||
@@ -95,6 +96,7 @@ class AuthController extends ChangeNotifier {
|
|||||||
target: target,
|
target: target,
|
||||||
code: code,
|
code: code,
|
||||||
deviceId: await _store.deviceId(),
|
deviceId: await _store.deviceId(),
|
||||||
|
countryCode: await _store.deviceRegion(),
|
||||||
platform: _platform,
|
platform: _platform,
|
||||||
osVersion: _osVersion,
|
osVersion: _osVersion,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import 'dart:math';
|
|||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
import '../models/auth_session.dart';
|
import '../models/auth_session.dart';
|
||||||
|
import 'device_id_provider.dart';
|
||||||
|
|
||||||
/// 令牌与设备号的本地持久化。
|
/// 令牌与设备号的本地持久化。
|
||||||
///
|
///
|
||||||
@@ -11,13 +12,17 @@ import '../models/auth_session.dart';
|
|||||||
/// `SharedPreferences.getInstance()` 在新版本里已标注弃用,两套混用还会让
|
/// `SharedPreferences.getInstance()` 在新版本里已标注弃用,两套混用还会让
|
||||||
/// widget 测试只 mock 到其中一套。
|
/// widget 测试只 mock 到其中一套。
|
||||||
///
|
///
|
||||||
/// 设备号是后端注册风控与后续"下载设备绑定"的依据,所以**首次生成后就固定下来**;
|
/// 设备号优先取系统标识(Android SSAID / iOS IDFV),这样卸载重装后还是同一台设备;
|
||||||
/// 不引 UUID 库(保持极简依赖),用「时间戳 + 随机数」拼一个够用的 id。
|
/// 系统标识不可用时才回退到本地生成并持久化的 UUID,保证任何环境都能跑。
|
||||||
class AuthSessionStore {
|
class AuthSessionStore {
|
||||||
AuthSessionStore({SharedPreferencesAsync? preferences})
|
AuthSessionStore({
|
||||||
: _preferences = preferences ?? SharedPreferencesAsync();
|
SharedPreferencesAsync? preferences,
|
||||||
|
DeviceIdProvider? deviceIdProvider,
|
||||||
|
}) : _preferences = preferences ?? SharedPreferencesAsync(),
|
||||||
|
_deviceIdProvider = deviceIdProvider ?? DeviceIdProvider();
|
||||||
|
|
||||||
final SharedPreferencesAsync _preferences;
|
final SharedPreferencesAsync _preferences;
|
||||||
|
final DeviceIdProvider _deviceIdProvider;
|
||||||
|
|
||||||
static const _kAccessToken = 'auth.accessToken';
|
static const _kAccessToken = 'auth.accessToken';
|
||||||
static const _kRefreshToken = 'auth.refreshToken';
|
static const _kRefreshToken = 'auth.refreshToken';
|
||||||
@@ -25,21 +30,46 @@ class AuthSessionStore {
|
|||||||
static const _kDeviceId = 'device.id';
|
static const _kDeviceId = 'device.id';
|
||||||
|
|
||||||
String? _cachedDeviceId;
|
String? _cachedDeviceId;
|
||||||
|
String? _cachedRegion;
|
||||||
|
|
||||||
Future<String> deviceId() async {
|
Future<String> deviceId() async {
|
||||||
if (_cachedDeviceId != null) return _cachedDeviceId!;
|
if (_cachedDeviceId != null) return _cachedDeviceId!;
|
||||||
var value = await _preferences.getString(_kDeviceId) ?? '';
|
final systemId = await _deviceIdProvider.systemDeviceId();
|
||||||
if (value.isEmpty) {
|
final value = systemId ?? await _localDeviceId();
|
||||||
final random = Random();
|
|
||||||
value =
|
|
||||||
'd-${DateTime.now().millisecondsSinceEpoch.toRadixString(36)}-'
|
|
||||||
'${random.nextInt(1 << 32).toRadixString(36)}';
|
|
||||||
await _preferences.setString(_kDeviceId, value);
|
|
||||||
}
|
|
||||||
_cachedDeviceId = value;
|
_cachedDeviceId = value;
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 设备区域(ISO-2),取不到返回空串;只在注册时作为服务端 IP 解析失败后的兜底。
|
||||||
|
Future<String> deviceRegion() async {
|
||||||
|
if (_cachedRegion != null) return _cachedRegion!;
|
||||||
|
final value = await _deviceIdProvider.deviceRegion() ?? '';
|
||||||
|
_cachedRegion = value;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 系统标识取不到时的兜底:本地 UUIDv4,生成一次后固定下来。
|
||||||
|
Future<String> _localDeviceId() async {
|
||||||
|
final stored = await _preferences.getString(_kDeviceId) ?? '';
|
||||||
|
if (stored.isNotEmpty) return stored;
|
||||||
|
final generated = 'd-${_uuidV4()}';
|
||||||
|
await _preferences.setString(_kDeviceId, generated);
|
||||||
|
return generated;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// UUIDv4:122 位随机,碰撞概率可忽略,不引第三方依赖。
|
||||||
|
String _uuidV4() {
|
||||||
|
final random = Random.secure();
|
||||||
|
final bytes = List<int>.generate(16, (_) => random.nextInt(256));
|
||||||
|
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
||||||
|
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||||
|
String hex(int start, int end) => bytes
|
||||||
|
.sublist(start, end)
|
||||||
|
.map((byte) => byte.toRadixString(16).padLeft(2, '0'))
|
||||||
|
.join();
|
||||||
|
return '${hex(0, 4)}-${hex(4, 6)}-${hex(6, 8)}-${hex(8, 10)}-${hex(10, 16)}';
|
||||||
|
}
|
||||||
|
|
||||||
Future<AuthSession?> read() async {
|
Future<AuthSession?> read() async {
|
||||||
final accessToken = await _preferences.getString(_kAccessToken) ?? '';
|
final accessToken = await _preferences.getString(_kAccessToken) ?? '';
|
||||||
final refreshToken = await _preferences.getString(_kRefreshToken) ?? '';
|
final refreshToken = await _preferences.getString(_kRefreshToken) ?? '';
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
import 'dart:io' show Platform;
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
|
/// 读取系统级设备标识,两端都不需要任何权限。
|
||||||
|
///
|
||||||
|
/// - Android:SSAID(`Settings.Secure.ANDROID_ID`),卸载重装不变;
|
||||||
|
/// - iOS:IDFV(`identifierForVendor`),卸载本 App 不变,同厂商应用全删才会变。
|
||||||
|
///
|
||||||
|
/// 两端都由原生侧提供,不引插件:项目 iOS 走 SPM,避免混入 CocoaPods。
|
||||||
|
/// 取不到(Web、测试环境、通道异常)时返回 null,由调用方回退到本地生成的 id。
|
||||||
|
class DeviceIdProvider {
|
||||||
|
static const MethodChannel _channel = MethodChannel(
|
||||||
|
'com.stormg.lumadrama/device',
|
||||||
|
);
|
||||||
|
|
||||||
|
Future<String?> systemDeviceId() async {
|
||||||
|
if (kIsWeb) return null;
|
||||||
|
try {
|
||||||
|
if (Platform.isAndroid) {
|
||||||
|
final ssaid = await _channel.invokeMethod<String>('ssaid');
|
||||||
|
if (ssaid != null && ssaid.isNotEmpty) return 'a-$ssaid';
|
||||||
|
}
|
||||||
|
if (Platform.isIOS) {
|
||||||
|
final idfv = await _channel.invokeMethod<String>('idfv');
|
||||||
|
if (idfv != null && idfv.isNotEmpty) return 'i-$idfv';
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// 原生通道不可用(widget 测试)时走本地兜底
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 设备所在区域(ISO-2),仅用于服务端 IP 解析失败时兜底注册国家。
|
||||||
|
/// Android 依次取网络运营商 / SIM 卡 / 系统语言的国家,iOS 取系统 region。
|
||||||
|
Future<String?> deviceRegion() async {
|
||||||
|
if (kIsWeb) return null;
|
||||||
|
try {
|
||||||
|
final region = await _channel.invokeMethod<String>('region');
|
||||||
|
final value = region?.trim().toUpperCase() ?? '';
|
||||||
|
if (value.length == 2) return value;
|
||||||
|
} catch (_) {
|
||||||
|
// 原生通道不可用(widget 测试)时返回 null,由服务端兜底
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
final FavoriteRepository _repository;
|
final FavoriteRepository _repository;
|
||||||
final int pageSize;
|
final int pageSize;
|
||||||
final Set<String> _saved = {};
|
final Set<String> _saved = {};
|
||||||
|
final Map<String, int> _favoriteCounts = {};
|
||||||
List<Drama> cards = const [];
|
List<Drama> cards = const [];
|
||||||
int total = 0;
|
int total = 0;
|
||||||
bool loading = false;
|
bool loading = false;
|
||||||
@@ -34,17 +35,53 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
|
|
||||||
bool isSaved(String dramaId) => _saved.contains(dramaId);
|
bool isSaved(String dramaId) => _saved.contains(dramaId);
|
||||||
|
|
||||||
/// 用统计快照校准收藏状态;已有列表卡片结构不因一次状态同步而改动。
|
/// 当前剧收藏数;包含本地 toggle 增量。
|
||||||
void applyServerState(String dramaId, {required bool saved}) {
|
int? favoriteCount(String dramaId) => _favoriteCounts[dramaId];
|
||||||
final changed = _saved.contains(dramaId) != saved;
|
|
||||||
|
/// 首次展示时缓存卡片基数;之后统一由本控制器维护,避免页面各存一份。
|
||||||
|
int? favoriteCountFor(Drama drama) {
|
||||||
|
final current = _favoriteCounts[drama.id];
|
||||||
|
if (current != null) return current;
|
||||||
|
final fallback = drama.favoriteCount;
|
||||||
|
if (fallback == null) return null;
|
||||||
|
final normalized = fallback < 0 ? 0 : fallback;
|
||||||
|
_favoriteCounts[drama.id] = normalized;
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 用 stats/detail 的服务端快照校准唯一状态和计数。
|
||||||
|
void applyServerState(
|
||||||
|
String dramaId, {
|
||||||
|
required bool saved,
|
||||||
|
int? favoriteCount,
|
||||||
|
}) {
|
||||||
|
var changed = _saved.contains(dramaId) != saved;
|
||||||
if (saved) {
|
if (saved) {
|
||||||
_saved.add(dramaId);
|
_saved.add(dramaId);
|
||||||
} else {
|
} else {
|
||||||
_saved.remove(dramaId);
|
_saved.remove(dramaId);
|
||||||
}
|
}
|
||||||
|
if (favoriteCount != null) {
|
||||||
|
final normalized = favoriteCount < 0 ? 0 : favoriteCount;
|
||||||
|
changed = changed || _favoriteCounts[dramaId] != normalized;
|
||||||
|
_favoriteCounts[dramaId] = normalized;
|
||||||
|
}
|
||||||
if (changed) notify();
|
if (changed) notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 详情等只有计数、没有当前收藏状态的接口使用。
|
||||||
|
void applyServerCount(
|
||||||
|
String dramaId,
|
||||||
|
int? favoriteCount, {
|
||||||
|
bool notify = true,
|
||||||
|
}) {
|
||||||
|
if (favoriteCount == null) return;
|
||||||
|
final normalized = favoriteCount < 0 ? 0 : favoriteCount;
|
||||||
|
if (_favoriteCounts[dramaId] == normalized) return;
|
||||||
|
_favoriteCounts[dramaId] = normalized;
|
||||||
|
if (notify) this.notify();
|
||||||
|
}
|
||||||
|
|
||||||
void notify() {
|
void notify() {
|
||||||
if (!_disposed) notifyListeners();
|
if (!_disposed) notifyListeners();
|
||||||
}
|
}
|
||||||
@@ -56,6 +93,7 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
loadingMore = false;
|
loadingMore = false;
|
||||||
error = null;
|
error = null;
|
||||||
loadMoreError = null;
|
loadMoreError = null;
|
||||||
|
lastErrorCode = null;
|
||||||
notify();
|
notify();
|
||||||
try {
|
try {
|
||||||
final page = await _repository.page(pageIndex: 1, pageSize: pageSize);
|
final page = await _repository.page(pageIndex: 1, pageSize: pageSize);
|
||||||
@@ -65,12 +103,14 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
_saved
|
_saved
|
||||||
..clear()
|
..clear()
|
||||||
..addAll(list.map((drama) => drama.id));
|
..addAll(list.map((drama) => drama.id));
|
||||||
|
_rememberCardCounts(list);
|
||||||
total = page.total;
|
total = page.total;
|
||||||
_pageIndex = 1;
|
_pageIndex = 1;
|
||||||
hasMore = page.list.isNotEmpty && cards.length < total;
|
hasMore = page.list.isNotEmpty && cards.length < total;
|
||||||
} catch (_) {
|
} catch (failure) {
|
||||||
if (!_disposed && request == _requestSeq) {
|
if (!_disposed && request == _requestSeq) {
|
||||||
error = 'favoritesError';
|
error = 'favoritesError';
|
||||||
|
if (failure is ApiException) lastErrorCode = failure.code;
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (!_disposed && request == _requestSeq) {
|
if (!_disposed && request == _requestSeq) {
|
||||||
@@ -86,6 +126,7 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
final request = ++_requestSeq;
|
final request = ++_requestSeq;
|
||||||
loadingMore = true;
|
loadingMore = true;
|
||||||
loadMoreError = null;
|
loadMoreError = null;
|
||||||
|
lastErrorCode = null;
|
||||||
notify();
|
notify();
|
||||||
try {
|
try {
|
||||||
final page = await _repository.page(
|
final page = await _repository.page(
|
||||||
@@ -99,12 +140,14 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
).where((drama) => known.add(drama.id)).toList(growable: false);
|
).where((drama) => known.add(drama.id)).toList(growable: false);
|
||||||
cards = [...cards, ...appended];
|
cards = [...cards, ...appended];
|
||||||
_saved.addAll(appended.map((drama) => drama.id));
|
_saved.addAll(appended.map((drama) => drama.id));
|
||||||
|
_rememberCardCounts(appended);
|
||||||
total = page.total;
|
total = page.total;
|
||||||
_pageIndex += 1;
|
_pageIndex += 1;
|
||||||
hasMore = page.list.isNotEmpty && cards.length < total;
|
hasMore = page.list.isNotEmpty && cards.length < total;
|
||||||
} catch (_) {
|
} catch (failure) {
|
||||||
if (!_disposed && request == _requestSeq) {
|
if (!_disposed && request == _requestSeq) {
|
||||||
loadMoreError = 'favoritesError';
|
loadMoreError = 'favoritesError';
|
||||||
|
if (failure is ApiException) lastErrorCode = failure.code;
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (!_disposed && request == _requestSeq) {
|
if (!_disposed && request == _requestSeq) {
|
||||||
@@ -121,12 +164,16 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
Future<bool> toggle(String dramaId, {Drama? card}) async {
|
Future<bool> toggle(String dramaId, {Drama? card}) async {
|
||||||
lastErrorCode = null;
|
lastErrorCode = null;
|
||||||
final wasSaved = _saved.contains(dramaId);
|
final wasSaved = _saved.contains(dramaId);
|
||||||
|
final previousCount = card == null
|
||||||
|
? favoriteCount(dramaId)
|
||||||
|
: favoriteCountFor(card);
|
||||||
final previousCards = cards;
|
final previousCards = cards;
|
||||||
final previousTotal = total;
|
final previousTotal = total;
|
||||||
final previousHasMore = hasMore;
|
final previousHasMore = hasMore;
|
||||||
// 乐观更新
|
// 乐观更新
|
||||||
if (wasSaved) {
|
if (wasSaved) {
|
||||||
_saved.remove(dramaId);
|
_saved.remove(dramaId);
|
||||||
|
_stepCount(dramaId, -1);
|
||||||
if (cards.any((drama) => drama.id == dramaId)) {
|
if (cards.any((drama) => drama.id == dramaId)) {
|
||||||
cards = cards.where((drama) => drama.id != dramaId).toList();
|
cards = cards.where((drama) => drama.id != dramaId).toList();
|
||||||
total = total > 0 ? total - 1 : 0;
|
total = total > 0 ? total - 1 : 0;
|
||||||
@@ -134,6 +181,7 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
_saved.add(dramaId);
|
_saved.add(dramaId);
|
||||||
|
_stepCount(dramaId, 1);
|
||||||
}
|
}
|
||||||
notify();
|
notify();
|
||||||
try {
|
try {
|
||||||
@@ -142,6 +190,7 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
if (saved) {
|
if (saved) {
|
||||||
_saved.add(dramaId);
|
_saved.add(dramaId);
|
||||||
if (wasSaved) {
|
if (wasSaved) {
|
||||||
|
_restoreCount(dramaId, previousCount);
|
||||||
cards = previousCards;
|
cards = previousCards;
|
||||||
total = previousTotal;
|
total = previousTotal;
|
||||||
hasMore = previousHasMore;
|
hasMore = previousHasMore;
|
||||||
@@ -152,6 +201,9 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
_saved.remove(dramaId);
|
_saved.remove(dramaId);
|
||||||
|
if (!wasSaved) {
|
||||||
|
_restoreCount(dramaId, previousCount);
|
||||||
|
}
|
||||||
if (cards.any((drama) => drama.id == dramaId)) {
|
if (cards.any((drama) => drama.id == dramaId)) {
|
||||||
cards = cards.where((drama) => drama.id != dramaId).toList();
|
cards = cards.where((drama) => drama.id != dramaId).toList();
|
||||||
total = total > 0 ? total - 1 : 0;
|
total = total > 0 ? total - 1 : 0;
|
||||||
@@ -170,6 +222,7 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
} else {
|
} else {
|
||||||
_saved.remove(dramaId);
|
_saved.remove(dramaId);
|
||||||
}
|
}
|
||||||
|
_restoreCount(dramaId, previousCount);
|
||||||
notify();
|
notify();
|
||||||
if (failure is ApiException) lastErrorCode = failure.code;
|
if (failure is ApiException) lastErrorCode = failure.code;
|
||||||
return false;
|
return false;
|
||||||
@@ -185,9 +238,13 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
final previousHasMore = hasMore;
|
final previousHasMore = hasMore;
|
||||||
final removed = cards.where((drama) => ids.contains(drama.id)).toList();
|
final removed = cards.where((drama) => ids.contains(drama.id)).toList();
|
||||||
if (removed.isEmpty) return true;
|
if (removed.isEmpty) return true;
|
||||||
|
final previousCounts = {
|
||||||
|
for (final drama in removed) drama.id: _favoriteCounts[drama.id],
|
||||||
|
};
|
||||||
cards = cards.where((drama) => !ids.contains(drama.id)).toList();
|
cards = cards.where((drama) => !ids.contains(drama.id)).toList();
|
||||||
for (final id in ids) {
|
for (final id in ids) {
|
||||||
_saved.remove(id);
|
_saved.remove(id);
|
||||||
|
_stepCount(id, -1);
|
||||||
}
|
}
|
||||||
total = total > removed.length ? total - removed.length : 0;
|
total = total > removed.length ? total - removed.length : 0;
|
||||||
hasMore = cards.length < total;
|
hasMore = cards.length < total;
|
||||||
@@ -202,6 +259,9 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
for (final drama in removed) {
|
for (final drama in removed) {
|
||||||
_saved.add(drama.id);
|
_saved.add(drama.id);
|
||||||
}
|
}
|
||||||
|
for (final entry in previousCounts.entries) {
|
||||||
|
_restoreCount(entry.key, entry.value);
|
||||||
|
}
|
||||||
notify();
|
notify();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -212,7 +272,9 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
final index = cards.indexWhere((drama) => drama.id == dramaId);
|
final index = cards.indexWhere((drama) => drama.id == dramaId);
|
||||||
if (index < 0) return true;
|
if (index < 0) return true;
|
||||||
final removed = cards[index];
|
final removed = cards[index];
|
||||||
|
final previousCount = _favoriteCounts[dramaId];
|
||||||
_saved.remove(dramaId);
|
_saved.remove(dramaId);
|
||||||
|
_stepCount(dramaId, -1);
|
||||||
final next = [...cards]..removeAt(index);
|
final next = [...cards]..removeAt(index);
|
||||||
cards = next;
|
cards = next;
|
||||||
total = total > 0 ? total - 1 : 0;
|
total = total > 0 ? total - 1 : 0;
|
||||||
@@ -229,6 +291,7 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
);
|
);
|
||||||
cards = restored;
|
cards = restored;
|
||||||
_saved.add(dramaId);
|
_saved.add(dramaId);
|
||||||
|
_restoreCount(dramaId, previousCount);
|
||||||
total += 1;
|
total += 1;
|
||||||
hasMore = cards.length < total;
|
hasMore = cards.length < total;
|
||||||
notify();
|
notify();
|
||||||
@@ -259,6 +322,30 @@ class FavoriteController extends ChangeNotifier {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _rememberCardCounts(List<Drama> dramas) {
|
||||||
|
for (final drama in dramas) {
|
||||||
|
final count = drama.favoriteCount;
|
||||||
|
if (count != null && !_favoriteCounts.containsKey(drama.id)) {
|
||||||
|
_favoriteCounts[drama.id] = count < 0 ? 0 : count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _stepCount(String dramaId, int delta) {
|
||||||
|
final current = _favoriteCounts[dramaId];
|
||||||
|
if (current == null) return;
|
||||||
|
final next = current + delta;
|
||||||
|
_favoriteCounts[dramaId] = next < 0 ? 0 : next;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _restoreCount(String dramaId, int? count) {
|
||||||
|
if (count == null) {
|
||||||
|
_favoriteCounts.remove(dramaId);
|
||||||
|
} else {
|
||||||
|
_favoriteCounts[dramaId] = count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_disposed = true;
|
_disposed = true;
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ class HomeFeedController extends ChangeNotifier {
|
|||||||
String? get cursor => _state(_channel).cursor;
|
String? get cursor => _state(_channel).cursor;
|
||||||
bool get hasMore => _state(_channel).hasMore;
|
bool get hasMore => _state(_channel).hasMore;
|
||||||
bool get loaded => _state(_channel).loaded;
|
bool get loaded => _state(_channel).loaded;
|
||||||
|
bool get isLoading => _state(_channel).loading;
|
||||||
bool get loadingMore => _state(_channel).loadingMore;
|
bool get loadingMore => _state(_channel).loadingMore;
|
||||||
bool get loadingFirstPage => !loaded && _state(_channel).loading;
|
bool get loadingFirstPage => !loaded && _state(_channel).loading;
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ class WatchRecordsController extends ChangeNotifier {
|
|||||||
String? error;
|
String? error;
|
||||||
String? loadMoreError;
|
String? loadMoreError;
|
||||||
String? actionError;
|
String? actionError;
|
||||||
|
int? lastErrorCode;
|
||||||
int _pageIndex = 0;
|
int _pageIndex = 0;
|
||||||
int _requestSeq = 0;
|
int _requestSeq = 0;
|
||||||
bool _disposed = false;
|
bool _disposed = false;
|
||||||
@@ -50,6 +51,7 @@ class WatchRecordsController extends ChangeNotifier {
|
|||||||
error = null;
|
error = null;
|
||||||
loadMoreError = null;
|
loadMoreError = null;
|
||||||
actionError = null;
|
actionError = null;
|
||||||
|
lastErrorCode = null;
|
||||||
_notify();
|
_notify();
|
||||||
try {
|
try {
|
||||||
final page = await _history.recent(pageIndex: 1, pageSize: pageSize);
|
final page = await _history.recent(pageIndex: 1, pageSize: pageSize);
|
||||||
@@ -71,6 +73,7 @@ class WatchRecordsController extends ChangeNotifier {
|
|||||||
);
|
);
|
||||||
if (!_disposed && request == _requestSeq) {
|
if (!_disposed && request == _requestSeq) {
|
||||||
error = failure is ApiException ? failure.message : 'progressError';
|
error = failure is ApiException ? failure.message : 'progressError';
|
||||||
|
if (failure is ApiException) lastErrorCode = failure.code;
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (!_disposed && request == _requestSeq) {
|
if (!_disposed && request == _requestSeq) {
|
||||||
@@ -86,6 +89,7 @@ class WatchRecordsController extends ChangeNotifier {
|
|||||||
final request = ++_requestSeq;
|
final request = ++_requestSeq;
|
||||||
loadingMore = true;
|
loadingMore = true;
|
||||||
loadMoreError = null;
|
loadMoreError = null;
|
||||||
|
lastErrorCode = null;
|
||||||
_notify();
|
_notify();
|
||||||
try {
|
try {
|
||||||
final page = await _history.recent(
|
final page = await _history.recent(
|
||||||
@@ -108,6 +112,7 @@ class WatchRecordsController extends ChangeNotifier {
|
|||||||
loadMoreError = failure is ApiException
|
loadMoreError = failure is ApiException
|
||||||
? failure.message
|
? failure.message
|
||||||
: 'progressError';
|
: 'progressError';
|
||||||
|
if (failure is ApiException) lastErrorCode = failure.code;
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (!_disposed && request == _requestSeq) {
|
if (!_disposed && request == _requestSeq) {
|
||||||
@@ -148,17 +153,19 @@ class WatchRecordsController extends ChangeNotifier {
|
|||||||
total = total > 0 ? total - 1 : 0;
|
total = total > 0 ? total - 1 : 0;
|
||||||
hasMore = records.length < total;
|
hasMore = records.length < total;
|
||||||
actionError = null;
|
actionError = null;
|
||||||
|
lastErrorCode = null;
|
||||||
_notify();
|
_notify();
|
||||||
try {
|
try {
|
||||||
await _history.remove(dramaId);
|
await _history.remove(dramaId);
|
||||||
return true;
|
return true;
|
||||||
} catch (_) {
|
} catch (failure) {
|
||||||
final next = [...records];
|
final next = [...records];
|
||||||
next.insert(index > next.length ? next.length : index, removed);
|
next.insert(index > next.length ? next.length : index, removed);
|
||||||
records = next;
|
records = next;
|
||||||
total += 1;
|
total += 1;
|
||||||
hasMore = records.length < total;
|
hasMore = records.length < total;
|
||||||
actionError = 'recordDeleteFailed';
|
actionError = 'recordDeleteFailed';
|
||||||
|
if (failure is ApiException) lastErrorCode = failure.code;
|
||||||
return false;
|
return false;
|
||||||
} finally {
|
} finally {
|
||||||
_notify();
|
_notify();
|
||||||
@@ -179,16 +186,18 @@ class WatchRecordsController extends ChangeNotifier {
|
|||||||
loadingMore = false;
|
loadingMore = false;
|
||||||
clearing = true;
|
clearing = true;
|
||||||
actionError = null;
|
actionError = null;
|
||||||
|
lastErrorCode = null;
|
||||||
_notify();
|
_notify();
|
||||||
try {
|
try {
|
||||||
await _history.clear();
|
await _history.clear();
|
||||||
return true;
|
return true;
|
||||||
} catch (_) {
|
} catch (failure) {
|
||||||
records = previous;
|
records = previous;
|
||||||
total = previousTotal;
|
total = previousTotal;
|
||||||
_pageIndex = previousPageIndex;
|
_pageIndex = previousPageIndex;
|
||||||
hasMore = records.length < total;
|
hasMore = records.length < total;
|
||||||
actionError = 'recordClearFailed';
|
actionError = 'recordClearFailed';
|
||||||
|
if (failure is ApiException) lastErrorCode = failure.code;
|
||||||
return false;
|
return false;
|
||||||
} finally {
|
} finally {
|
||||||
clearing = false;
|
clearing = false;
|
||||||
@@ -305,6 +314,23 @@ class WatchRecordsController extends ChangeNotifier {
|
|||||||
if (!_disposed) notifyListeners();
|
if (!_disposed) notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 切换账号/设备身份时清除内存数据,不删除服务端记录。
|
||||||
|
void reset() {
|
||||||
|
_requestSeq += 1;
|
||||||
|
records = const [];
|
||||||
|
total = 0;
|
||||||
|
loading = false;
|
||||||
|
loadingMore = false;
|
||||||
|
hasMore = false;
|
||||||
|
clearing = false;
|
||||||
|
error = null;
|
||||||
|
loadMoreError = null;
|
||||||
|
actionError = null;
|
||||||
|
lastErrorCode = null;
|
||||||
|
_pageIndex = 0;
|
||||||
|
_notify();
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_disposed = true;
|
_disposed = true;
|
||||||
|
|||||||
@@ -0,0 +1,239 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
/// 账号资料页只读字段的展示格式化。
|
||||||
|
///
|
||||||
|
/// 后端存的是 ISO 国家码、BCP-47 语言标签和 IANA 时区(`ID` / `id-ID` / `Asia/Jakarta`),
|
||||||
|
/// 直接展示对用户没有意义,这里统一转成当前界面语言的名称。
|
||||||
|
/// 国家与城市名只维护中文与英文两套:界面语言为印尼语时回退英文名,
|
||||||
|
/// 语言名与账号状态则三种界面语言都有。
|
||||||
|
library;
|
||||||
|
|
||||||
|
const _countryNamesZh = {
|
||||||
|
'ID': '印度尼西亚',
|
||||||
|
'MY': '马来西亚',
|
||||||
|
'SG': '新加坡',
|
||||||
|
'TH': '泰国',
|
||||||
|
'VN': '越南',
|
||||||
|
'PH': '菲律宾',
|
||||||
|
'KH': '柬埔寨',
|
||||||
|
'MM': '缅甸',
|
||||||
|
'LA': '老挝',
|
||||||
|
'BN': '文莱',
|
||||||
|
'CN': '中国',
|
||||||
|
'TW': '中国台湾',
|
||||||
|
'HK': '中国香港',
|
||||||
|
'MO': '中国澳门',
|
||||||
|
'JP': '日本',
|
||||||
|
'KR': '韩国',
|
||||||
|
'IN': '印度',
|
||||||
|
'PK': '巴基斯坦',
|
||||||
|
'BD': '孟加拉国',
|
||||||
|
'LK': '斯里兰卡',
|
||||||
|
'NP': '尼泊尔',
|
||||||
|
'US': '美国',
|
||||||
|
'CA': '加拿大',
|
||||||
|
'MX': '墨西哥',
|
||||||
|
'BR': '巴西',
|
||||||
|
'AR': '阿根廷',
|
||||||
|
'CL': '智利',
|
||||||
|
'CO': '哥伦比亚',
|
||||||
|
'PE': '秘鲁',
|
||||||
|
'VE': '委内瑞拉',
|
||||||
|
'EC': '厄瓜多尔',
|
||||||
|
'GT': '危地马拉',
|
||||||
|
'DO': '多米尼加',
|
||||||
|
'GB': '英国',
|
||||||
|
'DE': '德国',
|
||||||
|
'FR': '法国',
|
||||||
|
'ES': '西班牙',
|
||||||
|
'IT': '意大利',
|
||||||
|
'NL': '荷兰',
|
||||||
|
'PL': '波兰',
|
||||||
|
'RU': '俄罗斯',
|
||||||
|
'UA': '乌克兰',
|
||||||
|
'TR': '土耳其',
|
||||||
|
'SA': '沙特阿拉伯',
|
||||||
|
'AE': '阿联酋',
|
||||||
|
'IL': '以色列',
|
||||||
|
'EG': '埃及',
|
||||||
|
'NG': '尼日利亚',
|
||||||
|
'ZA': '南非',
|
||||||
|
'KE': '肯尼亚',
|
||||||
|
'MA': '摩洛哥',
|
||||||
|
'AU': '澳大利亚',
|
||||||
|
'NZ': '新西兰',
|
||||||
|
};
|
||||||
|
|
||||||
|
const _countryNamesEn = {
|
||||||
|
'ID': 'Indonesia',
|
||||||
|
'MY': 'Malaysia',
|
||||||
|
'SG': 'Singapore',
|
||||||
|
'TH': 'Thailand',
|
||||||
|
'VN': 'Vietnam',
|
||||||
|
'PH': 'Philippines',
|
||||||
|
'KH': 'Cambodia',
|
||||||
|
'MM': 'Myanmar',
|
||||||
|
'LA': 'Laos',
|
||||||
|
'BN': 'Brunei',
|
||||||
|
'CN': 'China',
|
||||||
|
'TW': 'Taiwan',
|
||||||
|
'HK': 'Hong Kong',
|
||||||
|
'MO': 'Macau',
|
||||||
|
'JP': 'Japan',
|
||||||
|
'KR': 'South Korea',
|
||||||
|
'IN': 'India',
|
||||||
|
'PK': 'Pakistan',
|
||||||
|
'BD': 'Bangladesh',
|
||||||
|
'LK': 'Sri Lanka',
|
||||||
|
'NP': 'Nepal',
|
||||||
|
'US': 'United States',
|
||||||
|
'CA': 'Canada',
|
||||||
|
'MX': 'Mexico',
|
||||||
|
'BR': 'Brazil',
|
||||||
|
'AR': 'Argentina',
|
||||||
|
'CL': 'Chile',
|
||||||
|
'CO': 'Colombia',
|
||||||
|
'PE': 'Peru',
|
||||||
|
'VE': 'Venezuela',
|
||||||
|
'EC': 'Ecuador',
|
||||||
|
'GT': 'Guatemala',
|
||||||
|
'DO': 'Dominican Republic',
|
||||||
|
'GB': 'United Kingdom',
|
||||||
|
'DE': 'Germany',
|
||||||
|
'FR': 'France',
|
||||||
|
'ES': 'Spain',
|
||||||
|
'IT': 'Italy',
|
||||||
|
'NL': 'Netherlands',
|
||||||
|
'PL': 'Poland',
|
||||||
|
'RU': 'Russia',
|
||||||
|
'UA': 'Ukraine',
|
||||||
|
'TR': 'Turkey',
|
||||||
|
'SA': 'Saudi Arabia',
|
||||||
|
'AE': 'United Arab Emirates',
|
||||||
|
'IL': 'Israel',
|
||||||
|
'EG': 'Egypt',
|
||||||
|
'NG': 'Nigeria',
|
||||||
|
'ZA': 'South Africa',
|
||||||
|
'KE': 'Kenya',
|
||||||
|
'MA': 'Morocco',
|
||||||
|
'AU': 'Australia',
|
||||||
|
'NZ': 'New Zealand',
|
||||||
|
};
|
||||||
|
|
||||||
|
const _timezoneNamesZh = {
|
||||||
|
'Asia/Jakarta': '雅加达',
|
||||||
|
'Asia/Kuala_Lumpur': '吉隆坡',
|
||||||
|
'Asia/Singapore': '新加坡',
|
||||||
|
'Asia/Bangkok': '曼谷',
|
||||||
|
'Asia/Ho_Chi_Minh': '胡志明市',
|
||||||
|
'Asia/Manila': '马尼拉',
|
||||||
|
'Asia/Phnom_Penh': '金边',
|
||||||
|
'Asia/Yangon': '仰光',
|
||||||
|
'Asia/Vientiane': '万象',
|
||||||
|
'Asia/Brunei': '斯里巴加湾市',
|
||||||
|
'Asia/Shanghai': '上海',
|
||||||
|
'Asia/Taipei': '台北',
|
||||||
|
'Asia/Hong_Kong': '香港',
|
||||||
|
'Asia/Macau': '澳门',
|
||||||
|
'Asia/Tokyo': '东京',
|
||||||
|
'Asia/Seoul': '首尔',
|
||||||
|
'Asia/Kolkata': '加尔各答',
|
||||||
|
'Asia/Karachi': '卡拉奇',
|
||||||
|
'Asia/Dhaka': '达卡',
|
||||||
|
'Asia/Colombo': '科伦坡',
|
||||||
|
'Asia/Kathmandu': '加德满都',
|
||||||
|
'America/New_York': '纽约',
|
||||||
|
'America/Toronto': '多伦多',
|
||||||
|
'America/Mexico_City': '墨西哥城',
|
||||||
|
'America/Sao_Paulo': '圣保罗',
|
||||||
|
'America/Argentina/Buenos_Aires': '布宜诺斯艾利斯',
|
||||||
|
'America/Santiago': '圣地亚哥',
|
||||||
|
'America/Bogota': '波哥大',
|
||||||
|
'America/Lima': '利马',
|
||||||
|
'America/Caracas': '加拉加斯',
|
||||||
|
'America/Guayaquil': '瓜亚基尔',
|
||||||
|
'America/Guatemala': '危地马拉城',
|
||||||
|
'America/Santo_Domingo': '圣多明各',
|
||||||
|
'Europe/London': '伦敦',
|
||||||
|
'Europe/Berlin': '柏林',
|
||||||
|
'Europe/Paris': '巴黎',
|
||||||
|
'Europe/Madrid': '马德里',
|
||||||
|
'Europe/Rome': '罗马',
|
||||||
|
'Europe/Amsterdam': '阿姆斯特丹',
|
||||||
|
'Europe/Warsaw': '华沙',
|
||||||
|
'Europe/Moscow': '莫斯科',
|
||||||
|
'Europe/Kyiv': '基辅',
|
||||||
|
'Europe/Istanbul': '伊斯坦布尔',
|
||||||
|
'Asia/Riyadh': '利雅得',
|
||||||
|
'Asia/Dubai': '迪拜',
|
||||||
|
'Asia/Jerusalem': '耶路撒冷',
|
||||||
|
'Africa/Cairo': '开罗',
|
||||||
|
'Africa/Lagos': '拉各斯',
|
||||||
|
'Africa/Johannesburg': '约翰内斯堡',
|
||||||
|
'Africa/Nairobi': '内罗毕',
|
||||||
|
'Africa/Casablanca': '卡萨布兰卡',
|
||||||
|
'Australia/Sydney': '悉尼',
|
||||||
|
'Pacific/Auckland': '奥克兰',
|
||||||
|
};
|
||||||
|
|
||||||
|
const _languageNames = {
|
||||||
|
'id': {'zh': '印度尼西亚语', 'en': 'Indonesian', 'id': 'Bahasa Indonesia'},
|
||||||
|
'en': {'zh': '英语', 'en': 'English', 'id': 'Inggris'},
|
||||||
|
'zh': {'zh': '中文', 'en': 'Chinese', 'id': 'Mandarin'},
|
||||||
|
};
|
||||||
|
|
||||||
|
const _statusNames = {
|
||||||
|
'normal': {'zh': '正常', 'en': 'Active', 'id': 'Aktif'},
|
||||||
|
'limited': {'zh': '受限', 'en': 'Limited', 'id': 'Dibatasi'},
|
||||||
|
'banned': {'zh': '已封禁', 'en': 'Banned', 'id': 'Diblokir'},
|
||||||
|
'deactivated': {'zh': '已注销', 'en': 'Deactivated', 'id': 'Dinonaktifkan'},
|
||||||
|
};
|
||||||
|
|
||||||
|
String _pick(Map<String, String> names, String localeName) =>
|
||||||
|
names[localeName] ?? names['en']!;
|
||||||
|
|
||||||
|
/// 国家码 → 国家名;未收录的码原样返回。
|
||||||
|
String countryName(String code, String localeName) {
|
||||||
|
final key = code.trim().toUpperCase();
|
||||||
|
if (key.isEmpty) return '';
|
||||||
|
final names = localeName == 'zh' ? _countryNamesZh : _countryNamesEn;
|
||||||
|
return names[key] ?? key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// IANA 时区 → 城市名;中文界面查表,其余语言取时区里的城市段。
|
||||||
|
String timezoneName(String timezone, String localeName) {
|
||||||
|
final value = timezone.trim();
|
||||||
|
if (value.isEmpty) return '';
|
||||||
|
if (localeName == 'zh') {
|
||||||
|
final name = _timezoneNamesZh[value];
|
||||||
|
if (name != null) return name;
|
||||||
|
}
|
||||||
|
final city = value.split('/').last.replaceAll('_', ' ');
|
||||||
|
return city.isEmpty ? value : city;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// BCP-47 语言标签 → 语言名,按主语言归类(`zh-TW` 也算中文)。
|
||||||
|
String languageName(String language, String localeName) {
|
||||||
|
final value = language.trim();
|
||||||
|
if (value.isEmpty) return '';
|
||||||
|
final primary = value.split(RegExp('[-_]')).first.toLowerCase();
|
||||||
|
final names = _languageNames[primary];
|
||||||
|
return names == null ? value : _pick(names, localeName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 账号状态 → 展示文案;未知状态原样返回。
|
||||||
|
String accountStatusText(String status, String localeName) {
|
||||||
|
final value = status.trim().toLowerCase();
|
||||||
|
final names = _statusNames[value];
|
||||||
|
return names == null ? status : _pick(names, localeName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// VIP 等级:0 表示未开通,避免用户看到一个孤零零的 0。
|
||||||
|
String vipLevelText(int level, String localeName) {
|
||||||
|
if (level > 0) return 'VIP $level';
|
||||||
|
return switch (localeName) {
|
||||||
|
'zh' => '未开通',
|
||||||
|
'id' => 'Belum aktif',
|
||||||
|
_ => 'Not subscribed',
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -78,7 +78,12 @@ abstract final class AppColors {
|
|||||||
/// 中性深灰卡片与控件表面。
|
/// 中性深灰卡片与控件表面。
|
||||||
static const contentCard = Color(0xFF16161A);
|
static const contentCard = Color(0xFF16161A);
|
||||||
static const contentSurface = Color(0xFF1C1C1E);
|
static const contentSurface = Color(0xFF1C1C1E);
|
||||||
static const skeletonSurface = Color(0xFF141414);
|
|
||||||
|
/// 首页、分类与搜索网格骨架的极暗底色。
|
||||||
|
static const skeletonSurface = Color(0xFF0E0E0E);
|
||||||
|
|
||||||
|
/// 播放器、推荐与详情页大面积媒体占位的深灰底色。
|
||||||
|
static const skeletonMedia = Color(0xFF1C1C1E);
|
||||||
static const contentChip = Color(0xFF2C2C2E);
|
static const contentChip = Color(0xFF2C2C2E);
|
||||||
static const contentBorder = Color(0x1AFFFFFF);
|
static const contentBorder = Color(0x1AFFFFFF);
|
||||||
static const filterChipSelected = Color(0xFF21090E);
|
static const filterChipSelected = Color(0xFF21090E);
|
||||||
|
|||||||
@@ -11,7 +11,8 @@ const Duration _shimmerPeriod = Duration(milliseconds: 1400);
|
|||||||
const double _shimmerTravel = 2.4;
|
const double _shimmerTravel = 2.4;
|
||||||
const double _shimmerStart = -1.2;
|
const double _shimmerStart = -1.2;
|
||||||
const double _subtitleWidthFactor = 0.62;
|
const double _subtitleWidthFactor = 0.62;
|
||||||
const Color _shimmerHighlight = Color(0x38FFFFFF);
|
const double _shimmerPhaseStep = 0.13;
|
||||||
|
const Color _shimmerHighlight = Color(0x0DFFFFFF);
|
||||||
|
|
||||||
/// 首页短剧网格的占位。行数至少铺满可视高度,并带一道扫光。
|
/// 首页短剧网格的占位。行数至少铺满可视高度,并带一道扫光。
|
||||||
class DramaGridSkeleton extends StatefulWidget {
|
class DramaGridSkeleton extends StatefulWidget {
|
||||||
@@ -53,21 +54,19 @@ class _DramaGridSkeletonState extends State<DramaGridSkeleton>
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return LayoutBuilder(
|
return LayoutBuilder(
|
||||||
builder: (context, constraints) {
|
builder: (context, constraints) {
|
||||||
final grid = _grid(constraints.maxWidth, constraints.maxHeight);
|
|
||||||
return AnimatedBuilder(
|
return AnimatedBuilder(
|
||||||
animation: _shimmer,
|
animation: _shimmer,
|
||||||
builder: (context, child) => ShaderMask(
|
builder: (context, _) => _grid(
|
||||||
blendMode: BlendMode.srcATop,
|
constraints.maxWidth,
|
||||||
shaderCallback: (bounds) => _shader(bounds),
|
constraints.maxHeight,
|
||||||
child: child,
|
_shimmer.value,
|
||||||
),
|
),
|
||||||
child: grid,
|
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _grid(double width, double height) {
|
Widget _grid(double width, double height, double shimmerValue) {
|
||||||
final itemWidth = _itemWidth(width);
|
final itemWidth = _itemWidth(width);
|
||||||
final itemExtent = _itemExtent(itemWidth);
|
final itemExtent = _itemExtent(itemWidth);
|
||||||
return GridView.builder(
|
return GridView.builder(
|
||||||
@@ -85,7 +84,8 @@ class _DramaGridSkeletonState extends State<DramaGridSkeleton>
|
|||||||
mainAxisExtent: itemExtent,
|
mainAxisExtent: itemExtent,
|
||||||
),
|
),
|
||||||
itemCount: _fillCount(height, itemExtent),
|
itemCount: _fillCount(height, itemExtent),
|
||||||
itemBuilder: (context, index) => _SkeletonCard(index: index),
|
itemBuilder: (context, index) =>
|
||||||
|
_SkeletonCard(index: index, shimmerValue: shimmerValue),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,48 +105,61 @@ class _DramaGridSkeletonState extends State<DramaGridSkeleton>
|
|||||||
final rows = (height / rowHeight).ceil() + 1;
|
final rows = (height / rowHeight).ceil() + 1;
|
||||||
return math.max(widget.itemCount, rows * widget.columns);
|
return math.max(widget.itemCount, rows * widget.columns);
|
||||||
}
|
}
|
||||||
|
|
||||||
Shader _shader(Rect bounds) {
|
|
||||||
final shift = _shimmerStart + _shimmerTravel * _shimmer.value;
|
|
||||||
return LinearGradient(
|
|
||||||
begin: Alignment(shift, -0.3),
|
|
||||||
end: Alignment(shift + 1, 0.3),
|
|
||||||
colors: const [
|
|
||||||
AppColors.skeletonSurface,
|
|
||||||
_shimmerHighlight,
|
|
||||||
AppColors.skeletonSurface,
|
|
||||||
],
|
|
||||||
).createShader(bounds);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class _SkeletonCard extends StatelessWidget {
|
class _SkeletonCard extends StatelessWidget {
|
||||||
const _SkeletonCard({required this.index});
|
const _SkeletonCard({required this.index, required this.shimmerValue});
|
||||||
|
|
||||||
final int index;
|
final int index;
|
||||||
|
final double shimmerValue;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Column(
|
final phase = (shimmerValue + index * _shimmerPhaseStep) % 1.0;
|
||||||
|
return Stack(
|
||||||
key: Key('drama-grid-skeleton-$index'),
|
key: Key('drama-grid-skeleton-$index'),
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
|
||||||
children: [
|
children: [
|
||||||
AspectRatio(
|
Column(
|
||||||
aspectRatio: AppDimens.cardCoverAspectRatio,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
child: const _SkeletonBlock(),
|
children: [
|
||||||
|
AspectRatio(
|
||||||
|
aspectRatio: AppDimens.cardCoverAspectRatio,
|
||||||
|
child: const _SkeletonBlock(),
|
||||||
|
),
|
||||||
|
const SizedBox(height: AppDimens.cardCoverTitleGap),
|
||||||
|
const _SkeletonBar(),
|
||||||
|
const SizedBox(height: AppDimens.skeletonTitleBarGap),
|
||||||
|
const FractionallySizedBox(
|
||||||
|
widthFactor: _subtitleWidthFactor,
|
||||||
|
child: _SkeletonBar(),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: AppDimens.cardCoverTitleGap),
|
Positioned.fill(
|
||||||
const _SkeletonBar(),
|
child: IgnorePointer(
|
||||||
const SizedBox(height: AppDimens.skeletonTitleBarGap),
|
child: ClipRRect(
|
||||||
const FractionallySizedBox(
|
borderRadius: BorderRadius.circular(AppDimens.homeCardRadius),
|
||||||
widthFactor: _subtitleWidthFactor,
|
child: DecoratedBox(
|
||||||
child: _SkeletonBar(),
|
decoration: BoxDecoration(gradient: _cardHighlight(phase)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
LinearGradient _cardHighlight(double shimmerValue) {
|
||||||
|
final shift = _shimmerStart + _shimmerTravel * shimmerValue;
|
||||||
|
return LinearGradient(
|
||||||
|
begin: Alignment(shift, -0.3),
|
||||||
|
end: Alignment(shift + 1, 0.3),
|
||||||
|
colors: const [Colors.transparent, _shimmerHighlight, Colors.transparent],
|
||||||
|
stops: const [0.42, 0.5, 0.58],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
class _SkeletonBlock extends StatelessWidget {
|
class _SkeletonBlock extends StatelessWidget {
|
||||||
const _SkeletonBlock();
|
const _SkeletonBlock();
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import 'package:provider/provider.dart';
|
|||||||
import '../../core/data/models/account_profile.dart';
|
import '../../core/data/models/account_profile.dart';
|
||||||
import '../../core/data/repositories/account_repository.dart';
|
import '../../core/data/repositories/account_repository.dart';
|
||||||
import '../../core/data/services/auth_controller.dart';
|
import '../../core/data/services/auth_controller.dart';
|
||||||
|
import '../../core/formatting/account_display.dart';
|
||||||
import '../../core/formatting/error_text.dart';
|
import '../../core/formatting/error_text.dart';
|
||||||
import '../../core/formatting/localized_date_time.dart';
|
import '../../core/formatting/localized_date_time.dart';
|
||||||
import '../../core/theme/app_colors.dart';
|
import '../../core/theme/app_colors.dart';
|
||||||
@@ -225,6 +226,7 @@ class _AccountProfilePageState extends State<AccountProfilePage> {
|
|||||||
);
|
);
|
||||||
|
|
||||||
Widget _readOnlyCard(AccountProfile profile, AppLocalizations l10n) {
|
Widget _readOnlyCard(AccountProfile profile, AppLocalizations l10n) {
|
||||||
|
final localeName = Localizations.localeOf(context).languageCode;
|
||||||
return _AccountCard(
|
return _AccountCard(
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
@@ -238,13 +240,34 @@ class _AccountProfilePageState extends State<AccountProfilePage> {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 10),
|
const SizedBox(height: 10),
|
||||||
_info(l10n.accountMaskedAccount, profile.maskedTarget),
|
_info(l10n.accountMaskedAccount, profile.maskedTarget),
|
||||||
_info(l10n.accountCountry, profile.countryCode),
|
_info(
|
||||||
|
l10n.accountCountry,
|
||||||
|
countryName(profile.countryCode, localeName),
|
||||||
|
),
|
||||||
_info(l10n.accountCurrency, profile.currency),
|
_info(l10n.accountCurrency, profile.currency),
|
||||||
_info(l10n.accountStatus, profile.status),
|
_info(
|
||||||
_info(l10n.accountLanguage, profile.language),
|
l10n.accountStatus,
|
||||||
_info(l10n.accountTimezone, profile.timezone),
|
accountStatusText(profile.status, localeName),
|
||||||
_info(l10n.accountRegion, profile.regionCode),
|
),
|
||||||
_info(l10n.accountVipLevel, '${profile.vipLevel}'),
|
_info(
|
||||||
|
l10n.accountLanguage,
|
||||||
|
languageName(profile.language, localeName),
|
||||||
|
),
|
||||||
|
_info(
|
||||||
|
l10n.accountTimezone,
|
||||||
|
timezoneName(profile.timezone, localeName),
|
||||||
|
),
|
||||||
|
// region 与 country 后端写的是同一个值,重复时不再单列一行
|
||||||
|
if (profile.regionCode.isNotEmpty &&
|
||||||
|
profile.regionCode != profile.countryCode)
|
||||||
|
_info(
|
||||||
|
l10n.accountRegion,
|
||||||
|
countryName(profile.regionCode, localeName),
|
||||||
|
),
|
||||||
|
_info(
|
||||||
|
l10n.accountVipLevel,
|
||||||
|
vipLevelText(profile.vipLevel, localeName),
|
||||||
|
),
|
||||||
if (profile.createdAt != null)
|
if (profile.createdAt != null)
|
||||||
_info(
|
_info(
|
||||||
l10n.accountCreatedAt,
|
l10n.accountCreatedAt,
|
||||||
@@ -275,7 +298,7 @@ class _AccountProfilePageState extends State<AccountProfilePage> {
|
|||||||
),
|
),
|
||||||
Flexible(
|
Flexible(
|
||||||
child: Text(
|
child: Text(
|
||||||
value.isEmpty ? '-' : value,
|
value.isEmpty ? '—' : value,
|
||||||
textAlign: TextAlign.right,
|
textAlign: TextAlign.right,
|
||||||
style: const TextStyle(fontSize: AppDimens.body),
|
style: const TextStyle(fontSize: AppDimens.body),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -38,7 +38,6 @@ class DramaDetailLogic extends ChangeNotifier {
|
|||||||
int? continueIndex;
|
int? continueIndex;
|
||||||
WatchProgress? progress;
|
WatchProgress? progress;
|
||||||
String? progressError;
|
String? progressError;
|
||||||
int _favoriteCountDelta = 0;
|
|
||||||
bool _disposed = false;
|
bool _disposed = false;
|
||||||
|
|
||||||
void notify() {
|
void notify() {
|
||||||
@@ -47,6 +46,7 @@ class DramaDetailLogic extends ChangeNotifier {
|
|||||||
|
|
||||||
/// 列表卡片只带一集可播预览,进详情时补一次完整剧集列表。
|
/// 列表卡片只带一集可播预览,进详情时补一次完整剧集列表。
|
||||||
Future<void> load(Future<Drama> Function() fetch) async {
|
Future<void> load(Future<Drama> Function() fetch) async {
|
||||||
|
favorites.applyServerCount(drama.id, drama.favoriteCount, notify: false);
|
||||||
if (drama.detailLoaded) {
|
if (drama.detailLoaded) {
|
||||||
await loadContinue();
|
await loadContinue();
|
||||||
return;
|
return;
|
||||||
@@ -57,6 +57,7 @@ class DramaDetailLogic extends ChangeNotifier {
|
|||||||
notify();
|
notify();
|
||||||
try {
|
try {
|
||||||
drama = await fetch();
|
drama = await fetch();
|
||||||
|
favorites.applyServerCount(drama.id, drama.favoriteCount);
|
||||||
await loadContinue();
|
await loadContinue();
|
||||||
} on ApiException catch (exception) {
|
} on ApiException catch (exception) {
|
||||||
failed = true;
|
failed = true;
|
||||||
@@ -139,25 +140,12 @@ class DramaDetailLogic extends ChangeNotifier {
|
|||||||
await loadContinue();
|
await loadContinue();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 详情页展示用的收藏数;没有服务端计数时继续保持缺省展示。
|
/// 详情页展示用的收藏数,统一从全局 FavoriteController 读取。
|
||||||
int? get adjustedFavoriteCount {
|
int? get adjustedFavoriteCount => favorites.favoriteCountFor(drama);
|
||||||
final base = drama.favoriteCount;
|
|
||||||
if (base == null) return null;
|
|
||||||
final adjusted = base + _favoriteCountDelta;
|
|
||||||
return adjusted < 0 ? 0 : adjusted;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 收藏切换:乐观状态由控制器负责回滚,这里只在成功后同步计数。
|
/// 收藏切换:状态与计数均由全局控制器维护。
|
||||||
Future<bool> toggleFavorite() async {
|
Future<bool> toggleFavorite() async {
|
||||||
final wasSaved = favorites.isSaved(drama.id);
|
return favorites.toggle(drama.id, card: drama);
|
||||||
final ok = await favorites.toggle(drama.id, card: drama);
|
|
||||||
if (!ok) return false;
|
|
||||||
final nowSaved = favorites.isSaved(drama.id);
|
|
||||||
if (nowSaved != wasSaved) {
|
|
||||||
_favoriteCountDelta += nowSaved ? 1 : -1;
|
|
||||||
notify();
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ class _DramaEpisodesLoadingState extends State<DramaEpisodesLoading>
|
|||||||
opacity: _opacity,
|
opacity: _opacity,
|
||||||
child: Container(
|
child: Container(
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: AppColors.raised,
|
color: AppColors.skeletonMedia,
|
||||||
borderRadius: BorderRadius.circular(_radius),
|
borderRadius: BorderRadius.circular(_radius),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
import '../../core/data/models/drama.dart';
|
import '../../core/data/models/drama.dart';
|
||||||
import '../../core/data/services/auth_controller.dart';
|
|
||||||
import '../../core/data/services/favorite_controller.dart';
|
import '../../core/data/services/favorite_controller.dart';
|
||||||
import '../../core/formatting/count_format.dart';
|
import '../../core/formatting/count_format.dart';
|
||||||
import '../../core/formatting/error_text.dart';
|
import '../../core/formatting/error_text.dart';
|
||||||
@@ -77,11 +76,6 @@ class _FavoritesContentState extends State<FavoritesContent> {
|
|||||||
@override
|
@override
|
||||||
void didChangeDependencies() {
|
void didChangeDependencies() {
|
||||||
super.didChangeDependencies();
|
super.didChangeDependencies();
|
||||||
final signedIn = context.watch<AuthController>().isSignedIn;
|
|
||||||
if (!signedIn) {
|
|
||||||
_requested = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (_requested) return;
|
if (_requested) return;
|
||||||
_requested = true;
|
_requested = true;
|
||||||
final favorites = context.read<FavoriteController>();
|
final favorites = context.read<FavoriteController>();
|
||||||
@@ -93,7 +87,6 @@ class _FavoritesContentState extends State<FavoritesContent> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
final signedIn = context.watch<AuthController>().isSignedIn;
|
|
||||||
return SafeArea(
|
return SafeArea(
|
||||||
bottom: false,
|
bottom: false,
|
||||||
child: Column(
|
child: Column(
|
||||||
@@ -104,9 +97,9 @@ class _FavoritesContentState extends State<FavoritesContent> {
|
|||||||
showBack: widget.showBack,
|
showBack: widget.showBack,
|
||||||
),
|
),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: signedIn
|
child: _FavoritesBody(
|
||||||
? _FavoritesBody(favorites: context.watch<FavoriteController>())
|
favorites: context.watch<FavoriteController>(),
|
||||||
: const AuthGatePanel(),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -122,6 +115,9 @@ class _FavoritesBody extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
|
if (favorites.lastErrorCode == 200007) {
|
||||||
|
return const AuthGatePanel();
|
||||||
|
}
|
||||||
if (favorites.loading && favorites.cards.isEmpty) {
|
if (favorites.loading && favorites.cards.isEmpty) {
|
||||||
return const Center(
|
return const Center(
|
||||||
child: CircularProgressIndicator(key: Key('favorites-loading')),
|
child: CircularProgressIndicator(key: Key('favorites-loading')),
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ const double _barButtonHeight = 30;
|
|||||||
const double _removeDialogButtonHeight = 32;
|
const double _removeDialogButtonHeight = 32;
|
||||||
const double _removeDialogRadius = 6;
|
const double _removeDialogRadius = 6;
|
||||||
const double _removeDialogBottomInset = 8;
|
const double _removeDialogBottomInset = 8;
|
||||||
|
const double _cancelFollowingDialogPadding = 20;
|
||||||
|
|
||||||
/// 播放历史移除确认。只把移除按钮压矮。
|
/// 播放历史移除确认。只把移除按钮压矮。
|
||||||
Future<bool> confirmHistoryRemove(BuildContext context) async {
|
Future<bool> confirmHistoryRemove(BuildContext context) async {
|
||||||
@@ -71,13 +72,32 @@ Future<bool> confirmCancelFollowing(BuildContext context) async {
|
|||||||
return await showDialog<bool>(
|
return await showDialog<bool>(
|
||||||
context: context,
|
context: context,
|
||||||
builder: (dialogContext) => AlertDialog(
|
builder: (dialogContext) => AlertDialog(
|
||||||
|
contentPadding: const EdgeInsets.all(_cancelFollowingDialogPadding),
|
||||||
|
actionsPadding: const EdgeInsets.fromLTRB(
|
||||||
|
_cancelFollowingDialogPadding,
|
||||||
|
0,
|
||||||
|
_cancelFollowingDialogPadding,
|
||||||
|
_cancelFollowingDialogPadding,
|
||||||
|
),
|
||||||
content: Text(l10n.confirmCancelFollowing),
|
content: Text(l10n.confirmCancelFollowing),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(
|
TextButton(
|
||||||
|
style: TextButton.styleFrom(
|
||||||
|
visualDensity: VisualDensity.standard,
|
||||||
|
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||||
|
minimumSize: const Size(0, _removeDialogButtonHeight),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||||
|
),
|
||||||
onPressed: () => Navigator.pop(dialogContext, false),
|
onPressed: () => Navigator.pop(dialogContext, false),
|
||||||
child: Text(l10n.cancel),
|
child: Text(l10n.cancel),
|
||||||
),
|
),
|
||||||
FilledButton(
|
FilledButton(
|
||||||
|
style: FilledButton.styleFrom(
|
||||||
|
visualDensity: VisualDensity.standard,
|
||||||
|
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||||
|
minimumSize: const Size(0, _removeDialogButtonHeight),
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||||
|
),
|
||||||
onPressed: () => Navigator.pop(dialogContext, true),
|
onPressed: () => Navigator.pop(dialogContext, true),
|
||||||
child: Text(l10n.cancelFollowing),
|
child: Text(l10n.cancelFollowing),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ import '../../core/data/services/watch_records_controller.dart';
|
|||||||
import '../../core/formatting/error_text.dart';
|
import '../../core/formatting/error_text.dart';
|
||||||
import '../../core/theme/app_colors.dart';
|
import '../../core/theme/app_colors.dart';
|
||||||
import '../../core/theme/app_dimens.dart';
|
import '../../core/theme/app_dimens.dart';
|
||||||
import '../../core/widgets/auth_gate.dart';
|
|
||||||
import '../../core/widgets/empty_state.dart';
|
import '../../core/widgets/empty_state.dart';
|
||||||
import '../../l10n/app_localizations.dart';
|
import '../../l10n/app_localizations.dart';
|
||||||
import '../player/open_player.dart';
|
import '../player/open_player.dart';
|
||||||
@@ -67,7 +66,7 @@ class _FollowingPageState extends State<FollowingPage> {
|
|||||||
history: context.read<WatchHistoryRepository>(),
|
history: context.read<WatchHistoryRepository>(),
|
||||||
catalog: context.read<CatalogRepository>(),
|
catalog: context.read<CatalogRepository>(),
|
||||||
);
|
);
|
||||||
if (_wasSignedIn) unawaited(_history.load());
|
unawaited(_history.load());
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
if (mounted) unawaited(widget.favoriteController.load());
|
if (mounted) unawaited(widget.favoriteController.load());
|
||||||
});
|
});
|
||||||
@@ -75,8 +74,16 @@ class _FollowingPageState extends State<FollowingPage> {
|
|||||||
|
|
||||||
void _onAuthChanged() {
|
void _onAuthChanged() {
|
||||||
final signedIn = _auth.isSignedIn;
|
final signedIn = _auth.isSignedIn;
|
||||||
if (signedIn && !_wasSignedIn) unawaited(_history.load());
|
if (signedIn == _wasSignedIn) return;
|
||||||
_wasSignedIn = signedIn;
|
_wasSignedIn = signedIn;
|
||||||
|
_leaveEditing();
|
||||||
|
_history.reset();
|
||||||
|
widget.favoriteController.clear();
|
||||||
|
unawaited(_reloadForIdentity());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _reloadForIdentity() async {
|
||||||
|
await Future.wait([_history.load(), widget.favoriteController.load()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -104,7 +111,6 @@ class _FollowingPageState extends State<FollowingPage> {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
final signedIn = context.watch<AuthController>().isSignedIn;
|
|
||||||
return ColoredBox(
|
return ColoredBox(
|
||||||
key: const Key('following-page'),
|
key: const Key('following-page'),
|
||||||
color: AppColors.appBackground,
|
color: AppColors.appBackground,
|
||||||
@@ -114,47 +120,44 @@ class _FollowingPageState extends State<FollowingPage> {
|
|||||||
children: [
|
children: [
|
||||||
_header(l10n),
|
_header(l10n),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: !signedIn
|
child: PageView(
|
||||||
? const AuthGatePanel()
|
key: const Key('following-tab-pages'),
|
||||||
: PageView(
|
controller: _pageController,
|
||||||
key: const Key('following-tab-pages'),
|
onPageChanged: _onPageChanged,
|
||||||
controller: _pageController,
|
children: [
|
||||||
onPageChanged: _onPageChanged,
|
FollowingKeepAliveTab(
|
||||||
children: [
|
child: FollowingFavoritesGrid(
|
||||||
FollowingKeepAliveTab(
|
controller: widget.favoriteController,
|
||||||
child: FollowingFavoritesGrid(
|
selection: FollowingFavoriteSelection(
|
||||||
controller: widget.favoriteController,
|
editing: _editing,
|
||||||
selection: FollowingFavoriteSelection(
|
selected: _selected,
|
||||||
editing: _editing,
|
onToggle: _toggleDrama,
|
||||||
selected: _selected,
|
),
|
||||||
onToggle: _toggleDrama,
|
scrollController: _favoriteScroll,
|
||||||
),
|
onGoHome: widget.onGoHome,
|
||||||
scrollController: _favoriteScroll,
|
|
||||||
onGoHome: widget.onGoHome,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
FollowingKeepAliveTab(
|
|
||||||
child: _HistoryList(
|
|
||||||
controller: _history,
|
|
||||||
editing: _editing,
|
|
||||||
scrollController: _historyScroll,
|
|
||||||
onListEmptied: _exitEditingIfEmpty,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (signedIn)
|
FollowingKeepAliveTab(
|
||||||
FollowingEditSlot(
|
child: _HistoryList(
|
||||||
tab: _tab,
|
controller: _history,
|
||||||
editing: _editing,
|
editing: _editing,
|
||||||
favorites: widget.favoriteController,
|
scrollController: _historyScroll,
|
||||||
selected: _selected,
|
onListEmptied: _exitEditingIfEmpty,
|
||||||
actions: FollowingEditActions(
|
),
|
||||||
onToggleAll: _toggleAll,
|
),
|
||||||
onRemove: () => unawaited(_cancelSelected()),
|
],
|
||||||
),
|
|
||||||
),
|
),
|
||||||
|
),
|
||||||
|
FollowingEditSlot(
|
||||||
|
tab: _tab,
|
||||||
|
editing: _editing,
|
||||||
|
favorites: widget.favoriteController,
|
||||||
|
selected: _selected,
|
||||||
|
actions: FollowingEditActions(
|
||||||
|
onToggleAll: _toggleAll,
|
||||||
|
onRemove: () => unawaited(_cancelSelected()),
|
||||||
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -297,7 +300,7 @@ class _FollowingPageState extends State<FollowingPage> {
|
|||||||
final tab = FollowingTab.values[index];
|
final tab = FollowingTab.values[index];
|
||||||
_leaveEditing();
|
_leaveEditing();
|
||||||
_tab.value = tab;
|
_tab.value = tab;
|
||||||
if (tab == FollowingTab.history && _auth.isSignedIn) {
|
if (tab == FollowingTab.history) {
|
||||||
unawaited(_history.load());
|
unawaited(_history.load());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ class MineLogic extends ChangeNotifier {
|
|||||||
bool recentLoading = false;
|
bool recentLoading = false;
|
||||||
String? recentError;
|
String? recentError;
|
||||||
bool _disposed = false;
|
bool _disposed = false;
|
||||||
|
int _requestSeq = 0;
|
||||||
|
|
||||||
void notify() {
|
void notify() {
|
||||||
if (!_disposed) notifyListeners();
|
if (!_disposed) notifyListeners();
|
||||||
@@ -25,21 +26,37 @@ class MineLogic extends ChangeNotifier {
|
|||||||
|
|
||||||
/// 最近观看:取分页首屏,剧名封面仍由目录卡片按 id 映射。
|
/// 最近观看:取分页首屏,剧名封面仍由目录卡片按 id 映射。
|
||||||
Future<void> refreshRecent() async {
|
Future<void> refreshRecent() async {
|
||||||
|
final request = ++_requestSeq;
|
||||||
recentLoading = true;
|
recentLoading = true;
|
||||||
recentError = null;
|
recentError = null;
|
||||||
notify();
|
notify();
|
||||||
try {
|
try {
|
||||||
final page = await history.recent(pageIndex: 1, pageSize: 10);
|
final page = await history.recent(pageIndex: 1, pageSize: 10);
|
||||||
|
if (_disposed || request != _requestSeq) return;
|
||||||
recent = page.list;
|
recent = page.list;
|
||||||
watchRecordTotal = page.total;
|
watchRecordTotal = page.total;
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
recentError = 'progressError';
|
if (!_disposed && request == _requestSeq) {
|
||||||
|
recentError = 'progressError';
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
recentLoading = false;
|
if (!_disposed && request == _requestSeq) {
|
||||||
notify();
|
recentLoading = false;
|
||||||
|
notify();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 切换账号/设备身份时先清空,避免旧身份数据回写或短暂混显。
|
||||||
|
void resetRecent() {
|
||||||
|
_requestSeq += 1;
|
||||||
|
recent = const [];
|
||||||
|
watchRecordTotal = null;
|
||||||
|
recentLoading = false;
|
||||||
|
recentError = null;
|
||||||
|
notify();
|
||||||
|
}
|
||||||
|
|
||||||
/// 页面重新可见时刷新最近观看,避免停留在旧进度。
|
/// 页面重新可见时刷新最近观看,避免停留在旧进度。
|
||||||
void syncPage({required bool active, required bool wasActive}) {
|
void syncPage({required bool active, required bool wasActive}) {
|
||||||
if (active && !wasActive) refreshRecent();
|
if (active && !wasActive) refreshRecent();
|
||||||
|
|||||||
+100
-11
@@ -6,8 +6,11 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
|
import '../../core/data/models/drama.dart';
|
||||||
|
import '../../core/data/models/watch_progress.dart';
|
||||||
import '../../core/data/repositories/watch_history_repository.dart';
|
import '../../core/data/repositories/watch_history_repository.dart';
|
||||||
import '../../core/data/services/auth_controller.dart';
|
import '../../core/data/services/auth_controller.dart';
|
||||||
|
import '../../core/data/services/catalog_controller.dart';
|
||||||
import '../../core/data/services/favorite_controller.dart';
|
import '../../core/data/services/favorite_controller.dart';
|
||||||
import '../../core/data/services/locale_controller.dart';
|
import '../../core/data/services/locale_controller.dart';
|
||||||
import '../../core/data/services/wallet_controller.dart';
|
import '../../core/data/services/wallet_controller.dart';
|
||||||
@@ -22,6 +25,7 @@ import '../downloads/downloads_page.dart';
|
|||||||
import '../account/account_profile_page.dart';
|
import '../account/account_profile_page.dart';
|
||||||
import '../filter/filter_page.dart';
|
import '../filter/filter_page.dart';
|
||||||
import '../notices/notices_page.dart';
|
import '../notices/notices_page.dart';
|
||||||
|
import '../player/open_player.dart';
|
||||||
import '../settings/settings_page.dart';
|
import '../settings/settings_page.dart';
|
||||||
import '../store/vip_page.dart';
|
import '../store/vip_page.dart';
|
||||||
import '../wallet/wallet_page.dart';
|
import '../wallet/wallet_page.dart';
|
||||||
@@ -53,25 +57,70 @@ class MyPage extends StatefulWidget {
|
|||||||
|
|
||||||
class _MyPageState extends State<MyPage> {
|
class _MyPageState extends State<MyPage> {
|
||||||
late final MineLogic logic;
|
late final MineLogic logic;
|
||||||
|
late final AuthController _auth;
|
||||||
|
late final FavoriteController _favorites;
|
||||||
|
late bool _wasSignedIn;
|
||||||
|
bool _activationRefreshScheduled = false;
|
||||||
|
|
||||||
bool get embedded => widget.callbacks.embedded;
|
bool get embedded => widget.callbacks.embedded;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
|
_auth = context.read<AuthController>();
|
||||||
|
_favorites = context.read<FavoriteController>();
|
||||||
|
_wasSignedIn = _auth.isSignedIn;
|
||||||
|
_auth.addListener(_onAuthChanged);
|
||||||
logic = MineBinding().create(
|
logic = MineBinding().create(
|
||||||
history: context.read<WatchHistoryRepository>(),
|
history: context.read<WatchHistoryRepository>(),
|
||||||
);
|
);
|
||||||
|
if (widget.active) _scheduleFavoriteLoad();
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void didUpdateWidget(covariant MyPage oldWidget) {
|
void didUpdateWidget(covariant MyPage oldWidget) {
|
||||||
super.didUpdateWidget(oldWidget);
|
super.didUpdateWidget(oldWidget);
|
||||||
logic.syncPage(active: widget.active, wasActive: oldWidget.active);
|
if (widget.active && !oldWidget.active) {
|
||||||
|
_scheduleActivationRefresh();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _scheduleFavoriteLoad() {
|
||||||
|
if (_activationRefreshScheduled) return;
|
||||||
|
_activationRefreshScheduled = true;
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
_activationRefreshScheduled = false;
|
||||||
|
if (mounted) unawaited(_favorites.load());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _scheduleActivationRefresh() {
|
||||||
|
if (_activationRefreshScheduled) return;
|
||||||
|
_activationRefreshScheduled = true;
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
_activationRefreshScheduled = false;
|
||||||
|
if (!mounted || !widget.active) return;
|
||||||
|
logic.syncPage(active: true, wasActive: false);
|
||||||
|
unawaited(_favorites.load());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _onAuthChanged() {
|
||||||
|
final signedIn = _auth.isSignedIn;
|
||||||
|
if (signedIn == _wasSignedIn) return;
|
||||||
|
_wasSignedIn = signedIn;
|
||||||
|
logic.resetRecent();
|
||||||
|
_favorites.clear();
|
||||||
|
unawaited(_reloadForIdentity());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _reloadForIdentity() async {
|
||||||
|
await Future.wait([logic.refreshRecent(), _favorites.load()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
|
_auth.removeListener(_onAuthChanged);
|
||||||
logic.dispose();
|
logic.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
@@ -141,12 +190,14 @@ class _MyPageState extends State<MyPage> {
|
|||||||
final wallet = context.watch<WalletController>();
|
final wallet = context.watch<WalletController>();
|
||||||
final continueWatching = logic.recent.take(10).toList(growable: false);
|
final continueWatching = logic.recent.take(10).toList(growable: false);
|
||||||
final followingCount =
|
final followingCount =
|
||||||
auth.isSignedIn &&
|
favorites.error == null && !(favorites.loading && favorites.total == 0)
|
||||||
favorites.error == null &&
|
|
||||||
!(favorites.loading && favorites.total == 0)
|
|
||||||
? favorites.total
|
? favorites.total
|
||||||
: null;
|
: null;
|
||||||
final watchRecordCount = auth.isSignedIn ? logic.watchRecordTotal : null;
|
final watchRecordCount =
|
||||||
|
logic.recentError == null &&
|
||||||
|
!(logic.recentLoading && logic.watchRecordTotal == null)
|
||||||
|
? logic.watchRecordTotal
|
||||||
|
: null;
|
||||||
final coinBalance = auth.isSignedIn && wallet.snapshot != null
|
final coinBalance = auth.isSignedIn && wallet.snapshot != null
|
||||||
? wallet.balance
|
? wallet.balance
|
||||||
: null;
|
: null;
|
||||||
@@ -175,6 +226,7 @@ class _MyPageState extends State<MyPage> {
|
|||||||
const SizedBox(height: AppDimens.mineSectionGap),
|
const SizedBox(height: AppDimens.mineSectionGap),
|
||||||
MineContinueWatching(
|
MineContinueWatching(
|
||||||
records: continueWatching,
|
records: continueWatching,
|
||||||
|
onOpenRecord: _openContinueRecord,
|
||||||
onOpenAll: _openHistoryTab,
|
onOpenAll: _openHistoryTab,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -216,7 +268,7 @@ class _MyPageState extends State<MyPage> {
|
|||||||
void _openDestination(MineDestination destination) {
|
void _openDestination(MineDestination destination) {
|
||||||
switch (destination) {
|
switch (destination) {
|
||||||
case MineDestination.history:
|
case MineDestination.history:
|
||||||
_push(const WatchRecordsPage());
|
unawaited(_openHistoryPage());
|
||||||
case MineDestination.downloads:
|
case MineDestination.downloads:
|
||||||
_push(const DownloadsPage());
|
_push(const DownloadsPage());
|
||||||
case MineDestination.wallet:
|
case MineDestination.wallet:
|
||||||
@@ -244,15 +296,52 @@ class _MyPageState extends State<MyPage> {
|
|||||||
callback();
|
callback();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
_push(const WatchRecordsPage());
|
unawaited(_openHistoryPage());
|
||||||
}
|
}
|
||||||
|
|
||||||
void _push(Widget page) {
|
/// 继续观看卡片:补齐剧集后直接进全屏播放页,播放器自己会定位到记录的秒数。
|
||||||
Navigator.of(context).push<void>(MaterialPageRoute(builder: (_) => page));
|
Future<void> _openContinueRecord(WatchProgress record) async {
|
||||||
|
final catalog = context.read<CatalogController>();
|
||||||
|
// 续看记录只有剧的概要信息,先拼一个占位对象让目录去取完整详情
|
||||||
|
final summary = Drama(
|
||||||
|
id: record.dramaId,
|
||||||
|
title: record.dramaTitle ?? '',
|
||||||
|
synopsis: '',
|
||||||
|
posterUrl: record.dramaCover ?? '',
|
||||||
|
);
|
||||||
|
Drama drama;
|
||||||
|
try {
|
||||||
|
drama = await catalog.requireDetail(summary);
|
||||||
|
} catch (_) {
|
||||||
|
if (!mounted) return;
|
||||||
|
final l10n = AppLocalizations.of(context)!;
|
||||||
|
ScaffoldMessenger.of(
|
||||||
|
context,
|
||||||
|
).showSnackBar(SnackBar(content: Text(l10n.detailLoadFailed)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!mounted) return;
|
||||||
|
await playDramaFromCatalog(
|
||||||
|
context,
|
||||||
|
drama,
|
||||||
|
episodeId: record.episodeId.isEmpty ? null : record.episodeId,
|
||||||
|
);
|
||||||
|
if (mounted) unawaited(logic.refreshRecent());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _openHistoryPage() async {
|
||||||
|
await _push(const WatchRecordsPage());
|
||||||
|
if (mounted) unawaited(logic.refreshRecent());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _push(Widget page) {
|
||||||
|
return Navigator.of(
|
||||||
|
context,
|
||||||
|
).push<void>(MaterialPageRoute(builder: (_) => page));
|
||||||
}
|
}
|
||||||
|
|
||||||
void _pushPlaceholder() {
|
void _pushPlaceholder() {
|
||||||
_push(const _MinePlaceholderPage());
|
unawaited(_push(const _MinePlaceholderPage()));
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _openProtected(Widget page) async {
|
Future<void> _openProtected(Widget page) async {
|
||||||
@@ -260,7 +349,7 @@ class _MyPageState extends State<MyPage> {
|
|||||||
await ensureSignedIn(context);
|
await ensureSignedIn(context);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (mounted) _push(page);
|
if (mounted) await _push(page);
|
||||||
}
|
}
|
||||||
|
|
||||||
void _openVip() {
|
void _openVip() {
|
||||||
|
|||||||
@@ -12,10 +12,14 @@ class MineContinueWatching extends StatelessWidget {
|
|||||||
const MineContinueWatching({
|
const MineContinueWatching({
|
||||||
super.key,
|
super.key,
|
||||||
required this.records,
|
required this.records,
|
||||||
|
required this.onOpenRecord,
|
||||||
required this.onOpenAll,
|
required this.onOpenAll,
|
||||||
});
|
});
|
||||||
|
|
||||||
final List<WatchProgress> records;
|
final List<WatchProgress> records;
|
||||||
|
|
||||||
|
/// 单张卡片:直接进入该剧的播放页,并定位到记录的集。
|
||||||
|
final ValueChanged<WatchProgress> onOpenRecord;
|
||||||
final VoidCallback onOpenAll;
|
final VoidCallback onOpenAll;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -94,7 +98,11 @@ class MineContinueWatching extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _card(AppLocalizations l10n, WatchProgress record, String languageCode) {
|
Widget _card(
|
||||||
|
AppLocalizations l10n,
|
||||||
|
WatchProgress record,
|
||||||
|
String languageCode,
|
||||||
|
) {
|
||||||
final title = record.localizedTitle(languageCode).trim();
|
final title = record.localizedTitle(languageCode).trim();
|
||||||
final episode = record.episodeNumber;
|
final episode = record.episodeNumber;
|
||||||
final hasProgress = record.duration > Duration.zero;
|
final hasProgress = record.duration > Duration.zero;
|
||||||
@@ -103,7 +111,7 @@ class MineContinueWatching extends StatelessWidget {
|
|||||||
child: InkWell(
|
child: InkWell(
|
||||||
key: Key('mine-continue-${record.dramaId}'),
|
key: Key('mine-continue-${record.dramaId}'),
|
||||||
borderRadius: BorderRadius.circular(AppDimens.homeCardRadius),
|
borderRadius: BorderRadius.circular(AppDimens.homeCardRadius),
|
||||||
onTap: onOpenAll,
|
onTap: () => onOpenRecord(record),
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
|
|||||||
@@ -119,7 +119,6 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
final Map<String, Future<void>> _episodeStatsInFlight = {};
|
final Map<String, Future<void>> _episodeStatsInFlight = {};
|
||||||
final Map<String, int> _episodeStatsRevision = {};
|
final Map<String, int> _episodeStatsRevision = {};
|
||||||
final Map<String, int> _dramaStatsRevision = {};
|
final Map<String, int> _dramaStatsRevision = {};
|
||||||
final Map<String, int> _dramaFavoriteCounts = {};
|
|
||||||
|
|
||||||
/// 解锁中的集 id 与失败文案;空表示没有进行中的解锁。
|
/// 解锁中的集 id 与失败文案;空表示没有进行中的解锁。
|
||||||
String? unlockingEpisodeId;
|
String? unlockingEpisodeId;
|
||||||
@@ -185,8 +184,6 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
|
|
||||||
EpisodeStats? episodeStats(String episodeId) => _episodeStats[episodeId];
|
EpisodeStats? episodeStats(String episodeId) => _episodeStats[episodeId];
|
||||||
|
|
||||||
int? dramaFavoriteCount(String dramaId) => _dramaFavoriteCounts[dramaId];
|
|
||||||
|
|
||||||
void notify() {
|
void notify() {
|
||||||
if (!_disposed) notifyListeners();
|
if (!_disposed) notifyListeners();
|
||||||
}
|
}
|
||||||
@@ -621,9 +618,6 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
);
|
);
|
||||||
_episodeStats[episodeId] = stats;
|
_episodeStats[episodeId] = stats;
|
||||||
_episodeStatsFetchedAt[episodeId] = _clock();
|
_episodeStatsFetchedAt[episodeId] = _clock();
|
||||||
if (stats.dramaId.isNotEmpty) {
|
|
||||||
_dramaFavoriteCounts[stats.dramaId] = stats.favoriteCount;
|
|
||||||
}
|
|
||||||
final episodeIndex = sessionEpisodes.indexWhere(
|
final episodeIndex = sessionEpisodes.indexWhere(
|
||||||
(episode) => episode.id == episodeId,
|
(episode) => episode.id == episodeId,
|
||||||
);
|
);
|
||||||
@@ -703,29 +697,13 @@ class PlayerLogic extends ChangeNotifier {
|
|||||||
notify();
|
notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 收藏成功时同时修正剧级计数和所有已缓存的同剧互动状态。
|
/// 收藏成功后让旧 stats 请求失效,计数本身只写 FavoriteController。
|
||||||
void applyDramaFavoriteState(
|
void markDramaFavoriteChanged(String dramaId) {
|
||||||
String dramaId, {
|
|
||||||
required bool favorited,
|
|
||||||
int? favoriteCount,
|
|
||||||
}) {
|
|
||||||
_dramaStatsRevision.update(
|
_dramaStatsRevision.update(
|
||||||
dramaId,
|
dramaId,
|
||||||
(value) => value + 1,
|
(value) => value + 1,
|
||||||
ifAbsent: () => 1,
|
ifAbsent: () => 1,
|
||||||
);
|
);
|
||||||
if (favoriteCount != null) {
|
|
||||||
_dramaFavoriteCounts[dramaId] = favoriteCount;
|
|
||||||
}
|
|
||||||
for (final entry in _episodeStats.entries.toList()) {
|
|
||||||
final stats = entry.value;
|
|
||||||
if (stats.dramaId != dramaId) continue;
|
|
||||||
_episodeStats[entry.key] = stats.copyWith(
|
|
||||||
favorited: favorited,
|
|
||||||
favoriteCount: favoriteCount,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
notify();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
String _fileUrl(String path) =>
|
String _fileUrl(String path) =>
|
||||||
|
|||||||
@@ -564,6 +564,7 @@ class _PlayerPageState extends State<PlayerPage>
|
|||||||
context.read<FavoriteController>().applyServerState(
|
context.read<FavoriteController>().applyServerState(
|
||||||
stats.dramaId,
|
stats.dramaId,
|
||||||
saved: stats.favorited,
|
saved: stats.favorited,
|
||||||
|
favoriteCount: stats.favoriteCount,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
setState(() {
|
setState(() {
|
||||||
@@ -571,21 +572,6 @@ class _PlayerPageState extends State<PlayerPage>
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 收藏状态确认后同步右侧剧级计数。
|
|
||||||
void _applyFavoriteDelta(Drama drama, {required bool nowSaved}) {
|
|
||||||
final current = logic.dramaFavoriteCount(drama.id) ?? drama.favoriteCount;
|
|
||||||
final next = current == null
|
|
||||||
? null
|
|
||||||
: nowSaved
|
|
||||||
? current + 1
|
|
||||||
: (current > 0 ? current - 1 : 0);
|
|
||||||
logic.applyDramaFavoriteState(
|
|
||||||
drama.id,
|
|
||||||
favorited: nowSaved,
|
|
||||||
favoriteCount: next,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _openComments(
|
Future<void> _openComments(
|
||||||
BuildContext context,
|
BuildContext context,
|
||||||
Drama drama,
|
Drama drama,
|
||||||
@@ -1026,6 +1012,7 @@ class _PlayerPageState extends State<PlayerPage>
|
|||||||
InteractionController interactions,
|
InteractionController interactions,
|
||||||
) {
|
) {
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
|
final favorites = context.watch<FavoriteController>();
|
||||||
final entry = logic.queue.entryAt(index);
|
final entry = logic.queue.entryAt(index);
|
||||||
final drama = entry.drama;
|
final drama = entry.drama;
|
||||||
final episode = _resolvedEpisode(index);
|
final episode = _resolvedEpisode(index);
|
||||||
@@ -1194,13 +1181,12 @@ class _PlayerPageState extends State<PlayerPage>
|
|||||||
liked: interactions.isEpisodeLiked(episode.id),
|
liked: interactions.isEpisodeLiked(episode.id),
|
||||||
likeCount:
|
likeCount:
|
||||||
interactions.episodeLikeCount(episode.id) ?? episode.likeCount,
|
interactions.episodeLikeCount(episode.id) ?? episode.likeCount,
|
||||||
favoriteCount:
|
favoriteCount: favorites.favoriteCountFor(drama),
|
||||||
logic.dramaFavoriteCount(drama.id) ?? drama.favoriteCount,
|
|
||||||
commentCount:
|
commentCount:
|
||||||
logic.episodeStats(episode.id)?.commentCount ??
|
logic.episodeStats(episode.id)?.commentCount ??
|
||||||
_commentCounts[episode.id] ??
|
_commentCounts[episode.id] ??
|
||||||
episode.commentCount,
|
episode.commentCount,
|
||||||
saved: context.watch<FavoriteController>().isSaved(drama.id),
|
saved: favorites.isSaved(drama.id),
|
||||||
onLike: () async {
|
onLike: () async {
|
||||||
await _toggleLike(context, interactions, episode);
|
await _toggleLike(context, interactions, episode);
|
||||||
},
|
},
|
||||||
@@ -1277,6 +1263,7 @@ class _PlayerPageState extends State<PlayerPage>
|
|||||||
) {
|
) {
|
||||||
if (logic.pip || logic.pipPreparing) return const SizedBox.expand();
|
if (logic.pip || logic.pipPreparing) return const SizedBox.expand();
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
|
final favorites = context.watch<FavoriteController>();
|
||||||
final entry = logic.queue.entryAt(index);
|
final entry = logic.queue.entryAt(index);
|
||||||
final drama = entry.drama;
|
final drama = entry.drama;
|
||||||
final episode = _resolvedEpisode(index);
|
final episode = _resolvedEpisode(index);
|
||||||
@@ -1306,9 +1293,8 @@ class _PlayerPageState extends State<PlayerPage>
|
|||||||
logic.episodeStats(episode.id)?.commentCount ??
|
logic.episodeStats(episode.id)?.commentCount ??
|
||||||
_commentCounts[episode.id] ??
|
_commentCounts[episode.id] ??
|
||||||
episode.commentCount,
|
episode.commentCount,
|
||||||
favoriteCount:
|
favoriteCount: favorites.favoriteCountFor(drama),
|
||||||
logic.dramaFavoriteCount(drama.id) ?? drama.favoriteCount,
|
saved: favorites.isSaved(drama.id),
|
||||||
saved: context.watch<FavoriteController>().isSaved(drama.id),
|
|
||||||
playing: logic.session.userWantsPlay,
|
playing: logic.session.userWantsPlay,
|
||||||
playbackSpeed: _playbackSpeed,
|
playbackSpeed: _playbackSpeed,
|
||||||
totalEpisodes: logic.visibleIndices.length,
|
totalEpisodes: logic.visibleIndices.length,
|
||||||
|
|||||||
@@ -166,7 +166,7 @@ extension _PlayerViewActions on _PlayerPageState {
|
|||||||
if (ok) {
|
if (ok) {
|
||||||
final nowSaved = favorites.isSaved(drama.id);
|
final nowSaved = favorites.isSaved(drama.id);
|
||||||
if (nowSaved != wasSaved) {
|
if (nowSaved != wasSaved) {
|
||||||
_applyFavoriteDelta(drama, nowSaved: nowSaved);
|
logic.markDramaFavoriteChanged(drama.id);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -269,8 +269,10 @@ class _HomeFeedOverlayState extends State<HomeFeedOverlay> {
|
|||||||
liked: widget.liked,
|
liked: widget.liked,
|
||||||
favoriteCount: widget.favoriteCount,
|
favoriteCount: widget.favoriteCount,
|
||||||
likeCount: widget.likeCount,
|
likeCount: widget.likeCount,
|
||||||
|
commentCount: widget.commentCount,
|
||||||
onSave: widget.onSave,
|
onSave: widget.onSave,
|
||||||
onLike: widget.onLike,
|
onLike: widget.onLike,
|
||||||
|
onComments: widget.onComments,
|
||||||
onEpisodes: widget.onEpisodes ?? widget.onOpenFullPlayer,
|
onEpisodes: widget.onEpisodes ?? widget.onOpenFullPlayer,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,19 +5,16 @@ import 'dart:math' as math;
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
import '../../../core/data/models/drama.dart';
|
import '../../../core/data/models/drama.dart';
|
||||||
import '../../../core/formatting/count_format.dart';
|
|
||||||
import '../../../core/formatting/localized_content.dart';
|
import '../../../core/formatting/localized_content.dart';
|
||||||
import '../../../core/theme/app_colors.dart';
|
import '../../../core/theme/app_colors.dart';
|
||||||
import '../../../l10n/app_localizations.dart';
|
import '../../../l10n/app_localizations.dart';
|
||||||
import '../../home/widgets/home_drama_classification.dart';
|
import '../../home/widgets/home_drama_classification.dart';
|
||||||
|
import 'interaction_rail.dart';
|
||||||
|
|
||||||
const double _seriesFont = 19;
|
const double _seriesFont = 19;
|
||||||
const double _tagFont = 13;
|
const double _tagFont = 13;
|
||||||
const double _synopsisFont = 13;
|
const double _synopsisFont = 13;
|
||||||
const double _watchAllHeight = 44;
|
const double _watchAllHeight = 44;
|
||||||
const double _actionGap = 28;
|
|
||||||
const double _actionIcon = 32;
|
|
||||||
const double _actionWidth = 64;
|
|
||||||
const List<Shadow> _textShadows = [
|
const List<Shadow> _textShadows = [
|
||||||
Shadow(color: AppColors.shadow, blurRadius: 6, offset: Offset(0, 1)),
|
Shadow(color: AppColors.shadow, blurRadius: 6, offset: Offset(0, 1)),
|
||||||
];
|
];
|
||||||
@@ -307,112 +304,64 @@ class HomeFeedActionRail extends StatelessWidget {
|
|||||||
required this.liked,
|
required this.liked,
|
||||||
required this.onSave,
|
required this.onSave,
|
||||||
required this.onLike,
|
required this.onLike,
|
||||||
|
required this.onComments,
|
||||||
required this.onEpisodes,
|
required this.onEpisodes,
|
||||||
this.favoriteCount,
|
this.favoriteCount,
|
||||||
this.likeCount,
|
this.likeCount,
|
||||||
|
this.commentCount,
|
||||||
});
|
});
|
||||||
|
|
||||||
final bool saved;
|
final bool saved;
|
||||||
final bool liked;
|
final bool liked;
|
||||||
final int? favoriteCount;
|
final int? favoriteCount;
|
||||||
final int? likeCount;
|
final int? likeCount;
|
||||||
|
final int? commentCount;
|
||||||
final VoidCallback onSave;
|
final VoidCallback onSave;
|
||||||
final VoidCallback onLike;
|
final VoidCallback onLike;
|
||||||
|
final VoidCallback onComments;
|
||||||
final VoidCallback onEpisodes;
|
final VoidCallback onEpisodes;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
return SizedBox(
|
return InteractionRail(
|
||||||
width: _actionWidth,
|
itemGap: 14,
|
||||||
child: Column(
|
items: [
|
||||||
mainAxisSize: MainAxisSize.min,
|
InteractionRailItem(
|
||||||
children: [
|
key: const Key('rail-save'),
|
||||||
_action(
|
asset: 'assets/icon/rail/rail_save.png',
|
||||||
key: const Key('rail-save'),
|
label: l10n.favorite,
|
||||||
icon: saved
|
count: favoriteCount,
|
||||||
? Icons.bookmark_rounded
|
countKey: const Key('rail-save-count'),
|
||||||
: Icons.bookmark_border_rounded,
|
selected: saved,
|
||||||
label: favoriteCount == null
|
onTap: onSave,
|
||||||
? l10n.favorite
|
),
|
||||||
: formatInteractionCount(favoriteCount!),
|
InteractionRailItem(
|
||||||
labelKey: const Key('rail-save-count'),
|
key: const Key('rail-like'),
|
||||||
onTap: onSave,
|
asset: 'assets/icon/rail/rail_like.png',
|
||||||
),
|
label: l10n.like,
|
||||||
const SizedBox(height: _actionGap),
|
count: likeCount,
|
||||||
_action(
|
countKey: const Key('rail-like-count'),
|
||||||
key: const Key('rail-like'),
|
selected: liked,
|
||||||
icon: liked
|
selectedColor: AppColors.doubleTapHeartRed,
|
||||||
? Icons.favorite_rounded
|
onTap: onLike,
|
||||||
: Icons.favorite_border_rounded,
|
),
|
||||||
iconColor: liked
|
InteractionRailItem(
|
||||||
? AppColors.doubleTapHeartRed
|
key: const Key('rail-comments'),
|
||||||
: AppColors.textPrimary,
|
asset: 'assets/icon/rail/rail_comment.png',
|
||||||
label: likeCount == null
|
label: l10n.comments,
|
||||||
? l10n.like
|
count: commentCount,
|
||||||
: formatInteractionCount(likeCount!),
|
countKey: const Key('rail-comments-count'),
|
||||||
labelKey: const Key('rail-like-count'),
|
onTap: onComments,
|
||||||
onTap: onLike,
|
),
|
||||||
),
|
InteractionRailItem(
|
||||||
const SizedBox(height: _actionGap),
|
key: const Key('rail-episodes'),
|
||||||
_action(
|
icon: Icons.layers_rounded,
|
||||||
key: const Key('rail-episodes'),
|
label: l10n.episodes,
|
||||||
icon: Icons.layers_rounded,
|
countKey: const Key('rail-episodes-label'),
|
||||||
label: l10n.episodes,
|
onTap: onEpisodes,
|
||||||
labelKey: const Key('rail-episodes-label'),
|
),
|
||||||
labelFontSize: 11,
|
],
|
||||||
onTap: onEpisodes,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Widget _action({
|
|
||||||
required Key key,
|
|
||||||
required IconData icon,
|
|
||||||
required String label,
|
|
||||||
required Key labelKey,
|
|
||||||
required VoidCallback onTap,
|
|
||||||
Color iconColor = AppColors.textPrimary,
|
|
||||||
double labelFontSize = 12,
|
|
||||||
}) {
|
|
||||||
return GestureDetector(
|
|
||||||
key: key,
|
|
||||||
behavior: HitTestBehavior.opaque,
|
|
||||||
onTap: onTap,
|
|
||||||
child: Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
Icon(
|
|
||||||
icon,
|
|
||||||
size: _actionIcon,
|
|
||||||
color: iconColor,
|
|
||||||
shadows: const [
|
|
||||||
Shadow(
|
|
||||||
color: AppColors.shadowSoft,
|
|
||||||
blurRadius: 4,
|
|
||||||
offset: Offset(0, 1),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 2),
|
|
||||||
Text(
|
|
||||||
label,
|
|
||||||
key: labelKey,
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
style: TextStyle(
|
|
||||||
color: AppColors.textPrimary,
|
|
||||||
fontSize: labelFontSize,
|
|
||||||
fontWeight: FontWeight.w500,
|
|
||||||
height: 1,
|
|
||||||
shadows: _textShadows,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,23 +7,25 @@ import '../../../core/theme/app_colors.dart';
|
|||||||
|
|
||||||
const double _buttonSize = 44;
|
const double _buttonSize = 44;
|
||||||
const double _iconSize = 32;
|
const double _iconSize = 32;
|
||||||
const double _itemGap = 24;
|
const double _defaultItemGap = 24;
|
||||||
|
|
||||||
/// 互动栏单项:图标、计数与点击。
|
/// 互动栏单项:图标、计数与点击。
|
||||||
class InteractionRailItem {
|
class InteractionRailItem {
|
||||||
const InteractionRailItem({
|
const InteractionRailItem({
|
||||||
required this.key,
|
required this.key,
|
||||||
required this.asset,
|
|
||||||
required this.label,
|
required this.label,
|
||||||
required this.onTap,
|
required this.onTap,
|
||||||
|
this.asset,
|
||||||
|
this.icon,
|
||||||
this.count,
|
this.count,
|
||||||
this.countKey,
|
this.countKey,
|
||||||
this.selected = false,
|
this.selected = false,
|
||||||
this.selectedColor = AppColors.blue,
|
this.selectedColor = AppColors.blue,
|
||||||
});
|
}) : assert((asset == null) != (icon == null));
|
||||||
|
|
||||||
final Key key;
|
final Key key;
|
||||||
final String asset;
|
final String? asset;
|
||||||
|
final IconData? icon;
|
||||||
final String label;
|
final String label;
|
||||||
final VoidCallback onTap;
|
final VoidCallback onTap;
|
||||||
final int? count;
|
final int? count;
|
||||||
@@ -34,9 +36,14 @@ class InteractionRailItem {
|
|||||||
|
|
||||||
/// 播放页与首页 feed 共用的右侧互动栏:收藏/评论/喜欢/分享。
|
/// 播放页与首页 feed 共用的右侧互动栏:收藏/评论/喜欢/分享。
|
||||||
class InteractionRail extends StatelessWidget {
|
class InteractionRail extends StatelessWidget {
|
||||||
const InteractionRail({super.key, required this.items});
|
const InteractionRail({
|
||||||
|
super.key,
|
||||||
|
required this.items,
|
||||||
|
this.itemGap = _defaultItemGap,
|
||||||
|
});
|
||||||
|
|
||||||
final List<InteractionRailItem> items;
|
final List<InteractionRailItem> items;
|
||||||
|
final double itemGap;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
@@ -44,7 +51,7 @@ class InteractionRail extends StatelessWidget {
|
|||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
for (var index = 0; index < items.length; index++) ...[
|
for (var index = 0; index < items.length; index++) ...[
|
||||||
if (index > 0) const SizedBox(height: _itemGap),
|
if (index > 0) SizedBox(height: itemGap),
|
||||||
_RailButton(item: items[index]),
|
_RailButton(item: items[index]),
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
@@ -68,14 +75,24 @@ class _RailButton extends StatelessWidget {
|
|||||||
child: IconButton(
|
child: IconButton(
|
||||||
onPressed: item.onTap,
|
onPressed: item.onTap,
|
||||||
padding: EdgeInsets.zero,
|
padding: EdgeInsets.zero,
|
||||||
icon: Image.asset(
|
icon: item.asset != null
|
||||||
item.asset,
|
? Image.asset(
|
||||||
width: _iconSize,
|
item.asset!,
|
||||||
height: _iconSize,
|
width: _iconSize,
|
||||||
fit: BoxFit.contain,
|
height: _iconSize,
|
||||||
color: item.selected ? item.selectedColor : AppColors.onPrimary,
|
fit: BoxFit.contain,
|
||||||
colorBlendMode: BlendMode.srcIn,
|
color: item.selected
|
||||||
),
|
? item.selectedColor
|
||||||
|
: AppColors.onPrimary,
|
||||||
|
colorBlendMode: BlendMode.srcIn,
|
||||||
|
)
|
||||||
|
: Icon(
|
||||||
|
item.icon,
|
||||||
|
size: _iconSize,
|
||||||
|
color: item.selected
|
||||||
|
? item.selectedColor
|
||||||
|
: AppColors.onPrimary,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 2),
|
const SizedBox(height: 2),
|
||||||
|
|||||||
@@ -178,14 +178,6 @@ class PlayerPlaybackOverlay extends StatelessWidget {
|
|||||||
selected: data.saved,
|
selected: data.saved,
|
||||||
onTap: actions.onSave,
|
onTap: actions.onSave,
|
||||||
),
|
),
|
||||||
InteractionRailItem(
|
|
||||||
key: const Key('player-rail-comments'),
|
|
||||||
asset: 'assets/icon/rail/rail_comment.png',
|
|
||||||
label: data.l10n.comments,
|
|
||||||
count: data.commentCount,
|
|
||||||
countKey: const Key('player-rail-comments-count'),
|
|
||||||
onTap: actions.onComments,
|
|
||||||
),
|
|
||||||
InteractionRailItem(
|
InteractionRailItem(
|
||||||
key: const Key('player-rail-like'),
|
key: const Key('player-rail-like'),
|
||||||
asset: 'assets/icon/rail/rail_like.png',
|
asset: 'assets/icon/rail/rail_like.png',
|
||||||
@@ -196,6 +188,14 @@ class PlayerPlaybackOverlay extends StatelessWidget {
|
|||||||
selectedColor: AppColors.doubleTapHeartRed,
|
selectedColor: AppColors.doubleTapHeartRed,
|
||||||
onTap: actions.onLike,
|
onTap: actions.onLike,
|
||||||
),
|
),
|
||||||
|
InteractionRailItem(
|
||||||
|
key: const Key('player-rail-comments'),
|
||||||
|
asset: 'assets/icon/rail/rail_comment.png',
|
||||||
|
label: data.l10n.comments,
|
||||||
|
count: data.commentCount,
|
||||||
|
countKey: const Key('player-rail-comments-count'),
|
||||||
|
onTap: actions.onComments,
|
||||||
|
),
|
||||||
InteractionRailItem(
|
InteractionRailItem(
|
||||||
key: const Key('player-rail-share'),
|
key: const Key('player-rail-share'),
|
||||||
asset: 'assets/icon/rail/rail_share.png',
|
asset: 'assets/icon/rail/rail_share.png',
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import '../../core/data/services/playlist_controller.dart';
|
|||||||
import '../../core/theme/app_colors.dart';
|
import '../../core/theme/app_colors.dart';
|
||||||
import '../../core/widgets/empty_state.dart';
|
import '../../core/widgets/empty_state.dart';
|
||||||
import '../../l10n/app_localizations.dart';
|
import '../../l10n/app_localizations.dart';
|
||||||
|
import '../home/home_feed_channel.dart';
|
||||||
import '../player/open_player.dart';
|
import '../player/open_player.dart';
|
||||||
import '../player/player_view.dart';
|
import '../player/player_view.dart';
|
||||||
import 'recommend_types.dart';
|
import 'recommend_types.dart';
|
||||||
@@ -48,9 +49,17 @@ class RecommendPage extends StatefulWidget {
|
|||||||
|
|
||||||
class _RecommendPageState extends State<RecommendPage>
|
class _RecommendPageState extends State<RecommendPage>
|
||||||
with AutomaticKeepAliveClientMixin<RecommendPage> {
|
with AutomaticKeepAliveClientMixin<RecommendPage> {
|
||||||
|
static const Duration _recommendRetryDelay = Duration(milliseconds: 1500);
|
||||||
|
static const int _maxRecommendRetries = 3;
|
||||||
|
|
||||||
RecommendInnerTab _tab = RecommendInnerTab.feed;
|
RecommendInnerTab _tab = RecommendInnerTab.feed;
|
||||||
final PageController _pageController = PageController();
|
final PageController _pageController = PageController();
|
||||||
int _scrubCancelRequest = 0;
|
int _scrubCancelRequest = 0;
|
||||||
|
bool _recommendDataRefreshScheduled = false;
|
||||||
|
bool _recommendRefreshInFlight = false;
|
||||||
|
int _recommendRetryAttempts = 0;
|
||||||
|
Timer? _recommendRetryTimer;
|
||||||
|
HomeFeedChannel? _observedFeedChannel;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
bool get wantKeepAlive => true;
|
bool get wantKeepAlive => true;
|
||||||
@@ -58,22 +67,82 @@ class _RecommendPageState extends State<RecommendPage>
|
|||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
|
_observedFeedChannel = widget.feedController.channel;
|
||||||
|
widget.feedController.addListener(_handleFeedControllerChanged);
|
||||||
if (widget.active) _scheduleRecommendData();
|
if (widget.active) _scheduleRecommendData();
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void didUpdateWidget(RecommendPage oldWidget) {
|
void didUpdateWidget(RecommendPage oldWidget) {
|
||||||
super.didUpdateWidget(oldWidget);
|
super.didUpdateWidget(oldWidget);
|
||||||
if (widget.active && !oldWidget.active) _scheduleRecommendData();
|
if (oldWidget.feedController != widget.feedController) {
|
||||||
|
oldWidget.feedController.removeListener(_handleFeedControllerChanged);
|
||||||
|
_cancelRecommendRetries();
|
||||||
|
_observedFeedChannel = widget.feedController.channel;
|
||||||
|
widget.feedController.addListener(_handleFeedControllerChanged);
|
||||||
|
}
|
||||||
|
if (oldWidget.active && !widget.active) {
|
||||||
|
_cancelRecommendRetries();
|
||||||
|
}
|
||||||
|
if (_requiresRecommendDataRefresh(oldWidget)) {
|
||||||
|
_scheduleRecommendData();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _requiresRecommendDataRefresh(RecommendPage oldWidget) {
|
||||||
|
if (!widget.active) return false;
|
||||||
|
return !oldWidget.active ||
|
||||||
|
oldWidget.feedController != widget.feedController ||
|
||||||
|
oldWidget.catalogApi != widget.catalogApi;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleFeedControllerChanged() {
|
||||||
|
final channel = widget.feedController.channel;
|
||||||
|
if (channel != _observedFeedChannel) {
|
||||||
|
_observedFeedChannel = channel;
|
||||||
|
_cancelRecommendRetries();
|
||||||
|
if (widget.active) _scheduleRecommendData();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_handleRecommendFeedState();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _handleRecommendFeedState() {
|
||||||
|
if (!mounted || !widget.active) return;
|
||||||
|
final feed = widget.feedController;
|
||||||
|
if (feed.dramas.isNotEmpty) {
|
||||||
|
_cancelRecommendRetries();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (feed.loaded &&
|
||||||
|
feed.lastError == null &&
|
||||||
|
!feed.isLoading &&
|
||||||
|
!_recommendRefreshInFlight) {
|
||||||
|
_cancelRecommendRetries();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (feed.loaded && feed.lastError != null && !_recommendRefreshInFlight) {
|
||||||
|
_scheduleRecommendRetry();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _scheduleRecommendData() {
|
void _scheduleRecommendData() {
|
||||||
final feed = widget.feedController;
|
if (_recommendDataRefreshScheduled) return;
|
||||||
if (!feed.loaded && !feed.loadingFirstPage) {
|
_recommendDataRefreshScheduled = true;
|
||||||
unawaited(feed.refreshCurrent());
|
|
||||||
}
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
_recommendDataRefreshScheduled = false;
|
||||||
if (!mounted || !widget.active) return;
|
if (!mounted || !widget.active) return;
|
||||||
|
final feed = widget.feedController;
|
||||||
|
if (feed.dramas.isEmpty || feed.lastError != null) {
|
||||||
|
_recommendRetryAttempts = 0;
|
||||||
|
if (!feed.isLoading && !_recommendRefreshInFlight) {
|
||||||
|
if (feed.loaded) {
|
||||||
|
_scheduleRecommendRetry();
|
||||||
|
} else {
|
||||||
|
unawaited(_refreshRecommendData());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
final playlists = _readPlaylists();
|
final playlists = _readPlaylists();
|
||||||
if (playlists != null && !playlists.loaded && !playlists.loading) {
|
if (playlists != null && !playlists.loaded && !playlists.loading) {
|
||||||
unawaited(playlists.load());
|
unawaited(playlists.load());
|
||||||
@@ -81,8 +150,51 @@ class _RecommendPageState extends State<RecommendPage>
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _scheduleRecommendRetry() {
|
||||||
|
if (!mounted ||
|
||||||
|
!widget.active ||
|
||||||
|
_recommendRefreshInFlight ||
|
||||||
|
_recommendRetryTimer != null ||
|
||||||
|
_recommendRetryAttempts >= _maxRecommendRetries) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState(() {
|
||||||
|
_recommendRetryTimer = Timer(_recommendRetryDelay, () {
|
||||||
|
_recommendRetryTimer = null;
|
||||||
|
if (!mounted || !widget.active) return;
|
||||||
|
_recommendRetryAttempts += 1;
|
||||||
|
unawaited(_refreshRecommendData());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _refreshRecommendData() async {
|
||||||
|
if (!mounted || !widget.active || _recommendRefreshInFlight) return;
|
||||||
|
setState(() => _recommendRefreshInFlight = true);
|
||||||
|
final succeeded = await widget.feedController.refreshCurrent();
|
||||||
|
if (!mounted) return;
|
||||||
|
_recommendRefreshInFlight = false;
|
||||||
|
if (!widget.active) return;
|
||||||
|
final feed = widget.feedController;
|
||||||
|
if (succeeded || (feed.loaded && feed.lastError == null)) {
|
||||||
|
_cancelRecommendRetries();
|
||||||
|
setState(() {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState(() {});
|
||||||
|
_scheduleRecommendRetry();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _cancelRecommendRetries() {
|
||||||
|
_recommendRetryTimer?.cancel();
|
||||||
|
_recommendRetryTimer = null;
|
||||||
|
_recommendRetryAttempts = 0;
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
|
widget.feedController.removeListener(_handleFeedControllerChanged);
|
||||||
|
_cancelRecommendRetries();
|
||||||
_pageController.dispose();
|
_pageController.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
@@ -169,39 +281,51 @@ class _RecommendPageState extends State<RecommendPage>
|
|||||||
}
|
}
|
||||||
|
|
||||||
Widget _recommendFeed(BuildContext context) {
|
Widget _recommendFeed(BuildContext context) {
|
||||||
|
final feed = widget.feedController;
|
||||||
final dramas = widget.feedController.dramas;
|
final dramas = widget.feedController.dramas;
|
||||||
if (dramas.isEmpty) {
|
if (dramas.isNotEmpty) {
|
||||||
final l10n = AppLocalizations.of(context)!;
|
return PlayerPage(
|
||||||
if (widget.feedController.loadingFirstPage) {
|
key: const Key('recommend-feed-player'),
|
||||||
return const _RecommendFeedSkeleton();
|
homeMode: true,
|
||||||
}
|
embedded: true,
|
||||||
|
active: widget.active && _tab == RecommendInnerTab.feed,
|
||||||
|
showHomeFeedHeader: false,
|
||||||
|
drama: dramas.first,
|
||||||
|
initialIndex: 0,
|
||||||
|
feedDramas: dramas,
|
||||||
|
feedChannel: widget.feedController.channel,
|
||||||
|
onOpenFullPlayer: (drama, episode) =>
|
||||||
|
_openDrama(drama, episodeId: episode.id),
|
||||||
|
onRefreshFeed: widget.feedController.refreshCurrent,
|
||||||
|
onLoadMore: widget.feedController.loadMore,
|
||||||
|
onImmersiveChanged: widget.onImmersiveChanged,
|
||||||
|
scrubCancelRequest: _scrubCancelRequest,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!feed.loaded ||
|
||||||
|
feed.isLoading ||
|
||||||
|
_recommendRefreshInFlight ||
|
||||||
|
_recommendRetryTimer != null) {
|
||||||
|
return const _RecommendFeedSkeleton();
|
||||||
|
}
|
||||||
|
final l10n = AppLocalizations.of(context)!;
|
||||||
|
if (feed.lastError != null) {
|
||||||
return ColoredBox(
|
return ColoredBox(
|
||||||
color: AppColors.mediaBlack,
|
color: AppColors.mediaBlack,
|
||||||
child: EmptyState(
|
child: EmptyState(
|
||||||
key: const Key('recommend-feed-empty'),
|
key: const Key('recommend-feed-empty'),
|
||||||
icon: Icons.movie_outlined,
|
icon: Icons.wifi_off_rounded,
|
||||||
title: l10n.noStories,
|
title: l10n.networkError,
|
||||||
actionLabel: l10n.retry,
|
|
||||||
onAction: () => unawaited(widget.feedController.refreshCurrent()),
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return PlayerPage(
|
return ColoredBox(
|
||||||
key: const Key('recommend-feed-player'),
|
color: AppColors.mediaBlack,
|
||||||
homeMode: true,
|
child: EmptyState(
|
||||||
embedded: true,
|
key: const Key('recommend-feed-empty'),
|
||||||
active: widget.active && _tab == RecommendInnerTab.feed,
|
icon: Icons.movie_outlined,
|
||||||
showHomeFeedHeader: false,
|
title: l10n.noStories,
|
||||||
drama: dramas.first,
|
),
|
||||||
initialIndex: 0,
|
|
||||||
feedDramas: dramas,
|
|
||||||
feedChannel: widget.feedController.channel,
|
|
||||||
onOpenFullPlayer: (drama, episode) =>
|
|
||||||
_openDrama(drama, episodeId: episode.id),
|
|
||||||
onRefreshFeed: widget.feedController.refreshCurrent,
|
|
||||||
onLoadMore: widget.feedController.loadMore,
|
|
||||||
onImmersiveChanged: widget.onImmersiveChanged,
|
|
||||||
scrubCancelRequest: _scrubCancelRequest,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -396,7 +520,7 @@ class _RecommendFeedSkeleton extends StatelessWidget {
|
|||||||
height: 176,
|
height: 176,
|
||||||
child: DecoratedBox(
|
child: DecoratedBox(
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: AppColors.skeletonSurface,
|
color: AppColors.skeletonMedia,
|
||||||
borderRadius: BorderRadius.all(Radius.circular(12)),
|
borderRadius: BorderRadius.all(Radius.circular(12)),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -435,7 +559,7 @@ class _SkeletonLine extends StatelessWidget {
|
|||||||
width: width,
|
width: width,
|
||||||
height: height,
|
height: height,
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: AppColors.skeletonSurface,
|
color: AppColors.skeletonMedia,
|
||||||
borderRadius: BorderRadius.circular(6),
|
borderRadius: BorderRadius.circular(6),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ import '../../core/platform/haptics.dart';
|
|||||||
import '../../core/theme/app_colors.dart';
|
import '../../core/theme/app_colors.dart';
|
||||||
import '../../core/theme/app_theme.dart';
|
import '../../core/theme/app_theme.dart';
|
||||||
import '../../core/widgets/app_pull_to_refresh.dart';
|
import '../../core/widgets/app_pull_to_refresh.dart';
|
||||||
import '../../core/widgets/auth_gate.dart';
|
|
||||||
import '../../core/widgets/empty_state.dart';
|
import '../../core/widgets/empty_state.dart';
|
||||||
import '../../core/widgets/paged_list_footer.dart';
|
import '../../core/widgets/paged_list_footer.dart';
|
||||||
import '../../core/widgets/subpage_header.dart';
|
import '../../core/widgets/subpage_header.dart';
|
||||||
@@ -35,7 +34,6 @@ class WatchRecordsPage extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final signedIn = context.watch<AuthController>().isSignedIn;
|
|
||||||
final l10n = AppLocalizations.of(context)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
return Theme(
|
return Theme(
|
||||||
data: AppTheme.dark(),
|
data: AppTheme.dark(),
|
||||||
@@ -49,11 +47,7 @@ class WatchRecordsPage extends StatelessWidget {
|
|||||||
title: l10n.watchHistory,
|
title: l10n.watchHistory,
|
||||||
backKey: const Key('watch-records-back'),
|
backKey: const Key('watch-records-back'),
|
||||||
),
|
),
|
||||||
Expanded(
|
Expanded(child: const _WatchRecordsBody()),
|
||||||
child: signedIn
|
|
||||||
? const _WatchRecordsBody()
|
|
||||||
: const AuthGatePanel(),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -71,10 +65,15 @@ class _WatchRecordsBody extends StatefulWidget {
|
|||||||
|
|
||||||
class _WatchRecordsBodyState extends State<_WatchRecordsBody> {
|
class _WatchRecordsBodyState extends State<_WatchRecordsBody> {
|
||||||
late final WatchRecordsController controller;
|
late final WatchRecordsController controller;
|
||||||
|
late final AuthController _auth;
|
||||||
|
late bool _signedIn;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
|
_auth = context.read<AuthController>();
|
||||||
|
_signedIn = _auth.isSignedIn;
|
||||||
|
_auth.addListener(_handleAuthChanged);
|
||||||
controller = WatchRecordsBinding().create(
|
controller = WatchRecordsBinding().create(
|
||||||
history: context.read<WatchHistoryRepository>(),
|
history: context.read<WatchHistoryRepository>(),
|
||||||
catalog: context.read<CatalogRepository>(),
|
catalog: context.read<CatalogRepository>(),
|
||||||
@@ -82,8 +81,17 @@ class _WatchRecordsBodyState extends State<_WatchRecordsBody> {
|
|||||||
unawaited(controller.load());
|
unawaited(controller.load());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _handleAuthChanged() {
|
||||||
|
final signedIn = _auth.isSignedIn;
|
||||||
|
if (_signedIn == signedIn || !mounted) return;
|
||||||
|
_signedIn = signedIn;
|
||||||
|
controller.reset();
|
||||||
|
unawaited(controller.load());
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
|
_auth.removeListener(_handleAuthChanged);
|
||||||
controller.dispose();
|
controller.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|||||||
+20
-20
@@ -216,7 +216,7 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "2.0.2"
|
version: "2.0.2"
|
||||||
html:
|
html:
|
||||||
dependency: transitive
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: html
|
name: html
|
||||||
sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699"
|
sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699"
|
||||||
@@ -248,10 +248,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: intl
|
name: intl
|
||||||
sha256: "3df61194eb431efc39c4ceba583b95633a403f46c9fd341e550ce0bfa50e9aa5"
|
sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867"
|
||||||
url: "https://pub.flutter-io.cn"
|
url: "https://pub.flutter-io.cn"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.20.2"
|
version: "0.20.3"
|
||||||
jni:
|
jni:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -328,10 +328,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: matcher
|
name: matcher
|
||||||
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861
|
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
|
||||||
url: "https://pub.flutter-io.cn"
|
url: "https://pub.flutter-io.cn"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.12.19"
|
version: "0.12.20"
|
||||||
material_color_utilities:
|
material_color_utilities:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -344,10 +344,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: meta
|
name: meta
|
||||||
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349"
|
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
|
||||||
url: "https://pub.flutter-io.cn"
|
url: "https://pub.flutter-io.cn"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.18.0"
|
version: "1.19.0"
|
||||||
mime:
|
mime:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -380,14 +380,6 @@ packages:
|
|||||||
url: "https://pub.flutter-io.cn"
|
url: "https://pub.flutter-io.cn"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "3.0.0"
|
version: "3.0.0"
|
||||||
petitparser:
|
|
||||||
dependency: transitive
|
|
||||||
description:
|
|
||||||
name: petitparser
|
|
||||||
sha256: "2f1564aadb14215e478563b5406cb80729d022158c01dc50c96013c2f7eb4790"
|
|
||||||
url: "https://pub.flutter-io.cn"
|
|
||||||
source: hosted
|
|
||||||
version: "7.1.0"
|
|
||||||
path:
|
path:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -444,6 +436,14 @@ packages:
|
|||||||
url: "https://pub.flutter-io.cn"
|
url: "https://pub.flutter-io.cn"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.3.0"
|
version: "2.3.0"
|
||||||
|
petitparser:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: petitparser
|
||||||
|
sha256: "2f1564aadb14215e478563b5406cb80729d022158c01dc50c96013c2f7eb4790"
|
||||||
|
url: "https://pub.flutter-io.cn"
|
||||||
|
source: hosted
|
||||||
|
version: "7.1.0"
|
||||||
platform:
|
platform:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -613,10 +613,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: test_api
|
name: test_api
|
||||||
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e"
|
sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
|
||||||
url: "https://pub.flutter-io.cn"
|
url: "https://pub.flutter-io.cn"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.7.11"
|
version: "0.7.12"
|
||||||
typed_data:
|
typed_data:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -637,10 +637,10 @@ packages:
|
|||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
name: vector_math
|
name: vector_math
|
||||||
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b
|
sha256: "92b9910f66ed1057fd4da7b040ae7c74cafacf885bdc81be496928d5049b032d"
|
||||||
url: "https://pub.flutter-io.cn"
|
url: "https://pub.flutter-io.cn"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.2.0"
|
version: "2.4.3"
|
||||||
video_player:
|
video_player:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@@ -730,5 +730,5 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "3.1.4"
|
version: "3.1.4"
|
||||||
sdks:
|
sdks:
|
||||||
dart: ">=3.12.2 <4.0.0"
|
dart: ">=3.13.0 <4.0.0"
|
||||||
flutter: ">=3.44.0"
|
flutter: ">=3.44.0"
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:fruitshorts/core/formatting/account_display.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('should_localize_country_name', () {
|
||||||
|
expect(countryName('ID', 'zh'), '印度尼西亚');
|
||||||
|
expect(countryName('us', 'en'), 'United States');
|
||||||
|
expect(countryName('TH', 'id'), 'Thailand');
|
||||||
|
// 未收录的码原样返回,避免展示成空白
|
||||||
|
expect(countryName('ZZ', 'zh'), 'ZZ');
|
||||||
|
expect(countryName('', 'zh'), '');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should_localize_timezone_to_city', () {
|
||||||
|
expect(timezoneName('Asia/Jakarta', 'zh'), '雅加达');
|
||||||
|
expect(timezoneName('Asia/Jakarta', 'en'), 'Jakarta');
|
||||||
|
expect(
|
||||||
|
timezoneName('America/Argentina/Buenos_Aires', 'en'),
|
||||||
|
'Buenos Aires',
|
||||||
|
);
|
||||||
|
expect(timezoneName('', 'zh'), '');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should_localize_language_by_primary_tag', () {
|
||||||
|
expect(languageName('id-ID', 'zh'), '印度尼西亚语');
|
||||||
|
expect(languageName('zh-TW', 'en'), 'Chinese');
|
||||||
|
expect(languageName('en-US', 'id'), 'Inggris');
|
||||||
|
expect(languageName('', 'zh'), '');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should_localize_status_and_vip_level', () {
|
||||||
|
expect(accountStatusText('normal', 'zh'), '正常');
|
||||||
|
expect(accountStatusText('banned', 'id'), 'Diblokir');
|
||||||
|
expect(accountStatusText('weird', 'zh'), 'weird');
|
||||||
|
expect(vipLevelText(0, 'zh'), '未开通');
|
||||||
|
expect(vipLevelText(2, 'zh'), 'VIP 2');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:fruitshorts/core/data/services/auth_session_store.dart';
|
||||||
|
import 'package:fruitshorts/core/data/services/device_id_provider.dart';
|
||||||
|
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
|
||||||
|
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
|
||||||
|
|
||||||
|
/// 可控的系统设备标识来源。
|
||||||
|
class _FakeDeviceIdProvider implements DeviceIdProvider {
|
||||||
|
_FakeDeviceIdProvider(this.value, {this.region});
|
||||||
|
|
||||||
|
final String? value;
|
||||||
|
final String? region;
|
||||||
|
int calls = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> systemDeviceId() async {
|
||||||
|
calls++;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> deviceRegion() async => region;
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUp(() {
|
||||||
|
SharedPreferencesAsyncPlatform.instance =
|
||||||
|
InMemorySharedPreferencesAsync.empty();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should_prefer_system_device_id_over_local_value', () async {
|
||||||
|
final provider = _FakeDeviceIdProvider('a-9774d56d682e549c');
|
||||||
|
final store = AuthSessionStore(deviceIdProvider: provider);
|
||||||
|
|
||||||
|
expect(await store.deviceId(), 'a-9774d56d682e549c');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should_fall_back_to_stable_local_uuid_when_system_id_missing', () async {
|
||||||
|
final store = AuthSessionStore(
|
||||||
|
deviceIdProvider: _FakeDeviceIdProvider(null),
|
||||||
|
);
|
||||||
|
|
||||||
|
final first = await store.deviceId();
|
||||||
|
final second = await store.deviceId();
|
||||||
|
|
||||||
|
// 同一次运行内固定,且符合 UUIDv4 形态
|
||||||
|
expect(first, second);
|
||||||
|
expect(first, startsWith('d-'));
|
||||||
|
expect(
|
||||||
|
RegExp(
|
||||||
|
r'^d-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$',
|
||||||
|
).hasMatch(first),
|
||||||
|
isTrue,
|
||||||
|
reason: '本地兜底必须是 UUIDv4,避免 32 位随机带来的碰撞',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should_cache_system_id_within_one_session', () async {
|
||||||
|
final provider = _FakeDeviceIdProvider('i-E621E1F8-C36C-495A-93FC-0C247A3E6E5F');
|
||||||
|
final store = AuthSessionStore(deviceIdProvider: provider);
|
||||||
|
|
||||||
|
await store.deviceId();
|
||||||
|
await store.deviceId();
|
||||||
|
|
||||||
|
expect(provider.calls, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('should_return_device_region_or_empty_string', () async {
|
||||||
|
final store = AuthSessionStore(
|
||||||
|
deviceIdProvider: _FakeDeviceIdProvider(null, region: 'TH'),
|
||||||
|
);
|
||||||
|
final missing = AuthSessionStore(
|
||||||
|
deviceIdProvider: _FakeDeviceIdProvider(null),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(await store.deviceRegion(), 'TH');
|
||||||
|
expect(await missing.deviceRegion(), '');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
// Author: fruit.com.cn
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:fruitshorts/core/widgets/drama_grid_skeleton.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('renders one narrow highlight overlay per skeleton card', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
tester.view.physicalSize = const Size(390, 1000);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
|
||||||
|
await tester.pumpWidget(
|
||||||
|
const MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: DramaGridSkeleton(
|
||||||
|
columns: 3,
|
||||||
|
horizontalPadding: 14,
|
||||||
|
crossAxisSpacing: 8,
|
||||||
|
mainAxisSpacing: 12,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump(const Duration(milliseconds: 100));
|
||||||
|
|
||||||
|
expect(find.byType(GridView), findsOneWidget);
|
||||||
|
expect(find.byType(ShaderMask), findsNothing);
|
||||||
|
for (var index = 0; index < 9; index++) {
|
||||||
|
final card = find.byKey(Key('drama-grid-skeleton-$index'));
|
||||||
|
expect(card, findsOneWidget);
|
||||||
|
expect(
|
||||||
|
find.descendant(of: card, matching: find.byType(IgnorePointer)),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
final overlay = find.descendant(
|
||||||
|
of: card,
|
||||||
|
matching: find.byWidgetPredicate(
|
||||||
|
(widget) =>
|
||||||
|
widget is DecoratedBox &&
|
||||||
|
widget.decoration is BoxDecoration &&
|
||||||
|
(widget.decoration as BoxDecoration).gradient != null,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(overlay, findsOneWidget);
|
||||||
|
final decoration =
|
||||||
|
tester.widget<DecoratedBox>(overlay).decoration as BoxDecoration;
|
||||||
|
final gradient = decoration.gradient! as LinearGradient;
|
||||||
|
expect(gradient.colors, const [
|
||||||
|
Colors.transparent,
|
||||||
|
Color(0x0DFFFFFF),
|
||||||
|
Colors.transparent,
|
||||||
|
]);
|
||||||
|
expect(gradient.stops, const [0.42, 0.5, 0.58]);
|
||||||
|
expect(gradient.stops![2] - gradient.stops![0], lessThanOrEqualTo(0.25));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -16,20 +16,20 @@ DramaDetailLogic _logic(
|
|||||||
FakeWatchHistory history, {
|
FakeWatchHistory history, {
|
||||||
FavoriteController? favorites,
|
FavoriteController? favorites,
|
||||||
PlaybackPositionCache? positionCache,
|
PlaybackPositionCache? positionCache,
|
||||||
}) =>
|
}) => DramaDetailLogic(
|
||||||
DramaDetailLogic(
|
drama: drama,
|
||||||
drama: drama,
|
history: history,
|
||||||
history: history,
|
playback: FakePlaybackRepository(),
|
||||||
playback: FakePlaybackRepository(),
|
favorites: favorites ?? FavoriteController(InMemoryFavoriteRepository()),
|
||||||
favorites: favorites ?? FavoriteController(InMemoryFavoriteRepository()),
|
positionCache: positionCache ?? PlaybackPositionCache(),
|
||||||
positionCache: positionCache ?? PlaybackPositionCache(),
|
);
|
||||||
);
|
|
||||||
|
|
||||||
Drama _card(String id) => Drama(
|
Drama _card(String id, {int? favoriteCount}) => Drama(
|
||||||
id: id,
|
id: id,
|
||||||
title: id,
|
title: id,
|
||||||
synopsis: 'synopsis',
|
synopsis: 'synopsis',
|
||||||
posterUrl: '/files/$id.jpg',
|
posterUrl: '/files/$id.jpg',
|
||||||
|
favoriteCount: favoriteCount,
|
||||||
totalEpisodes: 3,
|
totalEpisodes: 3,
|
||||||
episodes: [
|
episodes: [
|
||||||
Episode(
|
Episode(
|
||||||
@@ -42,11 +42,12 @@ Drama _card(String id) => Drama(
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
Drama _detail(String id) => Drama(
|
Drama _detail(String id, {int? favoriteCount}) => Drama(
|
||||||
id: id,
|
id: id,
|
||||||
title: id,
|
title: id,
|
||||||
synopsis: 'synopsis',
|
synopsis: 'synopsis',
|
||||||
posterUrl: '/files/$id.jpg',
|
posterUrl: '/files/$id.jpg',
|
||||||
|
favoriteCount: favoriteCount,
|
||||||
totalEpisodes: 3,
|
totalEpisodes: 3,
|
||||||
detailLoaded: true,
|
detailLoaded: true,
|
||||||
episodes: [
|
episodes: [
|
||||||
@@ -62,21 +63,24 @@ Drama _detail(String id) => Drama(
|
|||||||
);
|
);
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
test('should_upgrade_to_full_episode_list_when_detail_loads_for_list_card', () async {
|
test(
|
||||||
var calls = 0;
|
'should_upgrade_to_full_episode_list_when_detail_loads_for_list_card',
|
||||||
final logic = _logic(_card('signal'), FakeWatchHistory());
|
() async {
|
||||||
|
var calls = 0;
|
||||||
|
final logic = _logic(_card('signal'), FakeWatchHistory());
|
||||||
|
|
||||||
await logic.load(() async {
|
await logic.load(() async {
|
||||||
calls++;
|
calls++;
|
||||||
return _detail('signal');
|
return _detail('signal');
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(calls, 1);
|
expect(calls, 1);
|
||||||
expect(logic.loading, isFalse);
|
expect(logic.loading, isFalse);
|
||||||
expect(logic.failed, isFalse);
|
expect(logic.failed, isFalse);
|
||||||
expect(logic.drama.episodes, hasLength(3));
|
expect(logic.drama.episodes, hasLength(3));
|
||||||
logic.dispose();
|
logic.dispose();
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
test('should_keep_card_and_report_reason_when_load_fails', () async {
|
test('should_keep_card_and_report_reason_when_load_fails', () async {
|
||||||
final logic = _logic(_card('signal'), FakeWatchHistory());
|
final logic = _logic(_card('signal'), FakeWatchHistory());
|
||||||
@@ -107,6 +111,19 @@ void main() {
|
|||||||
logic.dispose();
|
logic.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('should_use_detail_favorite_count_as_authoritative', () async {
|
||||||
|
final favorites = FavoriteController(InMemoryFavoriteRepository());
|
||||||
|
final card = _card('signal', favoriteCount: 2);
|
||||||
|
expect(favorites.favoriteCountFor(card), 2);
|
||||||
|
final logic = _logic(card, FakeWatchHistory(), favorites: favorites);
|
||||||
|
|
||||||
|
await logic.load(() async => _detail('signal', favoriteCount: 9));
|
||||||
|
|
||||||
|
expect(favorites.favoriteCount('signal'), 9);
|
||||||
|
expect(logic.adjustedFavoriteCount, 9);
|
||||||
|
logic.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
test('should_prefer_recent_local_position_when_loading_continue', () async {
|
test('should_prefer_recent_local_position_when_loading_continue', () async {
|
||||||
final cache = PlaybackPositionCache();
|
final cache = PlaybackPositionCache();
|
||||||
cache.save(
|
cache.save(
|
||||||
|
|||||||
@@ -4,12 +4,16 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:fruitshorts/app.dart';
|
import 'package:fruitshorts/app.dart';
|
||||||
import 'package:fruitshorts/core/data/models/drama.dart';
|
import 'package:fruitshorts/core/data/models/drama.dart';
|
||||||
|
import 'package:fruitshorts/core/data/models/page_result.dart';
|
||||||
import 'package:fruitshorts/core/data/models/watch_progress.dart';
|
import 'package:fruitshorts/core/data/models/watch_progress.dart';
|
||||||
import 'package:fruitshorts/core/data/repositories/favorite_repository.dart';
|
import 'package:fruitshorts/core/data/repositories/favorite_repository.dart';
|
||||||
import 'package:fruitshorts/core/data/repositories/playback_repository.dart';
|
import 'package:fruitshorts/core/data/repositories/playback_repository.dart';
|
||||||
import 'package:fruitshorts/core/data/repositories/watch_history_repository.dart';
|
import 'package:fruitshorts/core/data/repositories/watch_history_repository.dart';
|
||||||
|
import 'package:fruitshorts/core/data/services/auth_controller.dart';
|
||||||
import 'package:fruitshorts/core/theme/app_colors.dart';
|
import 'package:fruitshorts/core/theme/app_colors.dart';
|
||||||
import 'package:fruitshorts/core/theme/app_dimens.dart';
|
import 'package:fruitshorts/core/theme/app_dimens.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
|
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
|
||||||
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
|
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
|
||||||
|
|
||||||
@@ -139,6 +143,31 @@ void main() {
|
|||||||
await tester.tap(find.byKey(const Key('following-cancel-follow')));
|
await tester.tap(find.byKey(const Key('following-cancel-follow')));
|
||||||
await tester.pumpAndSettle();
|
await tester.pumpAndSettle();
|
||||||
expect(find.text('Unfollow the selected dramas?'), findsOneWidget);
|
expect(find.text('Unfollow the selected dramas?'), findsOneWidget);
|
||||||
|
final dialog = tester.widget<AlertDialog>(find.byType(AlertDialog));
|
||||||
|
expect(dialog.contentPadding, const EdgeInsets.all(20));
|
||||||
|
expect(dialog.actionsPadding, const EdgeInsets.fromLTRB(20, 0, 20, 20));
|
||||||
|
expect(
|
||||||
|
tester
|
||||||
|
.getSize(
|
||||||
|
find.descendant(
|
||||||
|
of: find.byType(AlertDialog),
|
||||||
|
matching: find.byType(TextButton),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.height,
|
||||||
|
32,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
tester
|
||||||
|
.getSize(
|
||||||
|
find.descendant(
|
||||||
|
of: find.byType(AlertDialog),
|
||||||
|
matching: find.byType(FilledButton),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.height,
|
||||||
|
32,
|
||||||
|
);
|
||||||
await tester.tap(
|
await tester.tap(
|
||||||
find.descendant(
|
find.descendant(
|
||||||
of: find.byType(AlertDialog),
|
of: find.byType(AlertDialog),
|
||||||
@@ -165,7 +194,8 @@ void main() {
|
|||||||
testWidgets('should_unfollow_every_selected_drama_when_edit_confirms', (
|
testWidgets('should_unfollow_every_selected_drama_when_edit_confirms', (
|
||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
_signIn();
|
SharedPreferencesAsyncPlatform.instance =
|
||||||
|
InMemorySharedPreferencesAsync.empty();
|
||||||
final catalog = FakeCatalogRepository();
|
final catalog = FakeCatalogRepository();
|
||||||
final dramas = catalog.dramas.take(2).toList();
|
final dramas = catalog.dramas.take(2).toList();
|
||||||
final favorites = InMemoryFavoriteRepository(
|
final favorites = InMemoryFavoriteRepository(
|
||||||
@@ -203,16 +233,119 @@ void main() {
|
|||||||
expect(favorites.removeManyCalls, 1);
|
expect(favorites.removeManyCalls, 1);
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('should_show_auth_gate_when_signed_out', (tester) async {
|
testWidgets('should_show_device_favorites_and_history_when_signed_out', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
SharedPreferencesAsyncPlatform.instance =
|
SharedPreferencesAsyncPlatform.instance =
|
||||||
InMemorySharedPreferencesAsync.empty();
|
InMemorySharedPreferencesAsync.empty();
|
||||||
await tester.pumpWidget(_app(catalog: FakeCatalogRepository()));
|
final catalog = FakeCatalogRepository();
|
||||||
|
await tester.pumpWidget(
|
||||||
|
_app(
|
||||||
|
catalog: catalog,
|
||||||
|
favorites: InMemoryFavoriteRepository(
|
||||||
|
cards: catalog.dramas.take(1).toList(),
|
||||||
|
saved: {catalog.dramas.first.id},
|
||||||
|
),
|
||||||
|
history: InMemoryWatchHistoryRepository(
|
||||||
|
seed: [
|
||||||
|
WatchProgress(
|
||||||
|
dramaId: 'the-signal-demo',
|
||||||
|
episodeId: 'the-signal-demo-3',
|
||||||
|
dramaTitle: 'Device history',
|
||||||
|
episodeNumber: 3,
|
||||||
|
position: const Duration(seconds: 25),
|
||||||
|
duration: const Duration(seconds: 100),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
await tester.pumpAndSettle();
|
await tester.pumpAndSettle();
|
||||||
await tester.tap(find.byKey(const Key('tab-follow')));
|
await tester.tap(find.byKey(const Key('tab-follow')));
|
||||||
await tester.pumpAndSettle();
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
expect(find.byKey(const Key('auth-gate-panel')), findsOneWidget);
|
expect(find.byKey(const Key('auth-gate-panel')), findsNothing);
|
||||||
expect(find.byKey(const Key('following-favorites-grid')), findsNothing);
|
expect(find.byKey(const Key('following-favorites-grid')), findsOneWidget);
|
||||||
|
expect(
|
||||||
|
find.byKey(const Key('following-card-the-signal-demo')),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.byKey(const Key('following-tab-history')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(
|
||||||
|
find.byKey(const Key('following-history-card-the-signal-demo')),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
expect(find.text('Device history'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('should_reload_identity_data_after_login_and_logout', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
SharedPreferencesAsyncPlatform.instance =
|
||||||
|
InMemorySharedPreferencesAsync.empty();
|
||||||
|
final catalog = FakeCatalogRepository();
|
||||||
|
final favorites = _IdentityFavoriteRepository(
|
||||||
|
device: [catalog.dramas[0]],
|
||||||
|
account: [catalog.dramas[1]],
|
||||||
|
);
|
||||||
|
final history = _IdentityWatchHistoryRepository(
|
||||||
|
device: [_historyProgress('the-signal-demo', 'Device history')],
|
||||||
|
account: [_historyProgress('city-lights-demo', 'Account history')],
|
||||||
|
);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
_app(catalog: catalog, favorites: favorites, history: history),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.byKey(const Key('tab-follow')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(
|
||||||
|
find.byKey(const Key('following-card-the-signal-demo')),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
final initialFavoriteCalls = favorites.pageCalls;
|
||||||
|
final initialHistoryCalls = history.recentCalls;
|
||||||
|
final auth = Provider.of<AuthController>(
|
||||||
|
tester.element(find.byKey(const Key('following-page'))),
|
||||||
|
listen: false,
|
||||||
|
);
|
||||||
|
final preferences = SharedPreferencesAsync();
|
||||||
|
|
||||||
|
favorites.scope = 'account';
|
||||||
|
history.scope = 'account';
|
||||||
|
await _setSignedIn(preferences);
|
||||||
|
await auth.load();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(auth.isSignedIn, isTrue);
|
||||||
|
expect(favorites.pageCalls, greaterThan(initialFavoriteCalls));
|
||||||
|
expect(history.recentCalls, greaterThan(initialHistoryCalls));
|
||||||
|
expect(
|
||||||
|
find.byKey(const Key('following-card-the-signal-demo')),
|
||||||
|
findsNothing,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
find.byKey(const Key('following-card-city-lights-demo')),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(find.byKey(const Key('following-tab-history')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Account history'), findsOneWidget);
|
||||||
|
expect(find.text('Device history'), findsNothing);
|
||||||
|
|
||||||
|
favorites.scope = 'device';
|
||||||
|
history.scope = 'device';
|
||||||
|
await _clearSignedIn(preferences);
|
||||||
|
await auth.load();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(auth.isSignedIn, isFalse);
|
||||||
|
expect(find.text('Device history'), findsOneWidget);
|
||||||
|
expect(find.text('Account history'), findsNothing);
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('should_show_empty_favorites_and_history', (tester) async {
|
testWidgets('should_show_empty_favorites_and_history', (tester) async {
|
||||||
@@ -407,6 +540,21 @@ void _signIn() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _setSignedIn(SharedPreferencesAsync preferences) async {
|
||||||
|
await preferences.setString('auth.accessToken', 'access');
|
||||||
|
await preferences.setString('auth.refreshToken', 'refresh');
|
||||||
|
await preferences.setString(
|
||||||
|
'auth.user',
|
||||||
|
'{"uid":"9","nickname":"Viewer","avatarUrl":""}',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _clearSignedIn(SharedPreferencesAsync preferences) async {
|
||||||
|
await preferences.remove('auth.accessToken');
|
||||||
|
await preferences.remove('auth.refreshToken');
|
||||||
|
await preferences.remove('auth.user');
|
||||||
|
}
|
||||||
|
|
||||||
Widget _app({
|
Widget _app({
|
||||||
required FakeCatalogRepository catalog,
|
required FakeCatalogRepository catalog,
|
||||||
FavoriteRepository? favorites,
|
FavoriteRepository? favorites,
|
||||||
@@ -433,3 +581,102 @@ class _CountingCatalogRepository extends FakeCatalogRepository {
|
|||||||
return super.fetchDrama(dramaId);
|
return super.fetchDrama(dramaId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
WatchProgress _historyProgress(String dramaId, String title) {
|
||||||
|
return WatchProgress(
|
||||||
|
dramaId: dramaId,
|
||||||
|
episodeId: '$dramaId-3',
|
||||||
|
dramaTitle: title,
|
||||||
|
episodeNumber: 3,
|
||||||
|
position: const Duration(seconds: 25),
|
||||||
|
duration: const Duration(seconds: 100),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _IdentityFavoriteRepository implements FavoriteRepository {
|
||||||
|
_IdentityFavoriteRepository({
|
||||||
|
required List<Drama> device,
|
||||||
|
required List<Drama> account,
|
||||||
|
}) : _cards = {'device': device, 'account': account};
|
||||||
|
|
||||||
|
final Map<String, List<Drama>> _cards;
|
||||||
|
String scope = 'device';
|
||||||
|
int pageCalls = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<PageResult<Drama>> page({int pageIndex = 1, int pageSize = 20}) async {
|
||||||
|
pageCalls += 1;
|
||||||
|
final cards = _cards[scope]!;
|
||||||
|
final offset = (pageIndex - 1) * pageSize;
|
||||||
|
return PageResult(
|
||||||
|
total: cards.length,
|
||||||
|
list: offset >= cards.length
|
||||||
|
? const []
|
||||||
|
: cards.skip(offset).take(pageSize).toList(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> remove(String dramaId) async {
|
||||||
|
_cards[scope]!.removeWhere((drama) => drama.id == dramaId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> removeMany(List<String> dramaIds) async {
|
||||||
|
final ids = dramaIds.toSet();
|
||||||
|
_cards[scope]!.removeWhere((drama) => ids.contains(drama.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> toggle(String dramaId) async => true;
|
||||||
|
}
|
||||||
|
|
||||||
|
class _IdentityWatchHistoryRepository implements WatchHistoryRepository {
|
||||||
|
_IdentityWatchHistoryRepository({
|
||||||
|
required List<WatchProgress> device,
|
||||||
|
required List<WatchProgress> account,
|
||||||
|
}) : _records = {'device': device, 'account': account};
|
||||||
|
|
||||||
|
final Map<String, List<WatchProgress>> _records;
|
||||||
|
String scope = 'device';
|
||||||
|
int recentCalls = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> clear() async => _records[scope]!.clear();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<WatchProgress?> progressFor(String dramaId) async {
|
||||||
|
return _records[scope]!
|
||||||
|
.where((record) => record.dramaId == dramaId)
|
||||||
|
.firstOrNull;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<PageResult<WatchProgress>> recent({
|
||||||
|
int pageIndex = 1,
|
||||||
|
int pageSize = 20,
|
||||||
|
}) async {
|
||||||
|
recentCalls += 1;
|
||||||
|
final records = _records[scope]!;
|
||||||
|
final offset = (pageIndex - 1) * pageSize;
|
||||||
|
return PageResult(
|
||||||
|
total: records.length,
|
||||||
|
list: offset >= records.length
|
||||||
|
? const []
|
||||||
|
: records.skip(offset).take(pageSize).toList(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> remove(String dramaId) async {
|
||||||
|
_records[scope]!.removeWhere((record) => record.dramaId == dramaId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<WatchProgress?> save({
|
||||||
|
required String episodeId,
|
||||||
|
required Duration position,
|
||||||
|
Duration? duration,
|
||||||
|
bool finished = false,
|
||||||
|
}) async => null;
|
||||||
|
}
|
||||||
@@ -323,19 +323,46 @@ void main() {
|
|||||||
tester.widget<Text>(find.byKey(const Key('rail-save-count'))).data,
|
tester.widget<Text>(find.byKey(const Key('rail-save-count'))).data,
|
||||||
'3.2万',
|
'3.2万',
|
||||||
);
|
);
|
||||||
expect(
|
final likeImage = tester.widget<Image>(
|
||||||
find.descendant(
|
find.descendant(
|
||||||
of: find.byKey(const Key('rail-like')),
|
of: find.byKey(const Key('rail-like')),
|
||||||
matching: find.byIcon(Icons.favorite_rounded),
|
matching: find.byType(Image),
|
||||||
),
|
),
|
||||||
findsOneWidget,
|
|
||||||
);
|
);
|
||||||
expect(
|
final saveImage = tester.widget<Image>(
|
||||||
find.descendant(
|
find.descendant(
|
||||||
of: find.byKey(const Key('rail-save')),
|
of: find.byKey(const Key('rail-save')),
|
||||||
matching: find.byIcon(Icons.bookmark_border_rounded),
|
matching: find.byType(Image),
|
||||||
),
|
),
|
||||||
findsOneWidget,
|
);
|
||||||
|
expect(
|
||||||
|
(likeImage.image as AssetImage).assetName,
|
||||||
|
'assets/icon/rail/rail_like.png',
|
||||||
|
);
|
||||||
|
expect(likeImage.color, AppColors.doubleTapHeartRed);
|
||||||
|
expect(
|
||||||
|
(saveImage.image as AssetImage).assetName,
|
||||||
|
'assets/icon/rail/rail_save.png',
|
||||||
|
);
|
||||||
|
expect(saveImage.color, AppColors.onPrimary);
|
||||||
|
expect(find.byKey(const Key('rail-comments')), findsOneWidget);
|
||||||
|
expect(find.byKey(const Key('rail-share')), findsNothing);
|
||||||
|
expect(
|
||||||
|
tester.widget<Text>(find.byKey(const Key('rail-comments-count'))).data,
|
||||||
|
'12',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
(tester
|
||||||
|
.widget<Image>(
|
||||||
|
find.descendant(
|
||||||
|
of: find.byKey(const Key('rail-comments')),
|
||||||
|
matching: find.byType(Image),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.image
|
||||||
|
as AssetImage)
|
||||||
|
.assetName,
|
||||||
|
'assets/icon/rail/rail_comment.png',
|
||||||
);
|
);
|
||||||
expect(find.byKey(const Key('rail-episodes')), findsOneWidget);
|
expect(find.byKey(const Key('rail-episodes')), findsOneWidget);
|
||||||
expect(
|
expect(
|
||||||
@@ -345,9 +372,13 @@ void main() {
|
|||||||
),
|
),
|
||||||
findsOneWidget,
|
findsOneWidget,
|
||||||
);
|
);
|
||||||
expect(find.byKey(const Key('rail-comments')), findsNothing);
|
final saveRect = tester.getRect(find.byKey(const Key('rail-save')));
|
||||||
expect(find.byKey(const Key('rail-share')), findsNothing);
|
final likeRect = tester.getRect(find.byKey(const Key('rail-like')));
|
||||||
expect(find.text('Comments'), findsNothing);
|
final commentsRect = tester.getRect(find.byKey(const Key('rail-comments')));
|
||||||
|
final episodesRect = tester.getRect(find.byKey(const Key('rail-episodes')));
|
||||||
|
expect(likeRect.top - saveRect.bottom, closeTo(14, 0.1));
|
||||||
|
expect(commentsRect.top - likeRect.bottom, closeTo(14, 0.1));
|
||||||
|
expect(episodesRect.top - commentsRect.bottom, closeTo(14, 0.1));
|
||||||
expect(
|
expect(
|
||||||
tester.getRect(find.byKey(const Key('home-feed-action-rail'))).right,
|
tester.getRect(find.byKey(const Key('home-feed-action-rail'))).right,
|
||||||
closeTo(
|
closeTo(
|
||||||
@@ -672,7 +703,10 @@ void main() {
|
|||||||
final previewDecoration = previewContainer.decoration! as BoxDecoration;
|
final previewDecoration = previewContainer.decoration! as BoxDecoration;
|
||||||
expect(previewDecoration.color, AppColors.card);
|
expect(previewDecoration.color, AppColors.card);
|
||||||
expect(previewDecoration.borderRadius, BorderRadius.circular(8));
|
expect(previewDecoration.borderRadius, BorderRadius.circular(8));
|
||||||
expect((previewDecoration.border! as Border).top.color, AppColors.onPrimary);
|
expect(
|
||||||
|
(previewDecoration.border! as Border).top.color,
|
||||||
|
AppColors.onPrimary,
|
||||||
|
);
|
||||||
await gesture.moveBy(const Offset(-600, 0));
|
await gesture.moveBy(const Offset(-600, 0));
|
||||||
await tester.pump();
|
await tester.pump();
|
||||||
expect(
|
expect(
|
||||||
|
|||||||
@@ -6,11 +6,12 @@ import 'package:fruitshorts/core/data/models/page_result.dart';
|
|||||||
import 'package:fruitshorts/core/data/repositories/favorite_repository.dart';
|
import 'package:fruitshorts/core/data/repositories/favorite_repository.dart';
|
||||||
import 'package:fruitshorts/core/data/services/favorite_controller.dart';
|
import 'package:fruitshorts/core/data/services/favorite_controller.dart';
|
||||||
|
|
||||||
Drama _card(String id) => Drama(
|
Drama _card(String id, {int? favoriteCount}) => Drama(
|
||||||
id: id,
|
id: id,
|
||||||
title: 'Drama $id',
|
title: 'Drama $id',
|
||||||
synopsis: 'synopsis',
|
synopsis: 'synopsis',
|
||||||
posterUrl: '/files/$id.png',
|
posterUrl: '/files/$id.png',
|
||||||
|
favoriteCount: favoriteCount,
|
||||||
);
|
);
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
@@ -37,6 +38,31 @@ void main() {
|
|||||||
expect(controller.cards.map((drama) => drama.id), ['signal']);
|
expect(controller.cards.map((drama) => drama.id), ['signal']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'should_adjust_the_single_favorite_count_when_toggle_succeeds',
|
||||||
|
() async {
|
||||||
|
final controller = FavoriteController(InMemoryFavoriteRepository());
|
||||||
|
final card = _card('signal', favoriteCount: 12);
|
||||||
|
|
||||||
|
expect(controller.favoriteCountFor(card), 12);
|
||||||
|
expect(await controller.toggle('signal', card: card), isTrue);
|
||||||
|
expect(controller.favoriteCount('signal'), 13);
|
||||||
|
expect(await controller.toggle('signal', card: card), isTrue);
|
||||||
|
expect(controller.favoriteCount('signal'), 12);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test('should_apply_server_count_and_roll_back_toggle_failure', () async {
|
||||||
|
final repository = InMemoryFavoriteRepository()..failToggle = true;
|
||||||
|
final controller = FavoriteController(repository);
|
||||||
|
|
||||||
|
controller.applyServerState('signal', saved: false, favoriteCount: 20);
|
||||||
|
expect(controller.favoriteCount('signal'), 20);
|
||||||
|
expect(await controller.toggle('signal'), isFalse);
|
||||||
|
expect(controller.isSaved('signal'), isFalse);
|
||||||
|
expect(controller.favoriteCount('signal'), 20);
|
||||||
|
});
|
||||||
|
|
||||||
test('should_remove_card_and_state_when_toggled_off', () async {
|
test('should_remove_card_and_state_when_toggled_off', () async {
|
||||||
final repository = InMemoryFavoriteRepository(saved: {'signal'});
|
final repository = InMemoryFavoriteRepository(saved: {'signal'});
|
||||||
final controller = FavoriteController(repository);
|
final controller = FavoriteController(repository);
|
||||||
|
|||||||
@@ -187,22 +187,20 @@ void main() {
|
|||||||
expect(find.byKey(const Key('favorites-retry')), findsOneWidget);
|
expect(find.byKey(const Key('favorites-retry')), findsOneWidget);
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets(
|
testWidgets('should_show_device_favorites_when_signed_out', (tester) async {
|
||||||
'should_show_auth_gate_without_loading_favorites_when_signed_out',
|
final auth = await _auth(signedIn: false);
|
||||||
(tester) async {
|
final repository = InMemoryFavoriteRepository(
|
||||||
final auth = await _auth(signedIn: false);
|
saved: {'signal'},
|
||||||
final repository = InMemoryFavoriteRepository(
|
cards: [_card('signal')],
|
||||||
saved: {'signal'},
|
);
|
||||||
cards: [_card('signal')],
|
final favorites = FavoriteController(repository);
|
||||||
);
|
|
||||||
final favorites = FavoriteController(repository);
|
|
||||||
|
|
||||||
await _pumpPage(tester, auth: auth, favorites: favorites);
|
await _pumpPage(tester, auth: auth, favorites: favorites);
|
||||||
|
|
||||||
expect(find.byKey(const Key('auth-gate-panel')), findsOneWidget);
|
expect(find.byKey(const Key('auth-gate-panel')), findsNothing);
|
||||||
expect(repository.pageCalls, 0);
|
expect(find.text('Drama signal'), findsOneWidget);
|
||||||
},
|
expect(repository.pageCalls, 1);
|
||||||
);
|
});
|
||||||
|
|
||||||
testWidgets('should_open_player_when_favorite_card_is_tapped', (
|
testWidgets('should_open_player_when_favorite_card_is_tapped', (
|
||||||
tester,
|
tester,
|
||||||
|
|||||||
@@ -60,6 +60,20 @@ void main() {
|
|||||||
logic.dispose();
|
logic.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('should_clear_recent_when_identity_is_reset', () async {
|
||||||
|
final history = FakeWatchHistory()..recentRecords = const [_record];
|
||||||
|
final logic = MineLogic(history: history);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
logic.resetRecent();
|
||||||
|
|
||||||
|
expect(logic.recent, isEmpty);
|
||||||
|
expect(logic.watchRecordTotal, isNull);
|
||||||
|
expect(logic.recentLoading, isFalse);
|
||||||
|
expect(logic.recentError, isNull);
|
||||||
|
logic.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
testWidgets('should_forward_action_when_embedded_or_pop_when_standalone', (
|
testWidgets('should_forward_action_when_embedded_or_pop_when_standalone', (
|
||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
|
|||||||
@@ -3,12 +3,15 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:fruitshorts/app.dart';
|
import 'package:fruitshorts/app.dart';
|
||||||
|
import 'package:fruitshorts/core/data/models/drama.dart';
|
||||||
|
import 'package:fruitshorts/core/data/models/page_result.dart';
|
||||||
import 'package:fruitshorts/core/data/models/wallet.dart';
|
import 'package:fruitshorts/core/data/models/wallet.dart';
|
||||||
import 'package:fruitshorts/core/data/models/watch_progress.dart';
|
import 'package:fruitshorts/core/data/models/watch_progress.dart';
|
||||||
import 'package:fruitshorts/core/data/repositories/commerce_repository.dart';
|
import 'package:fruitshorts/core/data/repositories/commerce_repository.dart';
|
||||||
import 'package:fruitshorts/core/data/repositories/favorite_repository.dart';
|
import 'package:fruitshorts/core/data/repositories/favorite_repository.dart';
|
||||||
import 'package:fruitshorts/core/data/repositories/playback_repository.dart';
|
import 'package:fruitshorts/core/data/repositories/playback_repository.dart';
|
||||||
import 'package:fruitshorts/core/data/repositories/watch_history_repository.dart';
|
import 'package:fruitshorts/core/data/repositories/watch_history_repository.dart';
|
||||||
|
import 'package:fruitshorts/core/data/services/auth_controller.dart';
|
||||||
import 'package:fruitshorts/core/theme/app_colors.dart';
|
import 'package:fruitshorts/core/theme/app_colors.dart';
|
||||||
import 'package:fruitshorts/core/theme/app_dimens.dart';
|
import 'package:fruitshorts/core/theme/app_dimens.dart';
|
||||||
import 'package:fruitshorts/core/theme/app_theme.dart';
|
import 'package:fruitshorts/core/theme/app_theme.dart';
|
||||||
@@ -18,6 +21,8 @@ import 'package:fruitshorts/pages/mine/about_page.dart';
|
|||||||
import 'package:fruitshorts/pages/mine/mine_types.dart';
|
import 'package:fruitshorts/pages/mine/mine_types.dart';
|
||||||
import 'package:fruitshorts/pages/mine/widgets/mine_menu.dart';
|
import 'package:fruitshorts/pages/mine/widgets/mine_menu.dart';
|
||||||
import 'package:fruitshorts/pages/store/vip_page.dart';
|
import 'package:fruitshorts/pages/store/vip_page.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
|
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
|
||||||
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
|
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
|
||||||
|
|
||||||
@@ -67,7 +72,9 @@ void main() {
|
|||||||
expect(find.byKey(const Key('mine-vip-open')), findsOneWidget);
|
expect(find.byKey(const Key('mine-vip-open')), findsOneWidget);
|
||||||
expect(find.byKey(const Key('mine-continue-watching')), findsNothing);
|
expect(find.byKey(const Key('mine-continue-watching')), findsNothing);
|
||||||
expect(find.byKey(const Key('mine-stats')), findsOneWidget);
|
expect(find.byKey(const Key('mine-stats')), findsOneWidget);
|
||||||
expect(find.text('—'), findsNWidgets(3));
|
expect(_statValue(tester, const Key('mine-stat-following')), '3');
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-watch-records')), '0');
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-coins')), '—');
|
||||||
expect(find.byKey(const Key('mine-menu')), findsOneWidget);
|
expect(find.byKey(const Key('mine-menu')), findsOneWidget);
|
||||||
expect(find.byKey(const Key('mine-more-services')), findsOneWidget);
|
expect(find.byKey(const Key('mine-more-services')), findsOneWidget);
|
||||||
expect(find.byKey(const Key('mine-mini-player')), findsNothing);
|
expect(find.byKey(const Key('mine-mini-player')), findsNothing);
|
||||||
@@ -242,6 +249,99 @@ void main() {
|
|||||||
expect(find.byType(AuthPage), findsOneWidget);
|
expect(find.byType(AuthPage), findsOneWidget);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
testWidgets('should_show_device_counts_when_signed_out', (tester) async {
|
||||||
|
await _pumpApp(
|
||||||
|
tester,
|
||||||
|
signedIn: false,
|
||||||
|
history: InMemoryWatchHistoryRepository(seed: [_recent]),
|
||||||
|
);
|
||||||
|
await _openMine(tester);
|
||||||
|
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-following')), '3');
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-watch-records')), '1');
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-coins')), '—');
|
||||||
|
expect(find.byKey(const Key('mine-continue-watching')), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('should_switch_mine_counts_when_login_identity_changes', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final catalog = FakeCatalogRepository();
|
||||||
|
final favorites = _IdentityMineFavoriteRepository(
|
||||||
|
device: catalog.dramas.take(2).toList(),
|
||||||
|
account: [catalog.dramas[2]],
|
||||||
|
);
|
||||||
|
final history = _IdentityMineWatchHistoryRepository(
|
||||||
|
device: [_recent, _secondRecent],
|
||||||
|
account: [_accountRecent],
|
||||||
|
);
|
||||||
|
await _pumpApp(
|
||||||
|
tester,
|
||||||
|
signedIn: false,
|
||||||
|
favorite: favorites,
|
||||||
|
history: history,
|
||||||
|
);
|
||||||
|
await _openMine(tester);
|
||||||
|
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-following')), '2');
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-watch-records')), '2');
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-coins')), '—');
|
||||||
|
|
||||||
|
final auth = Provider.of<AuthController>(
|
||||||
|
tester.element(find.byKey(const Key('mine-page-surface'))),
|
||||||
|
listen: false,
|
||||||
|
);
|
||||||
|
final preferences = SharedPreferencesAsync();
|
||||||
|
favorites.scope = 'account';
|
||||||
|
history.scope = 'account';
|
||||||
|
await _setSignedIn(preferences);
|
||||||
|
await auth.load();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(auth.isSignedIn, isTrue);
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-following')), '1');
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-watch-records')), '1');
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-coins')), '320');
|
||||||
|
expect(find.text('Account history'), findsOneWidget);
|
||||||
|
expect(find.text('Device history'), findsNothing);
|
||||||
|
|
||||||
|
favorites.scope = 'device';
|
||||||
|
history.scope = 'device';
|
||||||
|
await _clearSignedIn(preferences);
|
||||||
|
await auth.load();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(auth.isSignedIn, isFalse);
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-following')), '2');
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-watch-records')), '2');
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-coins')), '—');
|
||||||
|
expect(find.text('Device history'), findsOneWidget);
|
||||||
|
expect(find.text('Account history'), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('should_refresh_watch_count_after_history_is_cleared', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final history = InMemoryWatchHistoryRepository(seed: [_recent]);
|
||||||
|
await _pumpApp(tester, signedIn: false, history: history);
|
||||||
|
await _openMine(tester);
|
||||||
|
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-watch-records')), '1');
|
||||||
|
|
||||||
|
await tester.tap(find.byKey(const Key('mine-history')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.byKey(const Key('watch-records-clear')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.widgetWithText(FilledButton, 'Clear'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byKey(const Key('watch-records-empty')), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.binding.handlePopRoute();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(_statValue(tester, const Key('mine-stat-watch-records')), '0');
|
||||||
|
});
|
||||||
|
|
||||||
testWidgets('should_render_signed_in_user_without_floating_mini_player', (
|
testWidgets('should_render_signed_in_user_without_floating_mini_player', (
|
||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
@@ -337,6 +437,24 @@ void main() {
|
|||||||
expect(find.byKey(const Key('following-history-grid')), findsOneWidget);
|
expect(find.byKey(const Key('following-history-grid')), findsOneWidget);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
testWidgets('should_open_player_when_tapping_continue_watching_card', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await _pumpApp(
|
||||||
|
tester,
|
||||||
|
signedIn: true,
|
||||||
|
history: InMemoryWatchHistoryRepository(seed: [_recent]),
|
||||||
|
);
|
||||||
|
await _openMine(tester);
|
||||||
|
|
||||||
|
await tester.tap(find.byKey(const Key('mine-continue-city-lights-demo')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.byKey(const Key('player-scaffold')), findsOneWidget);
|
||||||
|
// 继续观看直接进播放页,不应该先落到历史列表
|
||||||
|
expect(find.byKey(const Key('following-page')), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
testWidgets('should_open_vip_from_mine_without_floating_player', (
|
testWidgets('should_open_vip_from_mine_without_floating_player', (
|
||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
@@ -414,6 +532,34 @@ const _recent = WatchProgress(
|
|||||||
duration: Duration(minutes: 2),
|
duration: Duration(minutes: 2),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const _secondRecent = WatchProgress(
|
||||||
|
dramaId: 'vengeance-demo',
|
||||||
|
episodeId: 'vengeance-demo-1',
|
||||||
|
dramaTitle: 'Device history',
|
||||||
|
episodeNumber: 1,
|
||||||
|
totalEpisodes: 6,
|
||||||
|
position: Duration(seconds: 15),
|
||||||
|
duration: Duration(minutes: 2),
|
||||||
|
);
|
||||||
|
|
||||||
|
const _accountRecent = WatchProgress(
|
||||||
|
dramaId: 'the-signal-demo',
|
||||||
|
episodeId: 'the-signal-demo-2',
|
||||||
|
dramaTitle: 'Account history',
|
||||||
|
episodeNumber: 2,
|
||||||
|
totalEpisodes: 7,
|
||||||
|
position: Duration(seconds: 20),
|
||||||
|
duration: Duration(minutes: 2),
|
||||||
|
);
|
||||||
|
|
||||||
|
String _statValue(WidgetTester tester, Key key) {
|
||||||
|
return tester
|
||||||
|
.widget<Text>(
|
||||||
|
find.descendant(of: find.byKey(key), matching: find.byType(Text)).first,
|
||||||
|
)
|
||||||
|
.data!;
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _openMine(WidgetTester tester) async {
|
Future<void> _openMine(WidgetTester tester) async {
|
||||||
await tester.tap(find.byKey(const Key('tab-mine')));
|
await tester.tap(find.byKey(const Key('tab-mine')));
|
||||||
await tester.pumpAndSettle();
|
await tester.pumpAndSettle();
|
||||||
@@ -423,6 +569,7 @@ Future<void> _pumpApp(
|
|||||||
WidgetTester tester, {
|
WidgetTester tester, {
|
||||||
required bool signedIn,
|
required bool signedIn,
|
||||||
WatchHistoryRepository? history,
|
WatchHistoryRepository? history,
|
||||||
|
FavoriteRepository? favorite,
|
||||||
CommerceRepository? commerce,
|
CommerceRepository? commerce,
|
||||||
}) async {
|
}) async {
|
||||||
tester.view.physicalSize = const Size(390, 1000);
|
tester.view.physicalSize = const Size(390, 1000);
|
||||||
@@ -443,10 +590,12 @@ Future<void> _pumpApp(
|
|||||||
catalogRepository: catalog,
|
catalogRepository: catalog,
|
||||||
categoryRepository: FakeCategoryRepository(catalog: catalog),
|
categoryRepository: FakeCategoryRepository(catalog: catalog),
|
||||||
watchHistoryRepository: history ?? InMemoryWatchHistoryRepository(),
|
watchHistoryRepository: history ?? InMemoryWatchHistoryRepository(),
|
||||||
favoriteRepository: InMemoryFavoriteRepository(
|
favoriteRepository:
|
||||||
saved: catalog.dramas.map((drama) => drama.id).toSet(),
|
favorite ??
|
||||||
cards: catalog.dramas,
|
InMemoryFavoriteRepository(
|
||||||
),
|
saved: catalog.dramas.map((drama) => drama.id).toSet(),
|
||||||
|
cards: catalog.dramas,
|
||||||
|
),
|
||||||
playbackRepository: FakePlaybackRepository(),
|
playbackRepository: FakePlaybackRepository(),
|
||||||
commentRepository: FakeCommentRepository(),
|
commentRepository: FakeCommentRepository(),
|
||||||
interactionRepository: FakeInteractionRepository(),
|
interactionRepository: FakeInteractionRepository(),
|
||||||
@@ -457,6 +606,105 @@ Future<void> _pumpApp(
|
|||||||
await tester.pumpAndSettle();
|
await tester.pumpAndSettle();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _setSignedIn(SharedPreferencesAsync preferences) async {
|
||||||
|
await preferences.setString('auth.accessToken', 'access');
|
||||||
|
await preferences.setString('auth.refreshToken', 'refresh');
|
||||||
|
await preferences.setString(
|
||||||
|
'auth.user',
|
||||||
|
'{"uid":"U-100","nickname":"Viewer","avatarUrl":""}',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _clearSignedIn(SharedPreferencesAsync preferences) async {
|
||||||
|
await preferences.remove('auth.accessToken');
|
||||||
|
await preferences.remove('auth.refreshToken');
|
||||||
|
await preferences.remove('auth.user');
|
||||||
|
}
|
||||||
|
|
||||||
|
class _IdentityMineFavoriteRepository implements FavoriteRepository {
|
||||||
|
_IdentityMineFavoriteRepository({
|
||||||
|
required List<Drama> device,
|
||||||
|
required List<Drama> account,
|
||||||
|
}) : _cards = {'device': device, 'account': account};
|
||||||
|
|
||||||
|
final Map<String, List<Drama>> _cards;
|
||||||
|
String scope = 'device';
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<PageResult<Drama>> page({int pageIndex = 1, int pageSize = 20}) async {
|
||||||
|
final cards = _cards[scope]!;
|
||||||
|
final offset = (pageIndex - 1) * pageSize;
|
||||||
|
return PageResult(
|
||||||
|
total: cards.length,
|
||||||
|
list: offset >= cards.length
|
||||||
|
? const []
|
||||||
|
: cards.skip(offset).take(pageSize).toList(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> remove(String dramaId) async {
|
||||||
|
_cards[scope]!.removeWhere((drama) => drama.id == dramaId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> removeMany(List<String> dramaIds) async {
|
||||||
|
final ids = dramaIds.toSet();
|
||||||
|
_cards[scope]!.removeWhere((drama) => ids.contains(drama.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> toggle(String dramaId) async => true;
|
||||||
|
}
|
||||||
|
|
||||||
|
class _IdentityMineWatchHistoryRepository implements WatchHistoryRepository {
|
||||||
|
_IdentityMineWatchHistoryRepository({
|
||||||
|
required List<WatchProgress> device,
|
||||||
|
required List<WatchProgress> account,
|
||||||
|
}) : _records = {'device': device, 'account': account};
|
||||||
|
|
||||||
|
final Map<String, List<WatchProgress>> _records;
|
||||||
|
String scope = 'device';
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> clear() async => _records[scope]!.clear();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<WatchProgress?> progressFor(String dramaId) async {
|
||||||
|
return _records[scope]!
|
||||||
|
.where((record) => record.dramaId == dramaId)
|
||||||
|
.firstOrNull;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<PageResult<WatchProgress>> recent({
|
||||||
|
int pageIndex = 1,
|
||||||
|
int pageSize = 20,
|
||||||
|
}) async {
|
||||||
|
final records = _records[scope]!;
|
||||||
|
final offset = (pageIndex - 1) * pageSize;
|
||||||
|
return PageResult(
|
||||||
|
total: records.length,
|
||||||
|
list: offset >= records.length
|
||||||
|
? const []
|
||||||
|
: records.skip(offset).take(pageSize).toList(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> remove(String dramaId) async {
|
||||||
|
_records[scope]!.removeWhere((record) => record.dramaId == dramaId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<WatchProgress?> save({
|
||||||
|
required String episodeId,
|
||||||
|
required Duration position,
|
||||||
|
Duration? duration,
|
||||||
|
bool finished = false,
|
||||||
|
}) async => null;
|
||||||
|
}
|
||||||
|
|
||||||
class _MineWalletCommerceRepository implements CommerceRepository {
|
class _MineWalletCommerceRepository implements CommerceRepository {
|
||||||
const _MineWalletCommerceRepository();
|
const _MineWalletCommerceRepository();
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:fruitshorts/core/data/services/interaction_controller.dart';
|
import 'package:fruitshorts/core/data/services/interaction_controller.dart';
|
||||||
|
import 'package:fruitshorts/core/theme/app_colors.dart';
|
||||||
import 'package:fruitshorts/core/theme/app_theme.dart';
|
import 'package:fruitshorts/core/theme/app_theme.dart';
|
||||||
import 'package:fruitshorts/l10n/app_localizations.dart';
|
import 'package:fruitshorts/l10n/app_localizations.dart';
|
||||||
import 'package:fruitshorts/pages/player/widgets/home_feed_overlay.dart';
|
import 'package:fruitshorts/pages/player/widgets/home_feed_overlay.dart';
|
||||||
@@ -41,13 +42,13 @@ void main() {
|
|||||||
);
|
);
|
||||||
expect(repository.likeTargets, hasLength(1));
|
expect(repository.likeTargets, hasLength(1));
|
||||||
expect(haptics.lightImpacts, 1);
|
expect(haptics.lightImpacts, 1);
|
||||||
expect(
|
final likeImage = tester.widget<Image>(
|
||||||
find.descendant(
|
find.descendant(
|
||||||
of: find.byKey(const Key('rail-like')),
|
of: find.byKey(const Key('rail-like')),
|
||||||
matching: find.byIcon(Icons.favorite_rounded),
|
matching: find.byType(Image),
|
||||||
),
|
),
|
||||||
findsOneWidget,
|
|
||||||
);
|
);
|
||||||
|
expect(likeImage.color, AppColors.doubleTapHeartRed);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -630,6 +630,53 @@ void main() {
|
|||||||
expect(interactions.likeTargets, ['EPISODE:the-signal-demo-1']);
|
expect(interactions.likeTargets, ['EPISODE:the-signal-demo-1']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
testWidgets('should_keep_favorite_count_when_player_saves_and_returns', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await _pumpApp(tester);
|
||||||
|
await tester.tap(find.byKey(const Key('tab-recommend')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
final initialCount = _railLabel(tester, const Key('rail-save'));
|
||||||
|
await tester.tap(find.byKey(const Key('home-feed-series-name')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(_railLabel(tester, const Key('player-rail-save')), initialCount);
|
||||||
|
await tester.tap(find.byKey(const Key('player-rail-save')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
final savedCount = _railLabel(tester, const Key('player-rail-save'));
|
||||||
|
expect(savedCount, isNot(initialCount));
|
||||||
|
await tester.tap(find.byKey(const Key('player-back')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.byType(AuthPage), findsNothing);
|
||||||
|
expect(_railLabel(tester, const Key('rail-save')), savedCount);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('should_keep_favorite_state_when_recommend_opens_player', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await _pumpApp(tester);
|
||||||
|
await tester.tap(find.byKey(const Key('tab-recommend')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.byKey(const Key('rail-save')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
final savedCount = _railLabel(tester, const Key('rail-save'));
|
||||||
|
|
||||||
|
await tester.tap(find.byKey(const Key('home-feed-series-name')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(_railLabel(tester, const Key('player-rail-save')), savedCount);
|
||||||
|
final saveImage = tester.widget<Image>(
|
||||||
|
find.descendant(
|
||||||
|
of: find.byKey(const Key('player-rail-save')),
|
||||||
|
matching: find.byType(Image),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(saveImage.color, AppColors.blue);
|
||||||
|
});
|
||||||
|
|
||||||
testWidgets('should_keep_video_surface_background_black', (tester) async {
|
testWidgets('should_keep_video_surface_background_black', (tester) async {
|
||||||
await _pumpApp(tester);
|
await _pumpApp(tester);
|
||||||
await _openSeriesPlayer(tester);
|
await _openSeriesPlayer(tester);
|
||||||
@@ -646,9 +693,7 @@ void main() {
|
|||||||
expect(find.byKey(const Key('player-fallback-scrim')), findsNothing);
|
expect(find.byKey(const Key('player-fallback-scrim')), findsNothing);
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('should_open_comments_without_login', (
|
testWidgets('should_open_comments_without_login', (tester) async {
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await _pumpApp(tester);
|
await _pumpApp(tester);
|
||||||
await _openSeriesPlayer(tester);
|
await _openSeriesPlayer(tester);
|
||||||
|
|
||||||
@@ -1306,6 +1351,17 @@ void main() {
|
|||||||
expect(shareImage.width, 32);
|
expect(shareImage.width, 32);
|
||||||
expect(shareImage.height, 32);
|
expect(shareImage.height, 32);
|
||||||
expect(shareImage.colorBlendMode, BlendMode.srcIn);
|
expect(shareImage.colorBlendMode, BlendMode.srcIn);
|
||||||
|
final saveRect = tester.getRect(find.byKey(const Key('player-rail-save')));
|
||||||
|
final commentsRect = tester.getRect(
|
||||||
|
find.byKey(const Key('player-rail-comments')),
|
||||||
|
);
|
||||||
|
final likeRect = tester.getRect(find.byKey(const Key('player-rail-like')));
|
||||||
|
final shareRect = tester.getRect(
|
||||||
|
find.byKey(const Key('player-rail-share')),
|
||||||
|
);
|
||||||
|
expect(likeRect.top - saveRect.bottom, closeTo(24, 0.1));
|
||||||
|
expect(commentsRect.top - likeRect.bottom, closeTo(24, 0.1));
|
||||||
|
expect(shareRect.top - commentsRect.bottom, closeTo(24, 0.1));
|
||||||
|
|
||||||
final saveButton = tester.widget<IconButton>(
|
final saveButton = tester.widget<IconButton>(
|
||||||
find.descendant(
|
find.descendant(
|
||||||
@@ -1914,7 +1970,6 @@ void main() {
|
|||||||
find.text('Available unlock methods vary by title.'),
|
find.text('Available unlock methods vary by title.'),
|
||||||
findsOneWidget,
|
findsOneWidget,
|
||||||
);
|
);
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('should_require_login_before_opening_unlock_flow', (
|
testWidgets('should_require_login_before_opening_unlock_flow', (
|
||||||
|
|||||||
@@ -0,0 +1,360 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:fruitshorts/core/data/services/category_controller.dart';
|
||||||
|
import 'package:fruitshorts/core/data/services/home_feed_controller.dart';
|
||||||
|
import 'package:fruitshorts/l10n/app_localizations.dart';
|
||||||
|
import 'package:fruitshorts/pages/home/home_feed_channel.dart';
|
||||||
|
import 'package:fruitshorts/pages/recommend/recommend_page.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
|
import '../support/fake_catalog.dart';
|
||||||
|
import '../support/fake_category.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('should_show_skeleton_before_feed_is_loaded', (tester) async {
|
||||||
|
await _pumpRecommend(tester, active: false);
|
||||||
|
|
||||||
|
expect(find.byKey(const Key('recommend-feed-skeleton')), findsOneWidget);
|
||||||
|
expect(find.byKey(const Key('recommend-feed-empty')), findsNothing);
|
||||||
|
expect(find.text('Retry'), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('should_refresh_once_when_parent_rebuilds_repeatedly', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final fixture = await _pumpRecommend(tester, active: true);
|
||||||
|
|
||||||
|
expect(fixture.controller.refreshCalls, 1);
|
||||||
|
for (var index = 0; index < 20; index++) {
|
||||||
|
fixture.harnessKey.currentState!.rebuildSameInputs();
|
||||||
|
await tester.pump();
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(tester.takeException(), isNull);
|
||||||
|
expect(fixture.controller.refreshCalls, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('should_refresh_once_when_active_turns_on', (tester) async {
|
||||||
|
final fixture = await _pumpRecommend(tester, active: false);
|
||||||
|
expect(fixture.controller.refreshCalls, 0);
|
||||||
|
|
||||||
|
fixture.harnessKey.currentState!.update(active: true);
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(fixture.controller.refreshCalls, 1);
|
||||||
|
fixture.harnessKey.currentState!.rebuildSameInputs();
|
||||||
|
await tester.pump();
|
||||||
|
expect(fixture.controller.refreshCalls, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('should_refresh_again_when_data_source_changes', (tester) async {
|
||||||
|
final fixture = await _pumpRecommend(tester, active: true);
|
||||||
|
expect(fixture.controller.refreshCalls, 1);
|
||||||
|
|
||||||
|
fixture.harnessKey.currentState!.update(active: false);
|
||||||
|
await tester.pump();
|
||||||
|
expect(fixture.controller.refreshCalls, 1);
|
||||||
|
|
||||||
|
fixture.harnessKey.currentState!.update(active: true);
|
||||||
|
await tester.pump();
|
||||||
|
expect(fixture.controller.refreshCalls, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('should_auto_retry_three_times_then_show_network_error', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final fixture = await _pumpFailingRecommend(tester);
|
||||||
|
|
||||||
|
expect(fixture.controller.refreshCalls, 1);
|
||||||
|
expect(find.byKey(const Key('recommend-feed-skeleton')), findsOneWidget);
|
||||||
|
expect(find.byKey(const Key('recommend-feed-empty')), findsNothing);
|
||||||
|
|
||||||
|
for (var attempt = 0; attempt < 3; attempt++) {
|
||||||
|
await tester.pump(const Duration(milliseconds: 1500));
|
||||||
|
await tester.pump();
|
||||||
|
expect(fixture.controller.refreshCalls, attempt + 2);
|
||||||
|
if (attempt < 2) {
|
||||||
|
expect(
|
||||||
|
find.byKey(const Key('recommend-feed-skeleton')),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
expect(find.byKey(const Key('recommend-feed-empty')), findsNothing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final l10n = AppLocalizations.of(
|
||||||
|
tester.element(find.byType(RecommendPage)),
|
||||||
|
)!;
|
||||||
|
expect(fixture.controller.refreshCalls, 4);
|
||||||
|
expect(find.byKey(const Key('recommend-feed-skeleton')), findsNothing);
|
||||||
|
expect(find.byKey(const Key('recommend-feed-empty')), findsOneWidget);
|
||||||
|
expect(find.text(l10n.networkError), findsOneWidget);
|
||||||
|
expect(find.text(l10n.retry), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('should_cancel_pending_auto_retry_when_disposed', (tester) async {
|
||||||
|
final fixture = await _pumpFailingRecommend(tester);
|
||||||
|
expect(fixture.controller.refreshCalls, 1);
|
||||||
|
|
||||||
|
await tester.pumpWidget(const MaterialApp(home: SizedBox.shrink()));
|
||||||
|
await tester.pump(const Duration(seconds: 2));
|
||||||
|
|
||||||
|
expect(fixture.controller.refreshCalls, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'should_show_no_stories_without_retry_when_loaded_feed_is_empty',
|
||||||
|
(tester) async {
|
||||||
|
final fixture = await _pumpEmptyRecommend(tester);
|
||||||
|
|
||||||
|
final l10n = AppLocalizations.of(
|
||||||
|
tester.element(find.byType(RecommendPage)),
|
||||||
|
)!;
|
||||||
|
expect(fixture.controller.refreshCalls, 1);
|
||||||
|
expect(find.byKey(const Key('recommend-feed-skeleton')), findsNothing);
|
||||||
|
expect(find.byKey(const Key('recommend-feed-empty')), findsOneWidget);
|
||||||
|
expect(find.text(l10n.noStories), findsOneWidget);
|
||||||
|
expect(find.text(l10n.retry), findsNothing);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('should_not_refresh_after_dispose_when_channel_changes', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final fixture = await _pumpRecommend(tester, active: true);
|
||||||
|
expect(fixture.controller.refreshCalls, 1);
|
||||||
|
|
||||||
|
fixture.harnessKey.currentState!.update(active: true);
|
||||||
|
final selection = fixture.controller.selectChannel(HomeFeedChannel.anime);
|
||||||
|
await tester.pumpWidget(const MaterialApp(home: SizedBox.shrink()));
|
||||||
|
await selection;
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(fixture.controller.refreshCalls, 1);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<_RecommendFixture> _pumpRecommend(
|
||||||
|
WidgetTester tester, {
|
||||||
|
required bool active,
|
||||||
|
}) async {
|
||||||
|
tester.view.physicalSize = const Size(390, 844);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
|
||||||
|
final catalog = FakeCatalogRepository();
|
||||||
|
final controller = _RecordingHomeFeedController(catalog);
|
||||||
|
final categories = CategoryController(
|
||||||
|
FakeCategoryRepository(catalog: catalog),
|
||||||
|
);
|
||||||
|
final harnessKey = GlobalKey<_RecommendHarnessState>();
|
||||||
|
final fixture = _RecommendFixture(
|
||||||
|
controller: controller,
|
||||||
|
categoryController: categories,
|
||||||
|
harnessKey: harnessKey,
|
||||||
|
);
|
||||||
|
addTearDown(controller.dispose);
|
||||||
|
addTearDown(categories.dispose);
|
||||||
|
|
||||||
|
await tester.pumpWidget(fixture.app(active: active));
|
||||||
|
await tester.pump();
|
||||||
|
return fixture;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<_StatefulRecommendFixture> _pumpFailingRecommend(
|
||||||
|
WidgetTester tester,
|
||||||
|
) async {
|
||||||
|
tester.view.physicalSize = const Size(390, 844);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
|
||||||
|
final catalog = FakeCatalogRepository();
|
||||||
|
final controller = _StatefulHomeFeedController(catalog);
|
||||||
|
final categories = CategoryController(
|
||||||
|
FakeCategoryRepository(catalog: catalog),
|
||||||
|
);
|
||||||
|
addTearDown(controller.dispose);
|
||||||
|
addTearDown(categories.dispose);
|
||||||
|
|
||||||
|
final fixture = _StatefulRecommendFixture(
|
||||||
|
controller: controller,
|
||||||
|
categoryController: categories,
|
||||||
|
);
|
||||||
|
await tester.pumpWidget(fixture.app());
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 1));
|
||||||
|
return fixture;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<_StatefulRecommendFixture> _pumpEmptyRecommend(
|
||||||
|
WidgetTester tester,
|
||||||
|
) async {
|
||||||
|
tester.view.physicalSize = const Size(390, 844);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
|
||||||
|
final catalog = FakeCatalogRepository();
|
||||||
|
final controller = _StatefulHomeFeedController(catalog, fail: false);
|
||||||
|
final categories = CategoryController(
|
||||||
|
FakeCategoryRepository(catalog: catalog),
|
||||||
|
);
|
||||||
|
addTearDown(controller.dispose);
|
||||||
|
addTearDown(categories.dispose);
|
||||||
|
|
||||||
|
final fixture = _StatefulRecommendFixture(
|
||||||
|
controller: controller,
|
||||||
|
categoryController: categories,
|
||||||
|
);
|
||||||
|
await tester.pumpWidget(fixture.app());
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 1));
|
||||||
|
return fixture;
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RecommendFixture {
|
||||||
|
const _RecommendFixture({
|
||||||
|
required this.controller,
|
||||||
|
required this.categoryController,
|
||||||
|
required this.harnessKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
final _RecordingHomeFeedController controller;
|
||||||
|
final CategoryController categoryController;
|
||||||
|
final GlobalKey<_RecommendHarnessState> harnessKey;
|
||||||
|
|
||||||
|
Widget app({required bool active}) {
|
||||||
|
return MaterialApp(
|
||||||
|
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||||
|
supportedLocales: AppLocalizations.supportedLocales,
|
||||||
|
home: ChangeNotifierProvider<CategoryController>.value(
|
||||||
|
value: categoryController,
|
||||||
|
child: _RecommendHarness(
|
||||||
|
key: harnessKey,
|
||||||
|
controller: controller,
|
||||||
|
active: active,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _StatefulRecommendFixture {
|
||||||
|
const _StatefulRecommendFixture({
|
||||||
|
required this.controller,
|
||||||
|
required this.categoryController,
|
||||||
|
});
|
||||||
|
|
||||||
|
final _StatefulHomeFeedController controller;
|
||||||
|
final CategoryController categoryController;
|
||||||
|
|
||||||
|
Widget app() {
|
||||||
|
return MaterialApp(
|
||||||
|
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||||
|
supportedLocales: AppLocalizations.supportedLocales,
|
||||||
|
home: ChangeNotifierProvider<CategoryController>.value(
|
||||||
|
value: categoryController,
|
||||||
|
child: RecommendPage(
|
||||||
|
feedController: controller,
|
||||||
|
active: true,
|
||||||
|
videoOnly: true,
|
||||||
|
onSearch: () {},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RecommendHarness extends StatefulWidget {
|
||||||
|
const _RecommendHarness({
|
||||||
|
super.key,
|
||||||
|
required this.controller,
|
||||||
|
required this.active,
|
||||||
|
});
|
||||||
|
|
||||||
|
final HomeFeedController controller;
|
||||||
|
final bool active;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_RecommendHarness> createState() => _RecommendHarnessState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RecommendHarnessState extends State<_RecommendHarness> {
|
||||||
|
late HomeFeedController _controller;
|
||||||
|
late bool _active;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_controller = widget.controller;
|
||||||
|
_active = widget.active;
|
||||||
|
}
|
||||||
|
|
||||||
|
void rebuildSameInputs() {
|
||||||
|
setState(() {});
|
||||||
|
}
|
||||||
|
|
||||||
|
void update({required bool active}) {
|
||||||
|
setState(() {
|
||||||
|
_active = active;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return RecommendPage(
|
||||||
|
feedController: _controller,
|
||||||
|
active: _active,
|
||||||
|
videoOnly: true,
|
||||||
|
onSearch: () {},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _RecordingHomeFeedController extends HomeFeedController {
|
||||||
|
_RecordingHomeFeedController(super.repository);
|
||||||
|
|
||||||
|
int refreshCalls = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> refreshCurrent() async {
|
||||||
|
refreshCalls++;
|
||||||
|
notifyListeners();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _StatefulHomeFeedController extends HomeFeedController {
|
||||||
|
_StatefulHomeFeedController(super.repository, {this.fail = true});
|
||||||
|
|
||||||
|
final bool fail;
|
||||||
|
int refreshCalls = 0;
|
||||||
|
bool _loaded = false;
|
||||||
|
bool _isLoading = false;
|
||||||
|
String? _lastError;
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool get loaded => _loaded;
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool get isLoading => _isLoading;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String? get lastError => _lastError;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> refreshCurrent() async {
|
||||||
|
refreshCalls++;
|
||||||
|
_isLoading = true;
|
||||||
|
_lastError = null;
|
||||||
|
notifyListeners();
|
||||||
|
await Future<void>.delayed(Duration.zero);
|
||||||
|
_isLoading = false;
|
||||||
|
_loaded = true;
|
||||||
|
if (fail) _lastError = 'network error';
|
||||||
|
notifyListeners();
|
||||||
|
return !fail;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,6 +26,8 @@ void main() {
|
|||||||
expect(AppColors.cardAlt, const Color(0xFF101010));
|
expect(AppColors.cardAlt, const Color(0xFF101010));
|
||||||
expect(AppColors.raised, const Color(0xFF1C1C1E));
|
expect(AppColors.raised, const Color(0xFF1C1C1E));
|
||||||
expect(AppColors.border, const Color(0xFF1C1C1E));
|
expect(AppColors.border, const Color(0xFF1C1C1E));
|
||||||
|
expect(AppColors.skeletonSurface, const Color(0xFF0E0E0E));
|
||||||
|
expect(AppColors.skeletonMedia, const Color(0xFF1C1C1E));
|
||||||
expect(AppColors.textPrimary, const Color(0xFFFFFFFF));
|
expect(AppColors.textPrimary, const Color(0xFFFFFFFF));
|
||||||
expect(AppColors.textSecondary, const Color(0xFFB0B0B0));
|
expect(AppColors.textSecondary, const Color(0xFFB0B0B0));
|
||||||
expect(AppColors.textTertiary, const Color(0xFF8E8E93));
|
expect(AppColors.textTertiary, const Color(0xFF8E8E93));
|
||||||
|
|||||||
@@ -4,8 +4,11 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:fruitshorts/core/data/remote/api_client.dart';
|
import 'package:fruitshorts/core/data/remote/api_client.dart';
|
||||||
import 'package:fruitshorts/core/data/remote/auth_api.dart';
|
import 'package:fruitshorts/core/data/remote/auth_api.dart';
|
||||||
|
import 'package:fruitshorts/core/data/repositories/catalog_repository.dart';
|
||||||
|
import 'package:fruitshorts/core/data/repositories/watch_history_repository.dart';
|
||||||
import 'package:fruitshorts/core/data/services/auth_controller.dart';
|
import 'package:fruitshorts/core/data/services/auth_controller.dart';
|
||||||
import 'package:fruitshorts/core/data/services/auth_session_store.dart';
|
import 'package:fruitshorts/core/data/services/auth_session_store.dart';
|
||||||
|
import 'package:fruitshorts/core/platform/haptics.dart';
|
||||||
import 'package:fruitshorts/core/theme/app_colors.dart';
|
import 'package:fruitshorts/core/theme/app_colors.dart';
|
||||||
import 'package:fruitshorts/core/theme/app_theme.dart';
|
import 'package:fruitshorts/core/theme/app_theme.dart';
|
||||||
import 'package:fruitshorts/l10n/app_localizations.dart';
|
import 'package:fruitshorts/l10n/app_localizations.dart';
|
||||||
@@ -15,6 +18,8 @@ import 'package:shared_preferences_platform_interface/in_memory_shared_preferenc
|
|||||||
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
|
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
|
||||||
|
|
||||||
import '../support/fake_http_adapter.dart';
|
import '../support/fake_http_adapter.dart';
|
||||||
|
import '../support/fake_catalog.dart';
|
||||||
|
import '../support/fake_haptics.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
setUp(() {
|
setUp(() {
|
||||||
@@ -92,8 +97,15 @@ void main() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
await tester.pumpWidget(
|
await tester.pumpWidget(
|
||||||
ChangeNotifierProvider<AuthController>.value(
|
MultiProvider(
|
||||||
value: auth,
|
providers: [
|
||||||
|
ChangeNotifierProvider<AuthController>.value(value: auth),
|
||||||
|
Provider<WatchHistoryRepository>.value(
|
||||||
|
value: InMemoryWatchHistoryRepository(),
|
||||||
|
),
|
||||||
|
Provider<CatalogRepository>.value(value: FakeCatalogRepository()),
|
||||||
|
Provider<Haptics>.value(value: FakeHaptics()),
|
||||||
|
],
|
||||||
child: MaterialApp(
|
child: MaterialApp(
|
||||||
theme: AppTheme.dark(),
|
theme: AppTheme.dark(),
|
||||||
darkTheme: AppTheme.dark(),
|
darkTheme: AppTheme.dark(),
|
||||||
@@ -111,7 +123,8 @@ void main() {
|
|||||||
find.byKey(const Key('watch-records-page')),
|
find.byKey(const Key('watch-records-page')),
|
||||||
);
|
);
|
||||||
expect(scaffold.backgroundColor, AppColors.ink);
|
expect(scaffold.backgroundColor, AppColors.ink);
|
||||||
expect(find.byKey(const Key('auth-gate-panel')), findsOneWidget);
|
expect(find.byKey(const Key('auth-gate-panel')), findsNothing);
|
||||||
|
expect(find.byKey(const Key('watch-records-empty')), findsOneWidget);
|
||||||
expect(find.byType(Scaffold), findsOneWidget);
|
expect(find.byType(Scaffold), findsOneWidget);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@ import 'dart:convert';
|
|||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:fruitshorts/core/data/remote/api_client.dart';
|
import 'package:fruitshorts/core/data/remote/api_client.dart';
|
||||||
import 'package:fruitshorts/core/data/remote/watch_api.dart';
|
import 'package:fruitshorts/core/data/remote/watch_api.dart';
|
||||||
|
import 'package:fruitshorts/core/data/repositories/watch_history_repository.dart';
|
||||||
|
|
||||||
import '../support/fake_http_adapter.dart';
|
import '../support/fake_http_adapter.dart';
|
||||||
|
|
||||||
@@ -94,4 +95,60 @@ void main() {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('should_allow_guest_watch_read_save_and_clear', () async {
|
||||||
|
final adapter = FakeHttpAdapter((options) async {
|
||||||
|
if (options.method == 'GET' && options.uri.path.endsWith('/progress')) {
|
||||||
|
return FakeHttpResponse(
|
||||||
|
jsonEncode({
|
||||||
|
'code': 0,
|
||||||
|
'message': 'ok',
|
||||||
|
'data': {
|
||||||
|
'dramaId': '12',
|
||||||
|
'episodeId': '88',
|
||||||
|
'positionMs': '8000',
|
||||||
|
'durationMs': '60000',
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (options.method == 'GET') {
|
||||||
|
return FakeHttpResponse(
|
||||||
|
jsonEncode({
|
||||||
|
'code': 0,
|
||||||
|
'message': 'ok',
|
||||||
|
'data': {'total': '0', 'list': <Object>[]},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return FakeHttpResponse(
|
||||||
|
jsonEncode({'code': 0, 'message': 'ok', 'data': null}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
final repository = HttpWatchHistoryRepository(
|
||||||
|
WatchApi(ApiClient(baseUrl: 'http://127.0.0.1:8081', adapter: adapter)),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect((await repository.progressFor('12'))?.episodeId, '88');
|
||||||
|
expect((await repository.recent()).list, isEmpty);
|
||||||
|
await repository.save(
|
||||||
|
episodeId: '88',
|
||||||
|
position: const Duration(seconds: 8),
|
||||||
|
);
|
||||||
|
await repository.remove('12');
|
||||||
|
await repository.clear();
|
||||||
|
|
||||||
|
expect(
|
||||||
|
adapter.requests.map(
|
||||||
|
(request) => '${request.method} ${request.uri.path}',
|
||||||
|
),
|
||||||
|
[
|
||||||
|
'GET /app/watch/progress',
|
||||||
|
'GET /app/watch/recent',
|
||||||
|
'POST /app/watch/progress',
|
||||||
|
'DELETE /app/watch/progress/12',
|
||||||
|
'DELETE /app/watch/progress',
|
||||||
|
],
|
||||||
|
);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
@@ -174,9 +174,7 @@ void main() {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
testWidgets('should_show_auth_gate_without_loading_records_when_signed_out', (
|
testWidgets('should_show_device_history_when_signed_out', (tester) async {
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final auth = await _auth(signedIn: false);
|
final auth = await _auth(signedIn: false);
|
||||||
final history = CountingWatchHistory([_progress('the-signal-demo')]);
|
final history = CountingWatchHistory([_progress('the-signal-demo')]);
|
||||||
|
|
||||||
@@ -187,8 +185,59 @@ void main() {
|
|||||||
catalog: FakeCatalogRepository(),
|
catalog: FakeCatalogRepository(),
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(find.byKey(const Key('auth-gate-panel')), findsOneWidget);
|
expect(find.byKey(const Key('auth-gate-panel')), findsNothing);
|
||||||
expect(history.recentCalls, 0);
|
expect(find.text('The Signal'), findsOneWidget);
|
||||||
|
expect(history.recentCalls, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('should_reload_device_history_after_login', (tester) async {
|
||||||
|
final auth = _ToggleAuthController();
|
||||||
|
final history = CountingWatchHistory([_progress('the-signal-demo')]);
|
||||||
|
await _pumpPage(
|
||||||
|
tester,
|
||||||
|
auth: auth,
|
||||||
|
history: history,
|
||||||
|
catalog: FakeCatalogRepository(),
|
||||||
|
);
|
||||||
|
expect(history.recentCalls, 1);
|
||||||
|
|
||||||
|
auth.setSignedIn(true);
|
||||||
|
await tester.pump();
|
||||||
|
await tester.pump(const Duration(milliseconds: 50));
|
||||||
|
|
||||||
|
expect(history.recentCalls, 2);
|
||||||
|
expect(find.text('The Signal'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('should_remove_and_clear_device_history_when_signed_out', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final auth = await _auth(signedIn: false);
|
||||||
|
final history = CountingWatchHistory([
|
||||||
|
_progress('the-signal-demo'),
|
||||||
|
_progress('city-lights-demo'),
|
||||||
|
]);
|
||||||
|
await _pumpPage(
|
||||||
|
tester,
|
||||||
|
auth: auth,
|
||||||
|
history: history,
|
||||||
|
catalog: FakeCatalogRepository(),
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.tap(
|
||||||
|
find.byKey(const Key('watch-record-remove-the-signal-demo')),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byKey(const Key('watch-record-the-signal-demo')), findsNothing);
|
||||||
|
expect(history.removeCalls, 1);
|
||||||
|
|
||||||
|
await tester.tap(find.byKey(const Key('watch-records-clear')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.widgetWithText(FilledButton, 'Clear'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(history.clearCalls, 1);
|
||||||
|
expect(find.byKey(const Key('watch-records-empty')), findsOneWidget);
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets(
|
testWidgets(
|
||||||
@@ -313,9 +362,17 @@ Future<AuthController> _auth({required bool signedIn}) async {
|
|||||||
}
|
}
|
||||||
final client = ApiClient(
|
final client = ApiClient(
|
||||||
baseUrl: 'http://127.0.0.1:8081',
|
baseUrl: 'http://127.0.0.1:8081',
|
||||||
adapter: FakeHttpAdapter(
|
adapter: FakeHttpAdapter((options) async {
|
||||||
(_) async => FakeHttpResponse('{"code":0,"message":"ok","data":null}'),
|
if (options.uri.path == '/app/auth/login') {
|
||||||
),
|
return FakeHttpResponse(
|
||||||
|
'{"code":0,"message":"ok","data":{'
|
||||||
|
'"accessToken":"test-access","refreshToken":"test-refresh",'
|
||||||
|
'"expiresIn":7200,"user":{"uid":"1","nickname":"Viewer",'
|
||||||
|
'"avatarUrl":""}}}',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return FakeHttpResponse('{"code":0,"message":"ok","data":null}');
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
final auth = AuthController(AuthApi(client), AuthSessionStore());
|
final auth = AuthController(AuthApi(client), AuthSessionStore());
|
||||||
await auth.load();
|
await auth.load();
|
||||||
@@ -353,6 +410,7 @@ class CountingWatchHistory extends InMemoryWatchHistoryRepository {
|
|||||||
|
|
||||||
final List<WatchProgress> visibleRecords;
|
final List<WatchProgress> visibleRecords;
|
||||||
int recentCalls = 0;
|
int recentCalls = 0;
|
||||||
|
int removeCalls = 0;
|
||||||
int clearCalls = 0;
|
int clearCalls = 0;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -371,6 +429,12 @@ class CountingWatchHistory extends InMemoryWatchHistoryRepository {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> remove(String dramaId) async {
|
||||||
|
removeCalls++;
|
||||||
|
await super.remove(dramaId);
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<void> clear() async {
|
Future<void> clear() async {
|
||||||
clearCalls++;
|
clearCalls++;
|
||||||
@@ -440,3 +504,30 @@ class _AlwaysFailingWatchCatalog implements CatalogRepository {
|
|||||||
@override
|
@override
|
||||||
Future<HomeFeed> fetchHomeFeed() async => const HomeFeed();
|
Future<HomeFeed> fetchHomeFeed() async => const HomeFeed();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class _ToggleAuthController extends AuthController {
|
||||||
|
_ToggleAuthController()
|
||||||
|
: super(
|
||||||
|
AuthApi(
|
||||||
|
ApiClient(
|
||||||
|
baseUrl: 'http://127.0.0.1:8081',
|
||||||
|
adapter: FakeHttpAdapter(
|
||||||
|
(_) async =>
|
||||||
|
FakeHttpResponse('{"code":0,"message":"ok","data":null}'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
AuthSessionStore(),
|
||||||
|
);
|
||||||
|
|
||||||
|
bool _signedIn = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool get isSignedIn => _signedIn;
|
||||||
|
|
||||||
|
void setSignedIn(bool value) {
|
||||||
|
if (_signedIn == value) return;
|
||||||
|
_signedIn = value;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user