ConnectManager.cs 44 KB

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