ConnectManager.cs 39 KB

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