ConnectManager.cs 40 KB

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