feat: 主页账号备份,并修好 B50 预览缩不小

账号备份(AccountBackupCard + AccountBackupService):
- 并发读 GetUserData/Extend/Option/Rating/Charge/Activity/MissionData +
  Character + Map(分页)+ KaleidxScope + 各 itemKind 的 GetUserItemApi,
  汇成一个 JSON 字符串可复制到剪贴板。舞里程与总游玩数据本就在
  userData 的 point/totalPoint/playCount 里。
- itemKind 15(KaleidxScopeKey)不列进回读清单:客户端 ExportUserItems
  从不输出它,下行也没有读它的路径,钥匙实际是
  userKaleidxScopeList[].isKeyFound。
- 全程只发 GetUser*Api,不碰 UpsertUserAllApi。
- 逐段容错:私服没实现某个接口时其余照样备出,失败段单独列出——
  「读到但是空的」和「没读到」在 userItemList 里按 kind 分开存,可区分。
- 取数与拼装分开,buildBackupDocument/encode 部分是纯函数,单测覆盖。

B50 预览:原因是 InteractiveViewer(constrained:false) 给孩子无界约束,
FittedBox(fit: fitWidth) 在无界下根本不缩放,海报按 1762x1850 原尺寸铺开;
而 minScale 又算成 1.0,于是既巨大又缩不动。改为给一个 contain 尺寸的
有限盒子让 FittedBox 真正缩放,minScale 固定 1.0(这个版本没有
initialScale 可用)。RepaintBoundary 留在 FittedBox 内侧,绘制尺寸仍是
1762x1850,导出分辨率不受影响,并加了断言守住这点。
This commit is contained in:
Cookiues committed 2026-10-02 12:26:03 +08:00
1 parent a5fb2c97cd
commit 0cb5320290
8 files changed
+524 -36

No files matched your search

+17
View File
@@ -37,6 +37,23 @@ class AppStrings {
static const connectionShareEmpty = '当前会话既没有 Cookie 也没有令牌,无法导出。';
static const restoreSession = '恢复会话';
static const restoringSession = '恢复中...';
// 账号备份:把服务器可读到的用户数据汇成一个 JSON 字符串
static const accountBackupTitle = '账号备份';
static const accountBackupDesc =
'只读地把服务器上的用户数据汇成一串 JSON:道具清单、舞里程、游玩统计、'
'旅行伙伴、区域进度、万花筒进度、Rating 与成绩等。全程只发 GetUser* 接口,'
'不会写任何数据。';
static const accountBackupRun = '生成备份';
static String accountBackupRunning(String section) =>
section.isEmpty ? '备份中...' : '备份中:$section';
static const accountBackupCopy = '复制到剪贴板';
static const accountBackupCopied = '备份内容已复制到剪贴板';
static String accountBackupSize(String size) => '共 $size';
static String accountBackupPartial(List<String> failures) =>
'${failures.length} 段没读到(私服可能未实现该接口),其余照常:'
'${failures.join('、')}';
static const accountBackupSecurity = '备份含账号标识与进度数据;内容未加密,请勿贴到公开场合。';
static const sessionShareDetected = '已识别为连接信息(实验性功能),点击「恢复会话」直接续上这次登录。';
static const sessionRestoreFailed = '会话恢复失败';
static const sessionRestoreCookie =
+32 -21
View File
@@ -232,30 +232,41 @@ class _Best50PageState extends State<Best50Page> {
Expanded(
child: LayoutBuilder(
builder: (context, constraints) {
// 按视口宽度适配:横屏/桌面下海报占满宽度、竖向拖动看全图,
// 而不是被 contain 缩成中间一小块、两侧大片空白。
// minScale 再允许缩到整张可见,导出仍是原始 1762x1850。
// 海报要按视口整体缩放一档,进来才能看见完整一张(之前的现象是
// 「太大且缩不小」)。两处坑:
// 1. InteractiveViewer(constrained:false) 给子节点无界约束,
// 此时 FittedBox 根本不会缩放,必须先给一个有限大小的盒子。
// 2. InteractiveViewer 没有 initialScale,所以「初始就缩到位」
// 只能靠把子节点做成 contain 尺寸、minScale 固定 1.0。
// RepaintBoundary 放在 FittedBox 内侧:它自身的绘制尺寸仍是
// 1762x1850,导出分辨率不受这里缩放影响。
final fitWidth =
constraints.maxWidth / Best50Poster.canvasWidth;
final scaledHeight = Best50Poster.canvasHeight * fitWidth;
final containScale = constraints.maxHeight / scaledHeight;
final minScale = containScale < 1 ? containScale : 1.0;
final fitHeight =
constraints.maxHeight / Best50Poster.canvasHeight;
final contain = fitWidth < fitHeight ? fitWidth : fitHeight;
return InteractiveViewer(
constrained: false,
minScale: minScale,
maxScale: minScale * 6,
boundaryMargin: const EdgeInsets.all(24),
child: FittedBox(
fit: BoxFit.fitWidth,
child: RepaintBoundary(
key: _posterKey,
child: Best50Poster(
userName: widget.userName,
iconId: widget.iconId,
playerRating: widget.playerRating,
best35: best35,
best15: best15,
return Center(
child: InteractiveViewer(
constrained: false,
minScale: 1.0,
maxScale: 10.0,
boundaryMargin: const EdgeInsets.all(24),
child: SizedBox(
width: Best50Poster.canvasWidth * contain,
height: Best50Poster.canvasHeight * contain,
child: FittedBox(
fit: BoxFit.fill,
child: RepaintBoundary(
key: _posterKey,
child: Best50Poster(
userName: widget.userName,
iconId: widget.iconId,
playerRating: widget.playerRating,
best35: best35,
best15: best15,
),
),
),
),
),
+3
View File
@@ -10,6 +10,7 @@ import '../models/session_model.dart';
import '../models/user_data.dart';
import '../models/user_preview.dart';
import '../services/title_api_service.dart';
import '../widgets/account_backup_card.dart';
import '../widgets/app_notice.dart';
import '../widgets/connection_share_card.dart';
import 'about_page.dart';
@@ -539,6 +540,8 @@ class _HomePageState extends State<HomePage> {
),
const SizedBox(height: 12),
ConnectionShareCard(userId: widget.userId, token: widget.token),
const SizedBox(height: 12),
AccountBackupCard(userId: widget.userId, cookies: _session.cookies),
if (TitleApiService.lastRawResponse != null) ...[
const SizedBox(height: 12),
_DebugRawJsonCard(
+117
View File
@@ -0,0 +1,117 @@
import 'dart:convert';
import 'title_api_service.dart';
/// 一次账号备份的结果。
class AccountBackup {
static const int formatVersion = 1;
final Map<String, dynamic> document;
/// 读失败的段名(含原因)。备份不因为单段失败而整体作废——
/// 私服不一定实现了所有 GetUser* 接口。
final List<String> failedSections;
const AccountBackup({required this.document, required this.failedSections});
/// 备份正文就是这一长串 JSON。
String encode() => const JsonEncoder.withIndent(' ').convert(document);
int get byteLength => utf8.encode(encode()).length;
bool get isComplete => failedSections.isEmpty;
}
/// 把已经读到的各段数据拼成备份文档。与取数分开,方便单测。
Map<String, dynamic> buildBackupDocument({
required int userId,
required Map<String, Object?> sections,
DateTime? exportedAt,
}) {
return {
'backupFormat': AccountBackup.formatVersion,
'exportedAt': (exportedAt ?? DateTime.now()).toUtc().toIso8601String(),
'userId': userId,
'data': sections,
};
}
/// 备份要读的道具类别,对应 `Net.VO.Mai2.ItemKind`。
///
/// 只列客户端下行真会读的那些:`StateUserDownload.cs:49-52` 逐个 kind 拉
/// `GetUserItemApi`,而 itemKind 15(KaleidxScopeKey)客户端从不读
/// (钥匙是 `userKaleidxScopeList[].isKeyFound`),所以不在此列。
const List<int> kBackupItemKinds = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12];
/// 读取用户数据并汇总成备份。
///
/// 每段独立容错:某私服没实现某个接口时,其余部分照样能备出来,
/// 失败原因记在 [AccountBackup.failedSections] 里给界面显示。
class AccountBackupService {
final TitleApiService _api;
final int userId;
const AccountBackupService(this._api, {required this.userId});
/// [onSection] 每开始读一段回调一次,供界面显示进度。
Future<AccountBackup> run({void Function(String section)? onSection}) async {
final sections = <String, Object?>{};
final failed = <String>[];
Future<void> gather(String name, Future<Object?> Function() read) async {
onSection?.call(name);
try {
final value = await read();
sections[name] = value;
} catch (e) {
failed.add('$name: $e');
}
}
// 单段一个请求:并发跑,且一段失败不牵连其他段。
await Future.wait([
gather('userData', () => _api.getUserData(userId)),
gather('userExtend', () => _api.getUserExtend(userId)),
gather('userOption', () => _api.getUserOption(userId)),
gather('userRating', () => _api.getUserRating(userId)),
gather('userCharge', () => _api.getUserCharge(userId)),
gather('userActivity', () => _api.getUserActivity(userId)),
gather('userMissionData', () => _api.getUserMissionData(userId)),
gather(
'userCharacterList',
() async => [
for (final c in await _api.getUserCharacters(userId)) c.toWireJson(),
],
),
gather('userMapList', () => _api.getUserMaps(userId)),
gather(
'userKaleidxScopeList',
() async => [
for (final s in await _api.getUserKaleidxScopes(userId))
s.toWireJson(),
],
),
]);
// userItemList 是按 itemKind 分页拉的,按 kind 分组存放,
// 读回时一眼能看出哪类是空的、哪类根本没读到。
final items = <String, Object?>{};
await Future.wait([
for (final kind in kBackupItemKinds)
() async {
onSection?.call('itemKind $kind');
try {
items['$kind'] = await _api.getUserItems(userId, kind);
} catch (e) {
failed.add('userItemList/$kind: $e');
}
}(),
]);
sections['userItemList'] = items;
return AccountBackup(
document: buildBackupDocument(userId: userId, sections: sections),
failedSections: failed,
);
}
}
+184
View File
@@ -0,0 +1,184 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show Clipboard, ClipboardData;
import '../config/strings.dart';
import '../services/account_backup_service.dart';
import '../services/title_api_service.dart';
import 'app_card.dart';
import 'app_notice.dart';
/// 账号备份:把服务器能读到的用户数据汇成一长串 JSON,可复制到剪贴板。
///
/// 只读不写——全程只发 `GetUser*Api`,不会碰 UpsertUserAllApi,所以和
/// 「风险」页那些伪造包相比是安全操作。
class AccountBackupCard extends StatefulWidget {
final int userId;
final String? cookies;
const AccountBackupCard({super.key, required this.userId, this.cookies});
@override
State<AccountBackupCard> createState() => _AccountBackupCardState();
}
class _AccountBackupCardState extends State<AccountBackupCard> {
bool _running = false;
String _progress = '';
AccountBackup? _result;
String? _error;
Future<void> _run() async {
final service = TitleApiService.fromHolder(cookies: widget.cookies);
if (service == null) {
context.showSnack(AppStrings.ticketNotConfigured);
return;
}
setState(() {
_running = true;
_error = null;
_result = null;
_progress = '';
});
try {
final backup = await AccountBackupService(service, userId: widget.userId)
.run(
onSection: (section) {
if (mounted) setState(() => _progress = section);
},
);
if (!mounted) return;
setState(() {
_result = backup;
_running = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_error = '$e';
_running = false;
});
}
}
Future<void> _copy(String text) async {
await Clipboard.setData(ClipboardData(text: text));
if (!mounted) return;
context.showSnack(AppStrings.accountBackupCopied);
}
String _sizeLabel(int bytes) {
if (bytes < 1024) return '$bytes B';
if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
return '${(bytes / 1024 / 1024).toStringAsFixed(2)} MB';
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final result = _result;
return AppCard(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SectionTitle(
icon: Icons.folder_zip_outlined,
title: AppStrings.accountBackupTitle,
),
const SizedBox(height: 10),
Text(
AppStrings.accountBackupDesc,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 14),
SizedBox(
width: double.infinity,
child: FilledButton.tonalIcon(
onPressed: _running ? null : _run,
icon: _running
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.download_outlined, size: 20),
label: Text(
_running
? AppStrings.accountBackupRunning(_progress)
: AppStrings.accountBackupRun,
),
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 13),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
),
if (_error != null) ...[
const SizedBox(height: 12),
AppNotice(_error!, icon: Icons.error_outline, error: true),
],
if (result != null) ...[
const SizedBox(height: 12),
if (!result.isComplete) ...[
AppNotice(
AppStrings.accountBackupPartial(result.failedSections),
icon: Icons.warning_amber_rounded,
),
const SizedBox(height: 10),
],
Row(
children: [
Expanded(
child: Text(
AppStrings.accountBackupSize(_sizeLabel(result.byteLength)),
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
),
TextButton.icon(
onPressed: () => _copy(result.encode()),
icon: const Icon(Icons.copy_all, size: 18),
label: const Text(AppStrings.accountBackupCopy),
),
],
),
Container(
width: double.infinity,
constraints: const BoxConstraints(maxHeight: 260),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest.withValues(
alpha: 0.5,
),
borderRadius: BorderRadius.circular(8),
),
child: SingleChildScrollView(
child: SelectableText(
result.encode(),
style: theme.textTheme.bodySmall?.copyWith(
fontFamily: 'monospace',
fontSize: 11,
),
),
),
),
const SizedBox(height: 10),
Text(
AppStrings.accountBackupSecurity,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.error,
),
),
],
],
),
);
}
}