PhrPollFile.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using Bridge.Html5;
  2. using Logging;
  3. using System;
  4. using FetchTypeDefine;
  5. using static Bridge.Html5.Window;
  6. namespace PseudoHotReload
  7. {
  8. public class PhrPollFile
  9. {
  10. private readonly string _stampFile;
  11. private readonly int _interval;
  12. private string _lastStamp;
  13. private int _timeOutId;
  14. public PhrPollFile(string stampFile = "phr-stamp.txt", int interval = 1000, bool start = true)
  15. {
  16. _stampFile = stampFile;
  17. _interval = interval;
  18. if (start) Start();
  19. }
  20. private void CheckStamp()
  21. {
  22. var url = _stampFile + "?" + DateTime.Now.Ticks;
  23. Logger.Debug($"PHR:Fetching:{url}");
  24. new Fetch(url, new FetchParams { Method = "GET" })
  25. .Then(r =>
  26. {
  27. if (false == r.Ok) throw new Exception("Response was not ok.");
  28. return r.Text();
  29. })
  30. .Then(r =>
  31. {
  32. Logger.Debug($"PHR:Fetched:{r ?? "(null)"}");
  33. if (_lastStamp == null)
  34. {
  35. _lastStamp = r;
  36. _timeOutId = SetTimeout(CheckStamp, _interval);
  37. Logger.Debug($"PHR:Stamp stored,started another timer:{_timeOutId}");
  38. }
  39. else if (_lastStamp != r)
  40. {
  41. Logger.Info("PHR:Stamp change detected, reloading...");
  42. Window.Location.Reload(true);
  43. }
  44. else
  45. {
  46. _timeOutId = SetTimeout(CheckStamp, _interval);
  47. Logger.Debug($"PHR:Stamp nochg,started another timer:{_timeOutId}");
  48. }
  49. }).Catch(e =>
  50. {
  51. _timeOutId = SetTimeout(CheckStamp, _interval);
  52. Logger.Debug($"PHR:Server seem down,waiting until alive again,started another timer:{_timeOutId}");
  53. });
  54. }
  55. public void Start()
  56. {
  57. Stop();
  58. _lastStamp = null;
  59. _timeOutId = SetTimeout(CheckStamp, _interval);
  60. Logger.Debug($"PHR:Started on timer:{_timeOutId}");
  61. }
  62. public void Stop()
  63. {
  64. ClearTimeout(_timeOutId);
  65. }
  66. }
  67. }