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 = (_config.Configuration.UseHttps ? "https://" : "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. await _userManager.UpdateConfiguration(user.Id.ToString("N"), user.Configuration);
  355. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  356. return result;
  357. }
  358. public async Task<UserLinkResult> InviteUser(ConnectAuthorizationRequest request)
  359. {
  360. await _operationLock.WaitAsync().ConfigureAwait(false);
  361. try
  362. {
  363. return await InviteUserInternal(request).ConfigureAwait(false);
  364. }
  365. finally
  366. {
  367. _operationLock.Release();
  368. }
  369. }
  370. private async Task<UserLinkResult> InviteUserInternal(ConnectAuthorizationRequest request)
  371. {
  372. var connectUsername = request.ConnectUserName;
  373. var sendingUserId = request.SendingUserId;
  374. if (string.IsNullOrWhiteSpace(connectUsername))
  375. {
  376. throw new ArgumentNullException("connectUsername");
  377. }
  378. if (string.IsNullOrWhiteSpace(ConnectServerId))
  379. {
  380. throw new ArgumentNullException("ConnectServerId");
  381. }
  382. var sendingUser = GetUser(sendingUserId);
  383. var requesterUserName = sendingUser.ConnectUserName;
  384. if (string.IsNullOrWhiteSpace(requesterUserName))
  385. {
  386. throw new ArgumentException("A Connect account is required in order to send invitations.");
  387. }
  388. string connectUserId = null;
  389. var result = new UserLinkResult();
  390. try
  391. {
  392. var connectUser = await GetConnectUser(new ConnectUserQuery
  393. {
  394. NameOrEmail = connectUsername
  395. }, CancellationToken.None).ConfigureAwait(false);
  396. if (!connectUser.IsActive)
  397. {
  398. throw new ArgumentException("The Media Browser account has been disabled.");
  399. }
  400. connectUserId = connectUser.Id;
  401. result.GuestDisplayName = connectUser.Name;
  402. }
  403. catch (HttpException ex)
  404. {
  405. if (!ex.StatusCode.HasValue ||
  406. ex.StatusCode.Value != HttpStatusCode.NotFound ||
  407. !Validator.EmailIsValid(connectUsername))
  408. {
  409. throw;
  410. }
  411. }
  412. if (string.IsNullOrWhiteSpace(connectUserId))
  413. {
  414. return await SendNewUserInvitation(requesterUserName, connectUsername).ConfigureAwait(false);
  415. }
  416. var url = GetConnectUrl("ServerAuthorizations");
  417. var options = new HttpRequestOptions
  418. {
  419. Url = url,
  420. CancellationToken = CancellationToken.None
  421. };
  422. var accessToken = Guid.NewGuid().ToString("N");
  423. var postData = new Dictionary<string, string>
  424. {
  425. {"serverId", ConnectServerId},
  426. {"userId", connectUserId},
  427. {"userType", "Guest"},
  428. {"accessToken", accessToken},
  429. {"requesterUserName", requesterUserName}
  430. };
  431. options.SetPostData(postData);
  432. SetServerAccessToken(options);
  433. SetApplicationHeader(options);
  434. // No need to examine the response
  435. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  436. {
  437. var response = _json.DeserializeFromStream<ServerUserAuthorizationResponse>(stream);
  438. result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase);
  439. _data.PendingAuthorizations.Add(new ConnectAuthorizationInternal
  440. {
  441. ConnectUserId = response.UserId,
  442. Id = response.Id,
  443. ImageUrl = response.UserImageUrl,
  444. UserName = response.UserName,
  445. ExcludedLibraries = request.ExcludedLibraries,
  446. EnabledChannels = request.EnabledChannels,
  447. EnableLiveTv = request.EnableLiveTv,
  448. AccessToken = accessToken
  449. });
  450. CacheData();
  451. }
  452. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  453. return result;
  454. }
  455. private async Task<UserLinkResult> SendNewUserInvitation(string fromName, string email)
  456. {
  457. var url = GetConnectUrl("users/invite");
  458. var options = new HttpRequestOptions
  459. {
  460. Url = url,
  461. CancellationToken = CancellationToken.None
  462. };
  463. var postData = new Dictionary<string, string>
  464. {
  465. {"email", email},
  466. {"requesterUserName", fromName}
  467. };
  468. options.SetPostData(postData);
  469. SetApplicationHeader(options);
  470. // No need to examine the response
  471. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  472. {
  473. }
  474. return new UserLinkResult
  475. {
  476. IsNewUserInvitation = true,
  477. GuestDisplayName = email
  478. };
  479. }
  480. public Task RemoveConnect(string userId)
  481. {
  482. var user = GetUser(userId);
  483. return RemoveConnect(user, user.ConnectUserId);
  484. }
  485. private async Task RemoveConnect(User user, string connectUserId)
  486. {
  487. if (!string.IsNullOrWhiteSpace(connectUserId))
  488. {
  489. await CancelAuthorizationByConnectUserId(connectUserId).ConfigureAwait(false);
  490. }
  491. user.ConnectAccessKey = null;
  492. user.ConnectUserName = null;
  493. user.ConnectUserId = null;
  494. user.ConnectLinkType = null;
  495. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  496. }
  497. private async Task<ConnectUser> GetConnectUser(ConnectUserQuery query, CancellationToken cancellationToken)
  498. {
  499. var url = GetConnectUrl("user");
  500. if (!string.IsNullOrWhiteSpace(query.Id))
  501. {
  502. url = url + "?id=" + WebUtility.UrlEncode(query.Id);
  503. }
  504. else if (!string.IsNullOrWhiteSpace(query.NameOrEmail))
  505. {
  506. url = url + "?nameOrEmail=" + WebUtility.UrlEncode(query.NameOrEmail);
  507. }
  508. else if (!string.IsNullOrWhiteSpace(query.Name))
  509. {
  510. url = url + "?name=" + WebUtility.UrlEncode(query.Name);
  511. }
  512. else if (!string.IsNullOrWhiteSpace(query.Email))
  513. {
  514. url = url + "?name=" + WebUtility.UrlEncode(query.Email);
  515. }
  516. else
  517. {
  518. throw new ArgumentException("Empty ConnectUserQuery supplied");
  519. }
  520. var options = new HttpRequestOptions
  521. {
  522. CancellationToken = cancellationToken,
  523. Url = url
  524. };
  525. SetServerAccessToken(options);
  526. SetApplicationHeader(options);
  527. using (var stream = await _httpClient.Get(options).ConfigureAwait(false))
  528. {
  529. var response = _json.DeserializeFromStream<GetConnectUserResponse>(stream);
  530. return new ConnectUser
  531. {
  532. Email = response.Email,
  533. Id = response.Id,
  534. Name = response.Name,
  535. IsActive = response.IsActive,
  536. ImageUrl = response.ImageUrl
  537. };
  538. }
  539. }
  540. private void SetApplicationHeader(HttpRequestOptions options)
  541. {
  542. options.RequestHeaders.Add("X-Application", XApplicationValue);
  543. }
  544. private void SetServerAccessToken(HttpRequestOptions options)
  545. {
  546. if (string.IsNullOrWhiteSpace(ConnectAccessKey))
  547. {
  548. throw new ArgumentNullException("ConnectAccessKey");
  549. }
  550. options.RequestHeaders.Add("X-Connect-Token", ConnectAccessKey);
  551. }
  552. public async Task RefreshAuthorizations(CancellationToken cancellationToken)
  553. {
  554. await _operationLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  555. try
  556. {
  557. await RefreshAuthorizationsInternal(true, cancellationToken).ConfigureAwait(false);
  558. }
  559. finally
  560. {
  561. _operationLock.Release();
  562. }
  563. }
  564. private async Task RefreshAuthorizationsInternal(bool refreshImages, CancellationToken cancellationToken)
  565. {
  566. if (string.IsNullOrWhiteSpace(ConnectServerId))
  567. {
  568. throw new ArgumentNullException("ConnectServerId");
  569. }
  570. var url = GetConnectUrl("ServerAuthorizations");
  571. url += "?serverId=" + ConnectServerId;
  572. var options = new HttpRequestOptions
  573. {
  574. Url = url,
  575. CancellationToken = cancellationToken
  576. };
  577. SetServerAccessToken(options);
  578. SetApplicationHeader(options);
  579. try
  580. {
  581. using (var stream = (await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)).Content)
  582. {
  583. var list = _json.DeserializeFromStream<List<ServerUserAuthorizationResponse>>(stream);
  584. await RefreshAuthorizations(list, refreshImages).ConfigureAwait(false);
  585. }
  586. }
  587. catch (Exception ex)
  588. {
  589. _logger.ErrorException("Error refreshing server authorizations.", ex);
  590. }
  591. }
  592. private readonly SemaphoreSlim _connectImageSemaphore = new SemaphoreSlim(5, 5);
  593. private async Task RefreshAuthorizations(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  594. {
  595. var users = _userManager.Users.ToList();
  596. // Handle existing authorizations that were removed by the Connect server
  597. // Handle existing authorizations whose status may have been updated
  598. foreach (var user in users)
  599. {
  600. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  601. {
  602. var connectEntry = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.OrdinalIgnoreCase));
  603. if (connectEntry == null)
  604. {
  605. var deleteUser = user.ConnectLinkType.HasValue &&
  606. user.ConnectLinkType.Value == UserLinkType.Guest;
  607. user.ConnectUserId = null;
  608. user.ConnectAccessKey = null;
  609. user.ConnectUserName = null;
  610. user.ConnectLinkType = null;
  611. await _userManager.UpdateUser(user).ConfigureAwait(false);
  612. if (deleteUser)
  613. {
  614. _logger.Debug("Deleting guest user {0}", user.Name);
  615. await _userManager.DeleteUser(user).ConfigureAwait(false);
  616. }
  617. }
  618. else
  619. {
  620. var changed = !string.Equals(user.ConnectAccessKey, connectEntry.AccessToken, StringComparison.OrdinalIgnoreCase);
  621. if (changed)
  622. {
  623. user.ConnectUserId = connectEntry.UserId;
  624. user.ConnectAccessKey = connectEntry.AccessToken;
  625. await _userManager.UpdateUser(user).ConfigureAwait(false);
  626. }
  627. }
  628. }
  629. }
  630. var currentPendingList = _data.PendingAuthorizations.ToList();
  631. var newPendingList = new List<ConnectAuthorizationInternal>();
  632. foreach (var connectEntry in list)
  633. {
  634. if (string.Equals(connectEntry.UserType, "guest", StringComparison.OrdinalIgnoreCase))
  635. {
  636. var currentPendingEntry = currentPendingList.FirstOrDefault(i => string.Equals(i.Id, connectEntry.Id, StringComparison.OrdinalIgnoreCase));
  637. if (string.Equals(connectEntry.AcceptStatus, "accepted", StringComparison.OrdinalIgnoreCase))
  638. {
  639. var user = _userManager.Users
  640. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectEntry.UserId, StringComparison.OrdinalIgnoreCase));
  641. if (user == null)
  642. {
  643. // Add user
  644. user = await _userManager.CreateUser(_userManager.MakeValidUsername(connectEntry.UserName)).ConfigureAwait(false);
  645. user.ConnectUserName = connectEntry.UserName;
  646. user.ConnectUserId = connectEntry.UserId;
  647. user.ConnectLinkType = UserLinkType.Guest;
  648. user.ConnectAccessKey = connectEntry.AccessToken;
  649. await _userManager.UpdateUser(user).ConfigureAwait(false);
  650. user.Policy.IsHidden = true;
  651. user.Policy.EnableLiveTvManagement = false;
  652. user.Policy.EnableContentDeletion = false;
  653. user.Policy.EnableRemoteControlOfOtherUsers = false;
  654. user.Policy.EnableSharedDeviceControl = false;
  655. user.Policy.IsAdministrator = false;
  656. if (currentPendingEntry != null)
  657. {
  658. user.Policy.EnableLiveTvAccess = currentPendingEntry.EnableLiveTv;
  659. user.Policy.BlockedMediaFolders = currentPendingEntry.ExcludedLibraries;
  660. user.Policy.EnabledChannels = currentPendingEntry.EnabledChannels;
  661. user.Policy.EnableAllChannels = false;
  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. EnabledChannels = i.EnabledChannels,
  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. }