ApiClient.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. using MediaBrowser.Model.Configuration;
  2. using MediaBrowser.Model.Dto;
  3. using MediaBrowser.Model.Entities;
  4. using MediaBrowser.Model.Globalization;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Plugins;
  7. using MediaBrowser.Model.System;
  8. using MediaBrowser.Model.Tasks;
  9. using MediaBrowser.Model.Weather;
  10. using MediaBrowser.Model.Web;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.ApiInteraction
  18. {
  19. /// <summary>
  20. /// Provides api methods centered around an HttpClient
  21. /// </summary>
  22. public class ApiClient : BaseApiClient
  23. {
  24. /// <summary>
  25. /// Gets the HTTP client.
  26. /// </summary>
  27. /// <value>The HTTP client.</value>
  28. protected IAsyncHttpClient HttpClient { get; private set; }
  29. /// <summary>
  30. /// Initializes a new instance of the <see cref="ApiClient" /> class.
  31. /// </summary>
  32. /// <param name="logger">The logger.</param>
  33. /// <param name="httpClient">The HTTP client.</param>
  34. /// <exception cref="System.ArgumentNullException">httpClient</exception>
  35. public ApiClient(ILogger logger, IAsyncHttpClient httpClient)
  36. : base(logger)
  37. {
  38. if (httpClient == null)
  39. {
  40. throw new ArgumentNullException("httpClient");
  41. }
  42. HttpClient = httpClient;
  43. }
  44. /// <summary>
  45. /// Sets the authorization header.
  46. /// </summary>
  47. /// <param name="header">The header.</param>
  48. protected override void SetAuthorizationHeader(string header)
  49. {
  50. HttpClient.SetAuthorizationHeader(header);
  51. }
  52. /// <summary>
  53. /// Gets an image stream based on a url
  54. /// </summary>
  55. /// <param name="url">The URL.</param>
  56. /// <returns>Task{Stream}.</returns>
  57. /// <exception cref="System.ArgumentNullException">url</exception>
  58. public Task<Stream> GetImageStreamAsync(string url)
  59. {
  60. if (string.IsNullOrEmpty(url))
  61. {
  62. throw new ArgumentNullException("url");
  63. }
  64. return HttpClient.GetStreamAsync(url, Logger, CancellationToken.None);
  65. }
  66. /// <summary>
  67. /// Gets a BaseItem
  68. /// </summary>
  69. /// <param name="id">The id.</param>
  70. /// <param name="userId">The user id.</param>
  71. /// <returns>Task{BaseItemDto}.</returns>
  72. /// <exception cref="System.ArgumentNullException">id</exception>
  73. public async Task<BaseItemDto> GetItemAsync(string id, Guid userId)
  74. {
  75. if (string.IsNullOrEmpty(id))
  76. {
  77. throw new ArgumentNullException("id");
  78. }
  79. if (userId == Guid.Empty)
  80. {
  81. throw new ArgumentNullException("userId");
  82. }
  83. var url = GetApiUrl("Users/" + userId + "/Items/" + id);
  84. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  85. {
  86. return DeserializeFromStream<BaseItemDto>(stream);
  87. }
  88. }
  89. /// <summary>
  90. /// Gets the intros async.
  91. /// </summary>
  92. /// <param name="itemId">The item id.</param>
  93. /// <param name="userId">The user id.</param>
  94. /// <returns>Task{System.String[]}.</returns>
  95. /// <exception cref="System.ArgumentNullException">id</exception>
  96. public async Task<string[]> GetIntrosAsync(string itemId, Guid userId)
  97. {
  98. if (string.IsNullOrEmpty(itemId))
  99. {
  100. throw new ArgumentNullException("itemId");
  101. }
  102. if (userId == Guid.Empty)
  103. {
  104. throw new ArgumentNullException("userId");
  105. }
  106. var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/Intros");
  107. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  108. {
  109. return DeserializeFromStream<string[]>(stream);
  110. }
  111. }
  112. /// <summary>
  113. /// Gets a BaseItem
  114. /// </summary>
  115. /// <param name="userId">The user id.</param>
  116. /// <returns>Task{BaseItemDto}.</returns>
  117. /// <exception cref="System.ArgumentNullException">userId</exception>
  118. public async Task<BaseItemDto> GetRootFolderAsync(Guid userId)
  119. {
  120. if (userId == Guid.Empty)
  121. {
  122. throw new ArgumentNullException("userId");
  123. }
  124. var url = GetApiUrl("Users/" + userId + "/Items/Root");
  125. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  126. {
  127. return DeserializeFromStream<BaseItemDto>(stream);
  128. }
  129. }
  130. /// <summary>
  131. /// Gets all Users
  132. /// </summary>
  133. /// <returns>Task{UserDto[]}.</returns>
  134. public async Task<UserDto[]> GetAllUsersAsync()
  135. {
  136. var url = GetApiUrl("Users");
  137. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  138. {
  139. return DeserializeFromStream<UserDto[]>(stream);
  140. }
  141. }
  142. /// <summary>
  143. /// Queries for items
  144. /// </summary>
  145. /// <param name="query">The query.</param>
  146. /// <returns>Task{ItemsResult}.</returns>
  147. /// <exception cref="System.ArgumentNullException">query</exception>
  148. public async Task<ItemsResult> GetItemsAsync(ItemQuery query)
  149. {
  150. if (query == null)
  151. {
  152. throw new ArgumentNullException("query");
  153. }
  154. var url = GetItemListUrl(query);
  155. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  156. {
  157. return DeserializeFromStream<ItemsResult>(stream);
  158. }
  159. }
  160. /// <summary>
  161. /// Gets all People
  162. /// </summary>
  163. /// <param name="userId">The user id.</param>
  164. /// <param name="itemId">Optional itemId, to localize the search to a specific item or folder</param>
  165. /// <param name="personTypes">Use this to limit results to specific person types</param>
  166. /// <param name="startIndex">Used to skip over a given number of items. Use if paging.</param>
  167. /// <param name="limit">The maximum number of items to return</param>
  168. /// <param name="sortOrder">The sort order</param>
  169. /// <param name="recursive">if set to true items will be searched recursively.</param>
  170. /// <returns>Task{IbnItemsResult}.</returns>
  171. /// <exception cref="System.ArgumentNullException">userId</exception>
  172. public async Task<ItemsResult> GetAllPeopleAsync(
  173. Guid userId,
  174. string itemId = null,
  175. IEnumerable<string> personTypes = null,
  176. int? startIndex = null,
  177. int? limit = null,
  178. SortOrder? sortOrder = null,
  179. bool recursive = false)
  180. {
  181. if (userId == Guid.Empty)
  182. {
  183. throw new ArgumentNullException("userId");
  184. }
  185. var dict = new QueryStringDictionary();
  186. dict.AddIfNotNull("startIndex", startIndex);
  187. dict.AddIfNotNull("limit", limit);
  188. dict.Add("recursive", recursive);
  189. if (sortOrder.HasValue)
  190. {
  191. dict["sortOrder"] = sortOrder.Value.ToString();
  192. }
  193. dict.AddIfNotNull("personTypes", personTypes);
  194. var url = string.IsNullOrEmpty(itemId) ? "Users/" + userId + "/Items/Root/Persons" : "Users/" + userId + "/Items/" + itemId + "/Persons";
  195. url = GetApiUrl(url, dict);
  196. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  197. {
  198. return DeserializeFromStream<ItemsResult>(stream);
  199. }
  200. }
  201. /// <summary>
  202. /// Gets a studio
  203. /// </summary>
  204. /// <param name="name">The name.</param>
  205. /// <returns>Task{BaseItemDto}.</returns>
  206. /// <exception cref="System.ArgumentNullException">userId</exception>
  207. public async Task<BaseItemDto> GetStudioAsync(string name)
  208. {
  209. if (string.IsNullOrEmpty(name))
  210. {
  211. throw new ArgumentNullException("name");
  212. }
  213. var url = GetApiUrl("Library/Studios/" + name);
  214. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  215. {
  216. return DeserializeFromStream<BaseItemDto>(stream);
  217. }
  218. }
  219. /// <summary>
  220. /// Gets a genre
  221. /// </summary>
  222. /// <param name="name">The name.</param>
  223. /// <returns>Task{BaseItemDto}.</returns>
  224. /// <exception cref="System.ArgumentNullException">userId</exception>
  225. public async Task<BaseItemDto> GetGenreAsync(string name)
  226. {
  227. if (string.IsNullOrEmpty(name))
  228. {
  229. throw new ArgumentNullException("name");
  230. }
  231. var url = GetApiUrl("Library/Genres/" + name);
  232. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  233. {
  234. return DeserializeFromStream<BaseItemDto>(stream);
  235. }
  236. }
  237. /// <summary>
  238. /// Restarts the kernel or the entire server if necessary
  239. /// If the server application is restarting this request will fail to return, even if
  240. /// the operation is successful.
  241. /// </summary>
  242. /// <returns>Task.</returns>
  243. public Task PerformPendingRestartAsync()
  244. {
  245. var url = GetApiUrl("System/Restart");
  246. return PostAsync<EmptyRequestResult>(url, new QueryStringDictionary());
  247. }
  248. /// <summary>
  249. /// Gets the system status async.
  250. /// </summary>
  251. /// <returns>Task{SystemInfo}.</returns>
  252. public async Task<SystemInfo> GetSystemInfoAsync()
  253. {
  254. var url = GetApiUrl("System/Info");
  255. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  256. {
  257. return DeserializeFromStream<SystemInfo>(stream);
  258. }
  259. }
  260. /// <summary>
  261. /// Gets a person
  262. /// </summary>
  263. /// <param name="name">The name.</param>
  264. /// <returns>Task{BaseItemDto}.</returns>
  265. /// <exception cref="System.ArgumentNullException">userId</exception>
  266. public async Task<BaseItemDto> GetPersonAsync(string name)
  267. {
  268. if (string.IsNullOrEmpty(name))
  269. {
  270. throw new ArgumentNullException("name");
  271. }
  272. var url = GetApiUrl("Library/Persons/" + name);
  273. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  274. {
  275. return DeserializeFromStream<BaseItemDto>(stream);
  276. }
  277. }
  278. /// <summary>
  279. /// Gets a year
  280. /// </summary>
  281. /// <param name="year">The year.</param>
  282. /// <returns>Task{BaseItemDto}.</returns>
  283. /// <exception cref="System.ArgumentNullException">userId</exception>
  284. public async Task<BaseItemDto> GetYearAsync(int year)
  285. {
  286. var url = GetApiUrl("Library/Years/" + year);
  287. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  288. {
  289. return DeserializeFromStream<BaseItemDto>(stream);
  290. }
  291. }
  292. /// <summary>
  293. /// Gets a list of plugins installed on the server
  294. /// </summary>
  295. /// <returns>Task{PluginInfo[]}.</returns>
  296. public async Task<PluginInfo[]> GetInstalledPluginsAsync()
  297. {
  298. var url = GetApiUrl("Plugins");
  299. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  300. {
  301. return DeserializeFromStream<PluginInfo[]>(stream);
  302. }
  303. }
  304. /// <summary>
  305. /// Gets a list of plugins installed on the server
  306. /// </summary>
  307. /// <param name="plugin">The plugin.</param>
  308. /// <returns>Task{Stream}.</returns>
  309. /// <exception cref="System.ArgumentNullException">plugin</exception>
  310. public Task<Stream> GetPluginAssemblyAsync(PluginInfo plugin)
  311. {
  312. if (plugin == null)
  313. {
  314. throw new ArgumentNullException("plugin");
  315. }
  316. var url = GetApiUrl("Plugins/" + plugin.Id + "/Assembly");
  317. return HttpClient.GetStreamAsync(url, Logger, CancellationToken.None);
  318. }
  319. /// <summary>
  320. /// Gets the current server configuration
  321. /// </summary>
  322. /// <returns>Task{ServerConfiguration}.</returns>
  323. public async Task<ServerConfiguration> GetServerConfigurationAsync()
  324. {
  325. var url = GetApiUrl("System/Configuration");
  326. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  327. {
  328. return DeserializeFromStream<ServerConfiguration>(stream);
  329. }
  330. }
  331. /// <summary>
  332. /// Gets the scheduled tasks.
  333. /// </summary>
  334. /// <returns>Task{TaskInfo[]}.</returns>
  335. public async Task<TaskInfo[]> GetScheduledTasksAsync()
  336. {
  337. var url = GetApiUrl("ScheduledTasks");
  338. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  339. {
  340. return DeserializeFromStream<TaskInfo[]>(stream);
  341. }
  342. }
  343. /// <summary>
  344. /// Gets the scheduled task async.
  345. /// </summary>
  346. /// <param name="id">The id.</param>
  347. /// <returns>Task{TaskInfo}.</returns>
  348. /// <exception cref="System.ArgumentNullException">id</exception>
  349. public async Task<TaskInfo> GetScheduledTaskAsync(Guid id)
  350. {
  351. if (id == Guid.Empty)
  352. {
  353. throw new ArgumentNullException("id");
  354. }
  355. var url = GetApiUrl("ScheduledTasks/" + id);
  356. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  357. {
  358. return DeserializeFromStream<TaskInfo>(stream);
  359. }
  360. }
  361. /// <summary>
  362. /// Gets the plugin configuration file in plain text.
  363. /// </summary>
  364. /// <param name="pluginId">The plugin id.</param>
  365. /// <returns>Task{Stream}.</returns>
  366. /// <exception cref="System.ArgumentNullException">assemblyFileName</exception>
  367. public async Task<Stream> GetPluginConfigurationFileAsync(Guid pluginId)
  368. {
  369. if (pluginId == Guid.Empty)
  370. {
  371. throw new ArgumentNullException("pluginId");
  372. }
  373. var url = GetApiUrl("Plugins/" + pluginId + "/ConfigurationFile");
  374. return await HttpClient.GetStreamAsync(url, Logger, CancellationToken.None).ConfigureAwait(false);
  375. }
  376. /// <summary>
  377. /// Gets a user by id
  378. /// </summary>
  379. /// <param name="id">The id.</param>
  380. /// <returns>Task{UserDto}.</returns>
  381. /// <exception cref="System.ArgumentNullException">id</exception>
  382. public async Task<UserDto> GetUserAsync(Guid id)
  383. {
  384. if (id == Guid.Empty)
  385. {
  386. throw new ArgumentNullException("id");
  387. }
  388. var url = GetApiUrl("Users/" + id);
  389. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  390. {
  391. return DeserializeFromStream<UserDto>(stream);
  392. }
  393. }
  394. /// <summary>
  395. /// Gets the parental ratings async.
  396. /// </summary>
  397. /// <returns>Task{List{ParentalRating}}.</returns>
  398. public async Task<List<ParentalRating>> GetParentalRatingsAsync()
  399. {
  400. var url = GetApiUrl("Localization/ParentalRatings");
  401. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  402. {
  403. return DeserializeFromStream<List<ParentalRating>>(stream);
  404. }
  405. }
  406. /// <summary>
  407. /// Gets weather information for the default location as set in configuration
  408. /// </summary>
  409. /// <returns>Task{WeatherInfo}.</returns>
  410. public async Task<WeatherInfo> GetWeatherInfoAsync()
  411. {
  412. var url = GetApiUrl("Weather");
  413. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  414. {
  415. return DeserializeFromStream<WeatherInfo>(stream);
  416. }
  417. }
  418. /// <summary>
  419. /// Gets weather information for a specific location
  420. /// Location can be a US zipcode, or "city,state", "city,state,country", "city,country"
  421. /// It can also be an ip address, or "latitude,longitude"
  422. /// </summary>
  423. /// <param name="location">The location.</param>
  424. /// <returns>Task{WeatherInfo}.</returns>
  425. /// <exception cref="System.ArgumentNullException">location</exception>
  426. public async Task<WeatherInfo> GetWeatherInfoAsync(string location)
  427. {
  428. if (string.IsNullOrEmpty(location))
  429. {
  430. throw new ArgumentNullException("location");
  431. }
  432. var dict = new QueryStringDictionary();
  433. dict.Add("location", location);
  434. var url = GetApiUrl("Weather", dict);
  435. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  436. {
  437. return DeserializeFromStream<WeatherInfo>(stream);
  438. }
  439. }
  440. /// <summary>
  441. /// Gets local trailers for an item
  442. /// </summary>
  443. /// <param name="userId">The user id.</param>
  444. /// <param name="itemId">The item id.</param>
  445. /// <returns>Task{ItemsResult}.</returns>
  446. /// <exception cref="System.ArgumentNullException">query</exception>
  447. public async Task<BaseItemDto[]> GetLocalTrailersAsync(Guid userId, string itemId)
  448. {
  449. if (userId == Guid.Empty)
  450. {
  451. throw new ArgumentNullException("userId");
  452. }
  453. if (string.IsNullOrEmpty(itemId))
  454. {
  455. throw new ArgumentNullException("itemId");
  456. }
  457. var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/LocalTrailers");
  458. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  459. {
  460. return DeserializeFromStream<BaseItemDto[]>(stream);
  461. }
  462. }
  463. /// <summary>
  464. /// Gets special features for an item
  465. /// </summary>
  466. /// <param name="userId">The user id.</param>
  467. /// <param name="itemId">The item id.</param>
  468. /// <returns>Task{BaseItemDto[]}.</returns>
  469. /// <exception cref="System.ArgumentNullException">userId</exception>
  470. public async Task<BaseItemDto[]> GetSpecialFeaturesAsync(Guid userId, string itemId)
  471. {
  472. if (userId == Guid.Empty)
  473. {
  474. throw new ArgumentNullException("userId");
  475. }
  476. if (string.IsNullOrEmpty(itemId))
  477. {
  478. throw new ArgumentNullException("itemId");
  479. }
  480. var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/SpecialFeatures");
  481. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  482. {
  483. return DeserializeFromStream<BaseItemDto[]>(stream);
  484. }
  485. }
  486. /// <summary>
  487. /// Gets the cultures async.
  488. /// </summary>
  489. /// <returns>Task{CultureDto[]}.</returns>
  490. public async Task<CultureDto[]> GetCulturesAsync()
  491. {
  492. var url = GetApiUrl("Localization/Cultures");
  493. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  494. {
  495. return DeserializeFromStream<CultureDto[]>(stream);
  496. }
  497. }
  498. /// <summary>
  499. /// Gets the countries async.
  500. /// </summary>
  501. /// <returns>Task{CountryInfo[]}.</returns>
  502. public async Task<CountryInfo[]> GetCountriesAsync()
  503. {
  504. var url = GetApiUrl("Localization/Countries");
  505. using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
  506. {
  507. return DeserializeFromStream<CountryInfo[]>(stream);
  508. }
  509. }
  510. /// <summary>
  511. /// Marks an item as played or unplayed.
  512. /// This should not be used to update playstate following playback.
  513. /// There are separate playstate check-in methods for that. This should be used for a
  514. /// separate option to reset playstate.
  515. /// </summary>
  516. /// <param name="itemId">The item id.</param>
  517. /// <param name="userId">The user id.</param>
  518. /// <param name="wasPlayed">if set to <c>true</c> [was played].</param>
  519. /// <returns>Task.</returns>
  520. /// <exception cref="System.ArgumentNullException">itemId</exception>
  521. public Task UpdatePlayedStatusAsync(string itemId, Guid userId, bool wasPlayed)
  522. {
  523. if (string.IsNullOrEmpty(itemId))
  524. {
  525. throw new ArgumentNullException("itemId");
  526. }
  527. if (userId == Guid.Empty)
  528. {
  529. throw new ArgumentNullException("userId");
  530. }
  531. var url = GetApiUrl("Users/" + userId + "/PlayedItems/" + itemId);
  532. if (wasPlayed)
  533. {
  534. return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>());
  535. }
  536. return HttpClient.DeleteAsync(url, Logger, CancellationToken.None);
  537. }
  538. /// <summary>
  539. /// Updates the favorite status async.
  540. /// </summary>
  541. /// <param name="itemId">The item id.</param>
  542. /// <param name="userId">The user id.</param>
  543. /// <param name="isFavorite">if set to <c>true</c> [is favorite].</param>
  544. /// <returns>Task.</returns>
  545. /// <exception cref="System.ArgumentNullException">itemId</exception>
  546. public Task UpdateFavoriteStatusAsync(string itemId, Guid userId, bool isFavorite)
  547. {
  548. if (string.IsNullOrEmpty(itemId))
  549. {
  550. throw new ArgumentNullException("itemId");
  551. }
  552. if (userId == Guid.Empty)
  553. {
  554. throw new ArgumentNullException("userId");
  555. }
  556. var url = GetApiUrl("Users/" + userId + "/FavoriteItems/" + itemId);
  557. if (isFavorite)
  558. {
  559. return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>());
  560. }
  561. return HttpClient.DeleteAsync(url, Logger, CancellationToken.None);
  562. }
  563. /// <summary>
  564. /// Reports to the server that the user has begun playing an item
  565. /// </summary>
  566. /// <param name="itemId">The item id.</param>
  567. /// <param name="userId">The user id.</param>
  568. /// <returns>Task{UserItemDataDto}.</returns>
  569. /// <exception cref="System.ArgumentNullException">itemId</exception>
  570. public Task ReportPlaybackStartAsync(string itemId, Guid userId)
  571. {
  572. if (string.IsNullOrEmpty(itemId))
  573. {
  574. throw new ArgumentNullException("itemId");
  575. }
  576. if (userId == Guid.Empty)
  577. {
  578. throw new ArgumentNullException("userId");
  579. }
  580. var url = GetApiUrl("Users/" + userId + "/PlayingItems/" + itemId);
  581. return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>());
  582. }
  583. /// <summary>
  584. /// Reports playback progress to the server
  585. /// </summary>
  586. /// <param name="itemId">The item id.</param>
  587. /// <param name="userId">The user id.</param>
  588. /// <param name="positionTicks">The position ticks.</param>
  589. /// <returns>Task{UserItemDataDto}.</returns>
  590. /// <exception cref="System.ArgumentNullException">itemId</exception>
  591. public Task ReportPlaybackProgressAsync(string itemId, Guid userId, long? positionTicks)
  592. {
  593. if (string.IsNullOrEmpty(itemId))
  594. {
  595. throw new ArgumentNullException("itemId");
  596. }
  597. if (userId == Guid.Empty)
  598. {
  599. throw new ArgumentNullException("userId");
  600. }
  601. var dict = new QueryStringDictionary();
  602. dict.AddIfNotNull("positionTicks", positionTicks);
  603. var url = GetApiUrl("Users/" + userId + "/PlayingItems/" + itemId + "/Progress", dict);
  604. return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>());
  605. }
  606. /// <summary>
  607. /// Reports to the server that the user has stopped playing an item
  608. /// </summary>
  609. /// <param name="itemId">The item id.</param>
  610. /// <param name="userId">The user id.</param>
  611. /// <param name="positionTicks">The position ticks.</param>
  612. /// <returns>Task{UserItemDataDto}.</returns>
  613. /// <exception cref="System.ArgumentNullException">itemId</exception>
  614. public Task ReportPlaybackStoppedAsync(string itemId, Guid userId, long? positionTicks)
  615. {
  616. if (string.IsNullOrEmpty(itemId))
  617. {
  618. throw new ArgumentNullException("itemId");
  619. }
  620. if (userId == Guid.Empty)
  621. {
  622. throw new ArgumentNullException("userId");
  623. }
  624. var dict = new QueryStringDictionary();
  625. dict.AddIfNotNull("positionTicks", positionTicks);
  626. var url = GetApiUrl("Users/" + userId + "/PlayingItems/" + itemId, dict);
  627. return HttpClient.DeleteAsync(url, Logger, CancellationToken.None);
  628. }
  629. /// <summary>
  630. /// Clears a user's rating for an item
  631. /// </summary>
  632. /// <param name="itemId">The item id.</param>
  633. /// <param name="userId">The user id.</param>
  634. /// <returns>Task{UserItemDataDto}.</returns>
  635. /// <exception cref="System.ArgumentNullException">itemId</exception>
  636. public Task ClearUserItemRatingAsync(string itemId, Guid userId)
  637. {
  638. if (string.IsNullOrEmpty(itemId))
  639. {
  640. throw new ArgumentNullException("itemId");
  641. }
  642. if (userId == Guid.Empty)
  643. {
  644. throw new ArgumentNullException("userId");
  645. }
  646. var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/Rating");
  647. return HttpClient.DeleteAsync(url, Logger, CancellationToken.None);
  648. }
  649. /// <summary>
  650. /// Updates a user's rating for an item, based on likes or dislikes
  651. /// </summary>
  652. /// <param name="itemId">The item id.</param>
  653. /// <param name="userId">The user id.</param>
  654. /// <param name="likes">if set to <c>true</c> [likes].</param>
  655. /// <returns>Task{UserItemDataDto}.</returns>
  656. /// <exception cref="System.ArgumentNullException">itemId</exception>
  657. public Task<UserItemDataDto> UpdateUserItemRatingAsync(string itemId, Guid userId, bool likes)
  658. {
  659. if (string.IsNullOrEmpty(itemId))
  660. {
  661. throw new ArgumentNullException("itemId");
  662. }
  663. if (userId == Guid.Empty)
  664. {
  665. throw new ArgumentNullException("userId");
  666. }
  667. var dict = new QueryStringDictionary { };
  668. dict.Add("likes", likes);
  669. var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/Rating", dict);
  670. return PostAsync<UserItemDataDto>(url, new Dictionary<string, string>());
  671. }
  672. /// <summary>
  673. /// Authenticates a user and returns the result
  674. /// </summary>
  675. /// <param name="userId">The user id.</param>
  676. /// <param name="password">The password.</param>
  677. /// <exception cref="System.ArgumentNullException">userId</exception>
  678. public Task AuthenticateUserAsync(Guid userId, string password)
  679. {
  680. if (userId == Guid.Empty)
  681. {
  682. throw new ArgumentNullException("userId");
  683. }
  684. var url = GetApiUrl("Users/" + userId + "/Authenticate");
  685. var args = new Dictionary<string, string>();
  686. if (!string.IsNullOrEmpty(password))
  687. {
  688. args["password"] = password;
  689. }
  690. return PostAsync<EmptyRequestResult>(url, args);
  691. }
  692. /// <summary>
  693. /// Uploads the user image async.
  694. /// </summary>
  695. /// <param name="userId">The user id.</param>
  696. /// <param name="imageType">Type of the image.</param>
  697. /// <param name="image">The image.</param>
  698. /// <returns>Task{RequestResult}.</returns>
  699. /// <exception cref="System.NotImplementedException"></exception>
  700. public Task UploadUserImageAsync(Guid userId, ImageType imageType, Stream image)
  701. {
  702. // Implement when needed
  703. throw new NotImplementedException();
  704. }
  705. /// <summary>
  706. /// Updates the server configuration async.
  707. /// </summary>
  708. /// <param name="configuration">The configuration.</param>
  709. /// <returns>Task.</returns>
  710. /// <exception cref="System.ArgumentNullException">configuration</exception>
  711. public Task UpdateServerConfigurationAsync(ServerConfiguration configuration)
  712. {
  713. if (configuration == null)
  714. {
  715. throw new ArgumentNullException("configuration");
  716. }
  717. var url = GetApiUrl("System/Configuration");
  718. return PostAsync<ServerConfiguration, EmptyRequestResult>(url, configuration);
  719. }
  720. /// <summary>
  721. /// Updates the scheduled task triggers.
  722. /// </summary>
  723. /// <param name="id">The id.</param>
  724. /// <param name="triggers">The triggers.</param>
  725. /// <returns>Task{RequestResult}.</returns>
  726. /// <exception cref="System.ArgumentNullException">id</exception>
  727. public Task UpdateScheduledTaskTriggersAsync(Guid id, TaskTriggerInfo[] triggers)
  728. {
  729. if (id == Guid.Empty)
  730. {
  731. throw new ArgumentNullException("id");
  732. }
  733. if (triggers == null)
  734. {
  735. throw new ArgumentNullException("triggers");
  736. }
  737. var url = GetApiUrl("ScheduledTasks/" + id + "/Triggers");
  738. return PostAsync<TaskTriggerInfo[], EmptyRequestResult>(url, triggers);
  739. }
  740. /// <summary>
  741. /// Updates display preferences for a user
  742. /// </summary>
  743. /// <param name="userId">The user id.</param>
  744. /// <param name="itemId">The item id.</param>
  745. /// <param name="displayPreferences">The display preferences.</param>
  746. /// <returns>Task{DisplayPreferences}.</returns>
  747. /// <exception cref="System.ArgumentNullException">userId</exception>
  748. public Task UpdateDisplayPreferencesAsync(Guid userId, string itemId, DisplayPreferences displayPreferences)
  749. {
  750. if (userId == Guid.Empty)
  751. {
  752. throw new ArgumentNullException("userId");
  753. }
  754. if (string.IsNullOrEmpty(itemId))
  755. {
  756. throw new ArgumentNullException("itemId");
  757. }
  758. if (displayPreferences == null)
  759. {
  760. throw new ArgumentNullException("displayPreferences");
  761. }
  762. var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/DisplayPreferences");
  763. return PostAsync<DisplayPreferences, EmptyRequestResult>(url, displayPreferences);
  764. }
  765. /// <summary>
  766. /// Posts a set of data to a url, and deserializes the return stream into T
  767. /// </summary>
  768. /// <typeparam name="T"></typeparam>
  769. /// <param name="url">The URL.</param>
  770. /// <param name="args">The args.</param>
  771. /// <returns>Task{``0}.</returns>
  772. private Task<T> PostAsync<T>(string url, Dictionary<string, string> args)
  773. where T : class
  774. {
  775. return PostAsync<T>(url, args, SerializationFormat);
  776. }
  777. /// <summary>
  778. /// Posts a set of data to a url, and deserializes the return stream into T
  779. /// </summary>
  780. /// <typeparam name="T"></typeparam>
  781. /// <param name="url">The URL.</param>
  782. /// <param name="args">The args.</param>
  783. /// <param name="serializationFormat">The serialization format.</param>
  784. /// <returns>Task{``0}.</returns>
  785. private async Task<T> PostAsync<T>(string url, Dictionary<string, string> args, SerializationFormats serializationFormat)
  786. where T : class
  787. {
  788. url = AddDataFormat(url, serializationFormat);
  789. // Create the post body
  790. var strings = args.Keys.Select(key => string.Format("{0}={1}", key, args[key]));
  791. var postContent = string.Join("&", strings.ToArray());
  792. const string contentType = "application/x-www-form-urlencoded";
  793. using (var stream = await HttpClient.PostAsync(url, contentType, postContent, Logger, CancellationToken.None).ConfigureAwait(false))
  794. {
  795. return DeserializeFromStream<T>(stream);
  796. }
  797. }
  798. /// <summary>
  799. /// Posts an object of type TInputType to a given url, and deserializes the response into an object of type TOutputType
  800. /// </summary>
  801. /// <typeparam name="TInputType">The type of the T input type.</typeparam>
  802. /// <typeparam name="TOutputType">The type of the T output type.</typeparam>
  803. /// <param name="url">The URL.</param>
  804. /// <param name="obj">The obj.</param>
  805. /// <returns>Task{``1}.</returns>
  806. private Task<TOutputType> PostAsync<TInputType, TOutputType>(string url, TInputType obj)
  807. where TOutputType : class
  808. {
  809. return PostAsync<TInputType, TOutputType>(url, obj, SerializationFormat);
  810. }
  811. /// <summary>
  812. /// Posts an object of type TInputType to a given url, and deserializes the response into an object of type TOutputType
  813. /// </summary>
  814. /// <typeparam name="TInputType">The type of the T input type.</typeparam>
  815. /// <typeparam name="TOutputType">The type of the T output type.</typeparam>
  816. /// <param name="url">The URL.</param>
  817. /// <param name="obj">The obj.</param>
  818. /// <param name="serializationFormat">The serialization format.</param>
  819. /// <returns>Task{``1}.</returns>
  820. private async Task<TOutputType> PostAsync<TInputType, TOutputType>(string url, TInputType obj, SerializationFormats serializationFormat)
  821. where TOutputType : class
  822. {
  823. url = AddDataFormat(url, serializationFormat);
  824. const string contentType = "application/x-www-form-urlencoded";
  825. var postContent = DataSerializer.SerializeToJsonString(obj);
  826. using (var stream = await HttpClient.PostAsync(url, contentType, postContent, Logger, CancellationToken.None).ConfigureAwait(false))
  827. {
  828. return DeserializeFromStream<TOutputType>(stream);
  829. }
  830. }
  831. /// <summary>
  832. /// This is a helper around getting a stream from the server that contains serialized data
  833. /// </summary>
  834. /// <param name="url">The URL.</param>
  835. /// <returns>Task{Stream}.</returns>
  836. public Task<Stream> GetSerializedStreamAsync(string url)
  837. {
  838. return GetSerializedStreamAsync(url, SerializationFormat);
  839. }
  840. /// <summary>
  841. /// This is a helper around getting a stream from the server that contains serialized data
  842. /// </summary>
  843. /// <param name="url">The URL.</param>
  844. /// <param name="serializationFormat">The serialization format.</param>
  845. /// <returns>Task{Stream}.</returns>
  846. public Task<Stream> GetSerializedStreamAsync(string url, SerializationFormats serializationFormat)
  847. {
  848. url = AddDataFormat(url, serializationFormat);
  849. return HttpClient.GetStreamAsync(url, Logger, CancellationToken.None);
  850. }
  851. /// <summary>
  852. /// Adds the data format.
  853. /// </summary>
  854. /// <param name="url">The URL.</param>
  855. /// <param name="serializationFormat">The serialization format.</param>
  856. /// <returns>System.String.</returns>
  857. private string AddDataFormat(string url, SerializationFormats serializationFormat)
  858. {
  859. var format = serializationFormat == SerializationFormats.Protobuf ? "x-protobuf" : serializationFormat.ToString();
  860. if (url.IndexOf('?') == -1)
  861. {
  862. url += "?format=" + format;
  863. }
  864. else
  865. {
  866. url += "&format=" + format;
  867. }
  868. return url;
  869. }
  870. }
  871. }