ConnectEntryPoint.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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.Net.Sockets;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. using CommonIO;
  16. using MediaBrowser.Common.IO;
  17. using MediaBrowser.Common.Threading;
  18. namespace MediaBrowser.Server.Implementations.Connect
  19. {
  20. public class ConnectEntryPoint : IServerEntryPoint
  21. {
  22. private PeriodicTimer _timer;
  23. private readonly IHttpClient _httpClient;
  24. private readonly IApplicationPaths _appPaths;
  25. private readonly ILogger _logger;
  26. private readonly IConnectManager _connectManager;
  27. private readonly INetworkManager _networkManager;
  28. private readonly IApplicationHost _appHost;
  29. private readonly IFileSystem _fileSystem;
  30. public ConnectEntryPoint(IHttpClient httpClient, IApplicationPaths appPaths, ILogger logger, INetworkManager networkManager, IConnectManager connectManager, IApplicationHost appHost, IFileSystem fileSystem)
  31. {
  32. _httpClient = httpClient;
  33. _appPaths = appPaths;
  34. _logger = logger;
  35. _networkManager = networkManager;
  36. _connectManager = connectManager;
  37. _appHost = appHost;
  38. _fileSystem = fileSystem;
  39. }
  40. public void Run()
  41. {
  42. Task.Run(() => LoadCachedAddress());
  43. _timer = new PeriodicTimer(TimerCallback, null, TimeSpan.FromSeconds(5), TimeSpan.FromHours(3));
  44. }
  45. private readonly string[] _ipLookups =
  46. {
  47. "http://bot.whatismyipaddress.com",
  48. "https://connect.emby.media/service/ip"
  49. };
  50. private async void TimerCallback(object state)
  51. {
  52. IPAddress validIpAddress = null;
  53. foreach (var ipLookupUrl in _ipLookups)
  54. {
  55. try
  56. {
  57. validIpAddress = await GetIpAddress(ipLookupUrl).ConfigureAwait(false);
  58. // Try to find the ipv4 address, if present
  59. if (validIpAddress.AddressFamily == AddressFamily.InterNetwork)
  60. {
  61. break;
  62. }
  63. }
  64. catch (HttpException)
  65. {
  66. }
  67. catch (Exception ex)
  68. {
  69. _logger.ErrorException("Error getting connection info", ex);
  70. }
  71. }
  72. // If this produced an ipv6 address, try again
  73. if (validIpAddress == null || validIpAddress.AddressFamily == AddressFamily.InterNetworkV6)
  74. {
  75. foreach (var ipLookupUrl in _ipLookups)
  76. {
  77. try
  78. {
  79. validIpAddress = await GetIpAddress(ipLookupUrl, true).ConfigureAwait(false);
  80. // Try to find the ipv4 address, if present
  81. if (validIpAddress.AddressFamily == AddressFamily.InterNetwork)
  82. {
  83. break;
  84. }
  85. }
  86. catch (HttpException)
  87. {
  88. }
  89. catch (Exception ex)
  90. {
  91. _logger.ErrorException("Error getting connection info", ex);
  92. }
  93. }
  94. }
  95. if (validIpAddress != null)
  96. {
  97. ((ConnectManager)_connectManager).OnWanAddressResolved(validIpAddress);
  98. CacheAddress(validIpAddress);
  99. }
  100. }
  101. private async Task<IPAddress> GetIpAddress(string lookupUrl, bool preferIpv4 = false)
  102. {
  103. // Sometimes whatismyipaddress might fail, but it won't do us any good having users raise alarms over it.
  104. var logErrors = false;
  105. #if DEBUG
  106. logErrors = true;
  107. #endif
  108. using (var stream = await _httpClient.Get(new HttpRequestOptions
  109. {
  110. Url = lookupUrl,
  111. UserAgent = "Emby/" + _appHost.ApplicationVersion,
  112. LogErrors = logErrors,
  113. // Seeing block length errors with our server
  114. EnableHttpCompression = false,
  115. PreferIpv4 = preferIpv4
  116. }).ConfigureAwait(false))
  117. {
  118. using (var reader = new StreamReader(stream))
  119. {
  120. var addressString = await reader.ReadToEndAsync().ConfigureAwait(false);
  121. return IPAddress.Parse(addressString);
  122. }
  123. }
  124. }
  125. private string CacheFilePath
  126. {
  127. get { return Path.Combine(_appPaths.DataPath, "wan.txt"); }
  128. }
  129. private void CacheAddress(IPAddress address)
  130. {
  131. var path = CacheFilePath;
  132. try
  133. {
  134. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  135. _fileSystem.WriteAllText(path, address.ToString(), Encoding.UTF8);
  136. }
  137. catch (Exception ex)
  138. {
  139. _logger.ErrorException("Error saving data", ex);
  140. }
  141. }
  142. private void LoadCachedAddress()
  143. {
  144. var path = CacheFilePath;
  145. try
  146. {
  147. var endpoint = _fileSystem.ReadAllText(path, Encoding.UTF8);
  148. IPAddress ipAddress;
  149. if (IPAddress.TryParse(endpoint, out ipAddress))
  150. {
  151. ((ConnectManager)_connectManager).OnWanAddressResolved(ipAddress);
  152. }
  153. }
  154. catch (IOException)
  155. {
  156. // File isn't there. no biggie
  157. }
  158. catch (Exception ex)
  159. {
  160. _logger.ErrorException("Error loading data", ex);
  161. }
  162. }
  163. public void Dispose()
  164. {
  165. if (_timer != null)
  166. {
  167. _timer.Dispose();
  168. _timer = null;
  169. }
  170. }
  171. }
  172. }