ente/lib/utils/endpoint_finder.dart

67 lines
1.7 KiB
Dart
Raw Normal View History

2020-04-30 15:09:41 +00:00
import 'dart:async';
import 'package:connectivity/connectivity.dart';
import 'package:dio/dio.dart';
2020-05-02 16:28:54 +00:00
import 'package:logging/logging.dart';
2020-04-30 15:09:41 +00:00
class EndpointFinder {
final _dio = Dio();
2020-05-02 16:28:54 +00:00
final logger = Logger("EndpointFinder");
2020-04-30 15:09:41 +00:00
EndpointFinder._privateConstructor() {
2020-07-16 00:27:55 +00:00
_dio.options = BaseOptions(connectTimeout: 250);
2020-04-30 15:09:41 +00:00
}
static final EndpointFinder instance = EndpointFinder._privateConstructor();
2020-05-17 17:48:49 +00:00
bool _shouldContinueSearch;
2020-04-30 15:09:41 +00:00
Future<String> findEndpoint() {
2020-05-17 17:48:49 +00:00
_shouldContinueSearch = true;
2020-04-30 15:09:41 +00:00
return (Connectivity().getWifiIP()).then((ip) async {
2020-05-02 16:28:54 +00:00
logger.info(ip);
2020-04-30 15:09:41 +00:00
final ipSplit = ip.split(".");
var prefix = "";
for (int index = 0; index < ipSplit.length; index++) {
if (index != ipSplit.length - 1) {
prefix += ipSplit[index] + ".";
}
}
2020-06-17 19:47:49 +00:00
logger.info(prefix + "*");
2020-04-30 15:09:41 +00:00
2020-05-17 17:48:49 +00:00
for (int i = 1; i <= 255 && _shouldContinueSearch; i++) {
2020-04-30 15:09:41 +00:00
var endpoint = prefix + i.toString();
try {
final success = await ping(endpoint);
if (success) {
return endpoint;
}
} catch (e) {
// Do nothing
}
}
2020-05-17 17:48:49 +00:00
if (_shouldContinueSearch) {
throw TimeoutException("Could not find a valid endpoint");
} else {
// Exit gracefully
return Future.value(null);
}
2020-04-30 15:09:41 +00:00
});
}
2020-05-17 17:48:49 +00:00
void cancelSearch() {
_shouldContinueSearch = false;
}
2020-04-30 15:09:41 +00:00
Future<bool> ping(String endpoint) async {
return _dio.get("http://" + endpoint + ":8080/ping").then((response) {
if (response.data["message"] == "pong") {
2020-05-02 16:28:54 +00:00
logger.info("Found " + endpoint);
2020-04-30 15:09:41 +00:00
return true;
} else {
return false;
}
});
}
}