ConnectManager.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Connect;
  6. using MediaBrowser.Controller.Security;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.Net;
  9. using MediaBrowser.Model.Serialization;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Net;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Server.Implementations.Connect
  19. {
  20. public class ConnectManager : IConnectManager
  21. {
  22. private readonly ILogger _logger;
  23. private readonly IApplicationPaths _appPaths;
  24. private readonly IJsonSerializer _json;
  25. private readonly IEncryptionManager _encryption;
  26. private readonly IHttpClient _httpClient;
  27. private readonly IServerApplicationHost _appHost;
  28. private readonly IServerConfigurationManager _config;
  29. public string ConnectServerId { get; set; }
  30. public string ConnectAccessKey { get; set; }
  31. public string DiscoveredWanIpAddress { get; private set; }
  32. public string WanIpAddress
  33. {
  34. get
  35. {
  36. var address = _config.Configuration.WanDdns;
  37. if (string.IsNullOrWhiteSpace(address))
  38. {
  39. address = DiscoveredWanIpAddress;
  40. }
  41. return address;
  42. }
  43. }
  44. public string WanApiAddress
  45. {
  46. get
  47. {
  48. var ip = WanIpAddress;
  49. if (!string.IsNullOrEmpty(ip))
  50. {
  51. if (!ip.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
  52. !ip.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  53. {
  54. ip = "http://" + ip;
  55. }
  56. return ip + ":" + _config.Configuration.HttpServerPortNumber.ToString(CultureInfo.InvariantCulture);
  57. }
  58. return null;
  59. }
  60. }
  61. public ConnectManager(ILogger logger,
  62. IApplicationPaths appPaths,
  63. IJsonSerializer json,
  64. IEncryptionManager encryption,
  65. IHttpClient httpClient,
  66. IServerApplicationHost appHost,
  67. IServerConfigurationManager config)
  68. {
  69. _logger = logger;
  70. _appPaths = appPaths;
  71. _json = json;
  72. _encryption = encryption;
  73. _httpClient = httpClient;
  74. _appHost = appHost;
  75. _config = config;
  76. LoadCachedData();
  77. }
  78. internal void OnWanAddressResolved(string address)
  79. {
  80. DiscoveredWanIpAddress = address;
  81. UpdateConnectInfo();
  82. }
  83. private async void UpdateConnectInfo()
  84. {
  85. var wanApiAddress = WanApiAddress;
  86. if (string.IsNullOrWhiteSpace(wanApiAddress))
  87. {
  88. _logger.Warn("Cannot update Media Browser Connect information without a WanApiAddress");
  89. return;
  90. }
  91. try
  92. {
  93. var hasExistingRecord = !string.IsNullOrWhiteSpace(ConnectServerId) &&
  94. !string.IsNullOrWhiteSpace(ConnectAccessKey);
  95. var createNewRegistration = !hasExistingRecord;
  96. if (hasExistingRecord)
  97. {
  98. try
  99. {
  100. await UpdateServerRegistration(wanApiAddress).ConfigureAwait(false);
  101. }
  102. catch (HttpException ex)
  103. {
  104. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound || ex.StatusCode.Value != HttpStatusCode.Unauthorized)
  105. {
  106. throw;
  107. }
  108. createNewRegistration = true;
  109. }
  110. }
  111. if (createNewRegistration)
  112. {
  113. await CreateServerRegistration(wanApiAddress).ConfigureAwait(false);
  114. }
  115. }
  116. catch (Exception ex)
  117. {
  118. _logger.ErrorException("Error registering with Connect", ex);
  119. }
  120. }
  121. private async Task CreateServerRegistration(string wanApiAddress)
  122. {
  123. var url = "Servers";
  124. url = GetConnectUrl(url);
  125. var postData = new Dictionary<string, string>
  126. {
  127. {"name", _appHost.FriendlyName},
  128. {"url", wanApiAddress},
  129. {"systemid", _appHost.SystemId}
  130. };
  131. using (var stream = await _httpClient.Post(url, postData, CancellationToken.None).ConfigureAwait(false))
  132. {
  133. var data = _json.DeserializeFromStream<ServerRegistrationResponse>(stream);
  134. ConnectServerId = data.Id;
  135. ConnectAccessKey = data.AccessKey;
  136. CacheData();
  137. }
  138. }
  139. private async Task UpdateServerRegistration(string wanApiAddress)
  140. {
  141. var url = "Servers";
  142. url = GetConnectUrl(url);
  143. url += "?id=" + ConnectServerId;
  144. var options = new HttpRequestOptions
  145. {
  146. Url = url,
  147. CancellationToken = CancellationToken.None
  148. };
  149. options.SetPostData(new Dictionary<string, string>
  150. {
  151. {"name", _appHost.FriendlyName},
  152. {"url", wanApiAddress},
  153. {"systemid", _appHost.SystemId}
  154. });
  155. options.RequestHeaders.Add("X-Connect-Token", ConnectAccessKey);
  156. // No need to examine the response
  157. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  158. {
  159. }
  160. }
  161. private string CacheFilePath
  162. {
  163. get { return Path.Combine(_appPaths.DataPath, "connect.txt"); }
  164. }
  165. private void CacheData()
  166. {
  167. var path = CacheFilePath;
  168. try
  169. {
  170. Directory.CreateDirectory(Path.GetDirectoryName(path));
  171. var json = _json.SerializeToString(new ConnectData
  172. {
  173. AccessKey = ConnectAccessKey,
  174. ServerId = ConnectServerId
  175. });
  176. var encrypted = _encryption.EncryptString(json);
  177. File.WriteAllText(path, encrypted, Encoding.UTF8);
  178. }
  179. catch (Exception ex)
  180. {
  181. _logger.ErrorException("Error saving data", ex);
  182. }
  183. }
  184. private void LoadCachedData()
  185. {
  186. var path = CacheFilePath;
  187. try
  188. {
  189. var encrypted = File.ReadAllText(path, Encoding.UTF8);
  190. var json = _encryption.DecryptString(encrypted);
  191. var data = _json.DeserializeFromString<ConnectData>(json);
  192. ConnectAccessKey = data.AccessKey;
  193. ConnectServerId = data.ServerId;
  194. }
  195. catch (IOException)
  196. {
  197. // File isn't there. no biggie
  198. }
  199. catch (Exception ex)
  200. {
  201. _logger.ErrorException("Error loading data", ex);
  202. }
  203. }
  204. private string GetConnectUrl(string handler)
  205. {
  206. return "http://mb3admin.com/test/connect/" + handler;
  207. }
  208. }
  209. }