ConnectManager.cs 40 KB

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