diff --git a/.gitignore b/.gitignore
index 2088348..ab91c06 100644
--- a/.gitignore
+++ b/.gitignore
@@ -47,3 +47,4 @@ app.*.map.json
.widget_preview/
android/.kotlin/
.codebuddy/
+/.workbuddy/
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 56bfcec..1630107 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -21,7 +21,7 @@
-
+
@@ -42,10 +42,6 @@
android:label="ttstd_family_care"
android:name=".AppApplication"
android:icon="@mipmap/ic_launcher">
-
-
-
-
用于扫描设备二维码完成绑定
NSPhotoLibraryUsageDescription
用于查看本机相册照片并按文件夹浏览,以及从相册选取二维码图片完成设备绑定
+ NSPhotoLibraryAddUsageDescription
+ 用于将远程屏幕录制保存到系统相册
io.flutter.embedded_views_preview
diff --git a/lib/features/apps/presentation/apps_page.dart b/lib/features/apps/presentation/apps_page.dart
index 90e9e84..0be1319 100644
--- a/lib/features/apps/presentation/apps_page.dart
+++ b/lib/features/apps/presentation/apps_page.dart
@@ -1,4 +1,7 @@
+import 'dart:async';
+
import 'package:ttstd_family_care/core/network/cached_network_image.dart';
+import 'package:ttstd_family_care/core/network/error_message.dart';
import 'package:cupertino_ui/cupertino_ui.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
@@ -12,15 +15,49 @@ import 'package:ttstd_family_care/app/theme/dark_mode.dart';
import 'package:ttstd_family_care/core/widgets/app_page_scaffold.dart';
/// 应用列表页(对接 client「已安装应用」接口)。
-class AppsPage extends ConsumerWidget {
+class AppsPage extends ConsumerStatefulWidget {
const AppsPage({super.key});
@override
- Widget build(BuildContext context, WidgetRef ref) {
+ ConsumerState createState() => _AppsPageState();
+}
+
+class _AppsPageState extends ConsumerState {
+ Timer? _reloadTimer;
+
+ @override
+ void dispose() {
+ _reloadTimer?.cancel();
+ super.dispose();
+ }
+
+ Future _refreshApps(String sn, AppLocalizations l10n) async {
+ String? error;
+ try {
+ error = await ref.read(deviceRepositoryProvider).sendDeviceOp(sn, 'refresh');
+ } catch (exception) {
+ error = userMessageOf(exception);
+ }
+ if (!mounted || ref.read(selectedDeviceSnProvider) != sn) return;
+ if (error != null) {
+ _showAppOpResult(context, l10n, error);
+ return;
+ }
+
+ _reloadTimer?.cancel();
+ _reloadTimer = Timer(const Duration(seconds: 5), () {
+ if (ref.read(selectedDeviceSnProvider) == sn) {
+ ref.invalidate(deviceApksProvider(sn));
+ }
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
final sn = ref.watch(selectedDeviceSnProvider);
final appsAsync = sn == null
- ? const AsyncValue>.data(const [])
+ ? const AsyncValue>.data([])
: ref.watch(deviceApksProvider(sn));
return PopScope(
@@ -44,34 +81,54 @@ class AppsPage extends ConsumerWidget {
),
),
child: SafeArea(
- child: appsAsync.when(
- loading: () => const Center(child: CupertinoActivityIndicator()),
- error: (e, _) => Center(
- child: Text('${l10n.appsLoadFailed}:$e',
- style: TextStyle(color: DarkMode.color(context, AppColors.sub))),
+ child: CustomScrollView(
+ physics: const AlwaysScrollableScrollPhysics(
+ parent: BouncingScrollPhysics(),
),
- data: (apps) {
- if (apps.isEmpty) {
- return Center(
- child: Text(l10n.appsEmpty,
- style: TextStyle(color: DarkMode.color(context, AppColors.sub))),
- );
- }
- return ListView.builder(
- padding: const EdgeInsets.all(16),
- itemCount: apps.length,
- itemBuilder: (context, index) {
- final app = apps[index];
- return _appCell(context, ref, l10n, sn, app);
+ slivers: [
+ if (sn != null)
+ CupertinoSliverRefreshControl(
+ onRefresh: () => _refreshApps(sn, l10n),
+ ),
+ appsAsync.when(
+ loading: () => const SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(child: CupertinoActivityIndicator()),
+ ),
+ error: (_, _) => _statusSliver(context, l10n.appsLoadFailed),
+ data: (apps) {
+ if (apps.isEmpty) {
+ return _statusSliver(context, l10n.appsEmpty);
+ }
+ return SliverPadding(
+ padding: const EdgeInsets.all(16),
+ sliver: SliverList.builder(
+ itemCount: apps.length,
+ itemBuilder: (context, index) =>
+ _appCell(context, ref, l10n, sn, apps[index]),
+ ),
+ );
},
- );
- },
+ ),
+ ],
),
),
),
);
}
+ Widget _statusSliver(BuildContext context, String message) {
+ return SliverFillRemaining(
+ hasScrollBody: false,
+ child: Center(
+ child: Text(
+ message,
+ style: TextStyle(color: DarkMode.color(context, AppColors.sub)),
+ ),
+ ),
+ );
+ }
+
Widget _appCell(
BuildContext context,
WidgetRef ref,
diff --git a/lib/features/connection/data/video_recorder.dart b/lib/features/connection/data/video_recorder.dart
index 46df64a..70ef08b 100644
--- a/lib/features/connection/data/video_recorder.dart
+++ b/lib/features/connection/data/video_recorder.dart
@@ -1,99 +1,111 @@
import 'dart:io';
+import 'package:device_info_plus/device_info_plus.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:path_provider/path_provider.dart';
+import 'package:permission_handler/permission_handler.dart';
+import 'package:photo_manager/photo_manager.dart';
-/// 远程视频录制器:基于 flutter_webrtc 的 [MediaRecorder],
-/// 把远端视频轨道(MediaStreamTrack)直接封装为 MP4 保存到本地。
-///
-/// 跨平台(Android / iOS)由 flutter_webrtc 内部完成 H.264 编码与封装,
-/// 无需自行触碰原生 VideoSink。
-///
-/// 录制文件保存位置:
-/// - Android:/Android/data/<包名>/files/WebRTCRecordings/(app 专属外部存储,无需存储权限)
-/// - iOS:<App>/Documents/WebRTCRecordings/
+/// 先完成 MP4 封装,再导出到系统媒体库。
class VideoRecorder {
+ static const _channel = MethodChannel('com.ttstd.familycare/app');
+ static const _screenRecordingsDirectory = 'Movies/Screen recordings';
+
MediaRecorder? _recorder;
- bool _recording = false;
- String? _currentPath;
+ File? _recordingFile;
+ Future? _starting;
+ Future? _stopping;
- /// 是否正在录制。
- bool get isRecording => _recording;
-
- /// 是否为空(从未真正开始)。
- String? get currentPath => _currentPath;
-
- /// 开始录制指定媒体流中的视频轨道。
- ///
- /// 返回 true 表示成功开始;空流 / 无视频轨道会抛异常。
- Future start(MediaStream stream) async {
- if (_recording) return false;
- final videoTracks = stream.getVideoTracks();
- if (videoTracks.isEmpty) {
- throw Exception('当前没有可用的远端视频轨道,无法录制');
+ Future requestSavePermission() async {
+ if (Platform.isAndroid) {
+ final info = await DeviceInfoPlugin().androidInfo;
+ if (info.version.sdkInt >= 29) return true;
+ return (await Permission.storage.request()).isGranted;
}
- final path = await _buildOutputPath();
- // ignore: avoid_print
- print('[VideoRecorder] 录制开始,保存地址:$path');
- _recorder = MediaRecorder(albumName: 'WebRTCRecordings');
- await _recorder!.start(path, videoTrack: videoTracks.first);
- _currentPath = path;
- _recording = true;
- return true;
+ if (Platform.isIOS) {
+ final status = await PhotoManager.requestPermissionExtend(
+ requestOption: const PermissionRequestOption(
+ iosAccessLevel: IosAccessLevel.addOnly,
+ ),
+ );
+ return status.hasAccess;
+ }
+ return false;
+ }
+
+ Future start(MediaStream stream) {
+ final operation = _start(stream);
+ _starting = operation;
+ return operation.whenComplete(() => _starting = null);
+ }
+
+ Future _start(MediaStream stream) async {
+ final tracks = stream.getVideoTracks();
+ if (tracks.isEmpty) throw StateError('No remote video track');
+
+ final base = await getApplicationDocumentsDirectory();
+ final directory = Directory('${base.path}/WebRTCRecordings');
+ await directory.create(recursive: true);
+ final file = File(
+ '${directory.path}/screen-${DateTime.now().microsecondsSinceEpoch}.mp4',
+ );
+ final recorder = MediaRecorder();
+ await recorder.start(file.path, videoTrack: tracks.first);
+ _recorder = recorder;
+ _recordingFile = file;
}
- /// 停止录制,返回最终保存的文件路径;未开始录制返回 null。
Future stop() async {
- if (!_recording || _recorder == null) return null;
- try {
- await _recorder!.stop();
- } catch (e) {
- // 停止失败时仍清理状态,避免界面卡在"录制中"
- // ignore: avoid_print
- print('[VideoRecorder] stop error: $e');
- } finally {
- _recorder = null;
- _recording = false;
- }
- final p = _currentPath;
- _currentPath = null;
- // ignore: avoid_print
- print('[VideoRecorder] 录制结束,已保存至:$p');
- return p;
- }
+ await _starting;
+ final pending = _stopping;
+ if (pending != null) return pending;
+
+ final recorder = _recorder;
+ final file = _recordingFile;
+ if (recorder == null || file == null) return null;
- /// 释放资源(断开连接 / 页面销毁时调用)。
- Future dispose() async {
- if (_recording && _recorder != null) {
- try {
- await _recorder!.stop();
- } catch (_) {
- // 忽略
- }
- }
_recorder = null;
- _recording = false;
- _currentPath = null;
+ _recordingFile = null;
+ final operation = _finish(recorder, file);
+ _stopping = operation.whenComplete(() => _stopping = null);
+ return _stopping!;
}
- static String _pad(int n) => n.toString().padLeft(2, '0');
-
- static Future _getRecordingDir() async {
- final base = Platform.isAndroid
- ? (await getExternalStorageDirectory())!
- : await getApplicationDocumentsDirectory();
- final dir = Directory('${base.path}/WebRTCRecordings');
- if (!await dir.exists()) {
- await dir.create(recursive: true);
+ Future _finish(MediaRecorder recorder, File file) async {
+ await recorder.stop();
+ if (!await file.exists() || await file.length() == 0) {
+ throw StateError('Recording file is empty');
}
- return dir;
+ final name = file.uri.pathSegments.last;
+ final String location;
+ if (Platform.isAndroid) {
+ final asset = await PhotoManager.editor.saveVideo(
+ file,
+ title: name,
+ relativePath: _screenRecordingsDirectory,
+ );
+ final directory = asset.relativePath?.replaceFirst(RegExp(r'/+$'), '');
+ location = directory == null || directory.isEmpty
+ ? 'Movies(系统相册 → 视频)'
+ : '$directory/${asset.title ?? name}';
+ } else {
+ await _channel.invokeMethod('saveRecordingToPhotos', file.path);
+ location = '系统相册 / 视频 / $name';
+ }
+ try {
+ await file.delete();
+ } on FileSystemException {
+ // 已导出,应用内副本可留待清理。
+ }
+ return location;
}
- static Future _buildOutputPath() async {
- final dir = await _getRecordingDir();
- final now = DateTime.now();
- final name = 'rec_${now.year}${_pad(now.month)}${_pad(now.day)}_'
- '${_pad(now.hour)}${_pad(now.minute)}${_pad(now.second)}.mp4';
- return '${dir.path}/$name';
+ Future dispose() async {
+ try {
+ await stop();
+ } catch (_) {
+ // 保留导出失败的录制文件,断开连接仍可完成。
+ }
}
}
diff --git a/lib/features/connection/presentation/connection_controller.dart b/lib/features/connection/presentation/connection_controller.dart
index 8adbe1a..25c700b 100644
--- a/lib/features/connection/presentation/connection_controller.dart
+++ b/lib/features/connection/presentation/connection_controller.dart
@@ -280,44 +280,53 @@ class ConnectionController extends Notifier {
);
}
+ bool _recordingBusy = false;
+
/// 切换远程视频录制:开始 / 停止。
Future toggleRecord() async {
- if (state.recording) {
- await _stopRecording();
- return;
- }
- await _startRecording();
- }
-
- Future _startRecording() async {
- if (state.recording) return;
- final renderer = _orchestrator?.remoteRenderer;
- final stream = renderer?.srcObject;
- if (stream == null) {
- state = state.copyWith(recordStatus: '尚未接收到视频画面,无法录制');
- return;
- }
+ if (_recordingBusy || _disposed) return;
+ _recordingBusy = true;
+ final orchestrator = _orchestrator;
+ final stopping = state.recording;
try {
- final ok = await _videoRecorder.start(stream);
- if (ok) {
- state = state.copyWith(recording: true, recordStatus: '录制中...');
+ if (stopping) {
+ final location = await _videoRecorder.stop();
+ if (_disposed || _orchestrator != orchestrator) return;
+ state = state.copyWith(
+ recording: false,
+ recordStatus: location == null ? '录制已停止' : '已保存:$location',
+ );
+ return;
}
- } catch (e) {
- state = state.copyWith(recordStatus: '');
- debugPrint('[record] 开始录制失败: $e');
- }
- }
- Future _stopRecording() async {
- final path = await _videoRecorder.stop();
- state = state.copyWith(
- recording: false,
- recordStatus: path != null ? '已保存:$path' : '录制已停止',
- );
+ final stream = orchestrator?.remoteRenderer.srcObject;
+ if (stream == null) {
+ state = state.copyWith(recordStatus: '尚未接收到视频画面,无法录制');
+ return;
+ }
+ final allowed = await _videoRecorder.requestSavePermission();
+ if (_disposed || _orchestrator != orchestrator) return;
+ if (!allowed) {
+ state = state.copyWith(recordStatus: '请允许保存视频后再开始录制');
+ return;
+ }
+ await _videoRecorder.start(stream);
+ if (_disposed || _orchestrator != orchestrator) return;
+ state = state.copyWith(recording: true, recordStatus: '录制中...');
+ } catch (error) {
+ debugPrint('[record] 操作失败: $error');
+ if (_disposed || _orchestrator != orchestrator) return;
+ state = state.copyWith(
+ recording: false,
+ recordStatus: stopping ? '保存到相册失败' : '无法开始录制',
+ );
+ } finally {
+ _recordingBusy = false;
+ }
}
/// 关闭并清理。
- Future disconnect({String? errorMessage}) async {
+ Future disconnect({String? errorMessage}) async {
final signaling = ref.read(signalingClientProvider);
final orchestrator = _orchestrator;
_orchestrator = null;
@@ -329,13 +338,22 @@ class ConnectionController extends Notifier {
orchestrator.onConnectionState = null;
orchestrator.onReport = null;
}
- await _videoRecorder.dispose();
+ String? recordStatus;
+ try {
+ final location = await _videoRecorder.stop();
+ if (location != null) recordStatus = '已保存:$location';
+ } catch (error) {
+ debugPrint('[record] 退出时保存失败: $error');
+ recordStatus = '保存到相册失败';
+ }
await orchestrator?.dispose();
if (!_disposed) {
state = ConnectionSessionState(
state: errorMessage == null ? ConnectionState.ended : ConnectionState.error,
errorMessage: errorMessage,
+ recordStatus: recordStatus ?? '',
);
}
+ return recordStatus;
}
}
diff --git a/lib/features/connection/presentation/remote_control_page.dart b/lib/features/connection/presentation/remote_control_page.dart
index 0004201..505cccb 100644
--- a/lib/features/connection/presentation/remote_control_page.dart
+++ b/lib/features/connection/presentation/remote_control_page.dart
@@ -4,9 +4,11 @@ import 'package:cupertino_ui/cupertino_ui.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:material_ui/material_ui.dart';
+import 'package:ttstd_family_care/app/theme/dark_mode.dart';
import 'package:ttstd_family_care/core/widgets/app_page_scaffold.dart';
import '../../../core/platform/platform_capabilities.dart';
+import '../../../core/widgets/feature_ui.dart';
import '../../device/presentation/device_switcher.dart';
import '../data/connection_providers.dart';
import '../data/protobuf_codec.dart';
@@ -84,10 +86,24 @@ class _RemoteControlPageState extends ConsumerState {
// 无论从哪个入口离开页面,都在 pop 后断开远程连接。
return PopScope(
canPop: true,
- onPopInvokedWithResult: (didPop, _) {
- if (didPop) {
- ref.read(connectionControllerProvider.notifier).disconnect();
- }
+ onPopInvokedWithResult: (didPop, _) async {
+ if (!didPop) return;
+ final navigator = Navigator.of(context, rootNavigator: true);
+ final message = await ref.read(connectionControllerProvider.notifier).disconnect();
+ if (message == null || !navigator.mounted) return;
+ await showCupertinoDialog(
+ context: navigator.context,
+ builder: (dialogContext) => CupertinoAlertDialog(
+ title: const Text('屏幕录制'),
+ content: Text(message),
+ actions: [
+ CupertinoDialogAction(
+ onPressed: () => Navigator.of(dialogContext).pop(),
+ child: const Text('确定'),
+ ),
+ ],
+ ),
+ );
},
child: AppPageScaffold(
navigationBar: CupertinoNavigationBar(
@@ -298,8 +314,13 @@ class _RemoteControlPageState extends ConsumerState {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
decoration: BoxDecoration(
- color: CupertinoColors.systemGroupedBackground,
- border: Border(top: BorderSide(color: CupertinoColors.separator, width: 0.5)),
+ color: DarkMode.color(context, CupertinoColors.systemGroupedBackground),
+ border: Border(
+ top: BorderSide(
+ color: DarkMode.color(context, CupertinoColors.separator),
+ width: 0.5,
+ ),
+ ),
),
child: Column(
mainAxisSize: MainAxisSize.min,
@@ -524,10 +545,19 @@ class _CtrlButton extends StatelessWidget {
Icon(
icon,
size: 20,
- color: enabled ? CupertinoColors.activeBlue : CupertinoColors.systemGrey3,
+ color: DarkMode.color(
+ context,
+ enabled ? CupertinoColors.activeBlue : CupertinoColors.systemGrey3,
+ ),
),
const SizedBox(height: 4),
- Text(label, style: const TextStyle(fontSize: 12)),
+ Text(
+ label,
+ style: TextStyle(
+ fontSize: 12,
+ color: DarkMode.color(context, enabled ? AppColors.ink : AppColors.sub),
+ ),
+ ),
],
),
);
diff --git a/lib/features/device/data/device_api.dart b/lib/features/device/data/device_api.dart
index ed16a3f..78bc391 100644
--- a/lib/features/device/data/device_api.dart
+++ b/lib/features/device/data/device_api.dart
@@ -87,6 +87,19 @@ class DeviceApi {
}
}
+ Future> getCachedMyDevices() async {
+ final data = await DioClient.readCachedGet('v1/client/sn/my-devices');
+ return _parseList(data, DeviceBrief.fromJson);
+ }
+
+ Future getCachedLocation(String sn) async {
+ final data = await DioClient.readCachedGet(
+ 'v1/client/sn/location',
+ queryParameters: {'sn': sn},
+ );
+ return data is Map ? DeviceLocation.fromJson(data) : null;
+ }
+
/// 获取已绑定设备最新定位信息(无上报数据时返回 null)。
Future getLocation(String sn) async {
try {
@@ -453,6 +466,18 @@ class DeviceApi {
allowStale: true,
queryParameters: query,
);
+ return _parseScreenshots(payload);
+ }
+
+ Future> getCachedRecentScreenshots(String sn) async {
+ final payload = await DioClient.readCachedGet(
+ 'v1/client/sn/upload-screenshot',
+ queryParameters: {'sn': sn},
+ );
+ return _parseScreenshots(payload);
+ }
+
+ List _parseScreenshots(dynamic payload) {
// 防御性提取:兼容后台直接返回 List,或返回 { data: [...] } 的包裹结构。
final List listData;
if (payload is List) {
@@ -460,10 +485,8 @@ class DeviceApi {
} else if (payload is Map && payload['data'] is List) {
listData = payload['data'] as List;
} else {
- debugPrint('[DeviceApi] getRecentScreenshots 返回非预期结构: sn=$sn payload=$payload');
return const [];
}
- debugPrint('[DeviceApi] getRecentScreenshots sn=$sn count=${listData.length}');
final origin = Uri.parse(AppConstants.kBaseUrl).origin;
return listData.whereType