ConnectManager.cs 39 KB

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