ConnectManager.cs 6.5 KB

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