Files
TTSTDConnect/flutter_sender/lib/features/file/file_browser_page.dart
T
tongtong a9ba4bb7bc feat(sender): 设备指纹固定、/watch 实时刷新、中继连接与文件子协议上传
- 新增 PinStore:首次连接记录被控端签名指纹,变化时弹窗确认
- 新增 SignalingWatch:订阅 /watch,300ms 去抖后重拉设备列表
- 设置页新增"连接走信令中继",主控端按该开关走 ttstd_relay_start
- 中继模式禁用投屏并提示原因,状态卡区分直连/中继
- 新增 ControlFileClient:通过 msgType=7 分片上传/列目录,文件页加入口
- NativeCore/Bridge 暴露 relayStart/relayStop/sendFileRequest
2026-11-27 18:44:49 +08:00

535 lines
16 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import 'dart:io';
import 'package:flutter/material.dart';
import '../../core/control_file_client.dart';
import '../../core/file_client.dart';
/// 浏览 / 下载 / 上传被控端文件。
///
/// 默认走被控端内置的 LocalSend 风格 HTTP 服务(默认 53317);控制通道可用时,
/// 还可以用 `msg_type=7` 文件子协议上传(HTTP 端口被防火墙拦掉时的兜底)。
class FileBrowserPage extends StatefulWidget {
const FileBrowserPage({
super.key,
required this.host,
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;
@override
State<FileBrowserPage> createState() => _FileBrowserPageState();
}
class _FileBrowserPageState extends State<FileBrowserPage> {
late final TextEditingController _hostController =
TextEditingController(text: widget.host);
late final TextEditingController _portController =
TextEditingController(text: widget.initialPort.toString());
late final TextEditingController _tokenController =
TextEditingController(text: widget.initialToken);
late String _host = widget.host;
late int _port = widget.initialPort;
late String _token = widget.initialToken;
AndroidFileClient? _client;
RemoteDirectory? _directory;
String? _error;
bool _loading = false;
String _alias = '';
double? _progress;
String _progressLabel = '';
@override
void initState() {
super.initState();
_connect();
}
@override
void dispose() {
_portController.dispose();
_tokenController.dispose();
super.dispose();
}
Future<void> _connect() async {
if (_host.isEmpty || _host == '127.0.0.1') {
setState(() => _error = '还没有拿到被控端的局域网 IP,请在上方「IP」里手动填写(例如 192.168.1.23)');
return;
}
setState(() {
_loading = true;
_error = null;
});
final client = AndroidFileClient(host: _host, port: _port, token: _token);
try {
final info = await client.info();
final directory = await client.browse('');
if (!mounted) return;
setState(() {
_client = client;
_alias = (info['alias'] ?? '').toString();
_directory = directory;
_loading = false;
});
} on FileClientException catch (error) {
if (!mounted) return;
setState(() {
_error = error.message;
_loading = false;
});
} catch (error) {
if (!mounted) return;
setState(() {
_error = '$error';
_loading = false;
});
}
}
Future<void> _open(String path) async {
final client = _client;
if (client == null) return;
setState(() {
_loading = true;
_error = null;
});
try {
final directory = await client.browse(path);
if (!mounted) return;
setState(() {
_directory = directory;
_loading = false;
});
} on FileClientException catch (error) {
if (!mounted) return;
setState(() {
_error = error.message;
_loading = false;
});
}
}
Future<String> _downloadsDir() async {
final env = Platform.environment;
final home = env['USERPROFILE'] ?? env['HOME'] ?? Directory.current.path;
final dir = Directory('$home${Platform.pathSeparator}Downloads'
'${Platform.pathSeparator}TTSTD');
if (!await dir.exists()) {
await dir.create(recursive: true);
}
return dir.path;
}
Future<void> _download(RemoteFileEntry entry) async {
final client = _client;
if (client == null) return;
final dir = await _downloadsDir();
final target = '$dir${Platform.pathSeparator}${entry.name}';
setState(() {
_progress = 0;
_progressLabel = '下载 ${entry.name}';
});
try {
final written = await client.download(
entry.path,
target,
onProgress: (received, total) {
if (!mounted) return;
setState(() {
_progress = total > 0 ? received / total : null;
_progressLabel = '下载 ${entry.name} · ${_size(received)} / ${_size(total)}';
});
},
);
if (!mounted) return;
_toast('已保存到 $target(${_size(written)})');
} on FileClientException catch (error) {
if (!mounted) return;
_toast(error.message, error: true);
} finally {
if (mounted) {
setState(() {
_progress = null;
_progressLabel = '';
});
}
}
}
Future<void> _upload() async {
final client = _client;
final directory = _directory;
if (client == null || directory == null) 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,
directory.path,
onProgress: (sent, total) {
if (!mounted) return;
setState(() {
_progress = total > 0 ? sent / total : null;
_progressLabel = '上传中 · ${_size(sent)} / ${_size(total)}';
});
},
);
if (!mounted) return;
_toast('已上传到 $remote');
await _open(directory.path);
} on FileClientException catch (error) {
if (!mounted) return;
_toast(error.message, error: true);
} finally {
if (mounted) {
setState(() {
_progress = null;
_progressLabel = '';
});
}
}
}
/// 走控制通道(`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() {
final host = _hostController.text.trim();
final port = int.tryParse(_portController.text.trim()) ?? _port;
final token = _tokenController.text.trim();
setState(() {
_host = host;
_port = port;
_token = token;
});
widget.onConfigChanged?.call(host, port, token);
_toast('参数已保存');
_connect();
}
void _toast(String message, {bool error = false}) {
if (!mounted) return;
final messenger = ScaffoldMessenger.of(context);
messenger.hideCurrentSnackBar();
messenger.showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: error ? Theme.of(context).colorScheme.error : null,
),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final directory = _directory;
return Scaffold(
appBar: AppBar(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(_host.isEmpty ? '文件传输' : '$_host:$_port'),
if (_alias.isNotEmpty)
Text(_alias, style: theme.textTheme.bodySmall),
],
),
actions: [
IconButton(
tooltip: '刷新',
onPressed: _loading ? null : () => _open(directory?.path ?? ''),
icon: const Icon(Icons.refresh),
),
IconButton(
tooltip: '上传文件到当前目录',
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(
children: [
_buildConfigCard(theme),
if (_progress != null)
LinearProgressIndicator(value: _progress, minHeight: 3),
if (_progressLabel.isNotEmpty)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Align(
alignment: Alignment.centerLeft,
child: Text(_progressLabel, style: theme.textTheme.bodySmall),
),
),
_buildBreadcrumb(theme, directory),
Expanded(child: _buildBody(theme, directory)),
],
),
);
}
Widget _buildConfigCard(ThemeData theme) {
return Card(
margin: const EdgeInsets.fromLTRB(12, 12, 12, 4),
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('被控端文件服务', style: theme.textTheme.titleSmall),
const SizedBox(height: 8),
Row(
children: [
Expanded(
flex: 2,
child: TextField(
controller: _hostController,
decoration: const InputDecoration(
labelText: 'IP',
hintText: '192.168.1.23',
isDense: true,
),
),
),
const SizedBox(width: 10),
Expanded(
child: TextField(
controller: _portController,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
labelText: '端口',
isDense: true,
),
),
),
],
),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: TextField(
controller: _tokenController,
decoration: const InputDecoration(
labelText: '令牌(被控端主界面显示)',
isDense: true,
),
),
),
const SizedBox(width: 8),
FilledButton.tonal(
onPressed: _loading ? null : _saveConfig,
child: const Text('应用'),
),
],
),
],
),
),
);
}
Widget _buildBreadcrumb(ThemeData theme, RemoteDirectory? directory) {
if (directory == null) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Row(
children: [
IconButton(
tooltip: '上一级',
onPressed: directory.parent.isEmpty || _loading
? null
: () => _open(directory.parent),
icon: const Icon(Icons.arrow_upward),
),
Expanded(
child: SelectableText(
directory.path,
style: theme.textTheme.bodySmall,
maxLines: 1,
),
),
Text('${directory.entries.length} 项', style: theme.textTheme.bodySmall),
],
),
);
}
Widget _buildBody(ThemeData theme, RemoteDirectory? directory) {
if (_error != null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.folder_off, size: 56, color: theme.colorScheme.error),
const SizedBox(height: 12),
Text(_error!, textAlign: TextAlign.center),
const SizedBox(height: 16),
FilledButton.tonal(onPressed: _connect, child: const Text('重试')),
],
),
),
);
}
if (_loading && directory == null) {
return const Center(child: CircularProgressIndicator());
}
if (directory == null) {
return const Center(child: Text('暂无数据'));
}
if (directory.entries.isEmpty) {
return const Center(child: Text('这个目录是空的'));
}
return ListView.separated(
itemCount: directory.entries.length,
separatorBuilder: (_, __) => const Divider(height: 1),
itemBuilder: (context, index) {
final entry = directory.entries[index];
return ListTile(
dense: true,
leading: Icon(
entry.isDir ? Icons.folder : Icons.insert_drive_file_outlined,
color: entry.isDir ? theme.colorScheme.primary : null,
),
title: Text(entry.name, maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(entry.sizeLabel),
trailing: entry.isDir
? const Icon(Icons.chevron_right)
: IconButton(
tooltip: '下载到本机 Downloads/TTSTD',
onPressed: _progress == null ? () => _download(entry) : null,
icon: const Icon(Icons.download),
),
onTap: entry.isDir
? (_loading ? null : () => _open(entry.path))
: () => _download(entry),
);
},
);
}
}
String _size(int bytes) {
if (bytes <= 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
var value = bytes.toDouble();
var index = 0;
while (value >= 1024 && index < units.length - 1) {
value /= 1024;
index++;
}
return index == 0 ? '$bytes B' : '${value.toStringAsFixed(1)} ${units[index]}';
}