ConnectManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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.Entities;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.Security;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Net;
  11. using MediaBrowser.Model.Serialization;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Globalization;
  15. using System.IO;
  16. using System.Net;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.Server.Implementations.Connect
  21. {
  22. public class ConnectManager : IConnectManager
  23. {
  24. private readonly ILogger _logger;
  25. private readonly IApplicationPaths _appPaths;
  26. private readonly IJsonSerializer _json;
  27. private readonly IEncryptionManager _encryption;
  28. private readonly IHttpClient _httpClient;
  29. private readonly IServerApplicationHost _appHost;
  30. private readonly IServerConfigurationManager _config;
  31. private readonly IUserManager _userManager;
  32. private ConnectData _data = new ConnectData();
  33. public string ConnectServerId
  34. {
  35. get { return _data.ServerId; }
  36. }
  37. public string ConnectAccessKey
  38. {
  39. get { return _data.AccessKey; }
  40. }
  41. public string DiscoveredWanIpAddress { get; private set; }
  42. public string WanIpAddress
  43. {
  44. get
  45. {
  46. var address = _config.Configuration.WanDdns;
  47. if (string.IsNullOrWhiteSpace(address))
  48. {
  49. address = DiscoveredWanIpAddress;
  50. }
  51. return address;
  52. }
  53. }
  54. public string WanApiAddress
  55. {
  56. get
  57. {
  58. var ip = WanIpAddress;
  59. if (!string.IsNullOrEmpty(ip))
  60. {
  61. if (!ip.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
  62. !ip.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  63. {
  64. ip = "http://" + ip;
  65. }
  66. return ip + ":" + _config.Configuration.HttpServerPortNumber.ToString(CultureInfo.InvariantCulture);
  67. }
  68. return null;
  69. }
  70. }
  71. public ConnectManager(ILogger logger,
  72. IApplicationPaths appPaths,
  73. IJsonSerializer json,
  74. IEncryptionManager encryption,
  75. IHttpClient httpClient,
  76. IServerApplicationHost appHost,
  77. IServerConfigurationManager config, IUserManager userManager)
  78. {
  79. _logger = logger;
  80. _appPaths = appPaths;
  81. _json = json;
  82. _encryption = encryption;
  83. _httpClient = httpClient;
  84. _appHost = appHost;
  85. _config = config;
  86. _userManager = userManager;
  87. LoadCachedData();
  88. }
  89. internal void OnWanAddressResolved(string address)
  90. {
  91. DiscoveredWanIpAddress = address;
  92. UpdateConnectInfo();
  93. }
  94. private async void UpdateConnectInfo()
  95. {
  96. var wanApiAddress = WanApiAddress;
  97. if (string.IsNullOrWhiteSpace(wanApiAddress))
  98. {
  99. _logger.Warn("Cannot update Media Browser Connect information without a WanApiAddress");
  100. return;
  101. }
  102. try
  103. {
  104. var hasExistingRecord = !string.IsNullOrWhiteSpace(ConnectServerId) &&
  105. !string.IsNullOrWhiteSpace(ConnectAccessKey);
  106. var createNewRegistration = !hasExistingRecord;
  107. if (hasExistingRecord)
  108. {
  109. try
  110. {
  111. await UpdateServerRegistration(wanApiAddress).ConfigureAwait(false);
  112. }
  113. catch (HttpException ex)
  114. {
  115. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound || ex.StatusCode.Value != HttpStatusCode.Unauthorized)
  116. {
  117. throw;
  118. }
  119. createNewRegistration = true;
  120. }
  121. }
  122. if (createNewRegistration)
  123. {
  124. await CreateServerRegistration(wanApiAddress).ConfigureAwait(false);
  125. }
  126. }
  127. catch (Exception ex)
  128. {
  129. _logger.ErrorException("Error registering with Connect", ex);
  130. }
  131. }
  132. private async Task CreateServerRegistration(string wanApiAddress)
  133. {
  134. var url = "Servers";
  135. url = GetConnectUrl(url);
  136. var postData = new Dictionary<string, string>
  137. {
  138. {"name", _appHost.FriendlyName},
  139. {"url", wanApiAddress},
  140. {"systemid", _appHost.SystemId}
  141. };
  142. using (var stream = await _httpClient.Post(url, postData, CancellationToken.None).ConfigureAwait(false))
  143. {
  144. var data = _json.DeserializeFromStream<ServerRegistrationResponse>(stream);
  145. _data.ServerId = data.Id;
  146. _data.AccessKey = data.AccessKey;
  147. CacheData();
  148. }
  149. }
  150. private async Task UpdateServerRegistration(string wanApiAddress)
  151. {
  152. var url = "Servers";
  153. url = GetConnectUrl(url);
  154. url += "?id=" + ConnectServerId;
  155. var options = new HttpRequestOptions
  156. {
  157. Url = url,
  158. CancellationToken = CancellationToken.None
  159. };
  160. options.SetPostData(new Dictionary<string, string>
  161. {
  162. {"name", _appHost.FriendlyName},
  163. {"url", wanApiAddress},
  164. {"systemid", _appHost.SystemId}
  165. });
  166. SetServerAccessToken(options);
  167. // No need to examine the response
  168. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  169. {
  170. }
  171. }
  172. private string CacheFilePath
  173. {
  174. get { return Path.Combine(_appPaths.DataPath, "connect.txt"); }
  175. }
  176. private void CacheData()
  177. {
  178. var path = CacheFilePath;
  179. try
  180. {
  181. Directory.CreateDirectory(Path.GetDirectoryName(path));
  182. var json = _json.SerializeToString(_data);
  183. var encrypted = _encryption.EncryptString(json);
  184. File.WriteAllText(path, encrypted, Encoding.UTF8);
  185. }
  186. catch (Exception ex)
  187. {
  188. _logger.ErrorException("Error saving data", ex);
  189. }
  190. }
  191. private void LoadCachedData()
  192. {
  193. var path = CacheFilePath;
  194. try
  195. {
  196. var encrypted = File.ReadAllText(path, Encoding.UTF8);
  197. var json = _encryption.DecryptString(encrypted);
  198. _data = _json.DeserializeFromString<ConnectData>(json);
  199. }
  200. catch (IOException)
  201. {
  202. // File isn't there. no biggie
  203. }
  204. catch (Exception ex)
  205. {
  206. _logger.ErrorException("Error loading data", ex);
  207. }
  208. }
  209. private User GetUser(string id)
  210. {
  211. var user = _userManager.GetUserById(id);
  212. if (user == null)
  213. {
  214. throw new ArgumentException("User not found.");
  215. }
  216. return user;
  217. }
  218. private string GetConnectUrl(string handler)
  219. {
  220. return "https://connect.mediabrowser.tv/service/" + handler;
  221. }
  222. public async Task LinkUser(string userId, string connectUsername)
  223. {
  224. if (string.IsNullOrWhiteSpace(connectUsername))
  225. {
  226. throw new ArgumentNullException("connectUsername");
  227. }
  228. var connectUser = await GetConnectUser(new ConnectUserQuery
  229. {
  230. Name = connectUsername
  231. }, CancellationToken.None).ConfigureAwait(false);
  232. if (!connectUser.IsActive)
  233. {
  234. throw new ArgumentException("The Media Browser account has been disabled.");
  235. }
  236. var user = GetUser(userId);
  237. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  238. {
  239. await RemoveLink(user, connectUser.Id).ConfigureAwait(false);
  240. }
  241. var url = GetConnectUrl("ServerAuthorizations");
  242. var options = new HttpRequestOptions
  243. {
  244. Url = url,
  245. CancellationToken = CancellationToken.None
  246. };
  247. var accessToken = Guid.NewGuid().ToString("N");
  248. var postData = new Dictionary<string, string>
  249. {
  250. {"serverId", ConnectServerId},
  251. {"userId", connectUser.Id},
  252. {"userType", "Linked"},
  253. {"accessToken", accessToken}
  254. };
  255. options.SetPostData(postData);
  256. SetServerAccessToken(options);
  257. // No need to examine the response
  258. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  259. {
  260. var response = _json.DeserializeFromStream<ServerUserAuthorizationResponse>(stream);
  261. }
  262. user.ConnectAccessKey = accessToken;
  263. user.ConnectUserName = connectUser.Name;
  264. user.ConnectUserId = connectUser.Id;
  265. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  266. }
  267. public Task RemoveLink(string userId)
  268. {
  269. var user = GetUser(userId);
  270. return RemoveLink(user, user.ConnectUserId);
  271. }
  272. private async Task RemoveLink(User user, string connectUserId)
  273. {
  274. if (!string.IsNullOrWhiteSpace(connectUserId))
  275. {
  276. var url = GetConnectUrl("ServerAuthorizations");
  277. var options = new HttpRequestOptions
  278. {
  279. Url = url,
  280. CancellationToken = CancellationToken.None
  281. };
  282. var postData = new Dictionary<string, string>
  283. {
  284. {"serverId", ConnectServerId},
  285. {"userId", connectUserId}
  286. };
  287. options.SetPostData(postData);
  288. SetServerAccessToken(options);
  289. try
  290. {
  291. // No need to examine the response
  292. using (var stream = (await _httpClient.SendAsync(options, "DELETE").ConfigureAwait(false)).Content)
  293. {
  294. }
  295. }
  296. catch (HttpException ex)
  297. {
  298. // If connect says the auth doesn't exist, we can handle that gracefully since this is a remove operation
  299. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  300. {
  301. throw;
  302. }
  303. _logger.Debug("Connect returned a 404 when removing a user auth link. Handling it.");
  304. }
  305. }
  306. user.ConnectAccessKey = null;
  307. user.ConnectUserName = null;
  308. user.ConnectUserId = null;
  309. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  310. }
  311. private async Task<ConnectUser> GetConnectUser(ConnectUserQuery query, CancellationToken cancellationToken)
  312. {
  313. var url = GetConnectUrl("user");
  314. if (!string.IsNullOrWhiteSpace(query.Id))
  315. {
  316. url = url + "?id=" + WebUtility.UrlEncode(query.Id);
  317. }
  318. else if (!string.IsNullOrWhiteSpace(query.Name))
  319. {
  320. url = url + "?name=" + WebUtility.UrlEncode(query.Name);
  321. }
  322. else if (!string.IsNullOrWhiteSpace(query.Email))
  323. {
  324. url = url + "?email=" + WebUtility.UrlEncode(query.Email);
  325. }
  326. var options = new HttpRequestOptions
  327. {
  328. CancellationToken = cancellationToken,
  329. Url = url
  330. };
  331. SetServerAccessToken(options);
  332. using (var stream = await _httpClient.Get(options).ConfigureAwait(false))
  333. {
  334. var response = _json.DeserializeFromStream<GetConnectUserResponse>(stream);
  335. return new ConnectUser
  336. {
  337. Email = response.Email,
  338. Id = response.Id,
  339. Name = response.Name,
  340. IsActive = response.IsActive
  341. };
  342. }
  343. }
  344. private void SetServerAccessToken(HttpRequestOptions options)
  345. {
  346. options.RequestHeaders.Add("X-Connect-Token", ConnectAccessKey);
  347. }
  348. }
  349. }