ConnectManager.cs 39 KB

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