ConnectManager.cs 17 KB

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