From a9ba4bb7bc251bd0ee54f3f59bcd874366bc04c5 Mon Sep 17 00:00:00 2001 From: tongtongstudio Date: Fri, 27 Nov 2026 18:44:49 +0800 Subject: [PATCH] =?UTF-8?q?feat(sender):=20=E8=AE=BE=E5=A4=87=E6=8C=87?= =?UTF-8?q?=E7=BA=B9=E5=9B=BA=E5=AE=9A=E3=80=81/watch=20=E5=AE=9E=E6=97=B6?= =?UTF-8?q?=E5=88=B7=E6=96=B0=E3=80=81=E4=B8=AD=E7=BB=A7=E8=BF=9E=E6=8E=A5?= =?UTF-8?q?=E4=B8=8E=E6=96=87=E4=BB=B6=E5=AD=90=E5=8D=8F=E8=AE=AE=E4=B8=8A?= =?UTF-8?q?=E4=BC=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 PinStore:首次连接记录被控端签名指纹,变化时弹窗确认 - 新增 SignalingWatch:订阅 /watch,300ms 去抖后重拉设备列表 - 设置页新增"连接走信令中继",主控端按该开关走 ttstd_relay_start - 中继模式禁用投屏并提示原因,状态卡区分直连/中继 - 新增 ControlFileClient:通过 msgType=7 分片上传/列目录,文件页加入口 - NativeCore/Bridge 暴露 relayStart/relayStop/sendFileRequest --- flutter_sender/lib/core/bridge.dart | 44 ++++ .../lib/core/control_file_client.dart | 121 +++++++++++ flutter_sender/lib/core/models.dart | 7 + flutter_sender/lib/core/native_core.dart | 88 ++++++++ flutter_sender/lib/core/pin_store.dart | 77 +++++++ flutter_sender/lib/core/watch_client.dart | 141 +++++++++++++ .../lib/features/file/file_browser_page.dart | 81 +++++++- .../lib/features/settings/settings_page.dart | 13 ++ flutter_sender/lib/main.dart | 188 +++++++++++++++++- 9 files changed, 752 insertions(+), 8 deletions(-) create mode 100644 flutter_sender/lib/core/control_file_client.dart create mode 100644 flutter_sender/lib/core/pin_store.dart create mode 100644 flutter_sender/lib/core/watch_client.dart diff --git a/flutter_sender/lib/core/bridge.dart b/flutter_sender/lib/core/bridge.dart index 7b5aab3..38d8dca 100644 --- a/flutter_sender/lib/core/bridge.dart +++ b/flutter_sender/lib/core/bridge.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import 'dart:isolate'; import 'package:flutter/services.dart'; @@ -51,6 +52,24 @@ class SenderBridge { /// 事件形如 `{"type":8,"action":2,"text":""}`,`type` 是 msgType。 Map? nextInboundEvent() => _native?.pollEvent(); + /// 控制通道文件子协议(`msg_type=7`):发一条 JSON 请求并等响应。 + /// + /// FFI 那一层是阻塞的(等被控端响应),所以放到独立 isolate 里跑, + /// 避免上传时把界面卡住几秒。 + Future> sendFileRequest(Map request) async { + if (_native == null) { + throw StateError('当前平台没有原生控制通道'); + } + return Isolate.run(() { + final core = NativeCore(); + try { + return core.fileRequest(request); + } finally { + core.dispose(); + } + }); + } + Future _handleVideoCall(MethodCall call) async { switch (call.method) { case 'windowClosed': @@ -186,12 +205,37 @@ class SenderBridge { Future disconnect() async { final native = _native; if (native != null) { + native.stopRelay(); native.stopDemoServer(); return; } await _invokeIgnoringMissing('disconnect'); } + /// 通过信令服务器建立中继控制会话(跨网段用)。 + /// + /// 成功返回 null,失败返回原因。中继只承载控制帧,视频/音频仍需同网段直连。 + String? startRelay(DeviceInfo device, String signalingUrl) { + final native = _native; + if (native == null) return '中继需要桌面端原生 Core'; + if (device.id.trim().isEmpty) return '这台设备没有信令 id,无法走中继'; + if (signalingUrl.trim().isEmpty) return '没有配置信令服务器地址'; + return native.startRelay(signalingUrl.trim(), device.id.trim()); + } + + void stopRelay() => _native?.stopRelay(); + + /// 当前控制通道是否走中继(读 Rust 侧状态,避免界面自己记状态)。 + bool get isRelayActive { + final native = _native; + if (native == null) return false; + try { + return native.demoStatus()['relay'] == true; + } on Object { + return false; + } + } + Future sendControl(String type, Map payload) async { final native = _native; if (native != null) { diff --git a/flutter_sender/lib/core/control_file_client.dart b/flutter_sender/lib/core/control_file_client.dart new file mode 100644 index 0000000..8ec918b --- /dev/null +++ b/flutter_sender/lib/core/control_file_client.dart @@ -0,0 +1,121 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; + +/// 控制通道文件子协议(`msg_type=7`)的客户端。 +/// +/// 与 `FileClient`(HTTP `53317`)的区别:这里复用已加密的控制通道, +/// 适合文件服务端口被防火墙拦掉、或只连了 relay 的场景。 +/// 协议是一问一答的 JSON: +/// - `{"op":"prepare","body":"<{\"files\":[...]}>"}` +/// - `{"op":"chunk",...,"dataB64":""}` +/// - `{"op":"progress","sessionId":...}` / `{"op":"cancel",...}` / `{"op":"list","path":...}` +class ControlFileClient { + ControlFileClient({required this.send}); + + /// 发一条请求并等响应;由调用方负责把它放到后台执行(FFI 调用是阻塞的)。 + final Future> Function(Map request) send; + + /// 单个分片大小:256 KiB。再大 base64 后单帧会超过控制通道的 1 MiB 上限附近, + /// 再小则请求次数多、往返开销明显。 + static const int chunkSize = 256 * 1024; + + /// 浏览被控端目录(返回被控端 `FileBrowser` 的原始结构)。 + Future> list(String path) async { + final response = await send({'op': 'list', 'path': path}); + _throwIfError(response); + return response; + } + + /// 上传本地文件到被控端 `file-inbox` 目录,返回被控端保存的文件名。 + Future upload( + String localPath, { + void Function(int sent, int total)? onProgress, + }) async { + final file = File(localPath); + if (!await file.exists()) { + throw const ControlFileException('本地文件不存在'); + } + final length = await file.length(); + final name = localPath.split(RegExp(r'[\\/]')).last; + final fileId = 'f-${DateTime.now().microsecondsSinceEpoch}'; + + final prepared = await send({ + 'op': 'prepare', + // 被控端沿用 LocalSend 风格:body 是一段 JSON 字符串。 + 'body': jsonEncode({ + 'files': [ + { + 'id': fileId, + 'name': name, + 'size': length, + 'mime': 'application/octet-stream', + // 没有 crypto 依赖,算不了摘要;被控端只在续传判断时用它。 + 'sha256': '', + }, + ], + }), + }); + _throwIfError(prepared); + final sessionId = prepared['sessionId']?.toString() ?? ''; + if (sessionId.isEmpty) throw const ControlFileException('被控端没有返回 sessionId'); + final tokens = prepared['tokens']; + final token = tokens is Map ? tokens[fileId]?.toString() ?? '' : ''; + if (token.isEmpty) throw const ControlFileException('被控端拒绝了该文件(没有返回令牌)'); + + var offset = 0; + final handle = await file.open(); + try { + while (offset < length) { + await handle.setPosition(offset); + final bytes = await handle.read(math.min(chunkSize, length - offset)); + if (bytes.isEmpty) break; + final ack = await send({ + 'op': 'chunk', + 'sessionId': sessionId, + 'fileId': fileId, + 'token': token, + 'offset': offset, + 'dataB64': base64Encode(bytes), + }); + _throwIfError(ack); + offset += bytes.length; + onProgress?.call(offset, length); + } + } on Object { + // 传输中断时通知被控端清理会话,避免它一直占着临时文件。 + try { + await send({'op': 'cancel', 'sessionId': sessionId}); + } on Object { + // 取消失败也只能作罢:连接多半已经断了。 + } + rethrow; + } finally { + await handle.close(); + } + return name; + } + + /// 查询会话进度(`files: [{fileId, received, total}]`)。 + Future> progress(String sessionId) async { + final response = await send({'op': 'progress', 'sessionId': sessionId}); + _throwIfError(response); + return response; + } + + static void _throwIfError(Map response) { + final error = response['error']; + if (error is String && error.isNotEmpty) { + throw ControlFileException(error); + } + } +} + +class ControlFileException implements Exception { + const ControlFileException(this.message); + + final String message; + + @override + String toString() => message; +} diff --git a/flutter_sender/lib/core/models.dart b/flutter_sender/lib/core/models.dart index c36d21e..2e8cee4 100644 --- a/flutter_sender/lib/core/models.dart +++ b/flutter_sender/lib/core/models.dart @@ -125,6 +125,8 @@ class AppSettings { final int filePort; /// 被控端文件服务访问令牌,被控端主界面会显示。 final String fileToken; + /// 连接时是否走信令中继(跨网段)。中继只承载控制通道,不能投屏。 + final bool relayEnabled; const AppSettings({ this.signalingUrl = '', @@ -138,6 +140,7 @@ class AppSettings { this.bitrateMbps = 8, this.filePort = 53317, this.fileToken = '', + this.relayEnabled = false, }); static const defaults = AppSettings(); @@ -156,6 +159,7 @@ class AppSettings { int? bitrateMbps, int? filePort, String? fileToken, + bool? relayEnabled, }) { return AppSettings( signalingUrl: signalingUrl ?? this.signalingUrl, @@ -169,6 +173,7 @@ class AppSettings { bitrateMbps: bitrateMbps ?? this.bitrateMbps, filePort: filePort ?? this.filePort, fileToken: fileToken ?? this.fileToken, + relayEnabled: relayEnabled ?? this.relayEnabled, ); } @@ -187,6 +192,7 @@ class AppSettings { bitrateMbps: (json['bitrateMbps'] is num ? json['bitrateMbps'] as num : 8).toInt(), filePort: (json['filePort'] is num ? json['filePort'] as num : 53317).toInt(), fileToken: (json['fileToken'] ?? defaults.fileToken).toString(), + relayEnabled: json['relayEnabled'] as bool? ?? defaults.relayEnabled, ); } @@ -202,5 +208,6 @@ class AppSettings { 'bitrateMbps': bitrateMbps, 'filePort': filePort, 'fileToken': fileToken, + 'relayEnabled': relayEnabled, }; } diff --git a/flutter_sender/lib/core/native_core.dart b/flutter_sender/lib/core/native_core.dart index 802fcf2..75b02b8 100644 --- a/flutter_sender/lib/core/native_core.dart +++ b/flutter_sender/lib/core/native_core.dart @@ -94,11 +94,20 @@ class NativeCore { late final DartDemoStatusFn _demoStatus = _library .lookup>('ttstd_demo_status') .asFunction(); + late final DartRelayStartFn _relayStart = _library + .lookup>('ttstd_relay_start') + .asFunction(); + late final DartRelayStopFn _relayStop = _library + .lookup>('ttstd_relay_stop') + .asFunction(); late final DartDemoSendControlFn _demoSendControl = _library .lookup>('ttstd_demo_send_control') .asFunction(); /// 老版本 Core 没有这个导出,缺失时降级成「没有上行事件」。 late final DartEventNextFn? _eventNext = _resolveEventNext(); + late final DartFileRequestFn _fileRequest = _library + .lookup>('ttstd_file_request') + .asFunction(); late final DartDiscoveryStartFn _discoveryStart = _library .lookup>('ttstd_discovery_start') .asFunction(); @@ -209,6 +218,42 @@ class NativeCore { void stopDemoServer() => _demoStop(); + /// 通过信令服务器建立中继控制会话(只承载控制帧,不支持投屏)。 + /// + /// 成功返回 null;失败返回可直接展示的原因。 + String? startRelay(String baseUrl, String peerId) { + final urlBytes = utf8.encode(baseUrl); + final peerBytes = utf8.encode(peerId); + const capacity = 4096; + final out = calloc(capacity); + try { + return _withUtf8(baseUrl, (urlPtr) { + return _withUtf8(peerId, (peerPtr) { + final written = _relayStart( + urlPtr, + urlBytes.length, + peerPtr, + peerBytes.length, + out, + capacity, + ); + if (written < 0) return '中继启动失败(错误码 $written)'; + final text = utf8.decode(_copy(out, written)); + final decoded = jsonDecode(text); + if (decoded is Map && decoded['ok'] == true) return null; + if (decoded is Map && decoded['error'] != null) { + return decoded['error'].toString(); + } + return text; + }); + }); + } finally { + calloc.free(out); + } + } + + void stopRelay() => _relayStop(); + Map demoStatus() { final out = calloc(65536); try { @@ -244,6 +289,24 @@ class NativeCore { .asFunction(); } + /// 文件子协议(msgType=7):把 JSON 请求发给被控端并返回响应。 + /// + /// **阻塞调用**(最长 5 秒等待被控端响应),界面侧必须放到独立 isolate 里执行。 + Map fileRequest(Map request) { + final bytes = utf8.encode(jsonEncode(request)); + const capacity = 1 << 20; + return _withBytes(bytes, (ptr) { + final out = calloc(capacity); + try { + final written = _fileRequest(ptr, bytes.length, out, capacity); + _check(written, 'ttstd_file_request'); + return jsonDecode(utf8.decode(_copy(out, written))) as Map; + } finally { + calloc.free(out); + } + }); + } + /// 启动同网段自动发现(UDP 41003 信标),幂等。 bool startDiscovery({ int controlPort = 41001, @@ -457,6 +520,13 @@ typedef NativeDemoStatusFn = Int32 Function(Pointer, UintPtr); typedef DartDemoStatusFn = int Function(Pointer, int); typedef NativeEventNextFn = Int32 Function(Pointer, UintPtr); typedef DartEventNextFn = int Function(Pointer, int); +typedef NativeFileRequestFn = Int32 Function( + Pointer, + UintPtr, + Pointer, + UintPtr, +); +typedef DartFileRequestFn = int Function(Pointer, int, Pointer, int); typedef NativeDemoSendControlFn = Int32 Function( Uint16, Uint8, Pointer, UintPtr, ); @@ -469,3 +539,21 @@ typedef NativeDiscoveryDevicesFn = Int32 Function(Pointer, UintPtr); typedef DartDiscoveryDevicesFn = int Function(Pointer, int); typedef NativeDiscoveryConnectFn = Int32 Function(Pointer, UintPtr); typedef DartDiscoveryConnectFn = int Function(Pointer, int); +typedef NativeRelayStartFn = Int32 Function( + Pointer, + UintPtr, + Pointer, + UintPtr, + Pointer, + UintPtr, +); +typedef DartRelayStartFn = int Function( + Pointer, + int, + Pointer, + int, + Pointer, + int, +); +typedef NativeRelayStopFn = Void Function(); +typedef DartRelayStopFn = void Function(); diff --git a/flutter_sender/lib/core/pin_store.dart b/flutter_sender/lib/core/pin_store.dart new file mode 100644 index 0000000..95b431a --- /dev/null +++ b/flutter_sender/lib/core/pin_store.dart @@ -0,0 +1,77 @@ +import 'dart:convert'; +import 'dart:io'; + +/// 设备指纹归档(TOFU pinning)。 +/// +/// 落盘位置与诊断日志一致:可执行文件所在目录优先,失败再退到当前目录/临时目录。 +/// 键是设备 id(拿不到时用 `ip:端口`),值是被控端公布的 `sha256:` 指纹。 +class PinStore { + PinStore({this.fileName = 'ttstd_pinned_devices.json'}); + + final String fileName; + final Map _pins = {}; + File? _file; + + bool get isReady => _file != null; + + String get path => _file?.path ?? ''; + + /// 读取已有记录;目录不可写时保持空空如也(只是这次运行不做持久化)。 + void load() { + for (final directory in _directories()) { + try { + final candidate = File('${directory.path}${Platform.pathSeparator}$fileName'); + if (!candidate.existsSync()) { + // 先写一次空表验证目录可写,避免后面 save 时才失败。 + candidate.writeAsStringSync('{}', flush: true); + } + final decoded = jsonDecode(candidate.readAsStringSync()); + if (decoded is Map) { + _pins.clear(); + decoded.forEach((key, value) { + if (key is String && value is String && value.isNotEmpty) { + _pins[key] = value; + } + }); + } + _file = candidate; + return; + } on Object { + continue; + } + } + } + + String? pinOf(String key) => _pins[key]; + + void pin(String key, String fingerprint) { + _pins[key] = fingerprint; + _flush(); + } + + void unpin(String key) { + if (_pins.remove(key) != null) _flush(); + } + + /// 两个指纹是否是同一个(忽略大小写、`sha256:` 前缀与分隔冒号)。 + static bool same(String left, String right) => normalize(left) == normalize(right); + + static String normalize(String value) => + value.trim().toLowerCase().replaceFirst('sha256:', '').replaceAll(':', ''); + + void _flush() { + final file = _file; + if (file == null) return; + try { + file.writeAsStringSync(jsonEncode(_pins), flush: true); + } on Object { + // 落盘失败不影响本次运行:校验仍然按内存里的记录走。 + } + } + + static List _directories() => [ + File(Platform.resolvedExecutable).parent, + Directory.current, + Directory.systemTemp, + ]; +} diff --git a/flutter_sender/lib/core/watch_client.dart b/flutter_sender/lib/core/watch_client.dart new file mode 100644 index 0000000..729df36 --- /dev/null +++ b/flutter_sender/lib/core/watch_client.dart @@ -0,0 +1,141 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +/// 信令服务器 `WS /watch` 的客户端。 +/// +/// 服务器在连接建立后先推一条 `{"event":"snapshot","devices":[...]}`,之后推 +/// `online` / `offline` / `heartbeat`。这里只把事件翻译成「设备列表可能变了」, +/// 具体拉取交给调用方:`online` 事件里没有完整设备信息(端口/指纹/分辨率), +/// 与其在这里补一套字段解析,不如让调用方复用已有的 `/list` + 信标发现逻辑。 +class SignalingWatch { + SignalingWatch({ + required this.signalingUrl, + required this.onChanged, + this.onStateChanged, + }); + + /// 信令服务基地址(http/https),内部会换成 ws/wss。 + final String signalingUrl; + + /// 设备列表可能发生变化(snapshot / online / offline)。 + final void Function() onChanged; + + /// 连接状态变化,用于界面提示与诊断日志。 + final void Function(bool connected)? onStateChanged; + + static const Duration _maxBackoff = Duration(seconds: 15); + static const Duration _connectTimeout = Duration(seconds: 5); + + WebSocket? _socket; + StreamSubscription? _subscription; + Timer? _reconnectTimer; + Duration _backoff = const Duration(seconds: 1); + bool _stopped = false; + bool _connected = false; + + bool get isConnected => _connected; + + /// 把信令基地址换成 `/watch` 的 WebSocket 地址。 + /// + /// 支持带前缀的部署(`https://host/api/` → `wss://host/api/watch`)。 + static Uri? watchUri(String base) { + final trimmed = base.trim(); + if (trimmed.isEmpty) return null; + final uri = Uri.tryParse(trimmed); + if (uri == null || uri.host.isEmpty) return null; + final scheme = switch (uri.scheme) { + 'https' || 'wss' => 'wss', + 'http' || 'ws' => 'ws', + _ => null, + }; + if (scheme == null) return null; + final path = uri.path.endsWith('/') ? '${uri.path}watch' : '${uri.path}/watch'; + return uri.replace(scheme: scheme, path: path); + } + + void start() { + _stopped = false; + _backoff = const Duration(seconds: 1); + unawaited(_connect()); + } + + Future _connect() async { + if (_stopped) return; + final uri = watchUri(signalingUrl); + if (uri == null) { + _scheduleReconnect(); + return; + } + try { + final socket = await WebSocket.connect(uri.toString()).timeout(_connectTimeout); + if (_stopped) { + await socket.close(); + return; + } + _socket = socket; + _backoff = const Duration(seconds: 1); + _setConnected(true); + _subscription = socket.listen( + _handleMessage, + onDone: _handleClosed, + onError: (Object _) => _handleClosed(), + cancelOnError: true, + ); + } on Object { + _scheduleReconnect(); + } + } + + void _handleMessage(dynamic data) { + if (data is! String) return; + Object? decoded; + try { + decoded = jsonDecode(data); + } on FormatException { + return; + } + if (decoded is! Map) return; + final event = decoded['event']?.toString(); + if (event == 'snapshot' || event == 'online' || event == 'offline') { + onChanged(); + } + // heartbeat 不触发拉取:设备信息没变,只会白刷一遍 /list。 + } + + void _handleClosed() { + _subscription?.cancel(); + _subscription = null; + _socket = null; + _setConnected(false); + _scheduleReconnect(); + } + + void _setConnected(bool value) { + if (_connected == value) return; + _connected = value; + onStateChanged?.call(value); + } + + void _scheduleReconnect() { + if (_stopped) return; + _reconnectTimer?.cancel(); + // 指数退避,避免信令服务器没启动时每秒重连一次。 + _reconnectTimer = Timer(_backoff, () { + _backoff = _backoff * 2 > _maxBackoff ? _maxBackoff : _backoff * 2; + unawaited(_connect()); + }); + } + + void stop() { + _stopped = true; + _reconnectTimer?.cancel(); + _reconnectTimer = null; + _subscription?.cancel(); + _subscription = null; + final socket = _socket; + _socket = null; + _connected = false; + if (socket != null) unawaited(socket.close()); + } +} diff --git a/flutter_sender/lib/features/file/file_browser_page.dart b/flutter_sender/lib/features/file/file_browser_page.dart index 06d477f..fdbf71d 100644 --- a/flutter_sender/lib/features/file/file_browser_page.dart +++ b/flutter_sender/lib/features/file/file_browser_page.dart @@ -2,11 +2,13 @@ import 'dart:io'; import 'package:flutter/material.dart'; +import '../../core/control_file_client.dart'; import '../../core/file_client.dart'; /// 浏览 / 下载 / 上传被控端文件。 /// -/// 走被控端内置的 LocalSend 风格 HTTP 服务(默认 53317),与串流控制通道互不影响。 +/// 默认走被控端内置的 LocalSend 风格 HTTP 服务(默认 53317);控制通道可用时, +/// 还可以用 `msg_type=7` 文件子协议上传(HTTP 端口被防火墙拦掉时的兜底)。 class FileBrowserPage extends StatefulWidget { const FileBrowserPage({ super.key, @@ -14,12 +16,16 @@ class FileBrowserPage extends StatefulWidget { required this.initialPort, required this.initialToken, this.onConfigChanged, + this.controlChannel, }); final String host; final int initialPort; final String initialToken; + /// 控制通道文件客户端;为 null 表示当前没有可用控制通道。 + final ControlFileClient? controlChannel; + /// 用户改了地址/端口/令牌并保存时通知主界面写回设置。 final void Function(String host, int port, String token)? onConfigChanged; @@ -226,6 +232,74 @@ class _FileBrowserPageState extends State { } } + /// 走控制通道(`msg_type=7`)上传:HTTP 文件服务不可用时的兜底。 + /// + /// 文件落在被控端应用私有目录 `file-inbox`,因此这里只提示保存名, + /// 不再刷新 HTTP 目录列表(那棵树看不到这个目录)。 + Future _uploadViaControlChannel() async { + final client = widget.controlChannel; + if (client == null) { + _toast('控制通道不可用:请先连接被控端', error: true); + return; + } + final controller = TextEditingController(); + final localPath = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: const Text('通过控制通道上传'), + content: TextField( + controller: controller, + autofocus: true, + decoration: const InputDecoration( + labelText: '本地文件绝对路径', + hintText: r'C:\Users\me\Pictures\a.jpg', + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(dialogContext), child: const Text('取消')), + FilledButton( + onPressed: () => Navigator.pop(dialogContext, controller.text.trim()), + child: const Text('上传'), + ), + ], + ), + ); + controller.dispose(); + if (localPath == null || localPath.isEmpty) return; + + setState(() { + _progress = 0; + _progressLabel = '控制通道上传 ${localPath.split(Platform.pathSeparator).last}'; + }); + try { + final remote = await client.upload( + localPath, + onProgress: (sent, total) { + if (!mounted) return; + setState(() { + _progress = total > 0 ? sent / total : null; + _progressLabel = '上传中 · ${_size(sent)} / ${_size(total)}'; + }); + }, + ); + if (!mounted) return; + _toast('已通过控制通道上传:$remote(被控端 file-inbox)'); + } on ControlFileException catch (error) { + if (!mounted) return; + _toast(error.message, error: true); + } on Object catch (error) { + if (!mounted) return; + _toast('控制通道上传失败:$error', error: true); + } finally { + if (mounted) { + setState(() { + _progress = null; + _progressLabel = ''; + }); + } + } + } + void _saveConfig() { final host = _hostController.text.trim(); final port = int.tryParse(_portController.text.trim()) ?? _port; @@ -277,6 +351,11 @@ class _FileBrowserPageState extends State { onPressed: directory == null || _loading ? null : _upload, icon: const Icon(Icons.upload_file), ), + IconButton( + tooltip: '通过控制通道上传(HTTP 不可用时)', + onPressed: _loading ? null : _uploadViaControlChannel, + icon: const Icon(Icons.swap_vert), + ), ], ), body: Column( diff --git a/flutter_sender/lib/features/settings/settings_page.dart b/flutter_sender/lib/features/settings/settings_page.dart index 032c518..81b7dd0 100644 --- a/flutter_sender/lib/features/settings/settings_page.dart +++ b/flutter_sender/lib/features/settings/settings_page.dart @@ -30,6 +30,7 @@ class _SettingsPageState extends State { late bool _audioEnabled; late bool _clipboardSync; late bool _fileTransfer; + late bool _relayEnabled; late int _bitrateMbps; DeviceInfo? _localListener; ServiceCheckResult? _serviceResult; @@ -50,6 +51,7 @@ class _SettingsPageState extends State { _audioEnabled = widget.settings.audioEnabled; _clipboardSync = widget.settings.clipboardSync; _fileTransfer = widget.settings.fileTransfer; + _relayEnabled = widget.settings.relayEnabled; _bitrateMbps = widget.settings.bitrateMbps; _loadLocalListener(); _refreshListenerState(); @@ -180,6 +182,10 @@ class _SettingsPageState extends State { _snack('请填写外部信令服务器地址'); return; } + if (_relayEnabled && _useLocalSignaling) { + _snack('中继需要被控端也能访问的信令地址,请改用外部信令'); + return; + } if (int.tryParse(_localPort.text.trim()) == null) { _snack('本机端口必须是数字'); return; @@ -209,6 +215,7 @@ class _SettingsPageState extends State { audioEnabled: _audioEnabled, clipboardSync: _clipboardSync, fileTransfer: _fileTransfer, + relayEnabled: _relayEnabled, bitrateMbps: _bitrateMbps, filePort: int.tryParse(_filePort.text.trim()) ?? widget.settings.filePort, fileToken: _fileToken.text.trim(), @@ -410,6 +417,12 @@ class _SettingsPageState extends State { value: _fileTransfer, onChanged: (value) => setState(() => _fileTransfer = value), ), + SwitchListTile( + title: const Text('连接走信令中继'), + subtitle: const Text('跨网段时使用;中继只承载控制通道,不能投屏/传音频'), + value: _relayEnabled, + onChanged: (value) => setState(() => _relayEnabled = value), + ), Padding( padding: const EdgeInsets.fromLTRB(16, 4, 16, 8), child: Row( diff --git a/flutter_sender/lib/main.dart b/flutter_sender/lib/main.dart index 6e1f2f5..5070462 100644 --- a/flutter_sender/lib/main.dart +++ b/flutter_sender/lib/main.dart @@ -6,8 +6,11 @@ import 'package:flutter/services.dart'; import 'core/bridge.dart'; import 'core/diagnostic_log.dart'; +import 'core/control_file_client.dart'; import 'core/native_core.dart'; import 'core/models.dart'; +import 'core/pin_store.dart'; +import 'core/watch_client.dart'; import 'features/control/control_toolbar.dart'; import 'features/discovery/device_list.dart'; import 'features/file/file_browser_page.dart'; @@ -46,6 +49,7 @@ class _HomePageState extends State { NativeCore? _nativeCore; late final SenderBridge _bridge; final DiagnosticLog _diagnosticLog = DiagnosticLog(); + final PinStore _pins = PinStore(); Timer? _demoStatusTimer; Timer? _diagnosticTimer; Timer? _connectWatchdog; @@ -53,6 +57,12 @@ class _HomePageState extends State { Timer? _videoStatsTimer; Timer? _eventTimer; Timer? _clipboardTimer; + Timer? _watchRefreshTimer; + SignalingWatch? _watch; + bool _watchConnected = false; + bool _refreshQueued = false; + /// 当前控制通道是否走信令中继(中继模式不支持投屏)。 + bool _relayActive = false; List _devices = const []; DeviceInfo? _selected; @@ -99,6 +109,8 @@ class _HomePageState extends State { _bridge.onVideoKey = _onVideoKey; _diagnosticLog.start(); _diagnosticLog.write('app initialized; nativeError=${_nativeError ?? '-'}'); + _pins.load(); + _diagnosticLog.write('pinned devices file: ${_pins.path}'); _bridge.watchPhase().listen((phase) { _diagnosticLog.write('phase event -> ${phase.wireName} (${phase.label})'); if (mounted) setState(() => _phase = phase); @@ -149,6 +161,8 @@ class _HomePageState extends State { _videoStatsTimer?.cancel(); _eventTimer?.cancel(); _clipboardTimer?.cancel(); + _watchRefreshTimer?.cancel(); + _watch?.stop(); _diagnosticLog.dispose(); _bridge.stopDemoServer(); _bridge.stopLocalSignaling(); @@ -160,20 +174,28 @@ class _HomePageState extends State { if (_nativeCore == null || !mounted) return; try { final status = _bridge.demoStatus(); + final running = status['running'] == true; + final connected = status['peerConnected'] == true; + final keyEstablished = status['keyEstablished'] == true; + final relay = status['relay'] == true; + final sessionEnded = + _relayActive && !relay && _phase == ConnectionPhase.direct; setState(() { _demoStatus = status; - final running = status['running'] == true; - final connected = status['peerConnected'] == true; - final keyEstablished = status['keyEstablished'] == true; - if (running && connected && keyEstablished) { + _relayActive = relay; + if (connected && keyEstablished) { _connectWatchdog?.cancel(); _phase = ConnectionPhase.direct; - } else if (running && + } else if (sessionEnded) { + // 中继线程退出后 status 不再有进行中的会话,别把界面卡在「连接中」。 + _phase = ConnectionPhase.idle; + } else if ((running || relay) && _phase != ConnectionPhase.idle && _phase != ConnectionPhase.failed) { _phase = ConnectionPhase.probing; } }); + if (sessionEnded) _snack('中继会话已断开'); } on Object catch (error) { _diagnosticLog.write('demoStatus refresh failed: $error'); } @@ -356,6 +378,10 @@ class _HomePageState extends State { _snack('请先连接被控端'); return; } + if (_relayActive) { + _snack('中继模式只承载控制通道,投屏需要同一网段直连'); + return; + } setState(() { _mirrorRequesting = true; // 新一轮请求:清掉上一轮「关窗已停流」的标记与旧帧时间。 @@ -552,6 +578,10 @@ class _HomePageState extends State { host: host, initialPort: _settings.filePort, initialToken: _settings.fileToken, + // 控制通道文件子协议只在已连接时可用(需要控制密钥)。 + controlChannel: _phase.isConnected && _nativeCore != null + ? ControlFileClient(send: _bridge.sendFileRequest) + : null, onConfigChanged: (host, port, token) { final updated = _settings.copyWith(filePort: port, fileToken: token); setState(() => _settings = updated); @@ -600,11 +630,44 @@ class _HomePageState extends State { final url = await _bridge.resolveSignalingUrl(_settings); if (!mounted) return; setState(() => _effectiveSignalingUrl = url); + _restartWatch(url); unawaited(_refreshDevices()); } + /// 重启 `/watch` 订阅:信令地址或本机信令开关变化后必须换一条连接。 + void _restartWatch(String signalingUrl) { + _watchRefreshTimer?.cancel(); + _watch?.stop(); + _watch = SignalingWatch( + signalingUrl: signalingUrl, + onChanged: _onWatchEvent, + onStateChanged: (connected) { + _watchConnected = connected; + _diagnosticLog.write( + 'signaling watch ${connected ? 'connected' : 'disconnected'} ($signalingUrl)', + ); + if (mounted) setState(() {}); + }, + ); + _watch!.start(); + } + + /// `/watch` 说设备列表变了 → 去抖后拉一次,避免多设备同时上线时连环刷新。 + void _onWatchEvent() { + _watchRefreshTimer?.cancel(); + _watchRefreshTimer = Timer(const Duration(milliseconds: 300), () { + if (!mounted) return; + _diagnosticLog.write('signaling watch -> refresh devices'); + unawaited(_refreshDevices()); + }); + } + Future _refreshDevices() async { - if (_refreshing) return; + if (_refreshing) { + // 正在刷新时又来一次请求:记下来,等本轮结束后补一次,避免事件被吞掉。 + _refreshQueued = true; + return; + } setState(() => _refreshing = true); final devices = await _bridge.discover(signalingUrl: _effectiveSignalingUrl); if (!mounted) return; @@ -616,6 +679,10 @@ class _HomePageState extends State { _refreshing = false; }); _diagnosticLog.write('discover result: ${devices.length} devices'); + if (_refreshQueued) { + _refreshQueued = false; + unawaited(_refreshDevices()); + } } Future _connect() async { @@ -624,6 +691,11 @@ class _HomePageState extends State { _diagnosticLog.write( 'connect requested: ${device.id} ${device.ip}:${device.mediaPort}/${device.controlPort}', ); + if (!await _confirmFingerprint(device)) return; + if (_settings.relayEnabled) { + await _connectViaRelay(device); + return; + } _connectWatchdog?.cancel(); setState(() => _phase = ConnectionPhase.probing); _connectWatchdog = Timer(const Duration(seconds: 10), () { @@ -648,6 +720,86 @@ class _HomePageState extends State { } } + /// 跨网段连接:控制帧经信令服务器中转,不依赖被控端能反连本机。 + /// + /// 中继不承载视频/音频,界面会禁止发起投屏;文件、剪贴板、输入仍可用。 + Future _connectViaRelay(DeviceInfo device) async { + final signalingUrl = await _bridge.resolveSignalingUrl(_settings); + final error = _bridge.startRelay(device, signalingUrl); + if (!mounted) return; + if (error != null) { + _diagnosticLog.write('relay start failed: $error'); + setState(() => _phase = ConnectionPhase.failed); + _snack('中继连接失败:$error'); + return; + } + _diagnosticLog.write('relay start: ${device.id} via $signalingUrl'); + setState(() => _phase = ConnectionPhase.probing); + _connectWatchdog?.cancel(); + // 中继要多等几次 `/relay` 轮询(被控端可能刚开始轮询),窗口放宽到 20 秒。 + _connectWatchdog = Timer(const Duration(seconds: 20), () { + if (!mounted || _phase != ConnectionPhase.probing) return; + _diagnosticLog.write('relay handshake timeout after 20s'); + setState(() => _phase = ConnectionPhase.failed); + _snack('中继握手超时:确认被控端也注册到同一信令服务器'); + }); + } + + /// 设备指纹校验(TOFU)。 + /// + /// 首次连接记录被控端公布的指纹;以后必须一致,不一致时弹窗让用户确认 + /// (重装/换签名会变,中间人也会变)。被控端没公布指纹(旧版本)时放行并提示。 + Future _confirmFingerprint(DeviceInfo device) async { + final key = device.id.trim().isNotEmpty + ? device.id.trim() + : '${device.ip}:${device.controlPort}'; + final announced = device.fingerprint.trim(); + if (announced.isEmpty) { + _diagnosticLog.write('peer announced empty fp, skip pinning ($key)'); + _snack('被控端未公布指纹(旧版本),本次连接未经身份校验'); + return true; + } + final pinned = _pins.pinOf(key); + if (pinned == null) { + _pins.pin(key, announced); + _diagnosticLog.write('pinned device $key fp=$announced'); + return true; + } + if (PinStore.same(pinned, announced)) return true; + + _diagnosticLog.write('fingerprint mismatch $key pinned=$pinned announced=$announced'); + if (!mounted) return false; + final trusted = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('设备指纹变化'), + content: Text( + '这台设备公布的指纹和上次记录的不一致。\n\n' + '旧:$pinned\n新:$announced\n\n' + '重装应用或更换签名会改指纹;如果不是你做的,请先取消并检查网络。', + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('取消连接'), + ), + FilledButton( + onPressed: () => Navigator.of(context).pop(true), + child: const Text('仍然信任'), + ), + ], + ), + ); + if (trusted != true) { + _diagnosticLog.write('fingerprint rejected by user: $key'); + _snack('已拒绝连接:设备指纹不匹配'); + return false; + } + _pins.pin(key, announced); + _diagnosticLog.write('re-pinned device $key fp=$announced'); + return true; + } + Future _disconnect() async { _diagnosticLog.write('disconnect requested'); _connectWatchdog?.cancel(); @@ -660,7 +812,10 @@ class _HomePageState extends State { } await _bridge.disconnect(); if (!mounted) return; - setState(() => _phase = ConnectionPhase.idle); + setState(() { + _phase = ConnectionPhase.idle; + _relayActive = false; + }); } Future _openSettings() async { @@ -827,6 +982,7 @@ class _HomePageState extends State { final status = _demoStatus; final connected = status['peerConnected'] == true; final keyEstablished = status['keyEstablished'] == true; + final relay = status['relay'] == true; final peerIp = (status['peerIp'] as String? ?? '').trim(); return Card( @@ -850,6 +1006,7 @@ class _HomePageState extends State { ) else Text( + '${relay ? '信令中继' : '直连'} · ' '被控端 ${connected ? '已连接' : '未连接'} · ' '${keyEstablished ? '会话密钥已建立' : '等待 ECDH 协商'}' + (peerIp.isEmpty ? '' : ' · 对端 $peerIp'), @@ -990,6 +1147,23 @@ class _HomePageState extends State { ), ), ), + const SizedBox(height: 8), + Row( + children: [ + Icon( + _watchConnected ? Icons.bolt : Icons.bolt_outlined, + size: 14, + color: _watchConnected + ? Theme.of(context).colorScheme.primary + : Theme.of(context).disabledColor, + ), + const SizedBox(width: 6), + Text( + _watchConnected ? '信令 /watch 实时订阅已连接' : '信令 /watch 未连接,仅靠轮询刷新', + style: Theme.of(context).textTheme.labelSmall, + ), + ], + ), ], ), );