2
0

ConnectManager.cs 39 KB

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