ConnectManager.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Connect;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.Providers;
  10. using MediaBrowser.Controller.Security;
  11. using MediaBrowser.Model.Connect;
  12. using MediaBrowser.Model.Entities;
  13. using MediaBrowser.Model.Events;
  14. using MediaBrowser.Model.Logging;
  15. using MediaBrowser.Model.Net;
  16. using MediaBrowser.Model.Serialization;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Globalization;
  20. using System.IO;
  21. using System.Linq;
  22. using System.Net;
  23. using System.Text;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. namespace MediaBrowser.Server.Implementations.Connect
  27. {
  28. public class ConnectManager : IConnectManager
  29. {
  30. private readonly SemaphoreSlim _operationLock = new SemaphoreSlim(1, 1);
  31. private readonly ILogger _logger;
  32. private readonly IApplicationPaths _appPaths;
  33. private readonly IJsonSerializer _json;
  34. private readonly IEncryptionManager _encryption;
  35. private readonly IHttpClient _httpClient;
  36. private readonly IServerApplicationHost _appHost;
  37. private readonly IServerConfigurationManager _config;
  38. private readonly IUserManager _userManager;
  39. private readonly IProviderManager _providerManager;
  40. private ConnectData _data = new ConnectData();
  41. public string ConnectServerId
  42. {
  43. get { return _data.ServerId; }
  44. }
  45. public string ConnectAccessKey
  46. {
  47. get { return _data.AccessKey; }
  48. }
  49. public string DiscoveredWanIpAddress { get; private set; }
  50. public string WanIpAddress
  51. {
  52. get
  53. {
  54. var address = _config.Configuration.WanDdns;
  55. if (string.IsNullOrWhiteSpace(address))
  56. {
  57. address = DiscoveredWanIpAddress;
  58. }
  59. return address;
  60. }
  61. }
  62. public string WanApiAddress
  63. {
  64. get
  65. {
  66. var ip = WanIpAddress;
  67. if (!string.IsNullOrEmpty(ip))
  68. {
  69. if (!ip.StartsWith("http://", StringComparison.OrdinalIgnoreCase) &&
  70. !ip.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
  71. {
  72. ip = "http://" + ip;
  73. }
  74. return ip + ":" + _config.Configuration.PublicPort.ToString(CultureInfo.InvariantCulture);
  75. }
  76. return null;
  77. }
  78. }
  79. private string XApplicationValue
  80. {
  81. get { return "Media Browser Server/" + _appHost.ApplicationVersion; }
  82. }
  83. public ConnectManager(ILogger logger,
  84. IApplicationPaths appPaths,
  85. IJsonSerializer json,
  86. IEncryptionManager encryption,
  87. IHttpClient httpClient,
  88. IServerApplicationHost appHost,
  89. IServerConfigurationManager config, IUserManager userManager, IProviderManager providerManager)
  90. {
  91. _logger = logger;
  92. _appPaths = appPaths;
  93. _json = json;
  94. _encryption = encryption;
  95. _httpClient = httpClient;
  96. _appHost = appHost;
  97. _config = config;
  98. _userManager = userManager;
  99. _providerManager = providerManager;
  100. _userManager.UserConfigurationUpdated += _userManager_UserConfigurationUpdated;
  101. LoadCachedData();
  102. }
  103. internal void OnWanAddressResolved(string address)
  104. {
  105. DiscoveredWanIpAddress = address;
  106. UpdateConnectInfo();
  107. }
  108. private async void UpdateConnectInfo()
  109. {
  110. await _operationLock.WaitAsync().ConfigureAwait(false);
  111. try
  112. {
  113. await UpdateConnectInfoInternal().ConfigureAwait(false);
  114. }
  115. finally
  116. {
  117. _operationLock.Release();
  118. }
  119. }
  120. private async Task UpdateConnectInfoInternal()
  121. {
  122. var wanApiAddress = WanApiAddress;
  123. if (string.IsNullOrWhiteSpace(wanApiAddress))
  124. {
  125. _logger.Warn("Cannot update Media Browser Connect information without a WanApiAddress");
  126. return;
  127. }
  128. try
  129. {
  130. var localAddress = _appHost.GetSystemInfo().LocalAddress;
  131. var hasExistingRecord = !string.IsNullOrWhiteSpace(ConnectServerId) &&
  132. !string.IsNullOrWhiteSpace(ConnectAccessKey);
  133. var createNewRegistration = !hasExistingRecord;
  134. if (hasExistingRecord)
  135. {
  136. try
  137. {
  138. await UpdateServerRegistration(wanApiAddress, localAddress).ConfigureAwait(false);
  139. }
  140. catch (HttpException ex)
  141. {
  142. if (!ex.StatusCode.HasValue ||
  143. !new[] { HttpStatusCode.NotFound, HttpStatusCode.Unauthorized }.Contains(ex.StatusCode.Value))
  144. {
  145. throw;
  146. }
  147. createNewRegistration = true;
  148. }
  149. }
  150. if (createNewRegistration)
  151. {
  152. await CreateServerRegistration(wanApiAddress, localAddress).ConfigureAwait(false);
  153. }
  154. await RefreshAuthorizationsInternal(true, CancellationToken.None).ConfigureAwait(false);
  155. }
  156. catch (Exception ex)
  157. {
  158. _logger.ErrorException("Error registering with Connect", ex);
  159. }
  160. }
  161. private async Task CreateServerRegistration(string wanApiAddress, string localAddress)
  162. {
  163. if (string.IsNullOrWhiteSpace(wanApiAddress))
  164. {
  165. throw new ArgumentNullException("wanApiAddress");
  166. }
  167. var url = "Servers";
  168. url = GetConnectUrl(url);
  169. var postData = new Dictionary<string, string>
  170. {
  171. {"name", _appHost.FriendlyName},
  172. {"url", wanApiAddress},
  173. {"systemId", _appHost.SystemId}
  174. };
  175. if (!string.IsNullOrWhiteSpace(localAddress))
  176. {
  177. postData["localAddress"] = localAddress;
  178. }
  179. var options = new HttpRequestOptions
  180. {
  181. Url = url,
  182. CancellationToken = CancellationToken.None
  183. };
  184. options.SetPostData(postData);
  185. SetApplicationHeader(options);
  186. using (var response = await _httpClient.Post(options).ConfigureAwait(false))
  187. {
  188. var data = _json.DeserializeFromStream<ServerRegistrationResponse>(response.Content);
  189. _data.ServerId = data.Id;
  190. _data.AccessKey = data.AccessKey;
  191. CacheData();
  192. }
  193. }
  194. private async Task UpdateServerRegistration(string wanApiAddress, string localAddress)
  195. {
  196. if (string.IsNullOrWhiteSpace(wanApiAddress))
  197. {
  198. throw new ArgumentNullException("wanApiAddress");
  199. }
  200. if (string.IsNullOrWhiteSpace(ConnectServerId))
  201. {
  202. throw new ArgumentNullException("ConnectServerId");
  203. }
  204. var url = "Servers";
  205. url = GetConnectUrl(url);
  206. url += "?id=" + ConnectServerId;
  207. var postData = new Dictionary<string, string>
  208. {
  209. {"name", _appHost.FriendlyName},
  210. {"url", wanApiAddress},
  211. {"systemId", _appHost.SystemId}
  212. };
  213. if (!string.IsNullOrWhiteSpace(localAddress))
  214. {
  215. postData["localAddress"] = localAddress;
  216. }
  217. var options = new HttpRequestOptions
  218. {
  219. Url = url,
  220. CancellationToken = CancellationToken.None
  221. };
  222. options.SetPostData(postData);
  223. SetServerAccessToken(options);
  224. SetApplicationHeader(options);
  225. // No need to examine the response
  226. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  227. {
  228. }
  229. }
  230. private readonly object _dataFileLock = new object();
  231. private string CacheFilePath
  232. {
  233. get { return Path.Combine(_appPaths.DataPath, "connect.txt"); }
  234. }
  235. private void CacheData()
  236. {
  237. var path = CacheFilePath;
  238. try
  239. {
  240. Directory.CreateDirectory(Path.GetDirectoryName(path));
  241. var json = _json.SerializeToString(_data);
  242. var encrypted = _encryption.EncryptString(json);
  243. lock (_dataFileLock)
  244. {
  245. File.WriteAllText(path, encrypted, Encoding.UTF8);
  246. }
  247. }
  248. catch (Exception ex)
  249. {
  250. _logger.ErrorException("Error saving data", ex);
  251. }
  252. }
  253. private void LoadCachedData()
  254. {
  255. var path = CacheFilePath;
  256. try
  257. {
  258. lock (_dataFileLock)
  259. {
  260. var encrypted = File.ReadAllText(path, Encoding.UTF8);
  261. var json = _encryption.DecryptString(encrypted);
  262. _data = _json.DeserializeFromString<ConnectData>(json);
  263. }
  264. }
  265. catch (IOException)
  266. {
  267. // File isn't there. no biggie
  268. }
  269. catch (Exception ex)
  270. {
  271. _logger.ErrorException("Error loading data", ex);
  272. }
  273. }
  274. private User GetUser(string id)
  275. {
  276. var user = _userManager.GetUserById(id);
  277. if (user == null)
  278. {
  279. throw new ArgumentException("User not found.");
  280. }
  281. return user;
  282. }
  283. private string GetConnectUrl(string handler)
  284. {
  285. return "https://connect.mediabrowser.tv/service/" + handler;
  286. }
  287. public async Task<UserLinkResult> LinkUser(string userId, string connectUsername)
  288. {
  289. await _operationLock.WaitAsync().ConfigureAwait(false);
  290. try
  291. {
  292. return await LinkUserInternal(userId, connectUsername).ConfigureAwait(false);
  293. }
  294. finally
  295. {
  296. _operationLock.Release();
  297. }
  298. }
  299. private async Task<UserLinkResult> LinkUserInternal(string userId, string connectUsername)
  300. {
  301. if (string.IsNullOrWhiteSpace(userId))
  302. {
  303. throw new ArgumentNullException("userId");
  304. }
  305. if (string.IsNullOrWhiteSpace(connectUsername))
  306. {
  307. throw new ArgumentNullException("connectUsername");
  308. }
  309. if (string.IsNullOrWhiteSpace(ConnectServerId))
  310. {
  311. throw new ArgumentNullException("ConnectServerId");
  312. }
  313. var connectUser = await GetConnectUser(new ConnectUserQuery
  314. {
  315. NameOrEmail = connectUsername
  316. }, CancellationToken.None).ConfigureAwait(false);
  317. if (!connectUser.IsActive)
  318. {
  319. throw new ArgumentException("The Media Browser account has been disabled.");
  320. }
  321. var user = GetUser(userId);
  322. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  323. {
  324. await RemoveConnect(user, connectUser.Id).ConfigureAwait(false);
  325. }
  326. var url = GetConnectUrl("ServerAuthorizations");
  327. var options = new HttpRequestOptions
  328. {
  329. Url = url,
  330. CancellationToken = CancellationToken.None
  331. };
  332. var accessToken = Guid.NewGuid().ToString("N");
  333. var postData = new Dictionary<string, string>
  334. {
  335. {"serverId", ConnectServerId},
  336. {"userId", connectUser.Id},
  337. {"userType", "Linked"},
  338. {"accessToken", accessToken}
  339. };
  340. options.SetPostData(postData);
  341. SetServerAccessToken(options);
  342. SetApplicationHeader(options);
  343. var result = new UserLinkResult();
  344. // No need to examine the response
  345. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  346. {
  347. var response = _json.DeserializeFromStream<ServerUserAuthorizationResponse>(stream);
  348. result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase);
  349. }
  350. user.ConnectAccessKey = accessToken;
  351. user.ConnectUserName = connectUser.Name;
  352. user.ConnectUserId = connectUser.Id;
  353. user.ConnectLinkType = UserLinkType.LinkedUser;
  354. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  355. await _userManager.UpdateConfiguration(user.Id.ToString("N"), user.Configuration);
  356. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  357. return result;
  358. }
  359. public async Task<UserLinkResult> InviteUser(ConnectAuthorizationRequest request)
  360. {
  361. await _operationLock.WaitAsync().ConfigureAwait(false);
  362. try
  363. {
  364. return await InviteUserInternal(request).ConfigureAwait(false);
  365. }
  366. finally
  367. {
  368. _operationLock.Release();
  369. }
  370. }
  371. private async Task<UserLinkResult> InviteUserInternal(ConnectAuthorizationRequest request)
  372. {
  373. var connectUsername = request.ConnectUserName;
  374. var sendingUserId = request.SendingUserId;
  375. if (string.IsNullOrWhiteSpace(connectUsername))
  376. {
  377. throw new ArgumentNullException("connectUsername");
  378. }
  379. if (string.IsNullOrWhiteSpace(ConnectServerId))
  380. {
  381. throw new ArgumentNullException("ConnectServerId");
  382. }
  383. var sendingUser = GetUser(sendingUserId);
  384. var requesterUserName = sendingUser.ConnectUserName;
  385. if (string.IsNullOrWhiteSpace(requesterUserName))
  386. {
  387. throw new ArgumentException("A Connect account is required in order to send invitations.");
  388. }
  389. string connectUserId = null;
  390. var result = new UserLinkResult();
  391. try
  392. {
  393. var connectUser = await GetConnectUser(new ConnectUserQuery
  394. {
  395. NameOrEmail = connectUsername
  396. }, CancellationToken.None).ConfigureAwait(false);
  397. if (!connectUser.IsActive)
  398. {
  399. throw new ArgumentException("The Media Browser account has been disabled.");
  400. }
  401. connectUserId = connectUser.Id;
  402. result.GuestDisplayName = connectUser.Name;
  403. }
  404. catch (HttpException ex)
  405. {
  406. if (!ex.StatusCode.HasValue ||
  407. ex.StatusCode.Value != HttpStatusCode.NotFound ||
  408. !Validator.EmailIsValid(connectUsername))
  409. {
  410. throw;
  411. }
  412. }
  413. if (string.IsNullOrWhiteSpace(connectUserId))
  414. {
  415. return await SendNewUserInvitation(requesterUserName, connectUsername).ConfigureAwait(false);
  416. }
  417. var url = GetConnectUrl("ServerAuthorizations");
  418. var options = new HttpRequestOptions
  419. {
  420. Url = url,
  421. CancellationToken = CancellationToken.None
  422. };
  423. var accessToken = Guid.NewGuid().ToString("N");
  424. var postData = new Dictionary<string, string>
  425. {
  426. {"serverId", ConnectServerId},
  427. {"userId", connectUserId},
  428. {"userType", "Guest"},
  429. {"accessToken", accessToken},
  430. {"requesterUserName", requesterUserName}
  431. };
  432. options.SetPostData(postData);
  433. SetServerAccessToken(options);
  434. SetApplicationHeader(options);
  435. // No need to examine the response
  436. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  437. {
  438. var response = _json.DeserializeFromStream<ServerUserAuthorizationResponse>(stream);
  439. result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase);
  440. _data.PendingAuthorizations.Add(new ConnectAuthorizationInternal
  441. {
  442. ConnectUserId = response.UserId,
  443. Id = response.Id,
  444. ImageUrl = response.UserImageUrl,
  445. UserName = response.UserName,
  446. ExcludedLibraries = request.ExcludedLibraries,
  447. ExcludedChannels = request.ExcludedChannels,
  448. EnableLiveTv = request.EnableLiveTv,
  449. AccessToken = accessToken
  450. });
  451. CacheData();
  452. }
  453. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  454. return result;
  455. }
  456. private async Task<UserLinkResult> SendNewUserInvitation(string fromName, string email)
  457. {
  458. var url = GetConnectUrl("users/invite");
  459. var options = new HttpRequestOptions
  460. {
  461. Url = url,
  462. CancellationToken = CancellationToken.None
  463. };
  464. var postData = new Dictionary<string, string>
  465. {
  466. {"email", email},
  467. {"requesterUserName", fromName}
  468. };
  469. options.SetPostData(postData);
  470. SetApplicationHeader(options);
  471. // No need to examine the response
  472. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  473. {
  474. }
  475. return new UserLinkResult
  476. {
  477. IsNewUserInvitation = true,
  478. GuestDisplayName = email
  479. };
  480. }
  481. public Task RemoveConnect(string userId)
  482. {
  483. var user = GetUser(userId);
  484. return RemoveConnect(user, user.ConnectUserId);
  485. }
  486. private async Task RemoveConnect(User user, string connectUserId)
  487. {
  488. if (!string.IsNullOrWhiteSpace(connectUserId))
  489. {
  490. await CancelAuthorizationByConnectUserId(connectUserId).ConfigureAwait(false);
  491. }
  492. user.ConnectAccessKey = null;
  493. user.ConnectUserName = null;
  494. user.ConnectUserId = null;
  495. user.ConnectLinkType = null;
  496. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  497. }
  498. private async Task<ConnectUser> GetConnectUser(ConnectUserQuery query, CancellationToken cancellationToken)
  499. {
  500. var url = GetConnectUrl("user");
  501. if (!string.IsNullOrWhiteSpace(query.Id))
  502. {
  503. url = url + "?id=" + WebUtility.UrlEncode(query.Id);
  504. }
  505. else if (!string.IsNullOrWhiteSpace(query.NameOrEmail))
  506. {
  507. url = url + "?nameOrEmail=" + WebUtility.UrlEncode(query.NameOrEmail);
  508. }
  509. else if (!string.IsNullOrWhiteSpace(query.Name))
  510. {
  511. url = url + "?name=" + WebUtility.UrlEncode(query.Name);
  512. }
  513. else if (!string.IsNullOrWhiteSpace(query.Email))
  514. {
  515. url = url + "?name=" + WebUtility.UrlEncode(query.Email);
  516. }
  517. else
  518. {
  519. throw new ArgumentException("Empty ConnectUserQuery supplied");
  520. }
  521. var options = new HttpRequestOptions
  522. {
  523. CancellationToken = cancellationToken,
  524. Url = url
  525. };
  526. SetServerAccessToken(options);
  527. SetApplicationHeader(options);
  528. using (var stream = await _httpClient.Get(options).ConfigureAwait(false))
  529. {
  530. var response = _json.DeserializeFromStream<GetConnectUserResponse>(stream);
  531. return new ConnectUser
  532. {
  533. Email = response.Email,
  534. Id = response.Id,
  535. Name = response.Name,
  536. IsActive = response.IsActive,
  537. ImageUrl = response.ImageUrl
  538. };
  539. }
  540. }
  541. private void SetApplicationHeader(HttpRequestOptions options)
  542. {
  543. options.RequestHeaders.Add("X-Application", XApplicationValue);
  544. }
  545. private void SetServerAccessToken(HttpRequestOptions options)
  546. {
  547. if (string.IsNullOrWhiteSpace(ConnectAccessKey))
  548. {
  549. throw new ArgumentNullException("ConnectAccessKey");
  550. }
  551. options.RequestHeaders.Add("X-Connect-Token", ConnectAccessKey);
  552. }
  553. public async Task RefreshAuthorizations(CancellationToken cancellationToken)
  554. {
  555. await _operationLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  556. try
  557. {
  558. await RefreshAuthorizationsInternal(true, cancellationToken).ConfigureAwait(false);
  559. }
  560. finally
  561. {
  562. _operationLock.Release();
  563. }
  564. }
  565. private async Task RefreshAuthorizationsInternal(bool refreshImages, CancellationToken cancellationToken)
  566. {
  567. if (string.IsNullOrWhiteSpace(ConnectServerId))
  568. {
  569. throw new ArgumentNullException("ConnectServerId");
  570. }
  571. var url = GetConnectUrl("ServerAuthorizations");
  572. url += "?serverId=" + ConnectServerId;
  573. var options = new HttpRequestOptions
  574. {
  575. Url = url,
  576. CancellationToken = cancellationToken
  577. };
  578. SetServerAccessToken(options);
  579. SetApplicationHeader(options);
  580. try
  581. {
  582. using (var stream = (await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)).Content)
  583. {
  584. var list = _json.DeserializeFromStream<List<ServerUserAuthorizationResponse>>(stream);
  585. await RefreshAuthorizations(list, refreshImages).ConfigureAwait(false);
  586. }
  587. }
  588. catch (Exception ex)
  589. {
  590. _logger.ErrorException("Error refreshing server authorizations.", ex);
  591. }
  592. }
  593. private readonly SemaphoreSlim _connectImageSemaphore = new SemaphoreSlim(5, 5);
  594. private async Task RefreshAuthorizations(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  595. {
  596. var users = _userManager.Users.ToList();
  597. // Handle existing authorizations that were removed by the Connect server
  598. // Handle existing authorizations whose status may have been updated
  599. foreach (var user in users)
  600. {
  601. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  602. {
  603. var connectEntry = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.OrdinalIgnoreCase));
  604. if (connectEntry == null)
  605. {
  606. var deleteUser = user.ConnectLinkType.HasValue &&
  607. user.ConnectLinkType.Value == UserLinkType.Guest;
  608. user.ConnectUserId = null;
  609. user.ConnectAccessKey = null;
  610. user.ConnectUserName = null;
  611. user.ConnectLinkType = null;
  612. await _userManager.UpdateUser(user).ConfigureAwait(false);
  613. if (deleteUser)
  614. {
  615. _logger.Debug("Deleting guest user {0}", user.Name);
  616. await _userManager.DeleteUser(user).ConfigureAwait(false);
  617. }
  618. }
  619. else
  620. {
  621. var changed = !string.Equals(user.ConnectAccessKey, connectEntry.AccessToken, StringComparison.OrdinalIgnoreCase);
  622. if (changed)
  623. {
  624. user.ConnectUserId = connectEntry.UserId;
  625. user.ConnectAccessKey = connectEntry.AccessToken;
  626. await _userManager.UpdateUser(user).ConfigureAwait(false);
  627. }
  628. }
  629. }
  630. }
  631. var currentPendingList = _data.PendingAuthorizations.ToList();
  632. var newPendingList = new List<ConnectAuthorizationInternal>();
  633. foreach (var connectEntry in list)
  634. {
  635. if (string.Equals(connectEntry.UserType, "guest", StringComparison.OrdinalIgnoreCase))
  636. {
  637. var currentPendingEntry = currentPendingList.FirstOrDefault(i => string.Equals(i.Id, connectEntry.Id, StringComparison.OrdinalIgnoreCase));
  638. if (string.Equals(connectEntry.AcceptStatus, "accepted", StringComparison.OrdinalIgnoreCase))
  639. {
  640. var user = _userManager.Users
  641. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectEntry.UserId, StringComparison.OrdinalIgnoreCase));
  642. if (user == null)
  643. {
  644. // Add user
  645. user = await _userManager.CreateUser(_userManager.MakeValidUsername(connectEntry.UserName)).ConfigureAwait(false);
  646. user.ConnectUserName = connectEntry.UserName;
  647. user.ConnectUserId = connectEntry.UserId;
  648. user.ConnectLinkType = UserLinkType.Guest;
  649. user.ConnectAccessKey = connectEntry.AccessToken;
  650. await _userManager.UpdateUser(user).ConfigureAwait(false);
  651. user.Policy.IsHidden = true;
  652. user.Policy.EnableLiveTvManagement = false;
  653. user.Policy.EnableContentDeletion = false;
  654. user.Policy.EnableRemoteControlOfOtherUsers = false;
  655. user.Policy.EnableSharedDeviceControl = false;
  656. user.Policy.IsAdministrator = false;
  657. if (currentPendingEntry != null)
  658. {
  659. user.Policy.EnableLiveTvAccess = currentPendingEntry.EnableLiveTv;
  660. user.Policy.BlockedMediaFolders = currentPendingEntry.ExcludedLibraries;
  661. user.Policy.BlockedChannels = currentPendingEntry.ExcludedChannels;
  662. }
  663. await _userManager.UpdateConfiguration(user.Id.ToString("N"), user.Configuration);
  664. }
  665. }
  666. else if (string.Equals(connectEntry.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase))
  667. {
  668. currentPendingEntry = currentPendingEntry ?? new ConnectAuthorizationInternal();
  669. currentPendingEntry.ConnectUserId = connectEntry.UserId;
  670. currentPendingEntry.ImageUrl = connectEntry.UserImageUrl;
  671. currentPendingEntry.UserName = connectEntry.UserName;
  672. currentPendingEntry.Id = connectEntry.Id;
  673. currentPendingEntry.AccessToken = connectEntry.AccessToken;
  674. newPendingList.Add(currentPendingEntry);
  675. }
  676. }
  677. }
  678. _data.PendingAuthorizations = newPendingList;
  679. CacheData();
  680. await RefreshGuestNames(list, refreshImages).ConfigureAwait(false);
  681. }
  682. private async Task RefreshGuestNames(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  683. {
  684. var users = _userManager.Users
  685. .Where(i => !string.IsNullOrEmpty(i.ConnectUserId) &&
  686. (i.ConnectLinkType.HasValue && i.ConnectLinkType.Value == UserLinkType.Guest))
  687. .ToList();
  688. foreach (var user in users)
  689. {
  690. var authorization = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.Ordinal));
  691. if (authorization == null)
  692. {
  693. _logger.Warn("Unable to find connect authorization record for user {0}", user.Name);
  694. continue;
  695. }
  696. var syncConnectName = true;
  697. var syncConnectImage = true;
  698. if (syncConnectName)
  699. {
  700. var changed = !string.Equals(authorization.UserName, user.Name, StringComparison.OrdinalIgnoreCase);
  701. if (changed)
  702. {
  703. await user.Rename(authorization.UserName).ConfigureAwait(false);
  704. }
  705. }
  706. if (syncConnectImage)
  707. {
  708. var imageUrl = authorization.UserImageUrl;
  709. if (!string.IsNullOrWhiteSpace(imageUrl))
  710. {
  711. var changed = false;
  712. if (!user.HasImage(ImageType.Primary))
  713. {
  714. changed = true;
  715. }
  716. else if (refreshImages)
  717. {
  718. using (var response = await _httpClient.SendAsync(new HttpRequestOptions
  719. {
  720. Url = imageUrl,
  721. BufferContent = false
  722. }, "HEAD").ConfigureAwait(false))
  723. {
  724. var length = response.ContentLength;
  725. if (length != new FileInfo(user.GetImageInfo(ImageType.Primary, 0).Path).Length)
  726. {
  727. changed = true;
  728. }
  729. }
  730. }
  731. if (changed)
  732. {
  733. await _providerManager.SaveImage(user, imageUrl, _connectImageSemaphore, ImageType.Primary, null, CancellationToken.None).ConfigureAwait(false);
  734. await user.RefreshMetadata(new MetadataRefreshOptions
  735. {
  736. ForceSave = true,
  737. }, CancellationToken.None).ConfigureAwait(false);
  738. }
  739. }
  740. }
  741. }
  742. }
  743. public async Task<List<ConnectAuthorization>> GetPendingGuests()
  744. {
  745. var time = DateTime.UtcNow - _data.LastAuthorizationsRefresh;
  746. if (time.TotalMinutes >= 5)
  747. {
  748. await _operationLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  749. try
  750. {
  751. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  752. _data.LastAuthorizationsRefresh = DateTime.UtcNow;
  753. CacheData();
  754. }
  755. finally
  756. {
  757. _operationLock.Release();
  758. }
  759. }
  760. return _data.PendingAuthorizations.Select(i => new ConnectAuthorization
  761. {
  762. ConnectUserId = i.ConnectUserId,
  763. EnableLiveTv = i.EnableLiveTv,
  764. ExcludedChannels = i.ExcludedChannels,
  765. ExcludedLibraries = i.ExcludedLibraries,
  766. Id = i.Id,
  767. ImageUrl = i.ImageUrl,
  768. UserName = i.UserName
  769. }).ToList();
  770. }
  771. public async Task CancelAuthorization(string id)
  772. {
  773. await _operationLock.WaitAsync().ConfigureAwait(false);
  774. try
  775. {
  776. await CancelAuthorizationInternal(id).ConfigureAwait(false);
  777. }
  778. finally
  779. {
  780. _operationLock.Release();
  781. }
  782. }
  783. private async Task CancelAuthorizationInternal(string id)
  784. {
  785. var connectUserId = _data.PendingAuthorizations
  786. .First(i => string.Equals(i.Id, id, StringComparison.Ordinal))
  787. .ConnectUserId;
  788. await CancelAuthorizationByConnectUserId(connectUserId).ConfigureAwait(false);
  789. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  790. }
  791. private async Task CancelAuthorizationByConnectUserId(string connectUserId)
  792. {
  793. if (string.IsNullOrWhiteSpace(connectUserId))
  794. {
  795. throw new ArgumentNullException("connectUserId");
  796. }
  797. if (string.IsNullOrWhiteSpace(ConnectServerId))
  798. {
  799. throw new ArgumentNullException("ConnectServerId");
  800. }
  801. var url = GetConnectUrl("ServerAuthorizations");
  802. var options = new HttpRequestOptions
  803. {
  804. Url = url,
  805. CancellationToken = CancellationToken.None
  806. };
  807. var postData = new Dictionary<string, string>
  808. {
  809. {"serverId", ConnectServerId},
  810. {"userId", connectUserId}
  811. };
  812. options.SetPostData(postData);
  813. SetServerAccessToken(options);
  814. SetApplicationHeader(options);
  815. try
  816. {
  817. // No need to examine the response
  818. using (var stream = (await _httpClient.SendAsync(options, "DELETE").ConfigureAwait(false)).Content)
  819. {
  820. }
  821. }
  822. catch (HttpException ex)
  823. {
  824. // If connect says the auth doesn't exist, we can handle that gracefully since this is a remove operation
  825. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  826. {
  827. throw;
  828. }
  829. _logger.Debug("Connect returned a 404 when removing a user auth link. Handling it.");
  830. }
  831. }
  832. public async Task Authenticate(string username, string passwordMd5)
  833. {
  834. if (string.IsNullOrWhiteSpace(username))
  835. {
  836. throw new ArgumentNullException("username");
  837. }
  838. if (string.IsNullOrWhiteSpace(passwordMd5))
  839. {
  840. throw new ArgumentNullException("passwordMd5");
  841. }
  842. var options = new HttpRequestOptions
  843. {
  844. Url = GetConnectUrl("user/authenticate")
  845. };
  846. options.SetPostData(new Dictionary<string, string>
  847. {
  848. {"userName",username},
  849. {"password",passwordMd5}
  850. });
  851. SetApplicationHeader(options);
  852. // No need to examine the response
  853. using (var response = (await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)).Content)
  854. {
  855. }
  856. }
  857. async void _userManager_UserConfigurationUpdated(object sender, GenericEventArgs<User> e)
  858. {
  859. var user = e.Argument;
  860. await TryUploadUserPreferences(user, CancellationToken.None).ConfigureAwait(false);
  861. }
  862. private async Task TryUploadUserPreferences(User user, CancellationToken cancellationToken)
  863. {
  864. if (user == null)
  865. {
  866. throw new ArgumentNullException("user");
  867. }
  868. if (string.IsNullOrEmpty(user.ConnectUserId))
  869. {
  870. return;
  871. }
  872. if (string.IsNullOrEmpty(ConnectAccessKey))
  873. {
  874. return;
  875. }
  876. var url = GetConnectUrl("user/preferences");
  877. url += "?userId=" + user.ConnectUserId;
  878. url += "&key=userpreferences";
  879. var options = new HttpRequestOptions
  880. {
  881. Url = url,
  882. CancellationToken = cancellationToken
  883. };
  884. var postData = new Dictionary<string, string>();
  885. postData["data"] = _json.SerializeToString(ConnectUserPreferences.FromUserConfiguration(user.Configuration));
  886. options.SetPostData(postData);
  887. SetServerAccessToken(options);
  888. SetApplicationHeader(options);
  889. try
  890. {
  891. // No need to examine the response
  892. using (var stream = (await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)).Content)
  893. {
  894. }
  895. }
  896. catch (Exception ex)
  897. {
  898. _logger.ErrorException("Error uploading user preferences", ex);
  899. }
  900. }
  901. private async Task DownloadUserPreferences(User user, CancellationToken cancellationToken)
  902. {
  903. }
  904. public async Task<User> GetLocalUser(string connectUserId)
  905. {
  906. var user = _userManager.Users
  907. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUserId, StringComparison.OrdinalIgnoreCase));
  908. if (user == null)
  909. {
  910. await RefreshAuthorizations(CancellationToken.None).ConfigureAwait(false);
  911. }
  912. return _userManager.Users
  913. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUserId, StringComparison.OrdinalIgnoreCase));
  914. }
  915. public bool IsAuthorizationTokenValid(string token)
  916. {
  917. if (string.IsNullOrWhiteSpace(token))
  918. {
  919. throw new ArgumentNullException("token");
  920. }
  921. return _userManager.Users.Any(u => string.Equals(token, u.ConnectAccessKey, StringComparison.OrdinalIgnoreCase)) ||
  922. _data.PendingAuthorizations.Select(i => i.AccessToken).Contains(token, StringComparer.OrdinalIgnoreCase);
  923. }
  924. }
  925. }