D3NsClient.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using D3NsCore.Models;
  2. using D3NsCore.Tools;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Threading;
  6. namespace D3NsCore
  7. {
  8. public class D3NsClient : BasicServ
  9. {
  10. private ConfigAdapter _conf;
  11. private HttpAccess _http;
  12. private bool _isRunning;
  13. private Thread _thread;
  14. public string Domain => _conf.DnsRecordName + "." + _conf.Domain;
  15. public D3NsClient(string dbFile)
  16. {
  17. _conf = new ConfigAdapter(new DataAccess(dbFile).GetConfigs());
  18. _http = new HttpAccess();
  19. }
  20. public override void Start()
  21. {
  22. _isRunning = true;
  23. _thread = new Thread(Run) { IsBackground = true };
  24. _thread.Start();
  25. }
  26. public override void Stop()
  27. {
  28. _isRunning = false;
  29. _thread.Join();
  30. }
  31. private void Run()
  32. {
  33. var key = _conf.Key;
  34. var sec = _conf.Secret;
  35. if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(sec))
  36. {
  37. LogFatal("Please fill configs.");
  38. return;
  39. }
  40. string myIp, dnsIp;
  41. while (_isRunning) //TODO: Error handle
  42. {
  43. //Get my ip
  44. //Get dns ip
  45. //cmp
  46. // + put my ip to dns
  47. // - do nothing
  48. //sleep
  49. try
  50. {
  51. LogTrace("Getting my ip...");
  52. myIp = GetMyIp();
  53. LogInfo($"My ip is: {myIp}");
  54. LogTrace("Getting dns ip...");
  55. dnsIp = GetDnsIp();
  56. LogInfo($"Dns ip is: {dnsIp}");
  57. if (myIp != dnsIp)
  58. {
  59. LogInfo("Updating dns record...");
  60. PutDnsIp(myIp);
  61. }
  62. else
  63. {
  64. LogTrace("Nothing to do.");
  65. }
  66. }
  67. catch (WebException e)
  68. {
  69. LogError(e.Message);
  70. }
  71. LogTrace("Sleeping...");
  72. for (var i = 0; i < 600; i++)
  73. {
  74. if (_isRunning == false) break;
  75. Thread.Sleep(1000);
  76. }
  77. LogTrace("Wake up.");
  78. }
  79. LogInfo("Exit.");
  80. }
  81. // ---- utilitys ----
  82. private string GetMyIp() => _http.GetJsonAnon(new { REMOTE_ADDR = "" }, _conf.GetMyIp).REMOTE_ADDR;
  83. private string GetDnsIp() => _http.GetJsonAnon(new[] { new { data = "" } }, $"https://api.godaddy.com/v1/domains/{_conf.Domain}/records/A/{_conf.DnsRecordName}", new HttpHeader("Accept", "application/json"), new HttpHeader("Authorization", $"sso-key {_conf.Key}:{_conf.Secret}")).Select(p => p.data).Single();
  84. private void PutDnsIp(string ip) => _http.PutString($"https://api.godaddy.com/v1/domains/{_conf.Domain}/records/A/{_conf.DnsRecordName}", $"[{{\"data\":\"{ip}\",\"ttl\":600}}]", "application/json", new HttpHeader("Authorization", $"sso-key {_conf.Key}:{_conf.Secret}"));
  85. }
  86. }