import 'dart:convert'; import 'package:http/http.dart' as http; /// 后端返回的错误(HTTP 非 2xx,或后端明确返回 ok=false)。 class ApiException implements Exception { ApiException(this.message, {this.statusCode}); final String message; final int? statusCode; @override String toString() => message; } /// 已安装模型。 class ModelInfo { ModelInfo.fromJson(Map json) : id = json['id'] as String? ?? '', name = json['name'] as String? ?? '', description = json['description'] as String? ?? '', version = json['version'] as String? ?? '', author = json['author'] as String? ?? '', sizeBytes = (json['sizeBytes'] as num?)?.toInt() ?? 0, sizeText = json['sizeText'] as String? ?? '', tags = _stringList(json['tags']), hasPreview = json['hasPreview'] as bool? ?? false, previewUrl = json['previewUrl'] as String? ?? '', directory = json['directory'] as String? ?? '', dataDirectory = json['dataDirectory'] as String? ?? ''; final String id; final String name; final String description; final String version; final String author; final int sizeBytes; final String sizeText; final List tags; final bool hasPreview; final String previewUrl; final String directory; final String dataDirectory; String get metaText => 'v$version · $sizeText'; } /// 模型源。 class SourceInfo { SourceInfo.fromJson(Map json) : id = json['id'] as String? ?? '', name = json['name'] as String? ?? '', url = json['url'] as String? ?? '', enabled = json['enabled'] as bool? ?? false, builtIn = json['builtIn'] as bool? ?? false, host = json['host'] as String? ?? ''; final String id; final String name; final String url; final bool enabled; final bool builtIn; final String host; } /// 远端可下载模型。 class RemoteModelInfo { RemoteModelInfo.fromJson(Map json) : id = json['id'] as String? ?? '', name = json['name'] as String? ?? '', description = json['description'] as String? ?? '', version = json['version'] as String? ?? '', sizeBytes = (json['sizeBytes'] as num?)?.toInt() ?? 0, sizeText = json['sizeText'] as String? ?? '', sourceId = json['sourceId'] as String? ?? '', installed = json['installed'] as bool? ?? false, installedVersion = json['installedVersion'] as String?; final String id; final String name; final String description; final String version; final int sizeBytes; final String sizeText; final String sourceId; final bool installed; final String? installedVersion; } /// 一次远端源索引结果。 class SourceIndexInfo { SourceIndexInfo.fromJson(Map json) : sourceId = json['sourceId'] as String? ?? '', root = json['root'] as String? ?? '', fromCache = json['fromCache'] as bool? ?? false, error = json['error'] as String?, resolvedFrom = json['resolvedFrom'] as String? ?? '', models = (json['models'] as List? ?? const []) .map((e) => RemoteModelInfo.fromJson(e as Map)) .toList(); final String sourceId; final String root; final bool fromCache; final String? error; final String resolvedFrom; final List models; } /// 下载任务。 class JobInfo { JobInfo.fromJson(Map json) : id = json['id'] as String? ?? '', modelId = json['modelId'] as String? ?? '', name = json['name'] as String? ?? '', version = json['version'] as String? ?? '', state = json['state'] as String? ?? 'Queued', progress = (json['progress'] as num?)?.toDouble() ?? 0, statusText = json['statusText'] as String? ?? '', detailText = json['detailText'] as String? ?? '', error = json['error'] as String?, isActive = json['isActive'] as bool? ?? false, canRetry = json['canRetry'] as bool? ?? false, isDone = json['isDone'] as bool? ?? false; final String id; final String modelId; final String name; final String version; final String state; final double progress; final String statusText; final String detailText; final String? error; final bool isActive; final bool canRetry; final bool isDone; } /// 界面语言选项。 class LanguageInfo { LanguageInfo.fromJson(Map json) : code = json['code'] as String? ?? '', label = json['label'] as String? ?? ''; final String code; final String label; } /// 设置。 class SettingsInfo { SettingsInfo.fromJson(Map json) : language = json['language'] as String? ?? 'auto', theme = json['theme'] as String? ?? 'light', renderFps = (json['renderFps'] as num?)?.toInt() ?? 120, memoryMb = (json['memoryMb'] as num?)?.toInt() ?? 2048, memoryAuto = json['memoryAuto'] as bool? ?? true, autoUpdateOnStartup = json['autoUpdateOnStartup'] as bool? ?? true, requireSignedManifest = json['requireSignedManifest'] as bool? ?? true, updateRepository = json['updateRepository'] as String? ?? '', updateLocalRoot = json['updateLocalRoot'] as String?, modelRootOverride = json['modelRootOverride'] as String?, memoryBudgetMb = (json['memoryBudgetMb'] as num?)?.toInt() ?? 0, memoryUsageText = json['memoryUsageText'] as String? ?? '', modelRoot = json['modelRoot'] as String? ?? '', dataRoot = json['dataRoot'] as String? ?? '', settingsFile = json['settingsFile'] as String? ?? '', version = json['version'] as String? ?? '', platform = json['platform'] as String? ?? '', sources = (json['sources'] as List? ?? const []) .map((e) => SourceInfo.fromJson(e as Map)) .toList(), languages = (json['languages'] as List? ?? const []) .map((e) => LanguageInfo.fromJson(e as Map)) .toList(); final String language; final String theme; final int renderFps; final int memoryMb; final bool memoryAuto; final bool autoUpdateOnStartup; final bool requireSignedManifest; final String updateRepository; final String? updateLocalRoot; final String? modelRootOverride; final int memoryBudgetMb; final String memoryUsageText; final String modelRoot; final String dataRoot; final String settingsFile; final String version; final String platform; final List sources; final List languages; } /// 设置补丁:只提交要改的字段。 class SettingsPatch { const SettingsPatch({ this.language, this.theme, this.renderFps, this.memoryMb, this.memoryAuto, this.autoUpdateOnStartup, this.requireSignedManifest, this.updateRepository, this.updateLocalRoot, this.modelRootOverride, }); final String? language; final String? theme; final int? renderFps; final int? memoryMb; final bool? memoryAuto; final bool? autoUpdateOnStartup; final bool? requireSignedManifest; final String? updateRepository; final String? updateLocalRoot; final String? modelRootOverride; Map toJson() { final map = {}; if (language != null) map['language'] = language; if (theme != null) map['theme'] = theme; if (renderFps != null) map['renderFps'] = renderFps; if (memoryMb != null) map['memoryMb'] = memoryMb; if (memoryAuto != null) map['memoryAuto'] = memoryAuto; if (autoUpdateOnStartup != null) map['autoUpdateOnStartup'] = autoUpdateOnStartup; if (requireSignedManifest != null) map['requireSignedManifest'] = requireSignedManifest; if (updateRepository != null) map['updateRepository'] = updateRepository; if (updateLocalRoot != null) map['updateLocalRoot'] = updateLocalRoot; if (modelRootOverride != null) map['modelRootOverride'] = modelRootOverride; return map; } } /// 健康检查。 class HealthInfo { HealthInfo.fromJson(Map json) : ok = json['ok'] as bool? ?? false, version = json['version'] as String? ?? '', platform = json['platform'] as String? ?? '', uiAvailable = json['uiAvailable'] as bool? ?? false, uiError = json['uiError'] as String?; final bool ok; final String version; final String platform; final bool uiAvailable; final String? uiError; } /// 一次更新检查的结果。 class UpdateCheckInfo { UpdateCheckInfo.fromJson(Map json) : outcome = json['outcome'] as String? ?? '', message = json['message'] as String? ?? '', updatedModels = (json['updatedModels'] as num?)?.toInt() ?? 0, modelNames = _stringList(json['modelNames']), launcherMessage = json['launcherMessage'] as String?, error = json['error'] as String?, launcherLatest = json['launcherLatest'] as String?, sourceName = json['sourceName'] as String? ?? ''; final String outcome; final String message; final int updatedModels; final List modelNames; final String? launcherMessage; final String? error; final String? launcherLatest; final String sourceName; } /// 贡献者。 class ContributorInfo { ContributorInfo.fromJson(Map json) : name = json['name'] as String? ?? '', contributions = (json['contributions'] as num?)?.toInt() ?? 0, avatarUrl = json['avatarUrl'] as String?; final String name; final int contributions; final String? avatarUrl; } /// 关于页数据。 class AboutInfo { AboutInfo.fromJson(Map json) : appName = json['appName'] as String? ?? '', version = json['version'] as String? ?? '', platform = json['platform'] as String? ?? '', repository = json['repository'] as String? ?? '', sourceLanguage = json['sourceLanguage'] as String? ?? 'C#', frontend = json['frontend'] as String? ?? 'Flutter', contributors = (json['contributors'] as List? ?? const []) .map((e) => ContributorInfo.fromJson(e as Map)) .toList(); final String appName; final String version; final String platform; final String repository; /// 源码语言(后端 / 模型层),由后端 `/api/about` 返回。 final String sourceLanguage; /// 前端框架,由后端 `/api/about` 返回。 final String frontend; final List contributors; } /// 通用操作结果。 class ActionResult { ActionResult.fromJson(Map json) : ok = json['ok'] as bool? ?? false, message = json['message'] as String? ?? ''; final bool ok; final String message; } List _stringList(dynamic value) => (value as List? ?? const []).map((e) => e.toString()).toList(); /// GC-UI 后端客户端。 /// /// 后端是本地伴随进程,默认监听 127.0.0.1:17890;端口可用 /// `--dart-define=GC_UI_BASE_URL=http://127.0.0.1:12345` 覆盖。 class GcApi { GcApi({String? baseUrl}) : baseUrl = baseUrl ?? defaultBaseUrl; static const String defaultBaseUrl = String.fromEnvironment( 'GC_UI_BASE_URL', defaultValue: 'http://127.0.0.1:17890', ); final String baseUrl; Uri _uri(String path, [Map? query]) => Uri.parse('$baseUrl$path').replace(queryParameters: query); Future _send(String method, String path, {Map? query, Object? body}) async { final uri = _uri(path, query); late http.Response response; try { switch (method) { case 'GET': response = await http.get(uri).timeout(const Duration(seconds: 30)); break; case 'POST': response = await http .post(uri, headers: const {'Content-Type': 'application/json'}, body: body == null ? null : jsonEncode(body)) .timeout(const Duration(seconds: 120)); break; case 'DELETE': response = await http.delete(uri).timeout(const Duration(seconds: 30)); break; default: throw ApiException('不支持的方法 $method'); } } on ApiException { rethrow; } catch (error) { throw ApiException('无法连接后端($baseUrl):$error'); } final text = utf8.decode(response.bodyBytes); dynamic decoded; if (text.isNotEmpty) { try { decoded = jsonDecode(text); } catch (_) { decoded = null; } } if (response.statusCode >= 400) { final message = decoded is Map ? (decoded['message'] as String? ?? 'HTTP ${response.statusCode}') : 'HTTP ${response.statusCode}'; throw ApiException(message, statusCode: response.statusCode); } return decoded; } List> _asList(dynamic value) => (value as List? ?? const []) .map((e) => e as Map) .toList(); Future health() async => HealthInfo.fromJson(await _send('GET', '/api/health') as Map); Future> models() async => _asList(await _send('GET', '/api/models')).map(ModelInfo.fromJson).toList(); Future launchModel(String id) async => ActionResult.fromJson( await _send('POST', '/api/models/$id/launch') as Map); Future deleteModel(String id) async => ActionResult.fromJson( await _send('DELETE', '/api/models/$id') as Map); Future settings() async => SettingsInfo.fromJson(await _send('GET', '/api/settings') as Map); Future saveSettings(SettingsPatch patch) async => SettingsInfo.fromJson(await _send('POST', '/api/settings', body: patch.toJson()) as Map); Future> sources() async => _asList(await _send('GET', '/api/sources')).map(SourceInfo.fromJson).toList(); Future remoteModels({String? sourceId, bool force = false}) async => SourceIndexInfo.fromJson(await _send('GET', '/api/remote/models', query: { if (sourceId != null) 'sourceId': sourceId, 'force': force.toString(), }) as Map); Future> jobs() async => _asList(await _send('GET', '/api/download/jobs')).map(JobInfo.fromJson).toList(); Future startDownload(String sourceId, String modelId) async => JobInfo.fromJson(await _send('POST', '/api/download', body: {'sourceId': sourceId, 'modelId': modelId}) as Map); Future cancelJob(String id) async => JobInfo.fromJson( await _send('POST', '/api/download/$id/cancel') as Map); Future retryJob(String id) async => JobInfo.fromJson( await _send('POST', '/api/download/$id/retry') as Map); Future removeJob(String id) async => JobInfo.fromJson( await _send('POST', '/api/download/$id/remove') as Map); Future clearFinished() async => ActionResult.fromJson( await _send('POST', '/api/download/clear-finished') as Map); Future checkUpdate({bool force = true}) async => UpdateCheckInfo.fromJson( await _send('POST', '/api/update/check', body: {'force': force}) as Map); Future about() async => AboutInfo.fromJson(await _send('GET', '/api/about') as Map); Future openFolder(String path) async => ActionResult.fromJson( await _send('POST', '/api/shell/open-folder', body: {'path': path}) as Map); Future openUrl(String url) async => ActionResult.fromJson( await _send('POST', '/api/shell/open-url', body: {'url': url}) as Map); /// 模型封面图地址(直接给 Image.network 用)。 String previewUrl(ModelInfo model) => '$baseUrl${model.previewUrl}'; }