ConnectManager.cs 40 KB

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