RestClientCache.cs 2.5 KB

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