ConnectManager.cs 40 KB

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