1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- using System.Net;
- using RestSharp;
- namespace InABox.Clients
- {
- internal static class RestClientCache
- {
- private static Dictionary<String, Tuple<String, bool, DatabaseInfo>> _cache = new Dictionary<string, Tuple<string, bool, DatabaseInfo>>();
-
- public static String URL(String host)
- {
- if (_cache.TryGetValue(host, out var value))
- return value.Item1;
- return "";
- }
- public static bool IsSecure(String host)
- {
- if (_cache.TryGetValue(host, out var value))
- return value.Item2;
- return false;
- }
-
- public static DatabaseInfo Info(String host)
- {
- if (_cache.TryGetValue(host, out var value))
- return value.Item3;
- return new DatabaseInfo();
- }
-
- private static bool Check(String host, bool https)
- {
- var uri = new Uri(host);
- string schema = https ? "https" : "http";
- var url = $"{schema}://{uri.Host}:{uri.Port}";
- var req = new RestRequest("/info", Method.GET) { Timeout = 20000 };
- var res = new RestClient(new Uri(url)).Execute(req);
- if ((res.StatusCode != HttpStatusCode.OK) || (res.ErrorException != null))
- return false;
- try
- {
- var response = Core.Serialization.Deserialize<InfoResponse>(res.Content);
- if (response?.Info == null)
- return false;
- _cache[host] = new Tuple<string, bool, DatabaseInfo>(url, https, response.Info);
- return true;
- }
- catch (Exception e)
- {
- return false;
- }
- }
-
- public static String Check(string server)
- {
- var host = server.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
-
- if (String.IsNullOrWhiteSpace(host))
- return "";
-
- if (_cache.TryGetValue(host, out var cached))
- return cached.Item1;
-
- if (!Check(host, true))
- Check(host, false);
-
- return _cache.TryGetValue(host, out var check) ? check.Item1 : "";
- }
- }
- }
|