RestClientCache.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.Net;
  2. using RestSharp;
  3. namespace InABox.Clients
  4. {
  5. internal static class RestClientCache
  6. {
  7. private static Dictionary<String, Tuple<String, bool, DatabaseInfo>> _cache = new Dictionary<string, Tuple<string, bool, DatabaseInfo>>();
  8. public static String URL(String host)
  9. {
  10. if (_cache.TryGetValue(host, out var value))
  11. return value.Item1;
  12. return "";
  13. }
  14. public static bool IsSecure(String host)
  15. {
  16. if (_cache.TryGetValue(host, out var value))
  17. return value.Item2;
  18. return false;
  19. }
  20. public static DatabaseInfo Info(String host)
  21. {
  22. if (_cache.TryGetValue(host, out var value))
  23. return value.Item3;
  24. return new DatabaseInfo();
  25. }
  26. private static bool Check(String host, bool https)
  27. {
  28. var uri = new Uri(host);
  29. string schema = https ? "https" : "http";
  30. var url = $"{schema}://{uri.Host}:{uri.Port}";
  31. var req = new RestRequest("/info", Method.GET) { Timeout = 20000 };
  32. var res = new RestClient(new Uri(url)).Execute(req);
  33. if ((res.StatusCode != HttpStatusCode.OK) || (res.ErrorException != null))
  34. return false;
  35. try
  36. {
  37. var response = Core.Serialization.Deserialize<InfoResponse>(res.Content);
  38. if (response?.Info == null)
  39. return false;
  40. _cache[host] = new Tuple<string, bool, DatabaseInfo>(url, https, response.Info);
  41. return true;
  42. }
  43. catch (Exception e)
  44. {
  45. return false;
  46. }
  47. }
  48. public static String Check(string server)
  49. {
  50. var host = server.Split(new[] { "://" }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
  51. if (String.IsNullOrWhiteSpace(host))
  52. return "";
  53. if (_cache.TryGetValue(host, out var cached))
  54. return cached.Item1;
  55. if (!Check(host, true))
  56. Check(host, false);
  57. return _cache.TryGetValue(host, out var check) ? check.Item1 : "";
  58. }
  59. }
  60. }