ConnectEntryPoint.cs 6.5 KB

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