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 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 entries; factory RemoteDirectory.fromJson(Map json) { final raw = json['entries']; final entries = raw is List ? raw .whereType>() .map((item) => RemoteFileEntry.fromJson(Map.from(item))) .toList(growable: false) : const []; 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? query]) { return Uri( scheme: 'http', host: host, port: port, path: path, queryParameters: { ...?query, if (token.isNotEmpty) 'token': token, }, ); } HttpClient _client() => HttpClient()..connectionTimeout = timeout; /// 设备信息(无需令牌),同时用于连通性自检。 Future> 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; } on SocketException catch (error) { throw FileClientException('无法连接 $host:$port,请确认被控端待命服务已启动(${error.message})'); } finally { client.close(force: true); } } /// 列举目录。 Future 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); } on SocketException catch (error) { throw FileClientException('无法连接 $host:$port(${error.message})'); } finally { client.close(force: true); } } /// 下载文件到本地路径,返回写入字节数。 Future 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 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; 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; }