import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:provider/provider.dart'; import 'auth_service.dart'; class KodBoxService { static const String baseUrl = 'https://cloud.jdysya.top'; Future getToken(String username, String password) async { final response = await http.get( Uri.parse( '$baseUrl/?user/index/loginSubmit&name=$username&password=$password'), ); if (response.statusCode == 200) { final data = jsonDecode(response.body); if (data['code'] == true) { return data['data']['accessToken']; } else { throw Exception('获取token失败: ${data['info'] ?? '未知错误'}'); } } else { throw Exception('请求失败: ${response.statusCode}'); } } Future validateToken(String token) async { try { final response = await http.get( Uri.parse('$baseUrl/?admin/log/get&accessToken=$token'), ); if (response.statusCode == 200) { final data = jsonDecode(response.body); return data['code'] != '10001'; } return false; } catch (e) { return false; } } Future getValidToken(AuthService authService) async { final username = authService.credentials['kodbox_username']; final password = authService.credentials['kodbox_password']; final currentToken = authService.credentials['kodbox_token']; if (username == null || password == null) { throw Exception('请先在设置中配置 KodBox 用户名和密码'); } // 如果当前有token,先验证是否有效 if (currentToken != null) { final isValid = await validateToken(currentToken); if (isValid) { return currentToken; } } // 获取新token final newToken = await getToken(username, password); await authService.saveConfigs('kodbox_token', newToken); return newToken; } }