ApiClient.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  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.UniqueId + "/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{DtoUserItemData}.</returns>
  569. /// <exception cref="System.ArgumentNullException">itemId</exception>
  570. public Task<UserItemDataDto> 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 dict = new QueryStringDictionary();
  581. dict.Add("id", itemId);
  582. dict.Add("userId", userId);
  583. dict.Add("type", "start");
  584. var url = GetApiUrl("playbackcheckin", dict);
  585. return PostAsync<UserItemDataDto>(url, new Dictionary<string, string>());
  586. }
  587. /// <summary>
  588. /// Reports playback progress to the server
  589. /// </summary>
  590. /// <param name="itemId">The item id.</param>
  591. /// <param name="userId">The user id.</param>
  592. /// <param name="positionTicks">The position ticks.</param>
  593. /// <returns>Task{DtoUserItemData}.</returns>
  594. /// <exception cref="System.ArgumentNullException">itemId</exception>
  595. public Task<UserItemDataDto> ReportPlaybackProgressAsync(string itemId, Guid userId, long? positionTicks)
  596. {
  597. if (string.IsNullOrEmpty(itemId))
  598. {
  599. throw new ArgumentNullException("itemId");
  600. }
  601. if (userId == Guid.Empty)
  602. {
  603. throw new ArgumentNullException("userId");
  604. }
  605. var dict = new QueryStringDictionary();
  606. dict.Add("id", itemId);
  607. dict.Add("userId", userId);
  608. dict.Add("type", "progress");
  609. dict.AddIfNotNull("positionTicks", positionTicks);
  610. var url = GetApiUrl("playbackcheckin", dict);
  611. return PostAsync<UserItemDataDto>(url, new Dictionary<string, string>());
  612. }
  613. /// <summary>
  614. /// Reports to the server that the user has stopped playing an item
  615. /// </summary>
  616. /// <param name="itemId">The item id.</param>
  617. /// <param name="userId">The user id.</param>
  618. /// <param name="positionTicks">The position ticks.</param>
  619. /// <returns>Task{DtoUserItemData}.</returns>
  620. /// <exception cref="System.ArgumentNullException">itemId</exception>
  621. public Task<UserItemDataDto> ReportPlaybackStoppedAsync(string itemId, Guid userId, long? positionTicks)
  622. {
  623. if (string.IsNullOrEmpty(itemId))
  624. {
  625. throw new ArgumentNullException("itemId");
  626. }
  627. if (userId == Guid.Empty)
  628. {
  629. throw new ArgumentNullException("userId");
  630. }
  631. var dict = new QueryStringDictionary();
  632. dict.Add("id", itemId);
  633. dict.Add("userId", userId);
  634. dict.Add("type", "stopped");
  635. dict.AddIfNotNull("positionTicks", positionTicks);
  636. var url = GetApiUrl("playbackcheckin", dict);
  637. return PostAsync<UserItemDataDto>(url, new Dictionary<string, string>());
  638. }
  639. /// <summary>
  640. /// Clears a user's rating for an item
  641. /// </summary>
  642. /// <param name="itemId">The item id.</param>
  643. /// <param name="userId">The user id.</param>
  644. /// <returns>Task{DtoUserItemData}.</returns>
  645. /// <exception cref="System.ArgumentNullException">itemId</exception>
  646. public Task ClearUserItemRatingAsync(string itemId, Guid userId)
  647. {
  648. if (string.IsNullOrEmpty(itemId))
  649. {
  650. throw new ArgumentNullException("itemId");
  651. }
  652. if (userId == Guid.Empty)
  653. {
  654. throw new ArgumentNullException("userId");
  655. }
  656. var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/Rating");
  657. return HttpClient.DeleteAsync(url, Logger, CancellationToken.None);
  658. }
  659. /// <summary>
  660. /// Updates a user's rating for an item, based on likes or dislikes
  661. /// </summary>
  662. /// <param name="itemId">The item id.</param>
  663. /// <param name="userId">The user id.</param>
  664. /// <param name="likes">if set to <c>true</c> [likes].</param>
  665. /// <returns>Task{DtoUserItemData}.</returns>
  666. /// <exception cref="System.ArgumentNullException">itemId</exception>
  667. public Task<UserItemDataDto> UpdateUserItemRatingAsync(string itemId, Guid userId, bool likes)
  668. {
  669. if (string.IsNullOrEmpty(itemId))
  670. {
  671. throw new ArgumentNullException("itemId");
  672. }
  673. if (userId == Guid.Empty)
  674. {
  675. throw new ArgumentNullException("userId");
  676. }
  677. var dict = new QueryStringDictionary { };
  678. dict.Add("likes", likes);
  679. var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/Rating", dict);
  680. return PostAsync<UserItemDataDto>(url, new Dictionary<string, string>());
  681. }
  682. /// <summary>
  683. /// Authenticates a user and returns the result
  684. /// </summary>
  685. /// <param name="userId">The user id.</param>
  686. /// <param name="password">The password.</param>
  687. /// <exception cref="System.ArgumentNullException">userId</exception>
  688. public Task AuthenticateUserAsync(Guid userId, string password)
  689. {
  690. if (userId == Guid.Empty)
  691. {
  692. throw new ArgumentNullException("userId");
  693. }
  694. var url = GetApiUrl("Users/" + userId + "/Authenticate");
  695. var args = new Dictionary<string, string>();
  696. if (!string.IsNullOrEmpty(password))
  697. {
  698. args["password"] = password;
  699. }
  700. return PostAsync<EmptyRequestResult>(url, args);
  701. }
  702. /// <summary>
  703. /// Uploads the user image async.
  704. /// </summary>
  705. /// <param name="userId">The user id.</param>
  706. /// <param name="imageType">Type of the image.</param>
  707. /// <param name="image">The image.</param>
  708. /// <returns>Task{RequestResult}.</returns>
  709. /// <exception cref="System.NotImplementedException"></exception>
  710. public Task UploadUserImageAsync(Guid userId, ImageType imageType, Stream image)
  711. {
  712. // Implement when needed
  713. throw new NotImplementedException();
  714. }
  715. /// <summary>
  716. /// Updates the server configuration async.
  717. /// </summary>
  718. /// <param name="configuration">The configuration.</param>
  719. /// <returns>Task.</returns>
  720. /// <exception cref="System.ArgumentNullException">configuration</exception>
  721. public Task UpdateServerConfigurationAsync(ServerConfiguration configuration)
  722. {
  723. if (configuration == null)
  724. {
  725. throw new ArgumentNullException("configuration");
  726. }
  727. var url = GetApiUrl("System/Configuration");
  728. return PostAsync<ServerConfiguration, EmptyRequestResult>(url, configuration);
  729. }
  730. /// <summary>
  731. /// Updates the scheduled task triggers.
  732. /// </summary>
  733. /// <param name="id">The id.</param>
  734. /// <param name="triggers">The triggers.</param>
  735. /// <returns>Task{RequestResult}.</returns>
  736. /// <exception cref="System.ArgumentNullException">id</exception>
  737. public Task UpdateScheduledTaskTriggersAsync(Guid id, TaskTriggerInfo[] triggers)
  738. {
  739. if (id == Guid.Empty)
  740. {
  741. throw new ArgumentNullException("id");
  742. }
  743. if (triggers == null)
  744. {
  745. throw new ArgumentNullException("triggers");
  746. }
  747. var url = GetApiUrl("ScheduledTasks/" + id + "/Triggers");
  748. return PostAsync<TaskTriggerInfo[], EmptyRequestResult>(url, triggers);
  749. }
  750. /// <summary>
  751. /// Adds a virtual folder to either the default view or a user view
  752. /// </summary>
  753. /// <param name="name">The name.</param>
  754. /// <param name="userId">The user id.</param>
  755. /// <returns>Task{RequestResult}.</returns>
  756. /// <exception cref="System.ArgumentNullException">name</exception>
  757. public Task AddVirtualFolderAsync(string name, Guid? userId = null)
  758. {
  759. if (string.IsNullOrEmpty(name))
  760. {
  761. throw new ArgumentNullException("name");
  762. }
  763. var dict = new QueryStringDictionary();
  764. dict.Add("name", name);
  765. dict.Add("action", "AddVirtualFolder");
  766. dict.AddIfNotNull("userId", userId);
  767. var url = GetApiUrl("UpdateMediaLibrary", dict);
  768. return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>());
  769. }
  770. /// <summary>
  771. /// Removes a virtual folder, within either the default view or a user view
  772. /// </summary>
  773. /// <param name="name">The name.</param>
  774. /// <param name="userId">The user id.</param>
  775. /// <returns>Task.</returns>
  776. /// <exception cref="System.ArgumentNullException">name</exception>
  777. public Task RemoveVirtualFolderAsync(string name, Guid? userId = null)
  778. {
  779. if (string.IsNullOrEmpty(name))
  780. {
  781. throw new ArgumentNullException("name");
  782. }
  783. var dict = new QueryStringDictionary();
  784. dict.Add("name", name);
  785. dict.Add("action", "RemoveVirtualFolder");
  786. dict.AddIfNotNull("userId", userId);
  787. var url = GetApiUrl("UpdateMediaLibrary", dict);
  788. return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>());
  789. }
  790. /// <summary>
  791. /// Renames a virtual folder, within either the default view or a user view
  792. /// </summary>
  793. /// <param name="name">The name.</param>
  794. /// <param name="newName">The new name.</param>
  795. /// <param name="userId">The user id.</param>
  796. /// <returns>Task.</returns>
  797. /// <exception cref="System.ArgumentNullException">name</exception>
  798. public Task RenameVirtualFolderAsync(string name, string newName, Guid? userId = null)
  799. {
  800. if (string.IsNullOrEmpty(name))
  801. {
  802. throw new ArgumentNullException("name");
  803. }
  804. if (string.IsNullOrEmpty(newName))
  805. {
  806. throw new ArgumentNullException("newName");
  807. }
  808. var dict = new QueryStringDictionary();
  809. dict.Add("name", name);
  810. dict.Add("newName", newName);
  811. dict.Add("action", "RenameVirtualFolder");
  812. dict.AddIfNotNull("userId", userId);
  813. var url = GetApiUrl("UpdateMediaLibrary", dict);
  814. return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>());
  815. }
  816. /// <summary>
  817. /// Adds a media path to a virtual folder, within either the default view or a user view
  818. /// </summary>
  819. /// <param name="virtualFolderName">Name of the virtual folder.</param>
  820. /// <param name="mediaPath">The media path.</param>
  821. /// <param name="userId">The user id.</param>
  822. /// <returns>Task.</returns>
  823. /// <exception cref="System.ArgumentNullException">virtualFolderName</exception>
  824. public Task AddMediaPathAsync(string virtualFolderName, string mediaPath, Guid? userId = null)
  825. {
  826. if (string.IsNullOrEmpty(virtualFolderName))
  827. {
  828. throw new ArgumentNullException("virtualFolderName");
  829. }
  830. if (string.IsNullOrEmpty(mediaPath))
  831. {
  832. throw new ArgumentNullException("mediaPath");
  833. }
  834. var dict = new QueryStringDictionary();
  835. dict.Add("virtualFolderName", virtualFolderName);
  836. dict.Add("mediaPath", mediaPath);
  837. dict.Add("action", "AddMediaPath");
  838. dict.AddIfNotNull("userId", userId);
  839. var url = GetApiUrl("UpdateMediaLibrary", dict);
  840. return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>());
  841. }
  842. /// <summary>
  843. /// Removes a media path from a virtual folder, within either the default view or a user view
  844. /// </summary>
  845. /// <param name="virtualFolderName">Name of the virtual folder.</param>
  846. /// <param name="mediaPath">The media path.</param>
  847. /// <param name="userId">The user id.</param>
  848. /// <returns>Task.</returns>
  849. /// <exception cref="System.ArgumentNullException">virtualFolderName</exception>
  850. public Task RemoveMediaPathAsync(string virtualFolderName, string mediaPath, Guid? userId = null)
  851. {
  852. if (string.IsNullOrEmpty(virtualFolderName))
  853. {
  854. throw new ArgumentNullException("virtualFolderName");
  855. }
  856. if (string.IsNullOrEmpty(mediaPath))
  857. {
  858. throw new ArgumentNullException("mediaPath");
  859. }
  860. var dict = new QueryStringDictionary();
  861. dict.Add("virtualFolderName", virtualFolderName);
  862. dict.Add("mediaPath", mediaPath);
  863. dict.Add("action", "RemoveMediaPath");
  864. dict.AddIfNotNull("userId", userId);
  865. var url = GetApiUrl("UpdateMediaLibrary", dict);
  866. return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>());
  867. }
  868. /// <summary>
  869. /// Updates display preferences for a user
  870. /// </summary>
  871. /// <param name="userId">The user id.</param>
  872. /// <param name="itemId">The item id.</param>
  873. /// <param name="displayPreferences">The display preferences.</param>
  874. /// <returns>Task{DisplayPreferences}.</returns>
  875. /// <exception cref="System.ArgumentNullException">userId</exception>
  876. public Task UpdateDisplayPreferencesAsync(Guid userId, string itemId, DisplayPreferences displayPreferences)
  877. {
  878. if (userId == Guid.Empty)
  879. {
  880. throw new ArgumentNullException("userId");
  881. }
  882. if (string.IsNullOrEmpty(itemId))
  883. {
  884. throw new ArgumentNullException("itemId");
  885. }
  886. if (displayPreferences == null)
  887. {
  888. throw new ArgumentNullException("displayPreferences");
  889. }
  890. var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/DisplayPreferences");
  891. return PostAsync<DisplayPreferences, EmptyRequestResult>(url, displayPreferences);
  892. }
  893. /// <summary>
  894. /// Posts a set of data to a url, and deserializes the return stream into T
  895. /// </summary>
  896. /// <typeparam name="T"></typeparam>
  897. /// <param name="url">The URL.</param>
  898. /// <param name="args">The args.</param>
  899. /// <returns>Task{``0}.</returns>
  900. private Task<T> PostAsync<T>(string url, Dictionary<string, string> args)
  901. where T : class
  902. {
  903. return PostAsync<T>(url, args, SerializationFormat);
  904. }
  905. /// <summary>
  906. /// Posts a set of data to a url, and deserializes the return stream into T
  907. /// </summary>
  908. /// <typeparam name="T"></typeparam>
  909. /// <param name="url">The URL.</param>
  910. /// <param name="args">The args.</param>
  911. /// <param name="serializationFormat">The serialization format.</param>
  912. /// <returns>Task{``0}.</returns>
  913. private async Task<T> PostAsync<T>(string url, Dictionary<string, string> args, SerializationFormats serializationFormat)
  914. where T : class
  915. {
  916. url = AddDataFormat(url, serializationFormat);
  917. // Create the post body
  918. var strings = args.Keys.Select(key => string.Format("{0}={1}", key, args[key]));
  919. var postContent = string.Join("&", strings.ToArray());
  920. const string contentType = "application/x-www-form-urlencoded";
  921. using (var stream = await HttpClient.PostAsync(url, contentType, postContent, Logger, CancellationToken.None).ConfigureAwait(false))
  922. {
  923. return DeserializeFromStream<T>(stream);
  924. }
  925. }
  926. /// <summary>
  927. /// Posts an object of type TInputType to a given url, and deserializes the response into an object of type TOutputType
  928. /// </summary>
  929. /// <typeparam name="TInputType">The type of the T input type.</typeparam>
  930. /// <typeparam name="TOutputType">The type of the T output type.</typeparam>
  931. /// <param name="url">The URL.</param>
  932. /// <param name="obj">The obj.</param>
  933. /// <returns>Task{``1}.</returns>
  934. private Task<TOutputType> PostAsync<TInputType, TOutputType>(string url, TInputType obj)
  935. where TOutputType : class
  936. {
  937. return PostAsync<TInputType, TOutputType>(url, obj, SerializationFormat);
  938. }
  939. /// <summary>
  940. /// Posts an object of type TInputType to a given url, and deserializes the response into an object of type TOutputType
  941. /// </summary>
  942. /// <typeparam name="TInputType">The type of the T input type.</typeparam>
  943. /// <typeparam name="TOutputType">The type of the T output type.</typeparam>
  944. /// <param name="url">The URL.</param>
  945. /// <param name="obj">The obj.</param>
  946. /// <param name="serializationFormat">The serialization format.</param>
  947. /// <returns>Task{``1}.</returns>
  948. private async Task<TOutputType> PostAsync<TInputType, TOutputType>(string url, TInputType obj, SerializationFormats serializationFormat)
  949. where TOutputType : class
  950. {
  951. url = AddDataFormat(url, serializationFormat);
  952. const string contentType = "application/x-www-form-urlencoded";
  953. var postContent = DataSerializer.SerializeToJsonString(obj);
  954. using (var stream = await HttpClient.PostAsync(url, contentType, postContent, Logger, CancellationToken.None).ConfigureAwait(false))
  955. {
  956. return DeserializeFromStream<TOutputType>(stream);
  957. }
  958. }
  959. /// <summary>
  960. /// This is a helper around getting a stream from the server that contains serialized data
  961. /// </summary>
  962. /// <param name="url">The URL.</param>
  963. /// <returns>Task{Stream}.</returns>
  964. public Task<Stream> GetSerializedStreamAsync(string url)
  965. {
  966. return GetSerializedStreamAsync(url, SerializationFormat);
  967. }
  968. /// <summary>
  969. /// This is a helper around getting a stream from the server that contains serialized data
  970. /// </summary>
  971. /// <param name="url">The URL.</param>
  972. /// <param name="serializationFormat">The serialization format.</param>
  973. /// <returns>Task{Stream}.</returns>
  974. public Task<Stream> GetSerializedStreamAsync(string url, SerializationFormats serializationFormat)
  975. {
  976. url = AddDataFormat(url, serializationFormat);
  977. return HttpClient.GetStreamAsync(url, Logger, CancellationToken.None);
  978. }
  979. /// <summary>
  980. /// Adds the data format.
  981. /// </summary>
  982. /// <param name="url">The URL.</param>
  983. /// <param name="serializationFormat">The serialization format.</param>
  984. /// <returns>System.String.</returns>
  985. private string AddDataFormat(string url, SerializationFormats serializationFormat)
  986. {
  987. var format = serializationFormat == SerializationFormats.Protobuf ? "x-protobuf" : serializationFormat.ToString();
  988. if (url.IndexOf('?') == -1)
  989. {
  990. url += "?format=" + format;
  991. }
  992. else
  993. {
  994. url += "&format=" + format;
  995. }
  996. return url;
  997. }
  998. }
  999. }