ConnectManager.cs 39 KB

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