ConnectEntryPoint.cs 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Connect;
  5. using MediaBrowser.Controller.Plugins;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Net;
  8. using System;
  9. using System.IO;
  10. using System.Net;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using CommonIO;
  15. using MediaBrowser.Common.IO;
  16. using MediaBrowser.Common.Threading;
  17. namespace MediaBrowser.Server.Implementations.Connect
  18. {
  19. public class ConnectEntryPoint : IServerEntryPoint
  20. {
  21. private PeriodicTimer _timer;
  22. private readonly IHttpClient _httpClient;
  23. private readonly IApplicationPaths _appPaths;
  24. private readonly ILogger _logger;
  25. private readonly IConnectManager _connectManager;
  26. private readonly INetworkManager _networkManager;
  27. private readonly IApplicationHost _appHost;
  28. private readonly IFileSystem _fileSystem;
  29. public ConnectEntryPoint(IHttpClient httpClient, IApplicationPaths appPaths, ILogger logger, INetworkManager networkManager, IConnectManager connectManager, IApplicationHost appHost, IFileSystem fileSystem)
  30. {
  31. _httpClient = httpClient;
  32. _appPaths = appPaths;
  33. _logger = logger;
  34. _networkManager = networkManager;
  35. _connectManager = connectManager;
  36. _appHost = appHost;
  37. _fileSystem = fileSystem;
  38. }
  39. public void Run()
  40. {
  41. Task.Run(() => LoadCachedAddress());
  42. _timer = new PeriodicTimer(TimerCallback, null, TimeSpan.FromSeconds(5), TimeSpan.FromHours(3));
  43. }
  44. private readonly string[] _ipLookups = { "http://bot.whatismyipaddress.com", "https://connect.emby.media/service/ip" };
  45. private async void TimerCallback(object state)
  46. {
  47. var index = 0;
  48. foreach (var ipLookupUrl in _ipLookups)
  49. {
  50. try
  51. {
  52. // Sometimes whatismyipaddress might fail, but it won't do us any good having users raise alarms over it.
  53. var logErrors = index > 0;
  54. #if DEBUG
  55. logErrors = true;
  56. #endif
  57. using (var stream = await _httpClient.Get(new HttpRequestOptions
  58. {
  59. Url = ipLookupUrl,
  60. UserAgent = "Emby/" + _appHost.ApplicationVersion,
  61. LogErrors = logErrors,
  62. // Seeing block length errors with our server
  63. EnableHttpCompression = false,
  64. PreferIpv4 = true
  65. }).ConfigureAwait(false))
  66. {
  67. using (var reader = new StreamReader(stream))
  68. {
  69. var address = await reader.ReadToEndAsync().ConfigureAwait(false);
  70. if (IsValid(address, ipLookupUrl))
  71. {
  72. ((ConnectManager)_connectManager).OnWanAddressResolved(address);
  73. CacheAddress(address);
  74. return;
  75. }
  76. }
  77. }
  78. }
  79. catch (HttpException)
  80. {
  81. }
  82. catch (Exception ex)
  83. {
  84. _logger.ErrorException("Error getting connection info", ex);
  85. }
  86. index++;
  87. }
  88. }
  89. private string CacheFilePath
  90. {
  91. get { return Path.Combine(_appPaths.DataPath, "wan.txt"); }
  92. }
  93. private void CacheAddress(string address)
  94. {
  95. var path = CacheFilePath;
  96. try
  97. {
  98. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  99. _fileSystem.WriteAllText(path, address, Encoding.UTF8);
  100. }
  101. catch (Exception ex)
  102. {
  103. _logger.ErrorException("Error saving data", ex);
  104. }
  105. }
  106. private void LoadCachedAddress()
  107. {
  108. var path = CacheFilePath;
  109. try
  110. {
  111. var endpoint = _fileSystem.ReadAllText(path, Encoding.UTF8);
  112. if (IsValid(endpoint, "cache"))
  113. {
  114. ((ConnectManager)_connectManager).OnWanAddressResolved(endpoint);
  115. }
  116. }
  117. catch (IOException)
  118. {
  119. // File isn't there. no biggie
  120. }
  121. catch (Exception ex)
  122. {
  123. _logger.ErrorException("Error loading data", ex);
  124. }
  125. }
  126. private bool IsValid(string address, string source)
  127. {
  128. IPAddress ipAddress;
  129. var valid = IPAddress.TryParse(address, out ipAddress);
  130. if (!valid)
  131. {
  132. _logger.Error("{0} is not a valid ip address. Source: {1}", address, source);
  133. }
  134. return valid;
  135. }
  136. public void Dispose()
  137. {
  138. if (_timer != null)
  139. {
  140. _timer.Dispose();
  141. _timer = null;
  142. }
  143. }
  144. }
  145. }