ConnectManager.cs 43 KB

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