ConnectManager.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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. try
  302. {
  303. lock (_dataFileLock)
  304. {
  305. var encrypted = _fileSystem.ReadAllText(path, Encoding.UTF8);
  306. var json = _encryption.DecryptString(encrypted);
  307. _data = _json.DeserializeFromString<ConnectData>(json);
  308. }
  309. }
  310. catch (IOException)
  311. {
  312. // File isn't there. no biggie
  313. }
  314. catch (Exception ex)
  315. {
  316. _logger.ErrorException("Error loading data", ex);
  317. }
  318. }
  319. private User GetUser(string id)
  320. {
  321. var user = _userManager.GetUserById(id);
  322. if (user == null)
  323. {
  324. throw new ArgumentException("User not found.");
  325. }
  326. return user;
  327. }
  328. private string GetConnectUrl(string handler)
  329. {
  330. return "https://connect.emby.media/service/" + handler;
  331. }
  332. public async Task<UserLinkResult> LinkUser(string userId, string connectUsername)
  333. {
  334. if (string.IsNullOrWhiteSpace(ConnectServerId))
  335. {
  336. await UpdateConnectInfo().ConfigureAwait(false);
  337. }
  338. await _operationLock.WaitAsync().ConfigureAwait(false);
  339. try
  340. {
  341. return await LinkUserInternal(userId, connectUsername).ConfigureAwait(false);
  342. }
  343. finally
  344. {
  345. _operationLock.Release();
  346. }
  347. }
  348. private async Task<UserLinkResult> LinkUserInternal(string userId, string connectUsername)
  349. {
  350. if (string.IsNullOrWhiteSpace(userId))
  351. {
  352. throw new ArgumentNullException("userId");
  353. }
  354. if (string.IsNullOrWhiteSpace(connectUsername))
  355. {
  356. throw new ArgumentNullException("connectUsername");
  357. }
  358. if (string.IsNullOrWhiteSpace(ConnectServerId))
  359. {
  360. throw new ArgumentNullException("ConnectServerId");
  361. }
  362. var connectUser = await GetConnectUser(new ConnectUserQuery
  363. {
  364. NameOrEmail = connectUsername
  365. }, CancellationToken.None).ConfigureAwait(false);
  366. if (!connectUser.IsActive)
  367. {
  368. throw new ArgumentException("The Emby account has been disabled.");
  369. }
  370. var user = GetUser(userId);
  371. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  372. {
  373. await RemoveConnect(user, connectUser.Id).ConfigureAwait(false);
  374. }
  375. var url = GetConnectUrl("ServerAuthorizations");
  376. var options = new HttpRequestOptions
  377. {
  378. Url = url,
  379. CancellationToken = CancellationToken.None
  380. };
  381. var accessToken = Guid.NewGuid().ToString("N");
  382. var postData = new Dictionary<string, string>
  383. {
  384. {"serverId", ConnectServerId},
  385. {"userId", connectUser.Id},
  386. {"userType", "Linked"},
  387. {"accessToken", accessToken}
  388. };
  389. options.SetPostData(postData);
  390. SetServerAccessToken(options);
  391. SetApplicationHeader(options);
  392. var result = new UserLinkResult();
  393. // No need to examine the response
  394. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  395. {
  396. var response = _json.DeserializeFromStream<ServerUserAuthorizationResponse>(stream);
  397. result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase);
  398. }
  399. user.ConnectAccessKey = accessToken;
  400. user.ConnectUserName = connectUser.Name;
  401. user.ConnectUserId = connectUser.Id;
  402. user.ConnectLinkType = UserLinkType.LinkedUser;
  403. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  404. await _userManager.UpdateConfiguration(user.Id.ToString("N"), user.Configuration);
  405. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  406. return result;
  407. }
  408. public async Task<UserLinkResult> InviteUser(ConnectAuthorizationRequest request)
  409. {
  410. if (string.IsNullOrWhiteSpace(ConnectServerId))
  411. {
  412. await UpdateConnectInfo().ConfigureAwait(false);
  413. }
  414. await _operationLock.WaitAsync().ConfigureAwait(false);
  415. try
  416. {
  417. return await InviteUserInternal(request).ConfigureAwait(false);
  418. }
  419. finally
  420. {
  421. _operationLock.Release();
  422. }
  423. }
  424. private async Task<UserLinkResult> InviteUserInternal(ConnectAuthorizationRequest request)
  425. {
  426. var connectUsername = request.ConnectUserName;
  427. var sendingUserId = request.SendingUserId;
  428. if (string.IsNullOrWhiteSpace(connectUsername))
  429. {
  430. throw new ArgumentNullException("connectUsername");
  431. }
  432. if (string.IsNullOrWhiteSpace(ConnectServerId))
  433. {
  434. throw new ArgumentNullException("ConnectServerId");
  435. }
  436. var sendingUser = GetUser(sendingUserId);
  437. var requesterUserName = sendingUser.ConnectUserName;
  438. if (string.IsNullOrWhiteSpace(requesterUserName))
  439. {
  440. throw new ArgumentException("A Connect account is required in order to send invitations.");
  441. }
  442. string connectUserId = null;
  443. var result = new UserLinkResult();
  444. try
  445. {
  446. var connectUser = await GetConnectUser(new ConnectUserQuery
  447. {
  448. NameOrEmail = connectUsername
  449. }, CancellationToken.None).ConfigureAwait(false);
  450. if (!connectUser.IsActive)
  451. {
  452. throw new ArgumentException("The Emby account is not active. Please ensure the account has been activated by following the instructions within the email confirmation.");
  453. }
  454. connectUserId = connectUser.Id;
  455. result.GuestDisplayName = connectUser.Name;
  456. }
  457. catch (HttpException ex)
  458. {
  459. if (!ex.StatusCode.HasValue)
  460. {
  461. throw;
  462. }
  463. // If they entered a username, then whatever the error is just throw it, for example, user not found
  464. if (!Validator.EmailIsValid(connectUsername))
  465. {
  466. if (ex.StatusCode.Value == HttpStatusCode.NotFound)
  467. {
  468. throw new ResourceNotFoundException();
  469. }
  470. throw;
  471. }
  472. if (ex.StatusCode.Value != HttpStatusCode.NotFound)
  473. {
  474. throw;
  475. }
  476. }
  477. if (string.IsNullOrWhiteSpace(connectUserId))
  478. {
  479. return await SendNewUserInvitation(requesterUserName, connectUsername).ConfigureAwait(false);
  480. }
  481. var url = GetConnectUrl("ServerAuthorizations");
  482. var options = new HttpRequestOptions
  483. {
  484. Url = url,
  485. CancellationToken = CancellationToken.None
  486. };
  487. var accessToken = Guid.NewGuid().ToString("N");
  488. var postData = new Dictionary<string, string>
  489. {
  490. {"serverId", ConnectServerId},
  491. {"userId", connectUserId},
  492. {"userType", "Guest"},
  493. {"accessToken", accessToken},
  494. {"requesterUserName", requesterUserName}
  495. };
  496. options.SetPostData(postData);
  497. SetServerAccessToken(options);
  498. SetApplicationHeader(options);
  499. // No need to examine the response
  500. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  501. {
  502. var response = _json.DeserializeFromStream<ServerUserAuthorizationResponse>(stream);
  503. result.IsPending = string.Equals(response.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase);
  504. _data.PendingAuthorizations.Add(new ConnectAuthorizationInternal
  505. {
  506. ConnectUserId = response.UserId,
  507. Id = response.Id,
  508. ImageUrl = response.UserImageUrl,
  509. UserName = response.UserName,
  510. EnabledLibraries = request.EnabledLibraries,
  511. EnabledChannels = request.EnabledChannels,
  512. EnableLiveTv = request.EnableLiveTv,
  513. AccessToken = accessToken
  514. });
  515. CacheData();
  516. }
  517. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  518. return result;
  519. }
  520. private async Task<UserLinkResult> SendNewUserInvitation(string fromName, string email)
  521. {
  522. var url = GetConnectUrl("users/invite");
  523. var options = new HttpRequestOptions
  524. {
  525. Url = url,
  526. CancellationToken = CancellationToken.None
  527. };
  528. var postData = new Dictionary<string, string>
  529. {
  530. {"email", email},
  531. {"requesterUserName", fromName}
  532. };
  533. options.SetPostData(postData);
  534. SetApplicationHeader(options);
  535. // No need to examine the response
  536. using (var stream = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  537. {
  538. }
  539. return new UserLinkResult
  540. {
  541. IsNewUserInvitation = true,
  542. GuestDisplayName = email
  543. };
  544. }
  545. public Task RemoveConnect(string userId)
  546. {
  547. var user = GetUser(userId);
  548. return RemoveConnect(user, user.ConnectUserId);
  549. }
  550. private async Task RemoveConnect(User user, string connectUserId)
  551. {
  552. if (!string.IsNullOrWhiteSpace(connectUserId))
  553. {
  554. await CancelAuthorizationByConnectUserId(connectUserId).ConfigureAwait(false);
  555. }
  556. user.ConnectAccessKey = null;
  557. user.ConnectUserName = null;
  558. user.ConnectUserId = null;
  559. user.ConnectLinkType = null;
  560. await user.UpdateToRepository(ItemUpdateType.MetadataEdit, CancellationToken.None).ConfigureAwait(false);
  561. }
  562. private async Task<ConnectUser> GetConnectUser(ConnectUserQuery query, CancellationToken cancellationToken)
  563. {
  564. var url = GetConnectUrl("user");
  565. if (!string.IsNullOrWhiteSpace(query.Id))
  566. {
  567. url = url + "?id=" + WebUtility.UrlEncode(query.Id);
  568. }
  569. else if (!string.IsNullOrWhiteSpace(query.NameOrEmail))
  570. {
  571. url = url + "?nameOrEmail=" + WebUtility.UrlEncode(query.NameOrEmail);
  572. }
  573. else if (!string.IsNullOrWhiteSpace(query.Name))
  574. {
  575. url = url + "?name=" + WebUtility.UrlEncode(query.Name);
  576. }
  577. else if (!string.IsNullOrWhiteSpace(query.Email))
  578. {
  579. url = url + "?name=" + WebUtility.UrlEncode(query.Email);
  580. }
  581. else
  582. {
  583. throw new ArgumentException("Empty ConnectUserQuery supplied");
  584. }
  585. var options = new HttpRequestOptions
  586. {
  587. CancellationToken = cancellationToken,
  588. Url = url
  589. };
  590. SetServerAccessToken(options);
  591. SetApplicationHeader(options);
  592. using (var stream = await _httpClient.Get(options).ConfigureAwait(false))
  593. {
  594. var response = _json.DeserializeFromStream<GetConnectUserResponse>(stream);
  595. return new ConnectUser
  596. {
  597. Email = response.Email,
  598. Id = response.Id,
  599. Name = response.Name,
  600. IsActive = response.IsActive,
  601. ImageUrl = response.ImageUrl
  602. };
  603. }
  604. }
  605. private void SetApplicationHeader(HttpRequestOptions options)
  606. {
  607. options.RequestHeaders.Add("X-Application", XApplicationValue);
  608. }
  609. private void SetServerAccessToken(HttpRequestOptions options)
  610. {
  611. if (string.IsNullOrWhiteSpace(ConnectAccessKey))
  612. {
  613. throw new ArgumentNullException("ConnectAccessKey");
  614. }
  615. options.RequestHeaders.Add("X-Connect-Token", ConnectAccessKey);
  616. }
  617. public async Task RefreshAuthorizations(CancellationToken cancellationToken)
  618. {
  619. await _operationLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  620. try
  621. {
  622. await RefreshAuthorizationsInternal(true, cancellationToken).ConfigureAwait(false);
  623. }
  624. finally
  625. {
  626. _operationLock.Release();
  627. }
  628. }
  629. private async Task RefreshAuthorizationsInternal(bool refreshImages, CancellationToken cancellationToken)
  630. {
  631. if (string.IsNullOrWhiteSpace(ConnectServerId))
  632. {
  633. throw new ArgumentNullException("ConnectServerId");
  634. }
  635. var url = GetConnectUrl("ServerAuthorizations");
  636. url += "?serverId=" + ConnectServerId;
  637. var options = new HttpRequestOptions
  638. {
  639. Url = url,
  640. CancellationToken = cancellationToken
  641. };
  642. SetServerAccessToken(options);
  643. SetApplicationHeader(options);
  644. try
  645. {
  646. using (var stream = (await _httpClient.SendAsync(options, "GET").ConfigureAwait(false)).Content)
  647. {
  648. var list = _json.DeserializeFromStream<List<ServerUserAuthorizationResponse>>(stream);
  649. await RefreshAuthorizations(list, refreshImages).ConfigureAwait(false);
  650. }
  651. }
  652. catch (Exception ex)
  653. {
  654. _logger.ErrorException("Error refreshing server authorizations.", ex);
  655. }
  656. }
  657. private readonly SemaphoreSlim _connectImageSemaphore = new SemaphoreSlim(5, 5);
  658. private async Task RefreshAuthorizations(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  659. {
  660. var users = _userManager.Users.ToList();
  661. // Handle existing authorizations that were removed by the Connect server
  662. // Handle existing authorizations whose status may have been updated
  663. foreach (var user in users)
  664. {
  665. if (!string.IsNullOrWhiteSpace(user.ConnectUserId))
  666. {
  667. var connectEntry = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.OrdinalIgnoreCase));
  668. if (connectEntry == null)
  669. {
  670. var deleteUser = user.ConnectLinkType.HasValue &&
  671. user.ConnectLinkType.Value == UserLinkType.Guest;
  672. user.ConnectUserId = null;
  673. user.ConnectAccessKey = null;
  674. user.ConnectUserName = null;
  675. user.ConnectLinkType = null;
  676. await _userManager.UpdateUser(user).ConfigureAwait(false);
  677. if (deleteUser)
  678. {
  679. _logger.Debug("Deleting guest user {0}", user.Name);
  680. await _userManager.DeleteUser(user).ConfigureAwait(false);
  681. }
  682. }
  683. else
  684. {
  685. var changed = !string.Equals(user.ConnectAccessKey, connectEntry.AccessToken, StringComparison.OrdinalIgnoreCase);
  686. if (changed)
  687. {
  688. user.ConnectUserId = connectEntry.UserId;
  689. user.ConnectAccessKey = connectEntry.AccessToken;
  690. await _userManager.UpdateUser(user).ConfigureAwait(false);
  691. }
  692. }
  693. }
  694. }
  695. var currentPendingList = _data.PendingAuthorizations.ToList();
  696. var newPendingList = new List<ConnectAuthorizationInternal>();
  697. foreach (var connectEntry in list)
  698. {
  699. if (string.Equals(connectEntry.UserType, "guest", StringComparison.OrdinalIgnoreCase))
  700. {
  701. var currentPendingEntry = currentPendingList.FirstOrDefault(i => string.Equals(i.Id, connectEntry.Id, StringComparison.OrdinalIgnoreCase));
  702. if (string.Equals(connectEntry.AcceptStatus, "accepted", StringComparison.OrdinalIgnoreCase))
  703. {
  704. var user = _userManager.Users
  705. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectEntry.UserId, StringComparison.OrdinalIgnoreCase));
  706. if (user == null)
  707. {
  708. // Add user
  709. user = await _userManager.CreateUser(_userManager.MakeValidUsername(connectEntry.UserName)).ConfigureAwait(false);
  710. user.ConnectUserName = connectEntry.UserName;
  711. user.ConnectUserId = connectEntry.UserId;
  712. user.ConnectLinkType = UserLinkType.Guest;
  713. user.ConnectAccessKey = connectEntry.AccessToken;
  714. await _userManager.UpdateUser(user).ConfigureAwait(false);
  715. user.Policy.IsHidden = true;
  716. user.Policy.EnableLiveTvManagement = false;
  717. user.Policy.EnableContentDeletion = false;
  718. user.Policy.EnableRemoteControlOfOtherUsers = false;
  719. user.Policy.EnableSharedDeviceControl = false;
  720. user.Policy.IsAdministrator = false;
  721. if (currentPendingEntry != null)
  722. {
  723. user.Policy.EnabledFolders = currentPendingEntry.EnabledLibraries;
  724. user.Policy.EnableAllFolders = false;
  725. user.Policy.EnabledChannels = currentPendingEntry.EnabledChannels;
  726. user.Policy.EnableAllChannels = false;
  727. user.Policy.EnableLiveTvAccess = currentPendingEntry.EnableLiveTv;
  728. }
  729. await _userManager.UpdateConfiguration(user.Id.ToString("N"), user.Configuration);
  730. }
  731. }
  732. else if (string.Equals(connectEntry.AcceptStatus, "waiting", StringComparison.OrdinalIgnoreCase))
  733. {
  734. currentPendingEntry = currentPendingEntry ?? new ConnectAuthorizationInternal();
  735. currentPendingEntry.ConnectUserId = connectEntry.UserId;
  736. currentPendingEntry.ImageUrl = connectEntry.UserImageUrl;
  737. currentPendingEntry.UserName = connectEntry.UserName;
  738. currentPendingEntry.Id = connectEntry.Id;
  739. currentPendingEntry.AccessToken = connectEntry.AccessToken;
  740. newPendingList.Add(currentPendingEntry);
  741. }
  742. }
  743. }
  744. _data.PendingAuthorizations = newPendingList;
  745. CacheData();
  746. await RefreshGuestNames(list, refreshImages).ConfigureAwait(false);
  747. }
  748. private async Task RefreshGuestNames(List<ServerUserAuthorizationResponse> list, bool refreshImages)
  749. {
  750. var users = _userManager.Users
  751. .Where(i => !string.IsNullOrEmpty(i.ConnectUserId) && i.ConnectLinkType.HasValue && i.ConnectLinkType.Value == UserLinkType.Guest)
  752. .ToList();
  753. foreach (var user in users)
  754. {
  755. var authorization = list.FirstOrDefault(i => string.Equals(i.UserId, user.ConnectUserId, StringComparison.Ordinal));
  756. if (authorization == null)
  757. {
  758. _logger.Warn("Unable to find connect authorization record for user {0}", user.Name);
  759. continue;
  760. }
  761. var syncConnectName = true;
  762. var syncConnectImage = true;
  763. if (syncConnectName)
  764. {
  765. var changed = !string.Equals(authorization.UserName, user.Name, StringComparison.OrdinalIgnoreCase);
  766. if (changed)
  767. {
  768. await user.Rename(authorization.UserName).ConfigureAwait(false);
  769. }
  770. }
  771. if (syncConnectImage)
  772. {
  773. var imageUrl = authorization.UserImageUrl;
  774. if (!string.IsNullOrWhiteSpace(imageUrl))
  775. {
  776. var changed = false;
  777. if (!user.HasImage(ImageType.Primary))
  778. {
  779. changed = true;
  780. }
  781. else if (refreshImages)
  782. {
  783. using (var response = await _httpClient.SendAsync(new HttpRequestOptions
  784. {
  785. Url = imageUrl,
  786. BufferContent = false
  787. }, "HEAD").ConfigureAwait(false))
  788. {
  789. var length = response.ContentLength;
  790. if (length != _fileSystem.GetFileInfo(user.GetImageInfo(ImageType.Primary, 0).Path).Length)
  791. {
  792. changed = true;
  793. }
  794. }
  795. }
  796. if (changed)
  797. {
  798. await _providerManager.SaveImage(user, imageUrl, _connectImageSemaphore, ImageType.Primary, null, CancellationToken.None).ConfigureAwait(false);
  799. await user.RefreshMetadata(new MetadataRefreshOptions(_fileSystem)
  800. {
  801. ForceSave = true,
  802. }, CancellationToken.None).ConfigureAwait(false);
  803. }
  804. }
  805. }
  806. }
  807. }
  808. public async Task<List<ConnectAuthorization>> GetPendingGuests()
  809. {
  810. var time = DateTime.UtcNow - _data.LastAuthorizationsRefresh;
  811. if (time.TotalMinutes >= 5)
  812. {
  813. await _operationLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  814. try
  815. {
  816. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  817. _data.LastAuthorizationsRefresh = DateTime.UtcNow;
  818. CacheData();
  819. }
  820. catch (Exception ex)
  821. {
  822. _logger.ErrorException("Error refreshing authorization", ex);
  823. }
  824. finally
  825. {
  826. _operationLock.Release();
  827. }
  828. }
  829. return _data.PendingAuthorizations.Select(i => new ConnectAuthorization
  830. {
  831. ConnectUserId = i.ConnectUserId,
  832. EnableLiveTv = i.EnableLiveTv,
  833. EnabledChannels = i.EnabledChannels,
  834. EnabledLibraries = i.EnabledLibraries,
  835. Id = i.Id,
  836. ImageUrl = i.ImageUrl,
  837. UserName = i.UserName
  838. }).ToList();
  839. }
  840. public async Task CancelAuthorization(string id)
  841. {
  842. await _operationLock.WaitAsync().ConfigureAwait(false);
  843. try
  844. {
  845. await CancelAuthorizationInternal(id).ConfigureAwait(false);
  846. }
  847. finally
  848. {
  849. _operationLock.Release();
  850. }
  851. }
  852. private async Task CancelAuthorizationInternal(string id)
  853. {
  854. var connectUserId = _data.PendingAuthorizations
  855. .First(i => string.Equals(i.Id, id, StringComparison.Ordinal))
  856. .ConnectUserId;
  857. await CancelAuthorizationByConnectUserId(connectUserId).ConfigureAwait(false);
  858. await RefreshAuthorizationsInternal(false, CancellationToken.None).ConfigureAwait(false);
  859. }
  860. private async Task CancelAuthorizationByConnectUserId(string connectUserId)
  861. {
  862. if (string.IsNullOrWhiteSpace(connectUserId))
  863. {
  864. throw new ArgumentNullException("connectUserId");
  865. }
  866. if (string.IsNullOrWhiteSpace(ConnectServerId))
  867. {
  868. throw new ArgumentNullException("ConnectServerId");
  869. }
  870. var url = GetConnectUrl("ServerAuthorizations");
  871. var options = new HttpRequestOptions
  872. {
  873. Url = url,
  874. CancellationToken = CancellationToken.None
  875. };
  876. var postData = new Dictionary<string, string>
  877. {
  878. {"serverId", ConnectServerId},
  879. {"userId", connectUserId}
  880. };
  881. options.SetPostData(postData);
  882. SetServerAccessToken(options);
  883. SetApplicationHeader(options);
  884. try
  885. {
  886. // No need to examine the response
  887. using (var stream = (await _httpClient.SendAsync(options, "DELETE").ConfigureAwait(false)).Content)
  888. {
  889. }
  890. }
  891. catch (HttpException ex)
  892. {
  893. // If connect says the auth doesn't exist, we can handle that gracefully since this is a remove operation
  894. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  895. {
  896. throw;
  897. }
  898. _logger.Debug("Connect returned a 404 when removing a user auth link. Handling it.");
  899. }
  900. }
  901. public async Task Authenticate(string username, string passwordMd5)
  902. {
  903. if (string.IsNullOrWhiteSpace(username))
  904. {
  905. throw new ArgumentNullException("username");
  906. }
  907. if (string.IsNullOrWhiteSpace(passwordMd5))
  908. {
  909. throw new ArgumentNullException("passwordMd5");
  910. }
  911. var options = new HttpRequestOptions
  912. {
  913. Url = GetConnectUrl("user/authenticate")
  914. };
  915. options.SetPostData(new Dictionary<string, string>
  916. {
  917. {"userName",username},
  918. {"password",passwordMd5}
  919. });
  920. SetApplicationHeader(options);
  921. // No need to examine the response
  922. using (var response = (await _httpClient.SendAsync(options, "POST").ConfigureAwait(false)).Content)
  923. {
  924. }
  925. }
  926. public async Task<User> GetLocalUser(string connectUserId)
  927. {
  928. var user = _userManager.Users
  929. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUserId, StringComparison.OrdinalIgnoreCase));
  930. if (user == null)
  931. {
  932. await RefreshAuthorizations(CancellationToken.None).ConfigureAwait(false);
  933. }
  934. return _userManager.Users
  935. .FirstOrDefault(i => string.Equals(i.ConnectUserId, connectUserId, StringComparison.OrdinalIgnoreCase));
  936. }
  937. public User GetUserFromExchangeToken(string token)
  938. {
  939. if (string.IsNullOrWhiteSpace(token))
  940. {
  941. throw new ArgumentNullException("token");
  942. }
  943. return _userManager.Users.FirstOrDefault(u => string.Equals(token, u.ConnectAccessKey, StringComparison.OrdinalIgnoreCase));
  944. }
  945. public bool IsAuthorizationTokenValid(string token)
  946. {
  947. if (string.IsNullOrWhiteSpace(token))
  948. {
  949. throw new ArgumentNullException("token");
  950. }
  951. return _userManager.Users.Any(u => string.Equals(token, u.ConnectAccessKey, StringComparison.OrdinalIgnoreCase)) ||
  952. _data.PendingAuthorizations.Select(i => i.AccessToken).Contains(token, StringComparer.OrdinalIgnoreCase);
  953. }
  954. }
  955. }