import 'dart:io'; import 'package:flutter/material.dart'; import '../../core/file_client.dart'; /// 浏览 / 下载 / 上传被控端文件。 /// /// 走被控端内置的 LocalSend 风格 HTTP 服务(默认 53317),与串流控制通道互不影响。 class FileBrowserPage extends StatefulWidget { const FileBrowserPage({ super.key, required this.host, required this.initialPort, required this.initialToken, this.onConfigChanged, }); final String host; final int initialPort; final String initialToken; /// 用户改了地址/端口/令牌并保存时通知主界面写回设置。 final void Function(String host, int port, String token)? onConfigChanged; @override State createState() => _FileBrowserPageState(); } class _FileBrowserPageState extends State { 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 _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 _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 _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 _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 _upload() async { final client = _client; final directory = _directory; if (client == null || directory == null) 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, 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 = ''; }); } } } 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), ), ], ), 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]}'; }