stack_wallet/lib/networking/http.dart

109 lines
2.5 KiB
Dart
Raw Normal View History

import 'dart:convert';
2023-08-07 15:18:08 +00:00
import 'dart:io';
import 'package:flutter/foundation.dart';
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
2023-09-08 15:18:55 +00:00
// TODO expand this class
class Response {
final int code;
final String body;
Response(this.body, this.code);
}
class HTTP {
/// Visible for testing so we can override with a mock TorService
@visibleForTesting
TorService torService = TorService.sharedInstance;
2023-09-08 15:18:55 +00:00
Future<Response> 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.proxyInfo.host,
torService.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
2023-09-08 15:18:55 +00:00
final response = await request.close();
return Response(
await response.transform(utf8.decoder).join(),
response.statusCode,
);
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-09-08 15:18:55 +00:00
Future<Response> 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.proxyInfo.host,
torService.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);
2023-09-08 15:18:55 +00:00
final response = await request.close();
return Response(
await response.transform(utf8.decoder).join(),
response.statusCode,
);
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);
}
}
}