Files
tongtong d3ff293877 feat(sender): 首页移除投屏画面,请求投屏直开独立窗口,新增文件传输
- 删除首页 VideoView:画面只在独立原生窗口显示,首页改为状态卡片(分辨率/帧数/错误)

- 新增 MirrorBar 卡片,请求投屏/停止投屏从控制工具栏独立出来;点请求即打开独立窗口再下发 msg_type=8

- 停止投屏同时下发 stop 并关闭窗口;控制工具栏移除投屏按钮

- 独立窗口无画面时居中提示「等待被控端画面…」

- 新增 core/file_client.dart 与 file_browser_page:浏览/下载到 Downloads/TTSTD/上传,带进度与错误提示

- AppSettings 增加 filePort/fileToken 并接入设置页与首页文件卡片
2026-11-27 09:59:55 +08:00

240 lines
7.3 KiB
Dart
Raw Permalink 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:convert';
import 'dart:io';
/// 被控端目录项。
class RemoteFileEntry {
const RemoteFileEntry({
required this.name,
required this.path,
required this.isDir,
required this.size,
required this.modified,
});
final String name;
final String path;
final bool isDir;
final int size;
final int modified;
factory RemoteFileEntry.fromJson(Map<String, dynamic> json) {
return RemoteFileEntry(
name: (json['name'] ?? '').toString(),
path: (json['path'] ?? '').toString(),
isDir: json['dir'] == true,
size: json['size'] is num ? (json['size'] as num).toInt() : 0,
modified: json['mtime'] is num ? (json['mtime'] as num).toInt() : 0,
);
}
String get sizeLabel {
if (isDir) return '目录';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
var value = size.toDouble();
var index = 0;
while (value >= 1024 && index < units.length - 1) {
value /= 1024;
index++;
}
return index == 0 ? '${size} B' : '${value.toStringAsFixed(1)} ${units[index]}';
}
}
/// 一次目录列举的结果。
class RemoteDirectory {
const RemoteDirectory({
required this.path,
required this.parent,
required this.entries,
});
final String path;
final String parent;
final List<RemoteFileEntry> entries;
factory RemoteDirectory.fromJson(Map<String, dynamic> json) {
final raw = json['entries'];
final entries = raw is List
? raw
.whereType<Map<dynamic, dynamic>>()
.map((item) => RemoteFileEntry.fromJson(Map<String, dynamic>.from(item)))
.toList(growable: false)
: const <RemoteFileEntry>[];
return RemoteDirectory(
path: (json['path'] ?? '').toString(),
parent: (json['parent'] ?? '').toString(),
entries: entries,
);
}
}
/// 被控端文件服务客户端(LocalSend 风格 HTTP,默认 53317)。
///
/// 不依赖控制通道:只要被控端的待命服务在跑,就能浏览/下载/上传文件。
class AndroidFileClient {
AndroidFileClient({
required this.host,
required this.port,
required this.token,
this.timeout = const Duration(seconds: 15),
});
final String host;
final int port;
final String token;
final Duration timeout;
String get baseUrl => 'http://$host:$port';
Uri _uri(String path, [Map<String, String>? query]) {
return Uri(
scheme: 'http',
host: host,
port: port,
path: path,
queryParameters: <String, String>{
...?query,
if (token.isNotEmpty) 'token': token,
},
);
}
HttpClient _client() => HttpClient()..connectionTimeout = timeout;
/// 设备信息(无需令牌),同时用于连通性自检。
Future<Map<String, dynamic>> info() async {
final client = _client();
try {
final request = await client.getUrl(Uri.parse('$baseUrl/api/localsend/v2/info'));
final response = await request.close().timeout(timeout);
final body = await response.transform(utf8.decoder).join();
if (response.statusCode != 200) {
throw FileClientException('设备信息读取失败(HTTP ${response.statusCode})');
}
return jsonDecode(body) as Map<String, dynamic>;
} on SocketException catch (error) {
throw FileClientException('无法连接 $host:$port,请确认被控端待命服务已启动(${error.message})');
} finally {
client.close(force: true);
}
}
/// 列举目录。
Future<RemoteDirectory> browse(String path) async {
final client = _client();
try {
final request = await client.getUrl(_uri('/browse', {'path': path}));
final response = await request.close().timeout(timeout);
final body = await response.transform(utf8.decoder).join();
if (response.statusCode == 403) {
throw FileClientException('令牌无效,请填写被控端主界面显示的文件服务令牌');
}
if (response.statusCode != 200) {
throw FileClientException(_errorOf(body, response.statusCode));
}
return RemoteDirectory.fromJson(jsonDecode(body) as Map<String, dynamic>);
} on SocketException catch (error) {
throw FileClientException('无法连接 $host:$port(${error.message})');
} finally {
client.close(force: true);
}
}
/// 下载文件到本地路径,返回写入字节数。
Future<int> download(
String remotePath,
String localPath, {
void Function(int received, int total)? onProgress,
}) async {
final client = _client();
try {
final request = await client.getUrl(_uri('/download', {'path': remotePath}));
final response = await request.close().timeout(timeout);
if (response.statusCode != 200) {
final body = await response.transform(utf8.decoder).join();
throw FileClientException(_errorOf(body, response.statusCode));
}
final target = File(localPath);
await target.parent.create(recursive: true);
final sink = target.openWrite();
final total = response.contentLength;
var received = 0;
try {
await for (final chunk in response) {
sink.add(chunk);
received += chunk.length;
onProgress?.call(received, total);
}
} finally {
await sink.flush();
await sink.close();
}
return received;
} on SocketException catch (error) {
throw FileClientException('下载失败:${error.message}');
} finally {
client.close(force: true);
}
}
/// 上传本地文件到被控端目录,返回远端路径。
Future<String> upload(
String localPath,
String remoteDir, {
void Function(int sent, int total)? onProgress,
}) async {
final source = File(localPath);
if (!await source.exists()) {
throw FileClientException('本地文件不存在:$localPath');
}
final total = await source.length();
final client = _client();
try {
final request = await client.postUrl(
_uri('/api/localsend/v2/upload', {
'path': remoteDir,
'name': source.uri.pathSegments.last,
}),
);
request.headers.contentType = ContentType.binary;
request.contentLength = total;
var sent = 0;
await for (final chunk in source.openRead()) {
request.add(chunk);
sent += chunk.length;
onProgress?.call(sent, total);
}
final response = await request.close().timeout(timeout);
final body = await response.transform(utf8.decoder).join();
if (response.statusCode != 200) {
throw FileClientException(_errorOf(body, response.statusCode));
}
final json = jsonDecode(body) as Map<String, dynamic>;
return (json['path'] ?? '').toString();
} on SocketException catch (error) {
throw FileClientException('上传失败:${error.message}');
} finally {
client.close(force: true);
}
}
String _errorOf(String body, int statusCode) {
try {
final json = jsonDecode(body);
if (json is Map && json['error'] != null) return json['error'].toString();
} on Object catch (_) {
// 非 JSON 响应直接用原文。
}
return 'HTTP $statusCode:${body.isEmpty ? '无响应内容' : body}';
}
}
class FileClientException implements Exception {
FileClientException(this.message);
final String message;
@override
String toString() => message;
}