ConnectEntryPoint.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. namespace MediaBrowser.Server.Implementations.Connect
  17. {
  18. public class ConnectEntryPoint : IServerEntryPoint
  19. {
  20. private Timer _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. Task.Run(() => LoadCachedAddress());
  41. _timer = new Timer(TimerCallback, null, TimeSpan.FromSeconds(5), TimeSpan.FromHours(3));
  42. }
  43. private readonly string[] _ipLookups = { "http://bot.whatismyipaddress.com", "https://connect.emby.media/service/ip" };
  44. private async void TimerCallback(object state)
  45. {
  46. var index = 0;
  47. foreach (var ipLookupUrl in _ipLookups)
  48. {
  49. try
  50. {
  51. // Sometimes whatismyipaddress might fail, but it won't do us any good having users raise alarms over it.
  52. var logErrors = index > 0;
  53. #if DEBUG
  54. logErrors = true;
  55. #endif
  56. using (var stream = await _httpClient.Get(new HttpRequestOptions
  57. {
  58. Url = ipLookupUrl,
  59. UserAgent = "Emby/" + _appHost.ApplicationVersion,
  60. LogErrors = logErrors
  61. }).ConfigureAwait(false))
  62. {
  63. using (var reader = new StreamReader(stream))
  64. {
  65. var address = await reader.ReadToEndAsync().ConfigureAwait(false);
  66. if (IsValid(address, ipLookupUrl))
  67. {
  68. ((ConnectManager)_connectManager).OnWanAddressResolved(address);
  69. CacheAddress(address);
  70. return;
  71. }
  72. }
  73. }
  74. }
  75. catch (HttpException)
  76. {
  77. }
  78. catch (Exception ex)
  79. {
  80. _logger.ErrorException("Error getting connection info", ex);
  81. }
  82. index++;
  83. }
  84. }
  85. private string CacheFilePath
  86. {
  87. get { return Path.Combine(_appPaths.DataPath, "wan.txt"); }
  88. }
  89. private void CacheAddress(string address)
  90. {
  91. var path = CacheFilePath;
  92. try
  93. {
  94. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  95. _fileSystem.WriteAllText(path, address, Encoding.UTF8);
  96. }
  97. catch (Exception ex)
  98. {
  99. _logger.ErrorException("Error saving data", ex);
  100. }
  101. }
  102. private void LoadCachedAddress()
  103. {
  104. var path = CacheFilePath;
  105. try
  106. {
  107. var endpoint = _fileSystem.ReadAllText(path, Encoding.UTF8);
  108. if (IsValid(endpoint, "cache"))
  109. {
  110. ((ConnectManager)_connectManager).OnWanAddressResolved(endpoint);
  111. }
  112. }
  113. catch (IOException)
  114. {
  115. // File isn't there. no biggie
  116. }
  117. catch (Exception ex)
  118. {
  119. _logger.ErrorException("Error loading data", ex);
  120. }
  121. }
  122. private bool IsValid(string address, string source)
  123. {
  124. IPAddress ipAddress;
  125. var valid = IPAddress.TryParse(address, out ipAddress);
  126. if (!valid)
  127. {
  128. _logger.Error("{0} is not a valid ip address. Source: {1}", address, source);
  129. }
  130. return valid;
  131. }
  132. public void Dispose()
  133. {
  134. if (_timer != null)
  135. {
  136. _timer.Dispose();
  137. _timer = null;
  138. }
  139. }
  140. }
  141. }