import 'package:fis_jsonrpc/rpc.dart'; import 'package:vitalapp/architecture/utils/json_rpc_ex_interceptor.dart'; import 'package:vitalapp/global.dart'; import 'package:vitalapp/mock/mock.dart'; final _host = _ProxyHost(); abstract class RpcSettingCache { static String hostPath = "http://127.0.0.1:80"; static void setRpcHostPath(String path) { hostPath = path; final uri = Uri.parse(hostPath); rpc.setServerHost("${uri.host}:${uri.port}", uri.scheme == 'https'); rpc.clearCache(); } } /// JSON-RPC client proxy JsonRpcProxy get rpc => _host.getProxy(); class _ProxyHost { JsonRpcProxy? _proxy; final JsonRpcProxy _mockProxy = JsonRpcMockProxy() ..setServerHost(RpcSettingCache.hostPath); /// JSON-RPC client JsonRpcProxy getProxy() { if (kIsOnline == false) { return _mockProxy; } if (_proxy == null) { _init(); } return _proxy!; } /// 初始化代理 void _init() { _buildProxy(); // _listenServerHostChange(); } /// 构建代理实例 void _buildProxy() { final originServerHost = _proxy?.currentHostAddress ?? RpcSettingCache.hostPath; JsonRpcProxy jsonRpcProxy = JsonRpcProxy(); _proxy = jsonRpcProxy; if (originServerHost.isNotEmpty) { _setRpcHost(_proxy!, originServerHost); } // _proxy!.addInterceptor(_DefaultInterceptor()); _proxy!.addInterceptor(JsonRpcExInterceptor()); } // /// 监听服务地址变更 // void _listenServerHostChange() { // bus.on(bus.Keys.SERVER_ADDRESS_CHANGED, (arg) { // logger.i('EventBus - [${bus.Keys.SERVER_ADDRESS_CHANGED}]: $arg'); // _setRpcHost(rpc, arg); // rpc.clearCache(); // }); // } static void _setRpcHost(JsonRpcProxy rpc, url) { final uri = Uri.parse(url); rpc.setServerHost("${uri.host}:${uri.port}", uri.scheme == "https"); } } extension JsonRpcProxyExt on JsonRpcProxy { JsonRpcProxy get mock => _host._mockProxy; }