ConnectManager.cs 40 KB

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