新增:媒体上传客户端——MediaUploader 编排状态机 + 预签名直传 + 进度组件,修正 media 端点误挂 community 服务(T3-13)
CI / flutter-gates (push) Successful in 2m30s
CI / flutter-gates (push) Successful in 2m30s
- MediaUploader:选图→压缩(80→60 降质阶梯,10 MiB 超限拒绝)→createUpload →预签名 PUT 直传(进度回调)→confirm→ready assetId 交付;并发槽位 2、 顺序即 position、单图失败不拖垮整批;凭据过期预检与存储侧 403 各自动 换新凭据一次;失败重试复用压缩产物、从 createUpload 全新开始 - 孤儿防护:未 confirm 的 assetId 只以管线局部变量存在,快照 assetId 与 ready 态断言绑定,buildAttachRequests 非全员 ready 即抛 StateError - 线路修正:media 两步上传端点由 user 服务(:8082 MediaController)提供, T3-12 误挂 community 客户端(:8084 无 media 路由),补 mediaApi 分端口 直连,compose 真链路实测证实 - UploadProgressOverlay 四态进度层(05 号规范 §3.3);直传层本地 HttpServer 三线路测试(200/403/断连);compose 冒烟测试 (PATBOND_MEDIA_SMOKE=1 启用,默认跳过) - 新依赖:image_picker、flutter_image_compress(03 号评估选型) - flutter test 379 全绿(基线 347,+32)、analyze 0、format 无 diff Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
+13
-2
@@ -152,7 +152,9 @@ class _AppState extends State<App> {
|
|||||||
return ApiPetsRepository(api: api);
|
return ApiPetsRepository(api: api);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// community 服务分端口直连(:8084),token 刷新单飞经共享 [TokenRefresher]。
|
/// community 服务分端口直连(:8084);media 两步上传端点由 user 服务
|
||||||
|
/// (:8082 MediaController)提供,单独建 mediaApi 直连。token 刷新
|
||||||
|
/// 单飞经共享 [TokenRefresher]。
|
||||||
CommunityRepository _buildCommunityRepository() {
|
CommunityRepository _buildCommunityRepository() {
|
||||||
final dio = buildPatbondDio(
|
final dio = buildPatbondDio(
|
||||||
session: sessionManager,
|
session: sessionManager,
|
||||||
@@ -163,7 +165,16 @@ class _AppState extends State<App> {
|
|||||||
session: sessionManager,
|
session: sessionManager,
|
||||||
refresher: _ensureRefresher(),
|
refresher: _ensureRefresher(),
|
||||||
);
|
);
|
||||||
return ApiCommunityRepository(api: api);
|
final mediaDio = buildPatbondDio(
|
||||||
|
session: sessionManager,
|
||||||
|
baseUrl: patbondUserApiBaseUrl,
|
||||||
|
);
|
||||||
|
final mediaApi = ApiClient(
|
||||||
|
dio: mediaDio,
|
||||||
|
session: sessionManager,
|
||||||
|
refresher: _ensureRefresher(),
|
||||||
|
);
|
||||||
|
return ApiCommunityRepository(api: api, mediaApi: mediaApi);
|
||||||
}
|
}
|
||||||
|
|
||||||
AnalyticsPageName? _resolveRootPage() {
|
AnalyticsPageName? _resolveRootPage() {
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:patbond_flutter/core/theme/app_theme.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_uploader.dart';
|
||||||
|
|
||||||
|
/// 上传进度覆盖层(设计规范 05 号 §3.3):叠加在编辑态九宫格单格上,
|
||||||
|
/// 四视觉态映射 [MediaItemPhase]:
|
||||||
|
///
|
||||||
|
/// | 视觉态 | 阶段 | 形态 |
|
||||||
|
/// | --- | --- | --- |
|
||||||
|
/// | 排队 | queued / compressing | ink 40% scrim + 「等待中」白字胶囊 |
|
||||||
|
/// | 上传中 | uploading / confirming | scrim + 白色环形进度 36 + 百分比胶囊 |
|
||||||
|
/// | 成功 | ready | scrim 150ms 淡出,无残留角标 |
|
||||||
|
/// | 失败 | failed | error 12% scrim + errorDark 图标 + 底部「重试」通栏 |
|
||||||
|
///
|
||||||
|
/// 失败态整格点按重试([onRetry],仅可重试失败传入);组件本身不含
|
||||||
|
/// 图片,由九宫格把它叠在缩略图上(Stack)。
|
||||||
|
class UploadProgressOverlay extends StatelessWidget {
|
||||||
|
const UploadProgressOverlay({
|
||||||
|
required this.phase,
|
||||||
|
this.progress = 0,
|
||||||
|
this.onRetry,
|
||||||
|
super.key,
|
||||||
|
});
|
||||||
|
|
||||||
|
final MediaItemPhase phase;
|
||||||
|
|
||||||
|
/// 直传进度 0..1(uploading 态显示;confirming 定格 100%)。
|
||||||
|
final double progress;
|
||||||
|
|
||||||
|
/// 失败态整格点按回调;null 即失败不可重试(终态,只展示不响应)。
|
||||||
|
final VoidCallback? onRetry;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return switch (phase) {
|
||||||
|
MediaItemPhase.queued || MediaItemPhase.compressing => _Scrim(
|
||||||
|
child: Center(child: _pill(const Text('等待中', style: _pillTextSm))),
|
||||||
|
),
|
||||||
|
MediaItemPhase.uploading || MediaItemPhase.confirming => _Scrim(
|
||||||
|
child: Column(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: 36,
|
||||||
|
height: 36,
|
||||||
|
child: CircularProgressIndicator(
|
||||||
|
value: phase == MediaItemPhase.confirming ? 1.0 : progress,
|
||||||
|
color: Colors.white,
|
||||||
|
backgroundColor: Colors.white24,
|
||||||
|
strokeWidth: 3,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
_pill(
|
||||||
|
Text(
|
||||||
|
'${((phase == MediaItemPhase.confirming ? 1.0 : progress) * 100).round()}%',
|
||||||
|
style: _pillTextXs,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
// 成功:scrim 150ms 淡出后不留任何角标。
|
||||||
|
MediaItemPhase.ready => const IgnorePointer(
|
||||||
|
child: AnimatedOpacity(
|
||||||
|
opacity: 0,
|
||||||
|
duration: Duration(milliseconds: 150),
|
||||||
|
child: _Scrim(child: SizedBox.expand()),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
MediaItemPhase.failed => GestureDetector(
|
||||||
|
onTap: onRetry,
|
||||||
|
child: Container(
|
||||||
|
color: AppColors.error.withAlpha(31),
|
||||||
|
child: Column(
|
||||||
|
children: [
|
||||||
|
const Expanded(
|
||||||
|
child: Center(
|
||||||
|
child: Icon(
|
||||||
|
Icons.error_outline,
|
||||||
|
size: 24,
|
||||||
|
color: AppColors.errorDark,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (onRetry != null)
|
||||||
|
Container(
|
||||||
|
width: double.infinity,
|
||||||
|
color: AppColors.errorDark,
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||||
|
child: const Text(
|
||||||
|
'重试',
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(
|
||||||
|
color: Colors.white,
|
||||||
|
fontSize: 11,
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
static const _pillTextSm = TextStyle(
|
||||||
|
color: Colors.white,
|
||||||
|
fontSize: 12,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
);
|
||||||
|
|
||||||
|
static const _pillTextXs = TextStyle(
|
||||||
|
color: Colors.white,
|
||||||
|
fontSize: 11,
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// 白字衬 ink 80% 胶囊底(对 40% scrim 上的合成底色对比度兜底,§3.3)。
|
||||||
|
Widget _pill(Widget child) {
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: AppColors.ink.withAlpha(204),
|
||||||
|
borderRadius: const BorderRadius.all(Radius.circular(AppRadius.pill)),
|
||||||
|
),
|
||||||
|
child: child,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// ink 40% 全格 scrim。
|
||||||
|
class _Scrim extends StatelessWidget {
|
||||||
|
const _Scrim({required this.child});
|
||||||
|
|
||||||
|
final Widget child;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Container(color: AppColors.ink.withAlpha(102), child: child);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -62,10 +62,21 @@ abstract class CommunityRepository {
|
|||||||
/// `Idempotency-Key`(1~128 字符;每次逻辑提交换新键;token 刷新后的
|
/// `Idempotency-Key`(1~128 字符;每次逻辑提交换新键;token 刷新后的
|
||||||
/// 自动重放沿用同一个键——键在本层每次调用生成一次,重放走同一 headers)。
|
/// 自动重放沿用同一个键——键在本层每次调用生成一次,重放走同一 headers)。
|
||||||
/// 点赞/收藏/关注为 PUT/DELETE 语义幂等,无需幂等键。
|
/// 点赞/收藏/关注为 PUT/DELETE 语义幂等,无需幂等键。
|
||||||
|
///
|
||||||
|
/// 端口线路:community 域端点走 community 服务客户端;media 两步上传
|
||||||
|
/// 端点由 **user 服务**提供(13 号报告 §2,MediaController 在
|
||||||
|
/// patbond-user),经 [mediaApi] 直连——T3-13 真链路实测修正,
|
||||||
|
/// 未提供时回落主客户端(既有测试桩场景)。
|
||||||
class ApiCommunityRepository implements CommunityRepository {
|
class ApiCommunityRepository implements CommunityRepository {
|
||||||
ApiCommunityRepository({required this._api, this._uuid = const Uuid()});
|
ApiCommunityRepository({
|
||||||
|
required ApiClient api,
|
||||||
|
ApiClient? mediaApi,
|
||||||
|
this._uuid = const Uuid(),
|
||||||
|
}) : _api = api,
|
||||||
|
_mediaApi = mediaApi ?? api;
|
||||||
|
|
||||||
final ApiClient _api;
|
final ApiClient _api;
|
||||||
|
final ApiClient _mediaApi;
|
||||||
final Uuid _uuid;
|
final Uuid _uuid;
|
||||||
|
|
||||||
Future<Object?> _request(
|
Future<Object?> _request(
|
||||||
@@ -74,9 +85,10 @@ class ApiCommunityRepository implements CommunityRepository {
|
|||||||
Object? body,
|
Object? body,
|
||||||
Map<String, Object?>? query,
|
Map<String, Object?>? query,
|
||||||
bool idempotent = false,
|
bool idempotent = false,
|
||||||
|
bool media = false,
|
||||||
}) async {
|
}) async {
|
||||||
try {
|
try {
|
||||||
return await _api.request(
|
return await (media ? _mediaApi : _api).request(
|
||||||
path,
|
path,
|
||||||
method: method,
|
method: method,
|
||||||
body: body,
|
body: body,
|
||||||
@@ -101,6 +113,7 @@ class ApiCommunityRepository implements CommunityRepository {
|
|||||||
'/api/v1/media/uploads',
|
'/api/v1/media/uploads',
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: request.toJson(),
|
body: request.toJson(),
|
||||||
|
media: true,
|
||||||
);
|
);
|
||||||
return MediaUploadCredentials.fromJson(_asMap(data));
|
return MediaUploadCredentials.fromJson(_asMap(data));
|
||||||
}
|
}
|
||||||
@@ -111,6 +124,7 @@ class ApiCommunityRepository implements CommunityRepository {
|
|||||||
final data = await _request(
|
final data = await _request(
|
||||||
'/api/v1/media/uploads/$assetId/complete',
|
'/api/v1/media/uploads/$assetId/complete',
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
media: true,
|
||||||
);
|
);
|
||||||
return MediaAsset.fromJson(_asMap(data));
|
return MediaAsset.fromJson(_asMap(data));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter_image_compress/flutter_image_compress.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_picking.dart';
|
||||||
|
|
||||||
|
/// 压缩产物(直传本体)。mimeType 与直传 PUT 的 Content-Type、
|
||||||
|
/// createUpload 登记值三处必须一致(Content-Type 已签进预签名签名)。
|
||||||
|
class CompressedMediaImage {
|
||||||
|
const CompressedMediaImage({required this.bytes, required this.mimeType});
|
||||||
|
|
||||||
|
final Uint8List bytes;
|
||||||
|
final String mimeType;
|
||||||
|
|
||||||
|
int get byteSize => bytes.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 压缩抽象:quality 由 MediaUploader 的降质阶梯驱动(80 → 60),
|
||||||
|
/// 单测注入假实现控制产物大小。
|
||||||
|
abstract class MediaImageCompressor {
|
||||||
|
Future<CompressedMediaImage> compress(
|
||||||
|
PickedMediaImage source, {
|
||||||
|
required int quality,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 基于 flutter_image_compress 的原生压缩实现(03 号评估 §4.1 选型)。
|
||||||
|
///
|
||||||
|
/// 策略(03 号 §4.1 + 13 号报告偏差 #6):长边 ≤2048 重采样、统一转码
|
||||||
|
/// JPEG(服务端 mime 白名单不收 HEIC,客户端统一出 jpeg);
|
||||||
|
/// autoCorrectionAngle 矫正方向后不保留 EXIF——顺带剥离 GPS 定位隐私,
|
||||||
|
/// **不要开 keepExif**。
|
||||||
|
class NativeMediaImageCompressor implements MediaImageCompressor {
|
||||||
|
const NativeMediaImageCompressor({this.maxLongEdge = 2048});
|
||||||
|
|
||||||
|
final int maxLongEdge;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<CompressedMediaImage> compress(
|
||||||
|
PickedMediaImage source, {
|
||||||
|
required int quality,
|
||||||
|
}) async {
|
||||||
|
final bytes = await FlutterImageCompress.compressWithList(
|
||||||
|
source.bytes,
|
||||||
|
minWidth: maxLongEdge,
|
||||||
|
minHeight: maxLongEdge,
|
||||||
|
quality: quality,
|
||||||
|
format: CompressFormat.jpeg,
|
||||||
|
autoCorrectionAngle: true,
|
||||||
|
keepExif: false,
|
||||||
|
);
|
||||||
|
return CompressedMediaImage(bytes: bytes, mimeType: 'image/jpeg');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:dio/dio.dart';
|
||||||
|
|
||||||
|
/// 预签名直传失败。
|
||||||
|
///
|
||||||
|
/// - [statusCode] 为 null 表示网络层失败(断连/超时),可原凭据重试;
|
||||||
|
/// - 403 为存储侧拒绝签名(凭据过期/被改动),须重新 createUpload 换新凭据;
|
||||||
|
/// - 其余状态码按可重试处理(重试走完整重传)。
|
||||||
|
class MediaDirectUploadException implements Exception {
|
||||||
|
const MediaDirectUploadException({this.statusCode, required this.message});
|
||||||
|
|
||||||
|
final int? statusCode;
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
/// 存储侧拒绝了凭据(签名过期/不符),重试前必须换新凭据。
|
||||||
|
bool get isCredentialRejected => statusCode == 403;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'MediaDirectUploadException($statusCode): $message';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 预签名 PUT 直传抽象(两步上传第二步的传输层)。
|
||||||
|
///
|
||||||
|
/// 不走业务信封、不带 Bearer 鉴权——鉴权就是 URL 里的签名本身;
|
||||||
|
/// [headers] 即 createUpload 返回的 requiredHeaders,必须原样携带
|
||||||
|
/// (Content-Type 已签进签名,改动即 403)。
|
||||||
|
abstract class MediaDirectUploadClient {
|
||||||
|
Future<void> put({
|
||||||
|
required String url,
|
||||||
|
required Map<String, String> headers,
|
||||||
|
required Uint8List bytes,
|
||||||
|
void Function(int sent, int total)? onProgress,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 基于裸 Dio 的实现:独立实例,无 AuthInterceptor(预签名 URL 携带
|
||||||
|
/// Authorization 头会破坏 SigV4 校验),sendTimeout 按 10 MiB 弱网上限放宽。
|
||||||
|
class DioMediaDirectUploadClient implements MediaDirectUploadClient {
|
||||||
|
DioMediaDirectUploadClient({Dio? dio})
|
||||||
|
: _dio =
|
||||||
|
dio ??
|
||||||
|
Dio(
|
||||||
|
BaseOptions(
|
||||||
|
connectTimeout: const Duration(seconds: 5),
|
||||||
|
sendTimeout: const Duration(seconds: 120),
|
||||||
|
receiveTimeout: const Duration(seconds: 30),
|
||||||
|
validateStatus: (_) => true,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
final Dio _dio;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> put({
|
||||||
|
required String url,
|
||||||
|
required Map<String, String> headers,
|
||||||
|
required Uint8List bytes,
|
||||||
|
void Function(int sent, int total)? onProgress,
|
||||||
|
}) async {
|
||||||
|
final Response<Object?> response;
|
||||||
|
try {
|
||||||
|
response = await _dio.put<Object?>(
|
||||||
|
url,
|
||||||
|
data: Stream<Uint8List>.value(bytes),
|
||||||
|
options: Options(
|
||||||
|
headers: {...headers, Headers.contentLengthHeader: bytes.length},
|
||||||
|
),
|
||||||
|
onSendProgress: onProgress,
|
||||||
|
);
|
||||||
|
} on DioException catch (error) {
|
||||||
|
throw MediaDirectUploadException(message: '直传网络失败:${error.type.name}');
|
||||||
|
}
|
||||||
|
final status = response.statusCode ?? 0;
|
||||||
|
if (status < 200 || status >= 300) {
|
||||||
|
throw MediaDirectUploadException(
|
||||||
|
statusCode: status,
|
||||||
|
message: '存储侧拒绝直传:HTTP $status',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:image_picker/image_picker.dart';
|
||||||
|
|
||||||
|
/// 待上传的一张原始图(选择器产物,压缩前形态)。
|
||||||
|
///
|
||||||
|
/// 只持有内存字节:不落磁盘副本、不携带原始文件路径,配合压缩层剥离
|
||||||
|
/// EXIF(含 GPS)的隐私纪律(03 号评估 §4.1)。
|
||||||
|
class PickedMediaImage {
|
||||||
|
const PickedMediaImage({required this.bytes, this.name});
|
||||||
|
|
||||||
|
/// 原始字节(供压缩层消费与格内缩略预览)。
|
||||||
|
final Uint8List bytes;
|
||||||
|
|
||||||
|
/// 原始文件名(仅诊断用途,不参与上传——objectKey 由服务端生成)。
|
||||||
|
final String? name;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 图片选择抽象:MediaUploader 只依赖本接口,单测注入假实现,
|
||||||
|
/// widget 测试无需平台通道。
|
||||||
|
abstract class MediaImagePicker {
|
||||||
|
/// 拉起系统选择器,最多返回 [limit] 张;用户取消返回空列表。
|
||||||
|
Future<List<PickedMediaImage>> pickImages({required int limit});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 基于 image_picker 的系统选择器实现(03 号评估 §4.1 选型:官方维护、
|
||||||
|
/// pickMultiImage 多选,M3 不引入重型相册组件)。
|
||||||
|
class SystemMediaImagePicker implements MediaImagePicker {
|
||||||
|
SystemMediaImagePicker({ImagePicker? picker})
|
||||||
|
: _picker = picker ?? ImagePicker();
|
||||||
|
|
||||||
|
final ImagePicker _picker;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<PickedMediaImage>> pickImages({required int limit}) async {
|
||||||
|
// 仅剩一个空位时用单选(pickMultiImage 的 limit 在部分平台要求 ≥2)。
|
||||||
|
final files = limit <= 1
|
||||||
|
? [?await _picker.pickImage(source: ImageSource.gallery)]
|
||||||
|
: await _picker.pickMultiImage(limit: limit);
|
||||||
|
final images = <PickedMediaImage>[];
|
||||||
|
for (final file in files.take(limit)) {
|
||||||
|
images.add(
|
||||||
|
PickedMediaImage(bytes: await file.readAsBytes(), name: file.name),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return images;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,471 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:patbond_flutter/core/network/api_exception.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/community_models.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/community_repository.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_compression.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_direct_upload.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_picking.dart';
|
||||||
|
|
||||||
|
/// 单张图的上传阶段(05 号规范 §3.3 四视觉态的底层状态模型)。
|
||||||
|
///
|
||||||
|
/// 生命周期:queued → compressing → uploading(progress) → confirming
|
||||||
|
/// → ready | failed(retryable?)。ready 是唯一可交付态——**assetId 只在
|
||||||
|
/// ready 态对外可见**(孤儿防护:未 confirm 的 asset 不得被引用)。
|
||||||
|
enum MediaItemPhase {
|
||||||
|
queued,
|
||||||
|
compressing,
|
||||||
|
uploading,
|
||||||
|
confirming,
|
||||||
|
ready,
|
||||||
|
failed,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 单张图的不可变状态快照(UI 消费;内部任务状态见 _UploadTask)。
|
||||||
|
@immutable
|
||||||
|
class MediaUploadItem {
|
||||||
|
const MediaUploadItem({
|
||||||
|
required this.localId,
|
||||||
|
required this.phase,
|
||||||
|
required this.previewBytes,
|
||||||
|
this.progress = 0,
|
||||||
|
this.assetId,
|
||||||
|
this.errorMessage,
|
||||||
|
this.retryable = false,
|
||||||
|
}) : assert(
|
||||||
|
(assetId != null) == (phase == MediaItemPhase.ready),
|
||||||
|
'assetId 与 ready 态严格绑定(孤儿防护)',
|
||||||
|
);
|
||||||
|
|
||||||
|
/// 本地稳定标识(重试/删除寻址用,与服务端无关)。
|
||||||
|
final int localId;
|
||||||
|
|
||||||
|
final MediaItemPhase phase;
|
||||||
|
|
||||||
|
/// 缩略预览字节(原图,UI 直接 Image.memory 渲染)。
|
||||||
|
final Uint8List previewBytes;
|
||||||
|
|
||||||
|
/// 直传进度 0..1(uploading 有意义;confirming 视作 1.0)。
|
||||||
|
final double progress;
|
||||||
|
|
||||||
|
/// ready 态的可引用 asset 标识;其余态恒为 null(构造期断言兜底)。
|
||||||
|
final String? assetId;
|
||||||
|
|
||||||
|
/// failed 态的用户可读原因。
|
||||||
|
final String? errorMessage;
|
||||||
|
|
||||||
|
/// failed 态是否可重试(false = 终态,如压缩后仍超限)。
|
||||||
|
final bool retryable;
|
||||||
|
|
||||||
|
bool get isReady => phase == MediaItemPhase.ready;
|
||||||
|
bool get isFailed => phase == MediaItemPhase.failed;
|
||||||
|
bool get isBusy => !isReady && !isFailed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 内部任务:可变状态 + 生命周期旗标(cancelled 后一切在途结果作废)。
|
||||||
|
class _UploadTask {
|
||||||
|
_UploadTask({required this.localId, required this.source});
|
||||||
|
|
||||||
|
final int localId;
|
||||||
|
final PickedMediaImage source;
|
||||||
|
|
||||||
|
MediaItemPhase phase = MediaItemPhase.queued;
|
||||||
|
double progress = 0;
|
||||||
|
String? errorMessage;
|
||||||
|
bool retryable = false;
|
||||||
|
bool cancelled = false;
|
||||||
|
|
||||||
|
/// 压缩产物缓存(重试跳过重压缩)。
|
||||||
|
CompressedMediaImage? compressed;
|
||||||
|
|
||||||
|
/// confirm 成功前的服务端 assetId 只以管线局部变量存在,**不落任务
|
||||||
|
/// 状态、不出现在 [MediaUploadItem] 快照**——孤儿防护的结构保证;
|
||||||
|
/// confirm 通过后才写入 [readyAssetId]。
|
||||||
|
String? readyAssetId;
|
||||||
|
|
||||||
|
MediaUploadItem snapshot() => MediaUploadItem(
|
||||||
|
localId: localId,
|
||||||
|
phase: phase,
|
||||||
|
previewBytes: source.bytes,
|
||||||
|
progress: progress,
|
||||||
|
assetId: readyAssetId,
|
||||||
|
errorMessage: errorMessage,
|
||||||
|
retryable: retryable,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 媒体上传编排器(T3-13,03 号评估 §4.3 冻结接口的定稿实现)。
|
||||||
|
///
|
||||||
|
/// 职责:选图 → 压缩(降质阶梯 80→60,仍超 10 MiB 拒绝为终态失败)→
|
||||||
|
/// createUpload → 预签名 PUT 直传(进度回调;Content-Type 按
|
||||||
|
/// requiredHeaders 原样携带)→ confirm → ready assetId 交付。
|
||||||
|
///
|
||||||
|
/// 语义要点:
|
||||||
|
/// - **顺序保持**:items 顺序 = 加入顺序 = position 语义;并发上传的
|
||||||
|
/// 完成先后不影响顺序([buildAttachRequests] 按当前列表序发号)。
|
||||||
|
/// - **单飞槽位**:至多 [maxConcurrentUploads] 张同时占用网络管线,
|
||||||
|
/// 单图失败不拖垮整批。
|
||||||
|
/// - **凭据过期**:PUT 前过期预检、存储侧 403 各触发一次自动
|
||||||
|
/// re-createUpload(换新 assetId 新凭据);再失败交给手动重试。
|
||||||
|
/// - **失败重试**:retry 复用压缩产物、从 createUpload 全新开始
|
||||||
|
/// (统一覆盖「对象未上传保持 uploading」与「内容不符置 failed 终态」
|
||||||
|
/// 两种服务端分支——旧 asset 弃引用,由服务端超时清理兜底)。
|
||||||
|
/// - **孤儿防护**:未 confirm 的 assetId 只以管线局部变量存在;
|
||||||
|
/// 对外可见的 [MediaUploadItem.assetId] 与 ready 态严格绑定(断言),
|
||||||
|
/// [buildAttachRequests] 仅在全员 ready 时可用。
|
||||||
|
/// - 预签名凭据只存内存、用完即弃,不持久化(既有纪律)。
|
||||||
|
class MediaUploader extends ChangeNotifier {
|
||||||
|
MediaUploader({
|
||||||
|
required this._repository,
|
||||||
|
MediaImagePicker? picker,
|
||||||
|
MediaImageCompressor? compressor,
|
||||||
|
MediaDirectUploadClient? directUpload,
|
||||||
|
this.maxImages = 9,
|
||||||
|
this.maxConcurrentUploads = 2,
|
||||||
|
this.maxByteSize = 10 * 1024 * 1024,
|
||||||
|
DateTime Function()? now,
|
||||||
|
}) : _picker = picker ?? SystemMediaImagePicker(),
|
||||||
|
_compressor = compressor ?? const NativeMediaImageCompressor(),
|
||||||
|
_directUpload = directUpload ?? DioMediaDirectUploadClient(),
|
||||||
|
_now = now ?? DateTime.now,
|
||||||
|
_slots = maxConcurrentUploads;
|
||||||
|
|
||||||
|
final CommunityRepository _repository;
|
||||||
|
final MediaImagePicker _picker;
|
||||||
|
final MediaImageCompressor _compressor;
|
||||||
|
final MediaDirectUploadClient _directUpload;
|
||||||
|
final DateTime Function() _now;
|
||||||
|
|
||||||
|
/// 九宫格上限(05 号规范 §3.2)。
|
||||||
|
final int maxImages;
|
||||||
|
|
||||||
|
final int maxConcurrentUploads;
|
||||||
|
|
||||||
|
/// 与服务端 byteSize 上限一致(10 MiB,13 号报告偏差 #7)。
|
||||||
|
final int maxByteSize;
|
||||||
|
|
||||||
|
/// 凭据过期预检安全边距:距 expiresAt 不足此值即视为过期,直接换新。
|
||||||
|
static const credentialsSafetyMargin = Duration(seconds: 30);
|
||||||
|
|
||||||
|
/// 压缩降质阶梯(80 常规 → 60 兜底;仍超限即终态拒绝)。
|
||||||
|
static const qualityLadder = [80, 60];
|
||||||
|
|
||||||
|
final List<_UploadTask> _tasks = [];
|
||||||
|
int _nextLocalId = 1;
|
||||||
|
bool _picking = false;
|
||||||
|
|
||||||
|
int _slots;
|
||||||
|
final List<Completer<void>> _slotWaiters = [];
|
||||||
|
|
||||||
|
// ---- 对外状态 ----
|
||||||
|
|
||||||
|
/// 选择器是否拉起中(uploader 级 picking 态)。
|
||||||
|
bool get isPicking => _picking;
|
||||||
|
|
||||||
|
List<MediaUploadItem> get items =>
|
||||||
|
List.unmodifiable(_tasks.map((task) => task.snapshot()));
|
||||||
|
|
||||||
|
bool get isEmpty => _tasks.isEmpty;
|
||||||
|
int get remainingSlots => maxImages - _tasks.length;
|
||||||
|
int get readyCount =>
|
||||||
|
_tasks.where((t) => t.phase == MediaItemPhase.ready).length;
|
||||||
|
bool get allReady => _tasks.isNotEmpty && readyCount == _tasks.length;
|
||||||
|
bool get hasFailure => _tasks.any((t) => t.phase == MediaItemPhase.failed);
|
||||||
|
bool get hasBusyItem => _picking || _tasks.any((t) => t.snapshot().isBusy);
|
||||||
|
|
||||||
|
/// 页级汇总进度(05 号规范 §3.3 线性进度条):各图等权。
|
||||||
|
double get overallProgress {
|
||||||
|
if (_tasks.isEmpty) return 0;
|
||||||
|
var sum = 0.0;
|
||||||
|
for (final task in _tasks) {
|
||||||
|
sum += switch (task.phase) {
|
||||||
|
MediaItemPhase.ready => 1.0,
|
||||||
|
MediaItemPhase.uploading => task.progress,
|
||||||
|
MediaItemPhase.confirming => 1.0,
|
||||||
|
_ => 0.0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return sum / _tasks.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 交付口(T3-17 发布页组 CreatePostRequest.media 用):
|
||||||
|
/// 仅全员 ready 时可用——**任何非 ready 项在场即抛 [StateError]**,
|
||||||
|
/// 从类型上杜绝未 confirm asset 被引用。position 按当前列表序 0..n-1。
|
||||||
|
List<PostMediaAttachRequest> buildAttachRequests({int coverIndex = 0}) {
|
||||||
|
if (!allReady) {
|
||||||
|
throw StateError('存在未就绪的上传项,不得引用(孤儿防护)');
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
for (final (index, task) in _tasks.indexed)
|
||||||
|
PostMediaAttachRequest(
|
||||||
|
assetId: task.readyAssetId!,
|
||||||
|
position: index,
|
||||||
|
isCover: index == coverIndex,
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 操作 ----
|
||||||
|
|
||||||
|
/// 拉起系统选择器并把所选图片加入上传管线(剩余槽位自动截断)。
|
||||||
|
Future<void> pickAndAdd() async {
|
||||||
|
if (_picking || remainingSlots <= 0) return;
|
||||||
|
_picking = true;
|
||||||
|
notifyListeners();
|
||||||
|
try {
|
||||||
|
final images = await _picker.pickImages(limit: remainingSlots);
|
||||||
|
_picking = false;
|
||||||
|
addImages(images);
|
||||||
|
} catch (_) {
|
||||||
|
_picking = false;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 直接加入图片(选择器旁路,测试与分享外链场景用)。
|
||||||
|
void addImages(List<PickedMediaImage> images) {
|
||||||
|
for (final image in images.take(remainingSlots)) {
|
||||||
|
final task = _UploadTask(localId: _nextLocalId++, source: image);
|
||||||
|
_tasks.add(task);
|
||||||
|
unawaited(_run(task));
|
||||||
|
}
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 重试一张可重试失败图:复用压缩产物,从 createUpload 全新开始。
|
||||||
|
void retry(int localId) {
|
||||||
|
final task = _taskOrNull(localId);
|
||||||
|
if (task == null ||
|
||||||
|
task.phase != MediaItemPhase.failed ||
|
||||||
|
!task.retryable) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
task.errorMessage = null;
|
||||||
|
task.retryable = false;
|
||||||
|
task.progress = 0;
|
||||||
|
task.phase = MediaItemPhase.queued;
|
||||||
|
notifyListeners();
|
||||||
|
unawaited(_run(task));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 移除一张图(任意态可移除);在途请求结果一律作废,未 confirm 的
|
||||||
|
/// 服务端 asset 弃引用(服务端超时清理兜底)。
|
||||||
|
void remove(int localId) {
|
||||||
|
final task = _taskOrNull(localId);
|
||||||
|
if (task == null) return;
|
||||||
|
task.cancelled = true;
|
||||||
|
_tasks.remove(task);
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 清空全部(发布成功/离开页面时调用)。
|
||||||
|
void reset() {
|
||||||
|
for (final task in _tasks) {
|
||||||
|
task.cancelled = true;
|
||||||
|
}
|
||||||
|
_tasks.clear();
|
||||||
|
_picking = false;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
_UploadTask? _taskOrNull(int localId) {
|
||||||
|
for (final task in _tasks) {
|
||||||
|
if (task.localId == localId) return task;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 管线 ----
|
||||||
|
|
||||||
|
Future<void> _run(_UploadTask task) async {
|
||||||
|
await _acquireSlot();
|
||||||
|
try {
|
||||||
|
if (task.cancelled) return;
|
||||||
|
final compressed = await _compress(task);
|
||||||
|
if (compressed == null || task.cancelled) return;
|
||||||
|
await _uploadAndConfirm(task, compressed);
|
||||||
|
} finally {
|
||||||
|
_releaseSlot();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 压缩(降质阶梯);超限终态失败返回 null。
|
||||||
|
Future<CompressedMediaImage?> _compress(_UploadTask task) async {
|
||||||
|
final cached = task.compressed;
|
||||||
|
if (cached != null) return cached;
|
||||||
|
_transition(task, MediaItemPhase.compressing);
|
||||||
|
try {
|
||||||
|
for (final quality in qualityLadder) {
|
||||||
|
final result = await _compressor.compress(
|
||||||
|
task.source,
|
||||||
|
quality: quality,
|
||||||
|
);
|
||||||
|
if (task.cancelled) return null;
|
||||||
|
if (result.byteSize <= maxByteSize) {
|
||||||
|
task.compressed = result;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
_fail(task, message: '图片处理失败', retryable: true);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
_fail(task, message: '图片过大,压缩后仍超过 10 MB', retryable: false);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _uploadAndConfirm(
|
||||||
|
_UploadTask task,
|
||||||
|
CompressedMediaImage compressed,
|
||||||
|
) async {
|
||||||
|
// createUpload:登记 mime/byteSize,取预签名 PUT 凭据(内存态,不持久化)。
|
||||||
|
MediaUploadCredentials credentials;
|
||||||
|
try {
|
||||||
|
credentials = await _createUpload(compressed);
|
||||||
|
} on Exception catch (error) {
|
||||||
|
if (!task.cancelled) _failFromApi(task, error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (task.cancelled) return;
|
||||||
|
|
||||||
|
// 直传 PUT:过期预检与存储侧 403 各允许一次自动换新凭据。
|
||||||
|
_transition(task, MediaItemPhase.uploading);
|
||||||
|
var renewed = false;
|
||||||
|
while (true) {
|
||||||
|
if (_credentialsExpired(credentials)) {
|
||||||
|
if (renewed) {
|
||||||
|
_fail(task, message: '上传凭据已过期', retryable: true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
renewed = true;
|
||||||
|
try {
|
||||||
|
credentials = await _createUpload(compressed);
|
||||||
|
} on Exception catch (error) {
|
||||||
|
if (!task.cancelled) _failFromApi(task, error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (task.cancelled) return;
|
||||||
|
// 回到循环顶复检新凭据(服务端时钟异常仍过期即失败,不无限重取)。
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await _directUpload.put(
|
||||||
|
url: credentials.uploadUrl,
|
||||||
|
headers: credentials.requiredHeaders,
|
||||||
|
bytes: compressed.bytes,
|
||||||
|
onProgress: (sent, total) {
|
||||||
|
if (task.cancelled || total <= 0) return;
|
||||||
|
task.progress = sent / total;
|
||||||
|
notifyListeners();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
} on MediaDirectUploadException catch (error) {
|
||||||
|
if (task.cancelled) return;
|
||||||
|
if (error.isCredentialRejected && !renewed) {
|
||||||
|
renewed = true;
|
||||||
|
try {
|
||||||
|
credentials = await _createUpload(compressed);
|
||||||
|
} on Exception catch (creationError) {
|
||||||
|
_failFromApi(task, creationError);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (task.cancelled) return;
|
||||||
|
task.progress = 0;
|
||||||
|
notifyListeners();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
_fail(
|
||||||
|
task,
|
||||||
|
message: error.statusCode == null ? '网络中断,上传失败' : '上传被存储服务拒绝',
|
||||||
|
retryable: true,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (task.cancelled) return;
|
||||||
|
|
||||||
|
// confirm:42205 对象未上传保持 uploading / 内容不符置 failed 终态,
|
||||||
|
// 客户端统一按「可重试 + 重试换新 asset」处理,两分支都正确收敛。
|
||||||
|
_transition(task, MediaItemPhase.confirming);
|
||||||
|
final MediaAsset asset;
|
||||||
|
try {
|
||||||
|
asset = await _repository.completeMediaUpload(credentials.assetId);
|
||||||
|
} on Exception catch (error) {
|
||||||
|
if (!task.cancelled) _failFromApi(task, error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (task.cancelled) return;
|
||||||
|
if (asset.status != MediaAssetStatus.ready) {
|
||||||
|
_fail(task, message: '上传确认未通过', retryable: true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
task.readyAssetId = asset.id;
|
||||||
|
task.progress = 1;
|
||||||
|
_transition(task, MediaItemPhase.ready);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<MediaUploadCredentials> _createUpload(
|
||||||
|
CompressedMediaImage compressed,
|
||||||
|
) {
|
||||||
|
return _repository.createMediaUpload(
|
||||||
|
CreateMediaUploadRequest(
|
||||||
|
kind: MediaKind.image,
|
||||||
|
purpose: MediaPurpose.postImage,
|
||||||
|
mimeType: compressed.mimeType,
|
||||||
|
byteSize: compressed.byteSize,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _credentialsExpired(MediaUploadCredentials credentials) =>
|
||||||
|
!_now().add(credentialsSafetyMargin).isBefore(credentials.expiresAt);
|
||||||
|
|
||||||
|
void _failFromApi(_UploadTask task, Exception error) {
|
||||||
|
// 参数被服务端拒绝(40000:mime/byteSize 白名单外)重试无意义,终态。
|
||||||
|
final retryable =
|
||||||
|
error is! ApiBusinessException || error.code != ApiCodes.paramError;
|
||||||
|
_fail(
|
||||||
|
task,
|
||||||
|
message: error is ApiBusinessException ? error.message : '网络异常,请重试',
|
||||||
|
retryable: retryable,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _fail(
|
||||||
|
_UploadTask task, {
|
||||||
|
required String message,
|
||||||
|
required bool retryable,
|
||||||
|
}) {
|
||||||
|
if (task.cancelled) return;
|
||||||
|
task.phase = MediaItemPhase.failed;
|
||||||
|
task.errorMessage = message;
|
||||||
|
task.retryable = retryable;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _transition(_UploadTask task, MediaItemPhase phase) {
|
||||||
|
if (task.cancelled) return;
|
||||||
|
task.phase = phase;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _acquireSlot() {
|
||||||
|
if (_slots > 0) {
|
||||||
|
_slots--;
|
||||||
|
return Future.value();
|
||||||
|
}
|
||||||
|
final waiter = Completer<void>();
|
||||||
|
_slotWaiters.add(waiter);
|
||||||
|
return waiter.future;
|
||||||
|
}
|
||||||
|
|
||||||
|
void _releaseSlot() {
|
||||||
|
if (_slotWaiters.isNotEmpty) {
|
||||||
|
_slotWaiters.removeAt(0).complete();
|
||||||
|
} else {
|
||||||
|
_slots++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,9 +6,13 @@
|
|||||||
|
|
||||||
#include "generated_plugin_registrant.h"
|
#include "generated_plugin_registrant.h"
|
||||||
|
|
||||||
|
#include <file_selector_linux/file_selector_plugin.h>
|
||||||
#include <flutter_secure_storage_linux/flutter_secure_storage_linux_plugin.h>
|
#include <flutter_secure_storage_linux/flutter_secure_storage_linux_plugin.h>
|
||||||
|
|
||||||
void fl_register_plugins(FlPluginRegistry* registry) {
|
void fl_register_plugins(FlPluginRegistry* registry) {
|
||||||
|
g_autoptr(FlPluginRegistrar) file_selector_linux_registrar =
|
||||||
|
fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin");
|
||||||
|
file_selector_plugin_register_with_registrar(file_selector_linux_registrar);
|
||||||
g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar =
|
g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar =
|
||||||
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin");
|
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin");
|
||||||
flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar);
|
flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar);
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
#
|
#
|
||||||
|
|
||||||
list(APPEND FLUTTER_PLUGIN_LIST
|
list(APPEND FLUTTER_PLUGIN_LIST
|
||||||
|
file_selector_linux
|
||||||
flutter_secure_storage_linux
|
flutter_secure_storage_linux
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -5,11 +5,15 @@
|
|||||||
import FlutterMacOS
|
import FlutterMacOS
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
|
import file_selector_macos
|
||||||
|
import flutter_image_compress_macos
|
||||||
import flutter_secure_storage_darwin
|
import flutter_secure_storage_darwin
|
||||||
import package_info_plus
|
import package_info_plus
|
||||||
import shared_preferences_foundation
|
import shared_preferences_foundation
|
||||||
|
|
||||||
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||||
|
FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin"))
|
||||||
|
FlutterImageCompressMacosPlugin.register(with: registry.registrar(forPlugin: "FlutterImageCompressMacosPlugin"))
|
||||||
FlutterSecureStorageDarwinPlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStorageDarwinPlugin"))
|
FlutterSecureStorageDarwinPlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStorageDarwinPlugin"))
|
||||||
FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin"))
|
FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin"))
|
||||||
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
|
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
|
||||||
|
|||||||
+160
@@ -57,6 +57,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.19.1"
|
version: "1.19.1"
|
||||||
|
cross_file:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: cross_file
|
||||||
|
sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.3.5+5"
|
||||||
crypto:
|
crypto:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -121,6 +129,38 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "7.0.1"
|
version: "7.0.1"
|
||||||
|
file_selector_linux:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: file_selector_linux
|
||||||
|
sha256: da76400e7872ce7637ffdce12749ec24169c25f6195c28372208e65a24bcd2ab
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.9.4+1"
|
||||||
|
file_selector_macos:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: file_selector_macos
|
||||||
|
sha256: d57c62362766b5e7ae739448650b66c6aab7a68ba7ecc65e04018652645ae0f4
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.9.5+1"
|
||||||
|
file_selector_platform_interface:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: file_selector_platform_interface
|
||||||
|
sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.7.0"
|
||||||
|
file_selector_windows:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: file_selector_windows
|
||||||
|
sha256: fbefc5fb92c6d3cbe8d284a2cd971b593bb07d2cd6da8557b81a862250b4acec
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.9.3+6"
|
||||||
fixnum:
|
fixnum:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -134,6 +174,54 @@ packages:
|
|||||||
description: flutter
|
description: flutter
|
||||||
source: sdk
|
source: sdk
|
||||||
version: "0.0.0"
|
version: "0.0.0"
|
||||||
|
flutter_image_compress:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: flutter_image_compress
|
||||||
|
sha256: "98a48c05a7add6869c6838270e862124a4d571f9dd5d0cf209ed03a71b20ea84"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.5.1"
|
||||||
|
flutter_image_compress_common:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_image_compress_common
|
||||||
|
sha256: "76869e4d5f3d65f3431e7edff0b2d8ad1eea68b49c6a37772fdb1ae6016da9ed"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.1"
|
||||||
|
flutter_image_compress_macos:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_image_compress_macos
|
||||||
|
sha256: "0d2a842d2e544828fb32bda16dcfccb3149107df568898a4936d78232e486847"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.0"
|
||||||
|
flutter_image_compress_ohos:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_image_compress_ohos
|
||||||
|
sha256: "1491bb7bcfdf59e3b127c263c116cfbf8ed3afade6e7fa691d9622e838ed7e48"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.0.3+1"
|
||||||
|
flutter_image_compress_platform_interface:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_image_compress_platform_interface
|
||||||
|
sha256: bbefb7967bda565004fdabdb3300dcbfb40c7ef8402675d23206e5bddc358178
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.1.0"
|
||||||
|
flutter_image_compress_web:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_image_compress_web
|
||||||
|
sha256: "91cc58e091a1e09c7683d216d579e2b964119a8527fc43b64dfdb00f1acc94ec"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.1.5+1"
|
||||||
flutter_lints:
|
flutter_lints:
|
||||||
dependency: "direct dev"
|
dependency: "direct dev"
|
||||||
description:
|
description:
|
||||||
@@ -142,6 +230,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "6.0.0"
|
version: "6.0.0"
|
||||||
|
flutter_plugin_android_lifecycle:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: flutter_plugin_android_lifecycle
|
||||||
|
sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.0.35"
|
||||||
flutter_secure_storage:
|
flutter_secure_storage:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
@@ -224,6 +320,70 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "4.1.2"
|
version: "4.1.2"
|
||||||
|
image_picker:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: image_picker
|
||||||
|
sha256: d8402284df184bc05f4a2210c6c23983b0720f4cd87cbd05c5390a78af602667
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.2.3"
|
||||||
|
image_picker_android:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_android
|
||||||
|
sha256: "1c0c38790306fda4ed774095620444333e56a2b6bc8fc98f3a35c9398781cf54"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.8.13+22"
|
||||||
|
image_picker_for_web:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_for_web
|
||||||
|
sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "3.1.1"
|
||||||
|
image_picker_ios:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_ios
|
||||||
|
sha256: ee3885b6fcd71958fbc79770dd194c63371439d536d69c47b279171a486482ae
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.8.13+7"
|
||||||
|
image_picker_linux:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_linux
|
||||||
|
sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.2.2"
|
||||||
|
image_picker_macos:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_macos
|
||||||
|
sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.2.2+1"
|
||||||
|
image_picker_platform_interface:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_platform_interface
|
||||||
|
sha256: "567e056716333a1647c64bb6bd873cff7622233a5c3f694be28a583d4715690c"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.11.1"
|
||||||
|
image_picker_windows:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: image_picker_windows
|
||||||
|
sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.2.2"
|
||||||
jni:
|
jni:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
@@ -39,6 +39,10 @@ dependencies:
|
|||||||
flutter_secure_storage: ^11.0.0
|
flutter_secure_storage: ^11.0.0
|
||||||
uuid: ^4.6.0
|
uuid: ^4.6.0
|
||||||
package_info_plus: ^10.2.1
|
package_info_plus: ^10.2.1
|
||||||
|
# T3-13 媒体上传:系统选择器多选(03 号评估 §4.1 选型)。
|
||||||
|
image_picker: ^1.2.0
|
||||||
|
# T3-13 媒体上传:原生编解码压缩(长边重采样 + JPEG 质量 + EXIF 方向矫正)。
|
||||||
|
flutter_image_compress: ^2.4.0
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import '../../helpers/community_test_helpers.dart';
|
|||||||
void main() {
|
void main() {
|
||||||
late SessionManager session;
|
late SessionManager session;
|
||||||
late FakeHttpAdapter adapter;
|
late FakeHttpAdapter adapter;
|
||||||
|
late FakeHttpAdapter mediaAdapter;
|
||||||
late ApiCommunityRepository repository;
|
late ApiCommunityRepository repository;
|
||||||
|
|
||||||
Future<void> setUpWith(
|
Future<void> setUpWith(
|
||||||
@@ -28,39 +29,58 @@ void main() {
|
|||||||
adapter = FakeHttpAdapter(handler);
|
adapter = FakeHttpAdapter(handler);
|
||||||
dio.httpClientAdapter = adapter;
|
dio.httpClientAdapter = adapter;
|
||||||
final refresher = TokenRefresher(dio: dio, session: session);
|
final refresher = TokenRefresher(dio: dio, session: session);
|
||||||
|
// media 两步上传端点由 user 服务提供(13 号报告 §2),走独立客户端;
|
||||||
|
// 两 adapter 分开记录以断言线路不串。
|
||||||
|
final mediaDio = buildPatbondDio(
|
||||||
|
session: session,
|
||||||
|
baseUrl: 'http://user.local',
|
||||||
|
);
|
||||||
|
mediaAdapter = FakeHttpAdapter(handler);
|
||||||
|
mediaDio.httpClientAdapter = mediaAdapter;
|
||||||
repository = ApiCommunityRepository(
|
repository = ApiCommunityRepository(
|
||||||
api: ApiClient(dio: dio, session: session, refresher: refresher),
|
api: ApiClient(dio: dio, session: session, refresher: refresher),
|
||||||
|
mediaApi: ApiClient(
|
||||||
|
dio: mediaDio,
|
||||||
|
session: session,
|
||||||
|
refresher: refresher,
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
group('请求线路(路径 / 方法 / 鉴权 / 参数)', () {
|
group('请求线路(路径 / 方法 / 鉴权 / 参数)', () {
|
||||||
test('createMediaUpload:POST /api/v1/media/uploads,携带 Bearer', () async {
|
test(
|
||||||
await setUpWith(
|
'createMediaUpload:POST /api/v1/media/uploads 走 user 服务客户端,携带 Bearer',
|
||||||
(options) async =>
|
() async {
|
||||||
jsonResponse(201, okEnvelope(sampleUploadCredentialsJson())),
|
await setUpWith(
|
||||||
);
|
(options) async =>
|
||||||
|
jsonResponse(201, okEnvelope(sampleUploadCredentialsJson())),
|
||||||
|
);
|
||||||
|
|
||||||
final credentials = await repository.createMediaUpload(
|
final credentials = await repository.createMediaUpload(
|
||||||
const CreateMediaUploadRequest(
|
const CreateMediaUploadRequest(
|
||||||
kind: MediaKind.image,
|
kind: MediaKind.image,
|
||||||
purpose: MediaPurpose.postImage,
|
purpose: MediaPurpose.postImage,
|
||||||
mimeType: 'image/jpeg',
|
mimeType: 'image/jpeg',
|
||||||
byteSize: 204800,
|
byteSize: 204800,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
final request = adapter.requests.single;
|
// 线路:media 端点不打 community 客户端。
|
||||||
expect(request.path, '/api/v1/media/uploads');
|
expect(adapter.requests, isEmpty);
|
||||||
expect(request.method, 'POST');
|
final request = mediaAdapter.requests.single;
|
||||||
expect(request.headers['Authorization'], 'Bearer community-access');
|
expect(request.baseUrl, 'http://user.local');
|
||||||
expect(request.data, {
|
expect(request.path, '/api/v1/media/uploads');
|
||||||
'kind': 'image',
|
expect(request.method, 'POST');
|
||||||
'purpose': 'post_image',
|
expect(request.headers['Authorization'], 'Bearer community-access');
|
||||||
'mimeType': 'image/jpeg',
|
expect(request.data, {
|
||||||
'byteSize': 204800,
|
'kind': 'image',
|
||||||
});
|
'purpose': 'post_image',
|
||||||
expect(credentials.uploadUrl, contains('X-Amz-Signature'));
|
'mimeType': 'image/jpeg',
|
||||||
});
|
'byteSize': 204800,
|
||||||
|
});
|
||||||
|
expect(credentials.uploadUrl, contains('X-Amz-Signature'));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
test('completeMediaUpload:POST /complete 无请求体(服务端幂等)', () async {
|
test('completeMediaUpload:POST /complete 无请求体(服务端幂等)', () async {
|
||||||
await setUpWith(
|
await setUpWith(
|
||||||
@@ -70,7 +90,8 @@ void main() {
|
|||||||
|
|
||||||
final asset = await repository.completeMediaUpload('a-1');
|
final asset = await repository.completeMediaUpload('a-1');
|
||||||
|
|
||||||
final request = adapter.requests.single;
|
expect(adapter.requests, isEmpty);
|
||||||
|
final request = mediaAdapter.requests.single;
|
||||||
expect(request.path, '/api/v1/media/uploads/a-1/complete');
|
expect(request.path, '/api/v1/media/uploads/a-1/complete');
|
||||||
expect(request.method, 'POST');
|
expect(request.method, 'POST');
|
||||||
expect(asset.status, MediaAssetStatus.ready);
|
expect(asset.status, MediaAssetStatus.ready);
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_direct_upload.dart';
|
||||||
|
|
||||||
|
/// 预签名直传客户端(T3-13):本地 HttpServer 模拟 MinIO
|
||||||
|
/// (埋点队列测试先例)——200 成功、403 签名过期、传输中断三线路。
|
||||||
|
void main() {
|
||||||
|
Future<HttpServer> startServer(
|
||||||
|
Future<void> Function(HttpRequest request) handler,
|
||||||
|
) async {
|
||||||
|
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
server.listen((request) async => handler(request));
|
||||||
|
return server;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('200:PUT 本体逐字节到达,requiredHeaders 原样携带,无鉴权头泄漏', () async {
|
||||||
|
late Map<String, String?> seenHeaders;
|
||||||
|
late List<int> seenBody;
|
||||||
|
late String seenMethod;
|
||||||
|
final server = await startServer((request) async {
|
||||||
|
seenMethod = request.method;
|
||||||
|
seenHeaders = {
|
||||||
|
'content-type': request.headers.value('content-type'),
|
||||||
|
'authorization': request.headers.value('authorization'),
|
||||||
|
'x-device-id': request.headers.value('x-device-id'),
|
||||||
|
};
|
||||||
|
seenBody = await request.fold<List<int>>(
|
||||||
|
[],
|
||||||
|
(all, chunk) => all..addAll(chunk),
|
||||||
|
);
|
||||||
|
request.response.statusCode = 200;
|
||||||
|
await request.response.close();
|
||||||
|
});
|
||||||
|
addTearDown(() => server.close(force: true));
|
||||||
|
|
||||||
|
final bytes = Uint8List.fromList(List.generate(4096, (i) => i % 251));
|
||||||
|
final progress = <(int, int)>[];
|
||||||
|
await DioMediaDirectUploadClient().put(
|
||||||
|
url:
|
||||||
|
'http://127.0.0.1:${server.port}/patbond-media/post_image/a-1?X-Amz-Signature=sig',
|
||||||
|
headers: const {'Content-Type': 'image/jpeg'},
|
||||||
|
bytes: bytes,
|
||||||
|
onProgress: (sent, total) => progress.add((sent, total)),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(seenMethod, 'PUT');
|
||||||
|
expect(seenBody, bytes);
|
||||||
|
// Content-Type 已签进签名,必须原样携带。
|
||||||
|
expect(seenHeaders['content-type'], 'image/jpeg');
|
||||||
|
// 裸客户端:预签名 URL 即鉴权,业务侧 Bearer/设备头不得外漏给存储。
|
||||||
|
expect(seenHeaders['authorization'], isNull);
|
||||||
|
expect(seenHeaders['x-device-id'], isNull);
|
||||||
|
expect(progress.last.$1, progress.last.$2);
|
||||||
|
expect(progress.last.$2, bytes.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('403(签名过期/被改动)→ isCredentialRejected 异常', () async {
|
||||||
|
final server = await startServer((request) async {
|
||||||
|
await request.drain<void>();
|
||||||
|
request.response.statusCode = 403;
|
||||||
|
await request.response.close();
|
||||||
|
});
|
||||||
|
addTearDown(() => server.close(force: true));
|
||||||
|
|
||||||
|
await expectLater(
|
||||||
|
DioMediaDirectUploadClient().put(
|
||||||
|
url: 'http://127.0.0.1:${server.port}/patbond-media/a-1',
|
||||||
|
headers: const {'Content-Type': 'image/jpeg'},
|
||||||
|
bytes: Uint8List(16),
|
||||||
|
),
|
||||||
|
throwsA(
|
||||||
|
isA<MediaDirectUploadException>()
|
||||||
|
.having((e) => e.statusCode, 'statusCode', 403)
|
||||||
|
.having(
|
||||||
|
(e) => e.isCredentialRejected,
|
||||||
|
'isCredentialRejected',
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('传输中断(服务端半途断连)→ 网络型异常(statusCode null,可重试)', () async {
|
||||||
|
final server = await startServer((request) async {
|
||||||
|
// 读取少量字节后直接断开 socket,不回任何响应。
|
||||||
|
await request.take(1).drain<void>();
|
||||||
|
final socket = await request.response.detachSocket(writeHeaders: false);
|
||||||
|
await socket.close();
|
||||||
|
socket.destroy();
|
||||||
|
});
|
||||||
|
addTearDown(() => server.close(force: true));
|
||||||
|
|
||||||
|
await expectLater(
|
||||||
|
DioMediaDirectUploadClient().put(
|
||||||
|
url: 'http://127.0.0.1:${server.port}/patbond-media/a-1',
|
||||||
|
headers: const {'Content-Type': 'image/jpeg'},
|
||||||
|
bytes: Uint8List.fromList(List.filled(1 << 20, 7)),
|
||||||
|
),
|
||||||
|
throwsA(
|
||||||
|
isA<MediaDirectUploadException>()
|
||||||
|
.having((e) => e.statusCode, 'statusCode', isNull)
|
||||||
|
.having(
|
||||||
|
(e) => e.isCredentialRejected,
|
||||||
|
'isCredentialRejected',
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,470 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:patbond_flutter/core/network/api_exception.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/community_exceptions.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/community_models.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_direct_upload.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_uploader.dart';
|
||||||
|
|
||||||
|
import '../../helpers/community_test_helpers.dart';
|
||||||
|
import '../../helpers/media_test_helpers.dart';
|
||||||
|
|
||||||
|
/// MediaUploader 状态机全路径(T3-13):
|
||||||
|
/// 选图→压缩→createUpload→直传→confirm→ready 编排、并发顺序保持、
|
||||||
|
/// 弱网失败语义(凭据过期重取 / 403 换凭据 / 42205 重试)与孤儿防护。
|
||||||
|
void main() {
|
||||||
|
late FakeCommunityRepository repository;
|
||||||
|
late FakeMediaImagePicker picker;
|
||||||
|
late FakeMediaCompressor compressor;
|
||||||
|
late FakeDirectUploadClient direct;
|
||||||
|
int uploadSeq = 0;
|
||||||
|
|
||||||
|
MediaUploader build({
|
||||||
|
int maxConcurrentUploads = 2,
|
||||||
|
int maxByteSize = 10 * 1024 * 1024,
|
||||||
|
DateTime Function()? now,
|
||||||
|
}) {
|
||||||
|
return MediaUploader(
|
||||||
|
repository: repository,
|
||||||
|
picker: picker,
|
||||||
|
compressor: compressor,
|
||||||
|
directUpload: direct,
|
||||||
|
maxConcurrentUploads: maxConcurrentUploads,
|
||||||
|
maxByteSize: maxByteSize,
|
||||||
|
now: now,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
repository = FakeCommunityRepository();
|
||||||
|
picker = FakeMediaImagePicker([]);
|
||||||
|
compressor = FakeMediaCompressor();
|
||||||
|
direct = FakeDirectUploadClient();
|
||||||
|
uploadSeq = 0;
|
||||||
|
// 默认脚本:凭据按序发号,confirm 返回同 id 的 ready asset。
|
||||||
|
repository.onCreateMediaUpload = (request) async =>
|
||||||
|
credentials(assetId: 'a-${++uploadSeq}');
|
||||||
|
repository.onCompleteMediaUpload = (assetId) async =>
|
||||||
|
readyAsset(assetId: assetId);
|
||||||
|
});
|
||||||
|
|
||||||
|
group('happy path', () {
|
||||||
|
test('单图全程:阶段序列 + 进度 + ready assetId 交付', () async {
|
||||||
|
direct.manual = true;
|
||||||
|
final uploader = build();
|
||||||
|
final phases = <MediaItemPhase>[];
|
||||||
|
uploader.addListener(() {
|
||||||
|
if (uploader.items.isNotEmpty) phases.add(uploader.items.single.phase);
|
||||||
|
});
|
||||||
|
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
final call = direct.calls.single;
|
||||||
|
expect(uploader.items.single.phase, MediaItemPhase.uploading);
|
||||||
|
call.emitProgress(512, 1024);
|
||||||
|
expect(uploader.items.single.progress, 0.5);
|
||||||
|
// 上传中 assetId 不可见(孤儿防护)。
|
||||||
|
expect(uploader.items.single.assetId, isNull);
|
||||||
|
|
||||||
|
call.succeed();
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
final item = uploader.items.single;
|
||||||
|
expect(item.phase, MediaItemPhase.ready);
|
||||||
|
expect(item.assetId, 'a-1');
|
||||||
|
expect(item.progress, 1);
|
||||||
|
expect(uploader.allReady, isTrue);
|
||||||
|
expect(phases.first, MediaItemPhase.queued);
|
||||||
|
expect(
|
||||||
|
phases,
|
||||||
|
containsAllInOrder([
|
||||||
|
MediaItemPhase.queued,
|
||||||
|
MediaItemPhase.compressing,
|
||||||
|
MediaItemPhase.uploading,
|
||||||
|
MediaItemPhase.confirming,
|
||||||
|
MediaItemPhase.ready,
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
expect(repository.calls, ['createUpload:image/jpeg:64', 'complete:a-1']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('直传按凭据原样携带 requiredHeaders 与压缩产物字节', () async {
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage(seed: 7, size: 128)]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
final call = direct.calls.single;
|
||||||
|
expect(call.headers, {'Content-Type': 'image/jpeg'});
|
||||||
|
expect(call.url, contains('X-Amz-Signature'));
|
||||||
|
expect(call.bytes.length, 128);
|
||||||
|
// 登记 byteSize 与直传本体一致。
|
||||||
|
expect(repository.calls.first, 'createUpload:image/jpeg:128');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('压缩降质阶梯:80 超限降 60,登记与直传用 60 档产物', () async {
|
||||||
|
compressor.sizePerQuality = {80: 11 * 1024 * 1024, 60: 9 * 1024 * 1024};
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(compressor.qualities, [80, 60]);
|
||||||
|
expect(uploader.items.single.phase, MediaItemPhase.ready);
|
||||||
|
expect(direct.calls.single.bytes.length, 9 * 1024 * 1024);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('多图并发与顺序保持', () {
|
||||||
|
test('并发上限 2:第三张等槽位;完成乱序不影响 position 语义', () async {
|
||||||
|
direct.manual = true;
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([
|
||||||
|
pickedImage(seed: 1),
|
||||||
|
pickedImage(seed: 2),
|
||||||
|
pickedImage(seed: 3),
|
||||||
|
]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
// 只有前两张进入直传,第三张排队等槽位。
|
||||||
|
expect(direct.calls, hasLength(2));
|
||||||
|
expect(uploader.items[2].phase, MediaItemPhase.queued);
|
||||||
|
|
||||||
|
// 第二张先完成(乱序),释放槽位后第三张才发起。
|
||||||
|
direct.calls[1].succeed();
|
||||||
|
await pumpEventQueue();
|
||||||
|
expect(direct.calls, hasLength(3));
|
||||||
|
direct.calls[0].succeed();
|
||||||
|
direct.calls[2].succeed();
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(uploader.allReady, isTrue);
|
||||||
|
final attach = uploader.buildAttachRequests();
|
||||||
|
// position 按加入序 0..2,与完成先后无关;isCover 恰好首图。
|
||||||
|
expect(attach.map((a) => a.position), [0, 1, 2]);
|
||||||
|
expect(attach.map((a) => a.isCover), [true, false, false]);
|
||||||
|
// 完成序:第 2 张先确认(a-2),仍归位 index 1。
|
||||||
|
expect(attach[1].assetId, 'a-2');
|
||||||
|
expect(attach[0].assetId, 'a-1');
|
||||||
|
expect(attach[2].assetId, 'a-3');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('单图失败不拖垮整批:另一张照常 ready', () async {
|
||||||
|
direct.manual = true;
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage(seed: 1), pickedImage(seed: 2)]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
direct.calls[0].fail(const MediaDirectUploadException(message: '断连'));
|
||||||
|
direct.calls[1].succeed();
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(uploader.items[0].phase, MediaItemPhase.failed);
|
||||||
|
expect(uploader.items[0].retryable, isTrue);
|
||||||
|
expect(uploader.items[1].phase, MediaItemPhase.ready);
|
||||||
|
expect(uploader.hasFailure, isTrue);
|
||||||
|
expect(uploader.allReady, isFalse);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('弱网 / 失败语义', () {
|
||||||
|
test('直传网络中断 → failed 可重试;retry 复用压缩产物、换新 asset', () async {
|
||||||
|
direct.scriptedOutcomes.add(
|
||||||
|
const MediaDirectUploadException(message: '断连'),
|
||||||
|
);
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
expect(uploader.items.single.phase, MediaItemPhase.failed);
|
||||||
|
expect(uploader.items.single.retryable, isTrue);
|
||||||
|
|
||||||
|
uploader.retry(uploader.items.single.localId);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
final item = uploader.items.single;
|
||||||
|
expect(item.phase, MediaItemPhase.ready);
|
||||||
|
// 重试从 createUpload 全新开始(a-2),旧 a-1 弃引用。
|
||||||
|
expect(item.assetId, 'a-2');
|
||||||
|
// 压缩只做一次(产物缓存)。
|
||||||
|
expect(compressor.qualities, [80]);
|
||||||
|
expect(repository.calls, [
|
||||||
|
'createUpload:image/jpeg:64',
|
||||||
|
'createUpload:image/jpeg:64',
|
||||||
|
'complete:a-2',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('凭据过期预检:PUT 前重新 createUpload 换新凭据', () async {
|
||||||
|
final clock = DateTime.utc(2026, 9, 9, 12);
|
||||||
|
var issued = 0;
|
||||||
|
repository.onCreateMediaUpload = (request) async {
|
||||||
|
issued++;
|
||||||
|
return credentials(
|
||||||
|
assetId: 'a-$issued',
|
||||||
|
// 首张凭据已进入 30 秒安全边距,第二张充足。
|
||||||
|
expiresAt: issued == 1
|
||||||
|
? clock.add(const Duration(seconds: 10))
|
||||||
|
: clock.add(const Duration(minutes: 10)),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
final uploader = build(now: () => clock);
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(issued, 2);
|
||||||
|
expect(direct.calls.single.url, contains('/a-2?'));
|
||||||
|
expect(uploader.items.single.assetId, 'a-2');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('换新凭据仍过期 → failed 可重试,不再无限重取', () async {
|
||||||
|
final clock = DateTime.utc(2026, 9, 9, 12);
|
||||||
|
repository.onCreateMediaUpload = (request) async =>
|
||||||
|
credentials(expiresAt: clock);
|
||||||
|
final uploader = build(now: () => clock);
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(uploader.items.single.phase, MediaItemPhase.failed);
|
||||||
|
expect(uploader.items.single.retryable, isTrue);
|
||||||
|
expect(direct.calls, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('存储侧 403(签名过期)→ 自动换新凭据重传一次后 ready', () async {
|
||||||
|
direct.scriptedOutcomes.add(
|
||||||
|
const MediaDirectUploadException(statusCode: 403, message: '签名过期'),
|
||||||
|
);
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(direct.calls, hasLength(2));
|
||||||
|
expect(uploader.items.single.phase, MediaItemPhase.ready);
|
||||||
|
expect(uploader.items.single.assetId, 'a-2');
|
||||||
|
expect(repository.calls.last, 'complete:a-2');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('换新凭据后仍 403 → failed 可重试,不无限自动重传', () async {
|
||||||
|
direct.scriptedOutcomes.addAll([
|
||||||
|
const MediaDirectUploadException(statusCode: 403, message: '签名过期'),
|
||||||
|
const MediaDirectUploadException(statusCode: 403, message: '签名过期'),
|
||||||
|
]);
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(direct.calls, hasLength(2));
|
||||||
|
expect(uploader.items.single.phase, MediaItemPhase.failed);
|
||||||
|
expect(uploader.items.single.retryable, isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('confirm 42205(对象未上传/内容不符)→ failed 可重试,重试换新 asset', () async {
|
||||||
|
var confirms = 0;
|
||||||
|
repository.onCompleteMediaUpload = (assetId) async {
|
||||||
|
if (++confirms == 1) {
|
||||||
|
throw const MediaUploadStateException(message: '上传未完成');
|
||||||
|
}
|
||||||
|
return readyAsset(assetId: assetId);
|
||||||
|
};
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
expect(uploader.items.single.phase, MediaItemPhase.failed);
|
||||||
|
expect(uploader.items.single.retryable, isTrue);
|
||||||
|
expect(uploader.items.single.assetId, isNull);
|
||||||
|
|
||||||
|
uploader.retry(uploader.items.single.localId);
|
||||||
|
await pumpEventQueue();
|
||||||
|
expect(uploader.items.single.phase, MediaItemPhase.ready);
|
||||||
|
expect(uploader.items.single.assetId, 'a-2');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('confirm 返回非 ready 状态(防御)→ failed 可重试', () async {
|
||||||
|
repository.onCompleteMediaUpload = (assetId) async =>
|
||||||
|
MediaAsset.fromJson({
|
||||||
|
...readyAssetJson(assetId: assetId),
|
||||||
|
'status': 'uploading',
|
||||||
|
'url': null,
|
||||||
|
'readyAt': null,
|
||||||
|
});
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(uploader.items.single.phase, MediaItemPhase.failed);
|
||||||
|
expect(uploader.items.single.retryable, isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('createUpload 40000(参数拒绝)→ failed 终态不可重试', () async {
|
||||||
|
repository.onCreateMediaUpload = (request) async {
|
||||||
|
throw const ApiBusinessException(code: 40000, message: 'mime 不允许');
|
||||||
|
};
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
final item = uploader.items.single;
|
||||||
|
expect(item.phase, MediaItemPhase.failed);
|
||||||
|
expect(item.retryable, isFalse);
|
||||||
|
uploader.retry(item.localId);
|
||||||
|
await pumpEventQueue();
|
||||||
|
// 终态失败 retry 为 no-op。
|
||||||
|
expect(repository.calls, hasLength(1));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('压缩阶梯到底仍超限 → failed 终态,未发起任何网络调用', () async {
|
||||||
|
compressor.sizePerQuality = {80: 12 * 1024 * 1024, 60: 11 * 1024 * 1024};
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
final item = uploader.items.single;
|
||||||
|
expect(item.phase, MediaItemPhase.failed);
|
||||||
|
expect(item.retryable, isFalse);
|
||||||
|
expect(repository.calls, isEmpty);
|
||||||
|
expect(direct.calls, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('压缩异常 → failed 可重试', () async {
|
||||||
|
compressor.error = Exception('原生编解码失败');
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(uploader.items.single.phase, MediaItemPhase.failed);
|
||||||
|
expect(uploader.items.single.retryable, isTrue);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('孤儿防护(未 confirm 的 asset 不得被引用)', () {
|
||||||
|
test('非全员 ready 时 buildAttachRequests 抛 StateError', () async {
|
||||||
|
direct.manual = true;
|
||||||
|
final uploader = build();
|
||||||
|
expect(uploader.buildAttachRequests, throwsStateError);
|
||||||
|
|
||||||
|
uploader.addImages([pickedImage(seed: 1), pickedImage(seed: 2)]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
// 在途(uploading)。
|
||||||
|
expect(uploader.buildAttachRequests, throwsStateError);
|
||||||
|
|
||||||
|
direct.calls[0].succeed();
|
||||||
|
direct.calls[1].fail(const MediaDirectUploadException(message: '断连'));
|
||||||
|
await pumpEventQueue();
|
||||||
|
// 一 ready 一 failed:失败项在场仍禁止引用。
|
||||||
|
expect(uploader.readyCount, 1);
|
||||||
|
expect(uploader.buildAttachRequests, throwsStateError);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('全生命周期快照 assetId 仅 ready 态非空', () async {
|
||||||
|
direct.manual = true;
|
||||||
|
final uploader = build();
|
||||||
|
final observed = <MediaItemPhase, String?>{};
|
||||||
|
uploader.addListener(() {
|
||||||
|
for (final item in uploader.items) {
|
||||||
|
observed[item.phase] = item.assetId;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
direct.calls.single.succeed();
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(observed[MediaItemPhase.ready], 'a-1');
|
||||||
|
for (final MapEntry(:key, :value) in observed.entries) {
|
||||||
|
if (key != MediaItemPhase.ready) expect(value, isNull);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('直传在途 remove → 结果作废,不发 confirm', () async {
|
||||||
|
direct.manual = true;
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
uploader.remove(uploader.items.single.localId);
|
||||||
|
expect(uploader.isEmpty, isTrue);
|
||||||
|
|
||||||
|
direct.calls.single.succeed();
|
||||||
|
await pumpEventQueue();
|
||||||
|
// 已移除的图完成直传也不确认(asset 留给服务端超时清理)。
|
||||||
|
expect(repository.calls.where((c) => c.startsWith('complete')), isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reset 后在途 confirm 结果作废', () async {
|
||||||
|
direct.manual = true;
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage()]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
uploader.reset();
|
||||||
|
direct.calls.single.succeed();
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(uploader.isEmpty, isTrue);
|
||||||
|
expect(repository.calls.where((c) => c.startsWith('complete')), isEmpty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('选图与容量', () {
|
||||||
|
test('pickAndAdd:picking 态、limit=剩余槽位、产物入列', () async {
|
||||||
|
picker.results.addAll([pickedImage(seed: 1), pickedImage(seed: 2)]);
|
||||||
|
picker.gate = Completer<void>();
|
||||||
|
final uploader = build();
|
||||||
|
|
||||||
|
final picking = uploader.pickAndAdd();
|
||||||
|
expect(uploader.isPicking, isTrue);
|
||||||
|
picker.gate!.complete();
|
||||||
|
await picking;
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(uploader.isPicking, isFalse);
|
||||||
|
expect(picker.limits, [9]);
|
||||||
|
expect(uploader.items, hasLength(2));
|
||||||
|
expect(uploader.allReady, isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('用户取消选择(空结果)→ 恢复空闲,无副作用', () async {
|
||||||
|
final uploader = build();
|
||||||
|
await uploader.pickAndAdd();
|
||||||
|
await pumpEventQueue();
|
||||||
|
expect(uploader.isPicking, isFalse);
|
||||||
|
expect(uploader.isEmpty, isTrue);
|
||||||
|
expect(repository.calls, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('满 9 张后 pickAndAdd no-op;addImages 超量截断', () async {
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages(List.generate(11, (i) => pickedImage(seed: i)));
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
expect(uploader.items, hasLength(9));
|
||||||
|
expect(uploader.remainingSlots, 0);
|
||||||
|
await uploader.pickAndAdd();
|
||||||
|
expect(picker.limits, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('overallProgress 汇总:ready 计 1、uploading 计进度', () async {
|
||||||
|
direct.manual = true;
|
||||||
|
final uploader = build();
|
||||||
|
uploader.addImages([pickedImage(seed: 1), pickedImage(seed: 2)]);
|
||||||
|
await pumpEventQueue();
|
||||||
|
|
||||||
|
direct.calls[0].succeed();
|
||||||
|
await pumpEventQueue();
|
||||||
|
direct.calls[1].emitProgress(1, 2);
|
||||||
|
expect(uploader.overallProgress, closeTo(0.75, 0.001));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, dynamic> readyAssetJson({required String assetId}) => {
|
||||||
|
'id': assetId,
|
||||||
|
'kind': 'image',
|
||||||
|
'purpose': 'post_image',
|
||||||
|
'mimeType': 'image/jpeg',
|
||||||
|
'byteSize': 1024,
|
||||||
|
'widthPx': 1080,
|
||||||
|
'heightPx': 810,
|
||||||
|
'status': 'ready',
|
||||||
|
'url': 'http://minio.local/p.jpg?X-Amz-Signature=sig',
|
||||||
|
'readyAt': '2026-09-09T00:00:00.000Z',
|
||||||
|
'createdAt': '2026-09-09T00:00:00.000Z',
|
||||||
|
};
|
||||||
@@ -141,6 +141,9 @@ class FakeCommunityRepository implements CommunityRepository {
|
|||||||
Future<LikeState> Function(String postId, bool target)? onLikeToggle;
|
Future<LikeState> Function(String postId, bool target)? onLikeToggle;
|
||||||
Future<BookmarkState> Function(String postId, bool target)? onBookmarkToggle;
|
Future<BookmarkState> Function(String postId, bool target)? onBookmarkToggle;
|
||||||
Future<Post> Function(String postId)? onGetPost;
|
Future<Post> Function(String postId)? onGetPost;
|
||||||
|
Future<MediaUploadCredentials> Function(CreateMediaUploadRequest request)?
|
||||||
|
onCreateMediaUpload;
|
||||||
|
Future<MediaAsset> Function(String assetId)? onCompleteMediaUpload;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<CursorPage<FeedCard>> getFeed({int? limit, String? cursor}) {
|
Future<CursorPage<FeedCard>> getFeed({int? limit, String? cursor}) {
|
||||||
@@ -181,11 +184,16 @@ class FakeCommunityRepository implements CommunityRepository {
|
|||||||
@override
|
@override
|
||||||
Future<MediaUploadCredentials> createMediaUpload(
|
Future<MediaUploadCredentials> createMediaUpload(
|
||||||
CreateMediaUploadRequest request,
|
CreateMediaUploadRequest request,
|
||||||
) => throw UnimplementedError();
|
) {
|
||||||
|
calls.add('createUpload:${request.mimeType}:${request.byteSize}');
|
||||||
|
return onCreateMediaUpload!(request);
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<MediaAsset> completeMediaUpload(String assetId) =>
|
Future<MediaAsset> completeMediaUpload(String assetId) {
|
||||||
throw UnimplementedError();
|
calls.add('complete:$assetId');
|
||||||
|
return onCompleteMediaUpload!(assetId);
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<Post> createPost(CreatePostRequest request) =>
|
Future<Post> createPost(CreatePostRequest request) =>
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:patbond_flutter/features/community/community_models.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_compression.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_direct_upload.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_picking.dart';
|
||||||
|
|
||||||
|
/// media 上传链路测试件(T3-13):假选择器/压缩器/直传客户端,
|
||||||
|
/// 全部支持 Completer 控时序(helpers 既有先例)。
|
||||||
|
|
||||||
|
PickedMediaImage pickedImage({int seed = 1, int size = 64}) => PickedMediaImage(
|
||||||
|
bytes: Uint8List.fromList(List.filled(size, seed)),
|
||||||
|
name: 'img-$seed.jpg',
|
||||||
|
);
|
||||||
|
|
||||||
|
MediaUploadCredentials credentials({
|
||||||
|
String assetId = 'a-1',
|
||||||
|
DateTime? expiresAt,
|
||||||
|
}) => MediaUploadCredentials(
|
||||||
|
assetId: assetId,
|
||||||
|
uploadUrl:
|
||||||
|
'http://minio.local/patbond-media/post_image/$assetId?X-Amz-Signature=sig',
|
||||||
|
method: 'PUT',
|
||||||
|
requiredHeaders: const {'Content-Type': 'image/jpeg'},
|
||||||
|
expiresAt: expiresAt ?? DateTime.now().add(const Duration(minutes: 10)),
|
||||||
|
);
|
||||||
|
|
||||||
|
MediaAsset readyAsset({String assetId = 'a-1'}) => MediaAsset(
|
||||||
|
id: assetId,
|
||||||
|
kind: MediaKind.image,
|
||||||
|
purpose: 'post_image',
|
||||||
|
mimeType: 'image/jpeg',
|
||||||
|
byteSize: 1024,
|
||||||
|
widthPx: 1080,
|
||||||
|
heightPx: 810,
|
||||||
|
status: MediaAssetStatus.ready,
|
||||||
|
url: 'http://minio.local/p.jpg?X-Amz-Signature=sig',
|
||||||
|
readyAt: DateTime.utc(2026, 9, 9),
|
||||||
|
createdAt: DateTime.utc(2026, 9, 9),
|
||||||
|
);
|
||||||
|
|
||||||
|
class FakeMediaImagePicker implements MediaImagePicker {
|
||||||
|
FakeMediaImagePicker(this.results);
|
||||||
|
|
||||||
|
final List<PickedMediaImage> results;
|
||||||
|
final List<int> limits = [];
|
||||||
|
|
||||||
|
/// 非 null 时 pickImages 挂起等待(picking 态观测用)。
|
||||||
|
Completer<void>? gate;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<PickedMediaImage>> pickImages({required int limit}) async {
|
||||||
|
limits.add(limit);
|
||||||
|
await gate?.future;
|
||||||
|
return results.take(limit).toList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 假压缩器:默认原样透传出 image/jpeg;[sizePerQuality] 指定各降质档
|
||||||
|
/// 的产物大小(超限阶梯测试用)。
|
||||||
|
class FakeMediaCompressor implements MediaImageCompressor {
|
||||||
|
final List<int> qualities = [];
|
||||||
|
Map<int, int>? sizePerQuality;
|
||||||
|
Exception? error;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<CompressedMediaImage> compress(
|
||||||
|
PickedMediaImage source, {
|
||||||
|
required int quality,
|
||||||
|
}) async {
|
||||||
|
qualities.add(quality);
|
||||||
|
if (error != null) throw error!;
|
||||||
|
final size = sizePerQuality?[quality];
|
||||||
|
return CompressedMediaImage(
|
||||||
|
bytes: size == null
|
||||||
|
? source.bytes
|
||||||
|
: Uint8List.fromList(List.filled(size, 0)),
|
||||||
|
mimeType: 'image/jpeg',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 一次直传调用的观测句柄(进度回调驱动 + 结局手动控制)。
|
||||||
|
class DirectUploadCall {
|
||||||
|
DirectUploadCall({
|
||||||
|
required this.url,
|
||||||
|
required this.headers,
|
||||||
|
required this.bytes,
|
||||||
|
required this.onProgress,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String url;
|
||||||
|
final Map<String, String> headers;
|
||||||
|
final Uint8List bytes;
|
||||||
|
final void Function(int sent, int total)? onProgress;
|
||||||
|
final Completer<void> completer = Completer<void>();
|
||||||
|
|
||||||
|
void emitProgress(int sent, int total) => onProgress?.call(sent, total);
|
||||||
|
void succeed() => completer.complete();
|
||||||
|
void fail(MediaDirectUploadException error) => completer.completeError(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
class FakeDirectUploadClient implements MediaDirectUploadClient {
|
||||||
|
final List<DirectUploadCall> calls = [];
|
||||||
|
|
||||||
|
/// 非 null 时每次 put 自动以该结果收尾(null = 自动成功);
|
||||||
|
/// 设为 manual 后由测试经 [calls] 手动驱动。
|
||||||
|
bool manual = false;
|
||||||
|
final List<MediaDirectUploadException?> scriptedOutcomes = [];
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> put({
|
||||||
|
required String url,
|
||||||
|
required Map<String, String> headers,
|
||||||
|
required Uint8List bytes,
|
||||||
|
void Function(int sent, int total)? onProgress,
|
||||||
|
}) {
|
||||||
|
final call = DirectUploadCall(
|
||||||
|
url: url,
|
||||||
|
headers: headers,
|
||||||
|
bytes: bytes,
|
||||||
|
onProgress: onProgress,
|
||||||
|
);
|
||||||
|
calls.add(call);
|
||||||
|
if (!manual) {
|
||||||
|
final outcome = scriptedOutcomes.isEmpty
|
||||||
|
? null
|
||||||
|
: scriptedOutcomes.removeAt(0);
|
||||||
|
if (outcome == null) {
|
||||||
|
call.succeed();
|
||||||
|
} else {
|
||||||
|
call.fail(outcome);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return call.completer.future;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:dio/dio.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:patbond_flutter/core/network/api_client.dart';
|
||||||
|
import 'package:patbond_flutter/core/network/token_refresher.dart';
|
||||||
|
import 'package:patbond_flutter/features/auth/auth_models.dart';
|
||||||
|
import 'package:patbond_flutter/features/auth/session_manager.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/community_models.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/community_repository.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_compression.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_picking.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_uploader.dart';
|
||||||
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
|
import '../helpers/auth_test_helpers.dart';
|
||||||
|
|
||||||
|
/// T3-13 compose 真链路冒烟(默认跳过,不计入常规测试套件):
|
||||||
|
///
|
||||||
|
/// ```bash
|
||||||
|
/// # 先起后端六容器(patbond-api 仓库根):
|
||||||
|
/// # ./deploy/init-secrets.sh
|
||||||
|
/// # JAVA_HOME=<JDK17> ./mvnw -DskipTests package && docker compose up -d --build
|
||||||
|
/// PATBOND_MEDIA_SMOKE=1 flutter test test/smoke/media_upload_smoke_test.dart
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// 驱动**真实 MediaUploader** 走完整链路:注册取 token → createUpload
|
||||||
|
/// (user :8082)→ 预签名 PUT 直传 MinIO(:9000)→ confirm → ready
|
||||||
|
/// assetId → 引用发帖(community :8084)→ 预签名 GET 取回字节一致。
|
||||||
|
/// 压缩层用透传实现(flutter test VM 无原生编解码通道),其余全为生产实现。
|
||||||
|
void main() {
|
||||||
|
final enabled = Platform.environment['PATBOND_MEDIA_SMOKE'] == '1';
|
||||||
|
final env = Platform.environment;
|
||||||
|
final authBase = env['PATBOND_SMOKE_AUTH_BASE'] ?? 'http://127.0.0.1:8081';
|
||||||
|
final userBase = env['PATBOND_SMOKE_USER_BASE'] ?? 'http://127.0.0.1:8082';
|
||||||
|
final communityBase =
|
||||||
|
env['PATBOND_SMOKE_COMMUNITY_BASE'] ?? 'http://127.0.0.1:8084';
|
||||||
|
|
||||||
|
// 1x1 PNG(67 字节,合法图片本体;mime 声明与直传 Content-Type 一致)。
|
||||||
|
final pngBytes = base64Decode(
|
||||||
|
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8'
|
||||||
|
'z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
|
||||||
|
);
|
||||||
|
|
||||||
|
test(
|
||||||
|
'选图→压缩→createUpload→直传→confirm→ready→引用发帖→GET 回读',
|
||||||
|
() async {
|
||||||
|
// ---- 注册测试账号(一次性,随机凭据,不落任何持久化)----
|
||||||
|
final dio = Dio(BaseOptions(validateStatus: (_) => true));
|
||||||
|
final seed = DateTime.now().millisecondsSinceEpoch;
|
||||||
|
final register = await dio.post<Map<String, dynamic>>(
|
||||||
|
'$authBase/api/v1/auth/register',
|
||||||
|
data: {
|
||||||
|
'username': 'smoke$seed',
|
||||||
|
'phone': '+86139${(seed % 100000000).toString().padLeft(8, '0')}',
|
||||||
|
'password': 'Smoke1234!$seed',
|
||||||
|
},
|
||||||
|
options: Options(
|
||||||
|
headers: {
|
||||||
|
'Idempotency-Key': const Uuid().v4(),
|
||||||
|
'X-Device-Id': const Uuid().v4(),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(register.data?['code'], 0, reason: '注册失败:${register.data}');
|
||||||
|
|
||||||
|
final session = SessionManager(store: InMemoryTokenStore());
|
||||||
|
await session.updateTokens(
|
||||||
|
AuthTokens.fromJson(register.data!['data'] as Map<String, dynamic>),
|
||||||
|
);
|
||||||
|
final refresher = TokenRefresher(
|
||||||
|
dio: buildPatbondDio(session: session, baseUrl: authBase),
|
||||||
|
session: session,
|
||||||
|
);
|
||||||
|
final repository = ApiCommunityRepository(
|
||||||
|
api: ApiClient(
|
||||||
|
dio: buildPatbondDio(session: session, baseUrl: communityBase),
|
||||||
|
session: session,
|
||||||
|
refresher: refresher,
|
||||||
|
),
|
||||||
|
mediaApi: ApiClient(
|
||||||
|
dio: buildPatbondDio(session: session, baseUrl: userBase),
|
||||||
|
session: session,
|
||||||
|
refresher: refresher,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
// ---- 真实 MediaUploader 全链路 ----
|
||||||
|
final uploader = MediaUploader(
|
||||||
|
repository: repository,
|
||||||
|
compressor: _PassthroughPngCompressor(),
|
||||||
|
);
|
||||||
|
final done = Completer<void>();
|
||||||
|
uploader.addListener(() {
|
||||||
|
if (done.isCompleted) return;
|
||||||
|
if (uploader.allReady) done.complete();
|
||||||
|
if (uploader.hasFailure) {
|
||||||
|
done.completeError(
|
||||||
|
StateError('上传失败:${uploader.items.single.errorMessage}'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
uploader.addImages([
|
||||||
|
PickedMediaImage(bytes: pngBytes, name: 'smoke.png'),
|
||||||
|
]);
|
||||||
|
await done.future.timeout(const Duration(seconds: 60));
|
||||||
|
|
||||||
|
final item = uploader.items.single;
|
||||||
|
expect(item.phase, MediaItemPhase.ready);
|
||||||
|
expect(item.assetId, isNotEmpty);
|
||||||
|
|
||||||
|
// ---- ready assetId 引用发帖(孤儿防护出口)+ 预签名 GET 回读 ----
|
||||||
|
final post = await repository.createPost(
|
||||||
|
CreatePostRequest(
|
||||||
|
content: 'T3-13 媒体上传冒烟 $seed',
|
||||||
|
status: PostStatus.published,
|
||||||
|
media: uploader.buildAttachRequests(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(post.media.single.assetId, item.assetId);
|
||||||
|
final fetched = await dio.get<List<int>>(
|
||||||
|
post.media.single.url,
|
||||||
|
options: Options(responseType: ResponseType.bytes),
|
||||||
|
);
|
||||||
|
expect(fetched.statusCode, 200);
|
||||||
|
expect(fetched.data, pngBytes, reason: '预签名 GET 回读字节应与上传一致');
|
||||||
|
|
||||||
|
// 收尾:删除冒烟帖(asset 服务端软删语义随帖处理)。
|
||||||
|
await repository.deletePost(post.id);
|
||||||
|
},
|
||||||
|
skip: enabled ? false : '需 compose 后端在位,PATBOND_MEDIA_SMOKE=1 时执行',
|
||||||
|
timeout: const Timeout(Duration(minutes: 3)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 透传压缩器:原样输出字节并声明 image/png(仅冒烟用——测试 VM 无
|
||||||
|
/// flutter_image_compress 平台通道;生产走 NativeMediaImageCompressor)。
|
||||||
|
class _PassthroughPngCompressor implements MediaImageCompressor {
|
||||||
|
@override
|
||||||
|
Future<CompressedMediaImage> compress(
|
||||||
|
PickedMediaImage source, {
|
||||||
|
required int quality,
|
||||||
|
}) async => CompressedMediaImage(bytes: source.bytes, mimeType: 'image/png');
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:patbond_flutter/core/theme/app_theme.dart';
|
||||||
|
import 'package:patbond_flutter/core/widgets/upload_progress_overlay.dart';
|
||||||
|
import 'package:patbond_flutter/features/community/media_uploader.dart';
|
||||||
|
|
||||||
|
/// UploadProgressOverlay(05 号规范 §3.3):排队 / 上传中 / 失败三态
|
||||||
|
/// 形态与失败整格点按重试。
|
||||||
|
void main() {
|
||||||
|
Widget host(Widget overlay) => MaterialApp(
|
||||||
|
home: Scaffold(body: SizedBox(width: 100, height: 100, child: overlay)),
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('排队态:scrim + 「等待中」胶囊', (tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
host(const UploadProgressOverlay(phase: MediaItemPhase.queued)),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(find.text('等待中'), findsOneWidget);
|
||||||
|
expect(find.byType(CircularProgressIndicator), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('上传中态:环形进度带 value + 百分比胶囊', (tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
host(
|
||||||
|
const UploadProgressOverlay(
|
||||||
|
phase: MediaItemPhase.uploading,
|
||||||
|
progress: 0.4,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
final indicator = tester.widget<CircularProgressIndicator>(
|
||||||
|
find.byType(CircularProgressIndicator),
|
||||||
|
);
|
||||||
|
expect(indicator.value, 0.4);
|
||||||
|
expect(find.text('40%'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('confirming 定格 100%', (tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
host(
|
||||||
|
const UploadProgressOverlay(
|
||||||
|
phase: MediaItemPhase.confirming,
|
||||||
|
progress: 0.4,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(find.text('100%'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('失败态:errorDark 图标 + 重试通栏,整格点按触发 onRetry', (tester) async {
|
||||||
|
var retried = 0;
|
||||||
|
await tester.pumpWidget(
|
||||||
|
host(
|
||||||
|
UploadProgressOverlay(
|
||||||
|
phase: MediaItemPhase.failed,
|
||||||
|
onRetry: () => retried++,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
final icon = tester.widget<Icon>(find.byIcon(Icons.error_outline));
|
||||||
|
expect(icon.color, AppColors.errorDark);
|
||||||
|
expect(find.text('重试'), findsOneWidget);
|
||||||
|
// 整格(含图标区)点按即重试。
|
||||||
|
await tester.tap(find.byIcon(Icons.error_outline));
|
||||||
|
expect(retried, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('失败终态(onRetry null):不显示重试通栏', (tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
host(const UploadProgressOverlay(phase: MediaItemPhase.failed)),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(find.text('重试'), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('成功态:150ms 淡出且不拦截点击、无残留文案', (tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
host(const UploadProgressOverlay(phase: MediaItemPhase.ready)),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('等待中'), findsNothing);
|
||||||
|
expect(find.text('重试'), findsNothing);
|
||||||
|
expect(find.byType(IgnorePointer), findsWidgets);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -6,9 +6,12 @@
|
|||||||
|
|
||||||
#include "generated_plugin_registrant.h"
|
#include "generated_plugin_registrant.h"
|
||||||
|
|
||||||
|
#include <file_selector_windows/file_selector_windows.h>
|
||||||
#include <flutter_secure_storage_windows/flutter_secure_storage_windows_plugin.h>
|
#include <flutter_secure_storage_windows/flutter_secure_storage_windows_plugin.h>
|
||||||
|
|
||||||
void RegisterPlugins(flutter::PluginRegistry* registry) {
|
void RegisterPlugins(flutter::PluginRegistry* registry) {
|
||||||
|
FileSelectorWindowsRegisterWithRegistrar(
|
||||||
|
registry->GetRegistrarForPlugin("FileSelectorWindows"));
|
||||||
FlutterSecureStorageWindowsPluginRegisterWithRegistrar(
|
FlutterSecureStorageWindowsPluginRegisterWithRegistrar(
|
||||||
registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin"));
|
registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin"));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
#
|
#
|
||||||
|
|
||||||
list(APPEND FLUTTER_PLUGIN_LIST
|
list(APPEND FLUTTER_PLUGIN_LIST
|
||||||
|
file_selector_windows
|
||||||
flutter_secure_storage_windows
|
flutter_secure_storage_windows
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user