ConnectManager.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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.GetSystemInfo().LocalAddress;
  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.GetSystemInfo().LocalAddress, 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. ExcludedLibraries = request.ExcludedLibraries,
  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.EnableLiveTvAccess = currentPendingEntry.EnableLiveTv;
  680. user.Policy.BlockedMediaFolders = currentPendingEntry.ExcludedLibraries;
  681. user.Policy.EnabledChannels = currentPendingEntry.EnabledChannels;
  682. user.Policy.EnableAllChannels = false;
  683. }
  684. await _userManager.UpdateConfiguration(user.Id.ToString("N"), user.Configuration);
  685. }
  686. }
  687. else if (string.Equals(connectEntry.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase))
  688. {
  689. currentPendingEntry = currentPendingEntry ?? new ConnectAuthorizationInternal();
  690. currentPendingEntry.ConnectUserId = connectEntry.UserId;
  691. currentPendingEntry.ImageUrl = connectEntry.UserImageUrl;
  692. currentPendingEntry.UserName = connectEntry.UserName;
  693. currentPendingEntry.Id = connectEntry.Id;
  694. currentPendingEntry.AccessToken = connectEntry.AccessToken;
  695. newPendingList.Add(currentPendingEntry);
  696. }
  697. }
  698. }
  699. _data.PendingAuthorizations = newPendingList;
  700. CacheData();
  701. await RefreshGuestNames(list, refreshImages).ConfigureAwait(false);
  702. }
  703. private async Task RefreshGuestNames(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  704. {
  705. var users = _userManager.Users
  706. .Where(i => !string.IsNullOrEmpty(i.ConnectUserId) &&
  707. (i.ConnectLinkType.HasValue && i.ConnectLinkType.Value == UserLinkType.Guest))
  708. .ToList();
  709. foreach (var user in users)
  710. {
  711. var authorization = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.Ordinal));
  712. if (authorization == null)
  713. {
  714. _logger.Warn("Unable to find connect authorization record for user {0}", user.Name);
  715. continue;
  716. }
  717. var syncConnectName = true;
  718. var syncConnectImage = true;
  719. if (syncConnectName)
  720. {
  721. var changed = !string.Equals(authorization.UserName, user.Name, StringComparison.OrdinalIgnoreCase);
  722. if (changed)
  723. {
  724. await user.Rename(authorization.UserName).ConfigureAwait(false);
  725. }
  726. }
  727. if (syncConnectImage)
  728. {
  729. var imageUrl = authorization.UserImageUrl;
  730. if (!string.IsNullOrWhiteSpace(imageUrl))
  731. {
  732. var changed = false;
  733. if (!user.HasImage(ImageType.Primary))
  734. {
  735. changed = true;
  736. }
  737. else if (refreshImages)
  738. {
  739. using (var response = await _httpClient.SendAsync(new HttpRequestOptions
  740. {
  741. Url = imageUrl,
  742. BufferContent = false
  743. }, "HEAD").ConfigureAwait(false))
  744. {
  745. var length = response.ContentLength;
  746. if (length != new FileInfo(user.GetImageInfo(ImageType.Primary, 0).Path).Length)
  747. {
  748. changed = true;
  749. }
  750. }
  751. }
  752. if (changed)
  753. {
  754. await _providerManager.SaveImage(user, imageUrl, _connectImageSemaphore, ImageType.Primary, null, CancellationToken.None).ConfigureAwait(false);
  755. await user.RefreshMetadata(new MetadataRefreshOptions
  756. {
  757. ForceSave = true,
  758. }, CancellationToken.None).ConfigureAwait(false);
  759. }
  760. }
  761. }
  762. }
  763. }
  764. public async Task<List<ConnectAuthorization>> GetPendingGuests()
  765. {
  766. var time = DateTime.UtcNow - _data.LastAuthorizationsRefresh;
  767. if (time.TotalMinutes >= 5)
  768. {
  769. await _operationLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  770. try
  771. {
  772. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  773. _data.LastAuthorizationsRefresh = DateTime.UtcNow;
  774. CacheData();
  775. }
  776. finally
  777. {
  778. _operationLock.Release();
  779. }
  780. }
  781. return _data.PendingAuthorizations.Select(i => new ConnectAuthorization
  782. {
  783. ConnectUserId = i.ConnectUserId,
  784. EnableLiveTv = i.EnableLiveTv,
  785. EnabledChannels = i.EnabledChannels,
  786. ExcludedLibraries = i.ExcludedLibraries,
  787. Id = i.Id,
  788. ImageUrl = i.ImageUrl,
  789. UserName = i.UserName
  790. }).ToList();
  791. }
  792. public async Task CancelAuthorization(string id)
  793. {
  794. await _operationLock.WaitAsync().ConfigureAwait(false);
  795. try
  796. {
  797. await CancelAuthorizationInternal(id).ConfigureAwait(false);
  798. }
  799. finally
  800. {
  801. _operationLock.Release();
  802. }
  803. }
  804. private async Task CancelAuthorizationInternal(string id)
  805. {
  806. var connectUserId = _data.PendingAuthorizations
  807. .First(i => string.Equals(i.Id, id, StringComparison.Ordinal))
  808. .ConnectUserId;
  809. await CancelAuthorizationByConnectUserId(connectUserId).ConfigureAwait(false);
  810. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  811. }
  812. private async Task CancelAuthorizationByConnectUserId(string connectUserId)
  813. {
  814. if (string.IsNullOrWhiteSpace(connectUserId))
  815. {
  816. throw new ArgumentNullException("connectUserId");
  817. }
  818. if (string.IsNullOrWhiteSpace(ConnectServerId))
  819. {
  820. throw new ArgumentNullException("ConnectServerId");
  821. }
  822. var url = GetConnectUrl("ServerAuthorizations");
  823. var options = new HttpRequestOptions
  824. {
  825. Url = url,
  826. CancellationToken = CancellationToken.None
  827. };
  828. var postData = new Dictionary<string, string>
  829. {
  830. {"serverId", ConnectServerId},
  831. {"userId", connectUserId}
  832. };
  833. options.SetPostData(postData);
  834. SetServerAccessToken(options);
  835. SetApplicationHeader(options);
  836. try
  837. {
  838. // No need to examine the response
  839. using (var stream = (await _httpClient.SendAsync(options, "DELETE").ConfigureAwait(false)).Content)
  840. {
  841. }
  842. }
  843. catch (HttpException ex)
  844. {
  845. // If connect says the auth doesn't exist, we can handle that gracefully since this is a remove operation
  846. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  847. {
  848. throw;
  849. }
  850. _logger.Debug("Connect returned a 404 when removing a user auth link. Handling it.");
  851. }
  852. }
  853. public async Task Authenticate(string username, string passwordMd5)
  854. {
  855. if (string.IsNullOrWhiteSpace(username))
  856. {
  857. throw new ArgumentNullException("username");
  858. }
  859. if (string.IsNullOrWhiteSpace(passwordMd5))
  860. {
  861. throw new ArgumentNullException("passwordMd5");
  862. }
  863. var options = new HttpRequestOptions
  864. {
  865. Url = GetConnectUrl("user/authenticate")
  866. };
  867. options.SetPostData(new Dictionary<string, string>
  868. {
  869. {"userName",username},
  870. {"password",passwordMd5}
  871. });
  872. SetApplicationHeader(options);
  873. // No need to examine the response
  874. using (var response = (await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)).Content)
  875. {
  876. }
  877. }
  878. async void _userManager_UserConfigurationUpdated(object sender, GenericEventArgs<User> e)
  879. {
  880. var user = e.Argument;
  881. await TryUploadUserPreferences(user, CancellationToken.None).ConfigureAwait(false);
  882. }
  883. private async Task TryUploadUserPreferences(User user, CancellationToken cancellationToken)
  884. {
  885. if (user == null)
  886. {
  887. throw new ArgumentNullException("user");
  888. }
  889. if (string.IsNullOrEmpty(user.ConnectUserId))
  890. {
  891. return;
  892. }
  893. if (string.IsNullOrEmpty(ConnectAccessKey))
  894. {
  895. return;
  896. }
  897. var url = GetConnectUrl("user/preferences");
  898. url += "?userId=" + user.ConnectUserId;
  899. url += "&key=userpreferences";
  900. var options = new HttpRequestOptions
  901. {
  902. Url = url,
  903. CancellationToken = cancellationToken
  904. };
  905. var postData = new Dictionary<string, string>();
  906. postData["data"] = _json.SerializeToString(ConnectUserPreferences.FromUserConfiguration(user.Configuration));
  907. options.SetPostData(postData);
  908. SetServerAccessToken(options);
  909. SetApplicationHeader(options);
  910. try
  911. {
  912. // No need to examine the response
  913. using (var stream = (await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)).Content)
  914. {
  915. }
  916. }
  917. catch (Exception ex)
  918. {
  919. _logger.ErrorException("Error uploading user preferences", ex);
  920. }
  921. }
  922. private async Task DownloadUserPreferences(User user, CancellationToken cancellationToken)
  923. {
  924. }
  925. public async Task<User> GetLocalUser(string connectUserId)
  926. {
  927. var user = _userManager.Users
  928. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUserId, StringComparison.OrdinalIgnoreCase));
  929. if (user == null)
  930. {
  931. await RefreshAuthorizations(CancellationToken.None).ConfigureAwait(false);
  932. }
  933. return _userManager.Users
  934. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUserId, StringComparison.OrdinalIgnoreCase));
  935. }
  936. public bool IsAuthorizationTokenValid(string token)
  937. {
  938. if (string.IsNullOrWhiteSpace(token))
  939. {
  940. throw new ArgumentNullException("token");
  941. }
  942. return _userManager.Users.Any(u => string.Equals(token, u.ConnectAccessKey, StringComparison.OrdinalIgnoreCase)) ||
  943. _data.PendingAuthorizations.Select(i => i.AccessToken).Contains(token, StringComparer.OrdinalIgnoreCase);
  944. }
  945. }
  946. }