ConnectEntryPoint.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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 CommonIO;
  15. using MediaBrowser.Common.Threading;
  16. namespace MediaBrowser.Server.Implementations.Connect
  17. {
  18. public class ConnectEntryPoint : IServerEntryPoint
  19. {
  20. private PeriodicTimer _timer;
  21. private readonly IHttpClient _httpClient;
  22. private readonly IApplicationPaths _appPaths;
  23. private readonly ILogger _logger;
  24. private readonly IConnectManager _connectManager;
  25. private readonly INetworkManager _networkManager;
  26. private readonly IApplicationHost _appHost;
  27. private readonly IFileSystem _fileSystem;
  28. public ConnectEntryPoint(IHttpClient httpClient, IApplicationPaths appPaths, ILogger logger, INetworkManager networkManager, IConnectManager connectManager, IApplicationHost appHost, IFileSystem fileSystem)
  29. {
  30. _httpClient = httpClient;
  31. _appPaths = appPaths;
  32. _logger = logger;
  33. _networkManager = networkManager;
  34. _connectManager = connectManager;
  35. _appHost = appHost;
  36. _fileSystem = fileSystem;
  37. }
  38. public void Run()
  39. {
  40. LoadCachedAddress();
  41. _timer = new PeriodicTimer(TimerCallback, null, TimeSpan.FromSeconds(5), TimeSpan.FromHours(1));
  42. ((ConnectManager)_connectManager).Start();
  43. }
  44. private readonly string[] _ipLookups =
  45. {
  46. "http://bot.whatismyipaddress.com",
  47. "https://connect.emby.media/service/ip"
  48. };
  49. private async void TimerCallback(object state)
  50. {
  51. IPAddress validIpAddress = null;
  52. foreach (var ipLookupUrl in _ipLookups)
  53. {
  54. try
  55. {
  56. validIpAddress = await GetIpAddress(ipLookupUrl).ConfigureAwait(false);
  57. // Try to find the ipv4 address, if present
  58. if (validIpAddress.AddressFamily == AddressFamily.InterNetwork)
  59. {
  60. break;
  61. }
  62. }
  63. catch (HttpException)
  64. {
  65. }
  66. catch (Exception ex)
  67. {
  68. _logger.ErrorException("Error getting connection info", ex);
  69. }
  70. }
  71. // If this produced an ipv6 address, try again
  72. if (validIpAddress != null && validIpAddress.AddressFamily == AddressFamily.InterNetworkV6)
  73. {
  74. foreach (var ipLookupUrl in _ipLookups)
  75. {
  76. try
  77. {
  78. var newAddress = await GetIpAddress(ipLookupUrl, true).ConfigureAwait(false);
  79. // Try to find the ipv4 address, if present
  80. if (newAddress.AddressFamily == AddressFamily.InterNetwork)
  81. {
  82. validIpAddress = newAddress;
  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. _logger.Info("Loading data from {0}", path);
  146. try
  147. {
  148. var endpoint = _fileSystem.ReadAllText(path, Encoding.UTF8);
  149. IPAddress ipAddress;
  150. if (IPAddress.TryParse(endpoint, out ipAddress))
  151. {
  152. ((ConnectManager)_connectManager).OnWanAddressResolved(ipAddress);
  153. }
  154. }
  155. catch (IOException)
  156. {
  157. // File isn't there. no biggie
  158. }
  159. catch (Exception ex)
  160. {
  161. _logger.ErrorException("Error loading data", ex);
  162. }
  163. }
  164. public void Dispose()
  165. {
  166. if (_timer != null)
  167. {
  168. _timer.Dispose();
  169. _timer = null;
  170. }
  171. }
  172. }
  173. }