feat(sender): 设备指纹固定、/watch 实时刷新、中继连接与文件子协议上传
- 新增 PinStore:首次连接记录被控端签名指纹,变化时弹窗确认 - 新增 SignalingWatch:订阅 /watch,300ms 去抖后重拉设备列表 - 设置页新增"连接走信令中继",主控端按该开关走 ttstd_relay_start - 中继模式禁用投屏并提示原因,状态卡区分直连/中继 - 新增 ControlFileClient:通过 msgType=7 分片上传/列目录,文件页加入口 - NativeCore/Bridge 暴露 relayStart/relayStop/sendFileRequest
This commit is contained in:
1 parent
22bac28914
commit
a9ba4bb7bc
9 files changed
+752
-8
No files matched your search
@@ -1,6 +1,7 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
import 'dart:isolate';
|
||||||
|
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
@@ -51,6 +52,24 @@ class SenderBridge {
|
|||||||
/// 事件形如 `{"type":8,"action":2,"text":""}`,`type` 是 msgType。
|
/// 事件形如 `{"type":8,"action":2,"text":""}`,`type` 是 msgType。
|
||||||
Map<String, dynamic>? nextInboundEvent() => _native?.pollEvent();
|
Map<String, dynamic>? nextInboundEvent() => _native?.pollEvent();
|
||||||
|
|
||||||
|
/// 控制通道文件子协议(`msg_type=7`):发一条 JSON 请求并等响应。
|
||||||
|
///
|
||||||
|
/// FFI 那一层是阻塞的(等被控端响应),所以放到独立 isolate 里跑,
|
||||||
|
/// 避免上传时把界面卡住几秒。
|
||||||
|
Future<Map<String, dynamic>> sendFileRequest(Map<String, dynamic> request) async {
|
||||||
|
if (_native == null) {
|
||||||
|
throw StateError('当前平台没有原生控制通道');
|
||||||
|
}
|
||||||
|
return Isolate.run(() {
|
||||||
|
final core = NativeCore();
|
||||||
|
try {
|
||||||
|
return core.fileRequest(request);
|
||||||
|
} finally {
|
||||||
|
core.dispose();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _handleVideoCall(MethodCall call) async {
|
Future<void> _handleVideoCall(MethodCall call) async {
|
||||||
switch (call.method) {
|
switch (call.method) {
|
||||||
case 'windowClosed':
|
case 'windowClosed':
|
||||||
@@ -186,12 +205,37 @@ class SenderBridge {
|
|||||||
Future<void> disconnect() async {
|
Future<void> disconnect() async {
|
||||||
final native = _native;
|
final native = _native;
|
||||||
if (native != null) {
|
if (native != null) {
|
||||||
|
native.stopRelay();
|
||||||
native.stopDemoServer();
|
native.stopDemoServer();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await _invokeIgnoringMissing('disconnect');
|
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<void> sendControl(String type, Map<String, dynamic> payload) async {
|
Future<void> sendControl(String type, Map<String, dynamic> payload) async {
|
||||||
final native = _native;
|
final native = _native;
|
||||||
if (native != null) {
|
if (native != null) {
|
||||||
|
|||||||
@@ -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":"<base64>"}`
|
||||||
|
/// - `{"op":"progress","sessionId":...}` / `{"op":"cancel",...}` / `{"op":"list","path":...}`
|
||||||
|
class ControlFileClient {
|
||||||
|
ControlFileClient({required this.send});
|
||||||
|
|
||||||
|
/// 发一条请求并等响应;由调用方负责把它放到后台执行(FFI 调用是阻塞的)。
|
||||||
|
final Future<Map<String, dynamic>> Function(Map<String, dynamic> request) send;
|
||||||
|
|
||||||
|
/// 单个分片大小:256 KiB。再大 base64 后单帧会超过控制通道的 1 MiB 上限附近,
|
||||||
|
/// 再小则请求次数多、往返开销明显。
|
||||||
|
static const int chunkSize = 256 * 1024;
|
||||||
|
|
||||||
|
/// 浏览被控端目录(返回被控端 `FileBrowser` 的原始结构)。
|
||||||
|
Future<Map<String, dynamic>> list(String path) async {
|
||||||
|
final response = await send({'op': 'list', 'path': path});
|
||||||
|
_throwIfError(response);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 上传本地文件到被控端 `file-inbox` 目录,返回被控端保存的文件名。
|
||||||
|
Future<String> 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<Map<String, dynamic>> progress(String sessionId) async {
|
||||||
|
final response = await send({'op': 'progress', 'sessionId': sessionId});
|
||||||
|
_throwIfError(response);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void _throwIfError(Map<String, dynamic> 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;
|
||||||
|
}
|
||||||
@@ -125,6 +125,8 @@ class AppSettings {
|
|||||||
final int filePort;
|
final int filePort;
|
||||||
/// 被控端文件服务访问令牌,被控端主界面会显示。
|
/// 被控端文件服务访问令牌,被控端主界面会显示。
|
||||||
final String fileToken;
|
final String fileToken;
|
||||||
|
/// 连接时是否走信令中继(跨网段)。中继只承载控制通道,不能投屏。
|
||||||
|
final bool relayEnabled;
|
||||||
|
|
||||||
const AppSettings({
|
const AppSettings({
|
||||||
this.signalingUrl = '',
|
this.signalingUrl = '',
|
||||||
@@ -138,6 +140,7 @@ class AppSettings {
|
|||||||
this.bitrateMbps = 8,
|
this.bitrateMbps = 8,
|
||||||
this.filePort = 53317,
|
this.filePort = 53317,
|
||||||
this.fileToken = '',
|
this.fileToken = '',
|
||||||
|
this.relayEnabled = false,
|
||||||
});
|
});
|
||||||
|
|
||||||
static const defaults = AppSettings();
|
static const defaults = AppSettings();
|
||||||
@@ -156,6 +159,7 @@ class AppSettings {
|
|||||||
int? bitrateMbps,
|
int? bitrateMbps,
|
||||||
int? filePort,
|
int? filePort,
|
||||||
String? fileToken,
|
String? fileToken,
|
||||||
|
bool? relayEnabled,
|
||||||
}) {
|
}) {
|
||||||
return AppSettings(
|
return AppSettings(
|
||||||
signalingUrl: signalingUrl ?? this.signalingUrl,
|
signalingUrl: signalingUrl ?? this.signalingUrl,
|
||||||
@@ -169,6 +173,7 @@ class AppSettings {
|
|||||||
bitrateMbps: bitrateMbps ?? this.bitrateMbps,
|
bitrateMbps: bitrateMbps ?? this.bitrateMbps,
|
||||||
filePort: filePort ?? this.filePort,
|
filePort: filePort ?? this.filePort,
|
||||||
fileToken: fileToken ?? this.fileToken,
|
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(),
|
bitrateMbps: (json['bitrateMbps'] is num ? json['bitrateMbps'] as num : 8).toInt(),
|
||||||
filePort: (json['filePort'] is num ? json['filePort'] as num : 53317).toInt(),
|
filePort: (json['filePort'] is num ? json['filePort'] as num : 53317).toInt(),
|
||||||
fileToken: (json['fileToken'] ?? defaults.fileToken).toString(),
|
fileToken: (json['fileToken'] ?? defaults.fileToken).toString(),
|
||||||
|
relayEnabled: json['relayEnabled'] as bool? ?? defaults.relayEnabled,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,5 +208,6 @@ class AppSettings {
|
|||||||
'bitrateMbps': bitrateMbps,
|
'bitrateMbps': bitrateMbps,
|
||||||
'filePort': filePort,
|
'filePort': filePort,
|
||||||
'fileToken': fileToken,
|
'fileToken': fileToken,
|
||||||
|
'relayEnabled': relayEnabled,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -94,11 +94,20 @@ class NativeCore {
|
|||||||
late final DartDemoStatusFn _demoStatus = _library
|
late final DartDemoStatusFn _demoStatus = _library
|
||||||
.lookup<NativeFunction<NativeDemoStatusFn>>('ttstd_demo_status')
|
.lookup<NativeFunction<NativeDemoStatusFn>>('ttstd_demo_status')
|
||||||
.asFunction();
|
.asFunction();
|
||||||
|
late final DartRelayStartFn _relayStart = _library
|
||||||
|
.lookup<NativeFunction<NativeRelayStartFn>>('ttstd_relay_start')
|
||||||
|
.asFunction();
|
||||||
|
late final DartRelayStopFn _relayStop = _library
|
||||||
|
.lookup<NativeFunction<NativeRelayStopFn>>('ttstd_relay_stop')
|
||||||
|
.asFunction();
|
||||||
late final DartDemoSendControlFn _demoSendControl = _library
|
late final DartDemoSendControlFn _demoSendControl = _library
|
||||||
.lookup<NativeFunction<NativeDemoSendControlFn>>('ttstd_demo_send_control')
|
.lookup<NativeFunction<NativeDemoSendControlFn>>('ttstd_demo_send_control')
|
||||||
.asFunction();
|
.asFunction();
|
||||||
/// 老版本 Core 没有这个导出,缺失时降级成「没有上行事件」。
|
/// 老版本 Core 没有这个导出,缺失时降级成「没有上行事件」。
|
||||||
late final DartEventNextFn? _eventNext = _resolveEventNext();
|
late final DartEventNextFn? _eventNext = _resolveEventNext();
|
||||||
|
late final DartFileRequestFn _fileRequest = _library
|
||||||
|
.lookup<NativeFunction<NativeFileRequestFn>>('ttstd_file_request')
|
||||||
|
.asFunction();
|
||||||
late final DartDiscoveryStartFn _discoveryStart = _library
|
late final DartDiscoveryStartFn _discoveryStart = _library
|
||||||
.lookup<NativeFunction<NativeDiscoveryStartFn>>('ttstd_discovery_start')
|
.lookup<NativeFunction<NativeDiscoveryStartFn>>('ttstd_discovery_start')
|
||||||
.asFunction();
|
.asFunction();
|
||||||
@@ -209,6 +218,42 @@ class NativeCore {
|
|||||||
|
|
||||||
void stopDemoServer() => _demoStop();
|
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<Uint8>(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<String, dynamic> demoStatus() {
|
Map<String, dynamic> demoStatus() {
|
||||||
final out = calloc<Uint8>(65536);
|
final out = calloc<Uint8>(65536);
|
||||||
try {
|
try {
|
||||||
@@ -244,6 +289,24 @@ class NativeCore {
|
|||||||
.asFunction();
|
.asFunction();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 文件子协议(msgType=7):把 JSON 请求发给被控端并返回响应。
|
||||||
|
///
|
||||||
|
/// **阻塞调用**(最长 5 秒等待被控端响应),界面侧必须放到独立 isolate 里执行。
|
||||||
|
Map<String, dynamic> fileRequest(Map<String, dynamic> request) {
|
||||||
|
final bytes = utf8.encode(jsonEncode(request));
|
||||||
|
const capacity = 1 << 20;
|
||||||
|
return _withBytes(bytes, (ptr) {
|
||||||
|
final out = calloc<Uint8>(capacity);
|
||||||
|
try {
|
||||||
|
final written = _fileRequest(ptr, bytes.length, out, capacity);
|
||||||
|
_check(written, 'ttstd_file_request');
|
||||||
|
return jsonDecode(utf8.decode(_copy(out, written))) as Map<String, dynamic>;
|
||||||
|
} finally {
|
||||||
|
calloc.free(out);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/// 启动同网段自动发现(UDP 41003 信标),幂等。
|
/// 启动同网段自动发现(UDP 41003 信标),幂等。
|
||||||
bool startDiscovery({
|
bool startDiscovery({
|
||||||
int controlPort = 41001,
|
int controlPort = 41001,
|
||||||
@@ -457,6 +520,13 @@ typedef NativeDemoStatusFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
|||||||
typedef DartDemoStatusFn = int Function(Pointer<Uint8>, int);
|
typedef DartDemoStatusFn = int Function(Pointer<Uint8>, int);
|
||||||
typedef NativeEventNextFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
typedef NativeEventNextFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
||||||
typedef DartEventNextFn = int Function(Pointer<Uint8>, int);
|
typedef DartEventNextFn = int Function(Pointer<Uint8>, int);
|
||||||
|
typedef NativeFileRequestFn = Int32 Function(
|
||||||
|
Pointer<Uint8>,
|
||||||
|
UintPtr,
|
||||||
|
Pointer<Uint8>,
|
||||||
|
UintPtr,
|
||||||
|
);
|
||||||
|
typedef DartFileRequestFn = int Function(Pointer<Uint8>, int, Pointer<Uint8>, int);
|
||||||
typedef NativeDemoSendControlFn = Int32 Function(
|
typedef NativeDemoSendControlFn = Int32 Function(
|
||||||
Uint16, Uint8, Pointer<Uint8>, UintPtr,
|
Uint16, Uint8, Pointer<Uint8>, UintPtr,
|
||||||
);
|
);
|
||||||
@@ -469,3 +539,21 @@ typedef NativeDiscoveryDevicesFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
|||||||
typedef DartDiscoveryDevicesFn = int Function(Pointer<Uint8>, int);
|
typedef DartDiscoveryDevicesFn = int Function(Pointer<Uint8>, int);
|
||||||
typedef NativeDiscoveryConnectFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
typedef NativeDiscoveryConnectFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
||||||
typedef DartDiscoveryConnectFn = int Function(Pointer<Uint8>, int);
|
typedef DartDiscoveryConnectFn = int Function(Pointer<Uint8>, int);
|
||||||
|
typedef NativeRelayStartFn = Int32 Function(
|
||||||
|
Pointer<Uint8>,
|
||||||
|
UintPtr,
|
||||||
|
Pointer<Uint8>,
|
||||||
|
UintPtr,
|
||||||
|
Pointer<Uint8>,
|
||||||
|
UintPtr,
|
||||||
|
);
|
||||||
|
typedef DartRelayStartFn = int Function(
|
||||||
|
Pointer<Uint8>,
|
||||||
|
int,
|
||||||
|
Pointer<Uint8>,
|
||||||
|
int,
|
||||||
|
Pointer<Uint8>,
|
||||||
|
int,
|
||||||
|
);
|
||||||
|
typedef NativeRelayStopFn = Void Function();
|
||||||
|
typedef DartRelayStopFn = void Function();
|
||||||
@@ -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<String, String> _pins = <String, String>{};
|
||||||
|
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<Directory> _directories() => <Directory>[
|
||||||
|
File(Platform.resolvedExecutable).parent,
|
||||||
|
Directory.current,
|
||||||
|
Directory.systemTemp,
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -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<dynamic>? _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<void> _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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,11 +2,13 @@ import 'dart:io';
|
|||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../../core/control_file_client.dart';
|
||||||
import '../../core/file_client.dart';
|
import '../../core/file_client.dart';
|
||||||
|
|
||||||
/// 浏览 / 下载 / 上传被控端文件。
|
/// 浏览 / 下载 / 上传被控端文件。
|
||||||
///
|
///
|
||||||
/// 走被控端内置的 LocalSend 风格 HTTP 服务(默认 53317),与串流控制通道互不影响。
|
/// 默认走被控端内置的 LocalSend 风格 HTTP 服务(默认 53317);控制通道可用时,
|
||||||
|
/// 还可以用 `msg_type=7` 文件子协议上传(HTTP 端口被防火墙拦掉时的兜底)。
|
||||||
class FileBrowserPage extends StatefulWidget {
|
class FileBrowserPage extends StatefulWidget {
|
||||||
const FileBrowserPage({
|
const FileBrowserPage({
|
||||||
super.key,
|
super.key,
|
||||||
@@ -14,12 +16,16 @@ class FileBrowserPage extends StatefulWidget {
|
|||||||
required this.initialPort,
|
required this.initialPort,
|
||||||
required this.initialToken,
|
required this.initialToken,
|
||||||
this.onConfigChanged,
|
this.onConfigChanged,
|
||||||
|
this.controlChannel,
|
||||||
});
|
});
|
||||||
|
|
||||||
final String host;
|
final String host;
|
||||||
final int initialPort;
|
final int initialPort;
|
||||||
final String initialToken;
|
final String initialToken;
|
||||||
|
|
||||||
|
/// 控制通道文件客户端;为 null 表示当前没有可用控制通道。
|
||||||
|
final ControlFileClient? controlChannel;
|
||||||
|
|
||||||
/// 用户改了地址/端口/令牌并保存时通知主界面写回设置。
|
/// 用户改了地址/端口/令牌并保存时通知主界面写回设置。
|
||||||
final void Function(String host, int port, String token)? onConfigChanged;
|
final void Function(String host, int port, String token)? onConfigChanged;
|
||||||
|
|
||||||
@@ -226,6 +232,74 @@ class _FileBrowserPageState extends State<FileBrowserPage> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 走控制通道(`msg_type=7`)上传:HTTP 文件服务不可用时的兜底。
|
||||||
|
///
|
||||||
|
/// 文件落在被控端应用私有目录 `file-inbox`,因此这里只提示保存名,
|
||||||
|
/// 不再刷新 HTTP 目录列表(那棵树看不到这个目录)。
|
||||||
|
Future<void> _uploadViaControlChannel() async {
|
||||||
|
final client = widget.controlChannel;
|
||||||
|
if (client == null) {
|
||||||
|
_toast('控制通道不可用:请先连接被控端', error: true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final controller = TextEditingController();
|
||||||
|
final localPath = await showDialog<String>(
|
||||||
|
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() {
|
void _saveConfig() {
|
||||||
final host = _hostController.text.trim();
|
final host = _hostController.text.trim();
|
||||||
final port = int.tryParse(_portController.text.trim()) ?? _port;
|
final port = int.tryParse(_portController.text.trim()) ?? _port;
|
||||||
@@ -277,6 +351,11 @@ class _FileBrowserPageState extends State<FileBrowserPage> {
|
|||||||
onPressed: directory == null || _loading ? null : _upload,
|
onPressed: directory == null || _loading ? null : _upload,
|
||||||
icon: const Icon(Icons.upload_file),
|
icon: const Icon(Icons.upload_file),
|
||||||
),
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: '通过控制通道上传(HTTP 不可用时)',
|
||||||
|
onPressed: _loading ? null : _uploadViaControlChannel,
|
||||||
|
icon: const Icon(Icons.swap_vert),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
body: Column(
|
body: Column(
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ class _SettingsPageState extends State<SettingsPage> {
|
|||||||
late bool _audioEnabled;
|
late bool _audioEnabled;
|
||||||
late bool _clipboardSync;
|
late bool _clipboardSync;
|
||||||
late bool _fileTransfer;
|
late bool _fileTransfer;
|
||||||
|
late bool _relayEnabled;
|
||||||
late int _bitrateMbps;
|
late int _bitrateMbps;
|
||||||
DeviceInfo? _localListener;
|
DeviceInfo? _localListener;
|
||||||
ServiceCheckResult? _serviceResult;
|
ServiceCheckResult? _serviceResult;
|
||||||
@@ -50,6 +51,7 @@ class _SettingsPageState extends State<SettingsPage> {
|
|||||||
_audioEnabled = widget.settings.audioEnabled;
|
_audioEnabled = widget.settings.audioEnabled;
|
||||||
_clipboardSync = widget.settings.clipboardSync;
|
_clipboardSync = widget.settings.clipboardSync;
|
||||||
_fileTransfer = widget.settings.fileTransfer;
|
_fileTransfer = widget.settings.fileTransfer;
|
||||||
|
_relayEnabled = widget.settings.relayEnabled;
|
||||||
_bitrateMbps = widget.settings.bitrateMbps;
|
_bitrateMbps = widget.settings.bitrateMbps;
|
||||||
_loadLocalListener();
|
_loadLocalListener();
|
||||||
_refreshListenerState();
|
_refreshListenerState();
|
||||||
@@ -180,6 +182,10 @@ class _SettingsPageState extends State<SettingsPage> {
|
|||||||
_snack('请填写外部信令服务器地址');
|
_snack('请填写外部信令服务器地址');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (_relayEnabled && _useLocalSignaling) {
|
||||||
|
_snack('中继需要被控端也能访问的信令地址,请改用外部信令');
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (int.tryParse(_localPort.text.trim()) == null) {
|
if (int.tryParse(_localPort.text.trim()) == null) {
|
||||||
_snack('本机端口必须是数字');
|
_snack('本机端口必须是数字');
|
||||||
return;
|
return;
|
||||||
@@ -209,6 +215,7 @@ class _SettingsPageState extends State<SettingsPage> {
|
|||||||
audioEnabled: _audioEnabled,
|
audioEnabled: _audioEnabled,
|
||||||
clipboardSync: _clipboardSync,
|
clipboardSync: _clipboardSync,
|
||||||
fileTransfer: _fileTransfer,
|
fileTransfer: _fileTransfer,
|
||||||
|
relayEnabled: _relayEnabled,
|
||||||
bitrateMbps: _bitrateMbps,
|
bitrateMbps: _bitrateMbps,
|
||||||
filePort: int.tryParse(_filePort.text.trim()) ?? widget.settings.filePort,
|
filePort: int.tryParse(_filePort.text.trim()) ?? widget.settings.filePort,
|
||||||
fileToken: _fileToken.text.trim(),
|
fileToken: _fileToken.text.trim(),
|
||||||
@@ -410,6 +417,12 @@ class _SettingsPageState extends State<SettingsPage> {
|
|||||||
value: _fileTransfer,
|
value: _fileTransfer,
|
||||||
onChanged: (value) => setState(() => _fileTransfer = value),
|
onChanged: (value) => setState(() => _fileTransfer = value),
|
||||||
),
|
),
|
||||||
|
SwitchListTile(
|
||||||
|
title: const Text('连接走信令中继'),
|
||||||
|
subtitle: const Text('跨网段时使用;中继只承载控制通道,不能投屏/传音频'),
|
||||||
|
value: _relayEnabled,
|
||||||
|
onChanged: (value) => setState(() => _relayEnabled = value),
|
||||||
|
),
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
|
padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
|
||||||
child: Row(
|
child: Row(
|
||||||
|
|||||||
@@ -6,8 +6,11 @@ import 'package:flutter/services.dart';
|
|||||||
|
|
||||||
import 'core/bridge.dart';
|
import 'core/bridge.dart';
|
||||||
import 'core/diagnostic_log.dart';
|
import 'core/diagnostic_log.dart';
|
||||||
|
import 'core/control_file_client.dart';
|
||||||
import 'core/native_core.dart';
|
import 'core/native_core.dart';
|
||||||
import 'core/models.dart';
|
import 'core/models.dart';
|
||||||
|
import 'core/pin_store.dart';
|
||||||
|
import 'core/watch_client.dart';
|
||||||
import 'features/control/control_toolbar.dart';
|
import 'features/control/control_toolbar.dart';
|
||||||
import 'features/discovery/device_list.dart';
|
import 'features/discovery/device_list.dart';
|
||||||
import 'features/file/file_browser_page.dart';
|
import 'features/file/file_browser_page.dart';
|
||||||
@@ -46,6 +49,7 @@ class _HomePageState extends State<HomePage> {
|
|||||||
NativeCore? _nativeCore;
|
NativeCore? _nativeCore;
|
||||||
late final SenderBridge _bridge;
|
late final SenderBridge _bridge;
|
||||||
final DiagnosticLog _diagnosticLog = DiagnosticLog();
|
final DiagnosticLog _diagnosticLog = DiagnosticLog();
|
||||||
|
final PinStore _pins = PinStore();
|
||||||
Timer? _demoStatusTimer;
|
Timer? _demoStatusTimer;
|
||||||
Timer? _diagnosticTimer;
|
Timer? _diagnosticTimer;
|
||||||
Timer? _connectWatchdog;
|
Timer? _connectWatchdog;
|
||||||
@@ -53,6 +57,12 @@ class _HomePageState extends State<HomePage> {
|
|||||||
Timer? _videoStatsTimer;
|
Timer? _videoStatsTimer;
|
||||||
Timer? _eventTimer;
|
Timer? _eventTimer;
|
||||||
Timer? _clipboardTimer;
|
Timer? _clipboardTimer;
|
||||||
|
Timer? _watchRefreshTimer;
|
||||||
|
SignalingWatch? _watch;
|
||||||
|
bool _watchConnected = false;
|
||||||
|
bool _refreshQueued = false;
|
||||||
|
/// 当前控制通道是否走信令中继(中继模式不支持投屏)。
|
||||||
|
bool _relayActive = false;
|
||||||
|
|
||||||
List<DeviceInfo> _devices = const <DeviceInfo>[];
|
List<DeviceInfo> _devices = const <DeviceInfo>[];
|
||||||
DeviceInfo? _selected;
|
DeviceInfo? _selected;
|
||||||
@@ -99,6 +109,8 @@ class _HomePageState extends State<HomePage> {
|
|||||||
_bridge.onVideoKey = _onVideoKey;
|
_bridge.onVideoKey = _onVideoKey;
|
||||||
_diagnosticLog.start();
|
_diagnosticLog.start();
|
||||||
_diagnosticLog.write('app initialized; nativeError=${_nativeError ?? '-'}');
|
_diagnosticLog.write('app initialized; nativeError=${_nativeError ?? '-'}');
|
||||||
|
_pins.load();
|
||||||
|
_diagnosticLog.write('pinned devices file: ${_pins.path}');
|
||||||
_bridge.watchPhase().listen((phase) {
|
_bridge.watchPhase().listen((phase) {
|
||||||
_diagnosticLog.write('phase event -> ${phase.wireName} (${phase.label})');
|
_diagnosticLog.write('phase event -> ${phase.wireName} (${phase.label})');
|
||||||
if (mounted) setState(() => _phase = phase);
|
if (mounted) setState(() => _phase = phase);
|
||||||
@@ -149,6 +161,8 @@ class _HomePageState extends State<HomePage> {
|
|||||||
_videoStatsTimer?.cancel();
|
_videoStatsTimer?.cancel();
|
||||||
_eventTimer?.cancel();
|
_eventTimer?.cancel();
|
||||||
_clipboardTimer?.cancel();
|
_clipboardTimer?.cancel();
|
||||||
|
_watchRefreshTimer?.cancel();
|
||||||
|
_watch?.stop();
|
||||||
_diagnosticLog.dispose();
|
_diagnosticLog.dispose();
|
||||||
_bridge.stopDemoServer();
|
_bridge.stopDemoServer();
|
||||||
_bridge.stopLocalSignaling();
|
_bridge.stopLocalSignaling();
|
||||||
@@ -160,20 +174,28 @@ class _HomePageState extends State<HomePage> {
|
|||||||
if (_nativeCore == null || !mounted) return;
|
if (_nativeCore == null || !mounted) return;
|
||||||
try {
|
try {
|
||||||
final status = _bridge.demoStatus();
|
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(() {
|
setState(() {
|
||||||
_demoStatus = status;
|
_demoStatus = status;
|
||||||
final running = status['running'] == true;
|
_relayActive = relay;
|
||||||
final connected = status['peerConnected'] == true;
|
if (connected && keyEstablished) {
|
||||||
final keyEstablished = status['keyEstablished'] == true;
|
|
||||||
if (running && connected && keyEstablished) {
|
|
||||||
_connectWatchdog?.cancel();
|
_connectWatchdog?.cancel();
|
||||||
_phase = ConnectionPhase.direct;
|
_phase = ConnectionPhase.direct;
|
||||||
} else if (running &&
|
} else if (sessionEnded) {
|
||||||
|
// 中继线程退出后 status 不再有进行中的会话,别把界面卡在「连接中」。
|
||||||
|
_phase = ConnectionPhase.idle;
|
||||||
|
} else if ((running || relay) &&
|
||||||
_phase != ConnectionPhase.idle &&
|
_phase != ConnectionPhase.idle &&
|
||||||
_phase != ConnectionPhase.failed) {
|
_phase != ConnectionPhase.failed) {
|
||||||
_phase = ConnectionPhase.probing;
|
_phase = ConnectionPhase.probing;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
if (sessionEnded) _snack('中继会话已断开');
|
||||||
} on Object catch (error) {
|
} on Object catch (error) {
|
||||||
_diagnosticLog.write('demoStatus refresh failed: $error');
|
_diagnosticLog.write('demoStatus refresh failed: $error');
|
||||||
}
|
}
|
||||||
@@ -356,6 +378,10 @@ class _HomePageState extends State<HomePage> {
|
|||||||
_snack('请先连接被控端');
|
_snack('请先连接被控端');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (_relayActive) {
|
||||||
|
_snack('中继模式只承载控制通道,投屏需要同一网段直连');
|
||||||
|
return;
|
||||||
|
}
|
||||||
setState(() {
|
setState(() {
|
||||||
_mirrorRequesting = true;
|
_mirrorRequesting = true;
|
||||||
// 新一轮请求:清掉上一轮「关窗已停流」的标记与旧帧时间。
|
// 新一轮请求:清掉上一轮「关窗已停流」的标记与旧帧时间。
|
||||||
@@ -552,6 +578,10 @@ class _HomePageState extends State<HomePage> {
|
|||||||
host: host,
|
host: host,
|
||||||
initialPort: _settings.filePort,
|
initialPort: _settings.filePort,
|
||||||
initialToken: _settings.fileToken,
|
initialToken: _settings.fileToken,
|
||||||
|
// 控制通道文件子协议只在已连接时可用(需要控制密钥)。
|
||||||
|
controlChannel: _phase.isConnected && _nativeCore != null
|
||||||
|
? ControlFileClient(send: _bridge.sendFileRequest)
|
||||||
|
: null,
|
||||||
onConfigChanged: (host, port, token) {
|
onConfigChanged: (host, port, token) {
|
||||||
final updated = _settings.copyWith(filePort: port, fileToken: token);
|
final updated = _settings.copyWith(filePort: port, fileToken: token);
|
||||||
setState(() => _settings = updated);
|
setState(() => _settings = updated);
|
||||||
@@ -600,11 +630,44 @@ class _HomePageState extends State<HomePage> {
|
|||||||
final url = await _bridge.resolveSignalingUrl(_settings);
|
final url = await _bridge.resolveSignalingUrl(_settings);
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _effectiveSignalingUrl = url);
|
setState(() => _effectiveSignalingUrl = url);
|
||||||
|
_restartWatch(url);
|
||||||
unawaited(_refreshDevices());
|
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<void> _refreshDevices() async {
|
Future<void> _refreshDevices() async {
|
||||||
if (_refreshing) return;
|
if (_refreshing) {
|
||||||
|
// 正在刷新时又来一次请求:记下来,等本轮结束后补一次,避免事件被吞掉。
|
||||||
|
_refreshQueued = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
setState(() => _refreshing = true);
|
setState(() => _refreshing = true);
|
||||||
final devices = await _bridge.discover(signalingUrl: _effectiveSignalingUrl);
|
final devices = await _bridge.discover(signalingUrl: _effectiveSignalingUrl);
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
@@ -616,6 +679,10 @@ class _HomePageState extends State<HomePage> {
|
|||||||
_refreshing = false;
|
_refreshing = false;
|
||||||
});
|
});
|
||||||
_diagnosticLog.write('discover result: ${devices.length} devices');
|
_diagnosticLog.write('discover result: ${devices.length} devices');
|
||||||
|
if (_refreshQueued) {
|
||||||
|
_refreshQueued = false;
|
||||||
|
unawaited(_refreshDevices());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _connect() async {
|
Future<void> _connect() async {
|
||||||
@@ -624,6 +691,11 @@ class _HomePageState extends State<HomePage> {
|
|||||||
_diagnosticLog.write(
|
_diagnosticLog.write(
|
||||||
'connect requested: ${device.id} ${device.ip}:${device.mediaPort}/${device.controlPort}',
|
'connect requested: ${device.id} ${device.ip}:${device.mediaPort}/${device.controlPort}',
|
||||||
);
|
);
|
||||||
|
if (!await _confirmFingerprint(device)) return;
|
||||||
|
if (_settings.relayEnabled) {
|
||||||
|
await _connectViaRelay(device);
|
||||||
|
return;
|
||||||
|
}
|
||||||
_connectWatchdog?.cancel();
|
_connectWatchdog?.cancel();
|
||||||
setState(() => _phase = ConnectionPhase.probing);
|
setState(() => _phase = ConnectionPhase.probing);
|
||||||
_connectWatchdog = Timer(const Duration(seconds: 10), () {
|
_connectWatchdog = Timer(const Duration(seconds: 10), () {
|
||||||
@@ -648,6 +720,86 @@ class _HomePageState extends State<HomePage> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 跨网段连接:控制帧经信令服务器中转,不依赖被控端能反连本机。
|
||||||
|
///
|
||||||
|
/// 中继不承载视频/音频,界面会禁止发起投屏;文件、剪贴板、输入仍可用。
|
||||||
|
Future<void> _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<bool> _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<bool>(
|
||||||
|
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<void> _disconnect() async {
|
Future<void> _disconnect() async {
|
||||||
_diagnosticLog.write('disconnect requested');
|
_diagnosticLog.write('disconnect requested');
|
||||||
_connectWatchdog?.cancel();
|
_connectWatchdog?.cancel();
|
||||||
@@ -660,7 +812,10 @@ class _HomePageState extends State<HomePage> {
|
|||||||
}
|
}
|
||||||
await _bridge.disconnect();
|
await _bridge.disconnect();
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _phase = ConnectionPhase.idle);
|
setState(() {
|
||||||
|
_phase = ConnectionPhase.idle;
|
||||||
|
_relayActive = false;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _openSettings() async {
|
Future<void> _openSettings() async {
|
||||||
@@ -827,6 +982,7 @@ class _HomePageState extends State<HomePage> {
|
|||||||
final status = _demoStatus;
|
final status = _demoStatus;
|
||||||
final connected = status['peerConnected'] == true;
|
final connected = status['peerConnected'] == true;
|
||||||
final keyEstablished = status['keyEstablished'] == true;
|
final keyEstablished = status['keyEstablished'] == true;
|
||||||
|
final relay = status['relay'] == true;
|
||||||
final peerIp = (status['peerIp'] as String? ?? '').trim();
|
final peerIp = (status['peerIp'] as String? ?? '').trim();
|
||||||
|
|
||||||
return Card(
|
return Card(
|
||||||
@@ -850,6 +1006,7 @@ class _HomePageState extends State<HomePage> {
|
|||||||
)
|
)
|
||||||
else
|
else
|
||||||
Text(
|
Text(
|
||||||
|
'${relay ? '信令中继' : '直连'} · '
|
||||||
'被控端 ${connected ? '已连接' : '未连接'} · '
|
'被控端 ${connected ? '已连接' : '未连接'} · '
|
||||||
'${keyEstablished ? '会话密钥已建立' : '等待 ECDH 协商'}' +
|
'${keyEstablished ? '会话密钥已建立' : '等待 ECDH 协商'}' +
|
||||||
(peerIp.isEmpty ? '' : ' · 对端 $peerIp'),
|
(peerIp.isEmpty ? '' : ' · 对端 $peerIp'),
|
||||||
@@ -990,6 +1147,23 @@ class _HomePageState extends State<HomePage> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
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,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
Reference in new issue
Block a user