stack_wallet/lib/networking/http.dart

88 lines
2.1 KiB
Dart
Raw Normal View History

import 'dart:convert';
2023-08-07 15:18:08 +00:00
import 'dart:io';
2023-08-07 16:46:34 +00:00
import 'package:socks5_proxy/socks_client.dart';
import 'package:stackwallet/services/tor_service.dart';
2023-08-07 15:18:08 +00:00
import 'package:stackwallet/utilities/logger.dart';
// WIP wrapper layer
abstract class HTTP {
2023-08-07 15:18:08 +00:00
static Future<HttpClientResponse> get({
required Uri url,
Map<String, String>? headers,
required bool routeOverTor,
}) async {
2023-08-07 15:18:08 +00:00
final httpClient = HttpClient();
try {
if (routeOverTor) {
2023-08-07 16:46:34 +00:00
SocksTCPClient.assignToHttpClient(httpClient, [
ProxySettings(
TorService.sharedInstance.proxyInfo.host,
TorService.sharedInstance.proxyInfo.port,
2023-08-07 16:46:34 +00:00
),
]);
}
final HttpClientRequest request = await httpClient.getUrl(
url,
);
2023-08-07 15:18:08 +00:00
2023-08-07 16:46:34 +00:00
request.headers.clear();
if (headers != null) {
headers.forEach((key, value) => request.headers.add);
2023-08-07 15:18:08 +00:00
}
2023-08-07 16:46:34 +00:00
return request.close();
2023-08-07 15:18:08 +00:00
} catch (e, s) {
Logging.instance.log(
"HTTP.get() rethrew: $e\n$s",
level: LogLevel.Info,
);
rethrow;
} finally {
httpClient.close(force: true);
}
}
2023-08-07 15:18:08 +00:00
static Future<HttpClientResponse> post({
required Uri url,
Map<String, String>? headers,
Object? body,
Encoding? encoding,
required bool routeOverTor,
}) async {
2023-08-07 15:18:08 +00:00
final httpClient = HttpClient();
try {
if (routeOverTor) {
2023-08-07 17:19:09 +00:00
SocksTCPClient.assignToHttpClient(httpClient, [
ProxySettings(
TorService.sharedInstance.proxyInfo.host,
TorService.sharedInstance.proxyInfo.port,
2023-08-07 17:19:09 +00:00
),
]);
2023-08-07 16:46:34 +00:00
}
final HttpClientRequest request = await httpClient.postUrl(
url,
);
2023-08-07 15:18:08 +00:00
2023-08-07 16:46:34 +00:00
request.headers.clear();
2023-08-07 15:18:08 +00:00
2023-08-07 16:46:34 +00:00
if (headers != null) {
headers.forEach((key, value) => request.headers.add);
2023-08-07 15:18:08 +00:00
}
2023-08-07 16:46:34 +00:00
request.write(body);
return request.close();
2023-08-07 15:18:08 +00:00
} catch (e, s) {
Logging.instance.log(
"HTTP.post() rethrew: $e\n$s",
level: LogLevel.Info,
);
2023-08-07 15:18:08 +00:00
rethrow;
} finally {
httpClient.close(force: true);
}
}
}