ConnectEntryPoint.cs 6.4 KB

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