ApiClient.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. using MediaBrowser.Model.Authentication;
  2. using MediaBrowser.Model.Configuration;
  3. using MediaBrowser.Model.DTO;
  4. using MediaBrowser.Model.Weather;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Text;
  11. namespace MediaBrowser.ApiInteraction.Portable
  12. {
  13. public class ApiClient : BaseApiClient
  14. {
  15. private HttpWebRequest GetNewRequest(string url)
  16. {
  17. return HttpWebRequest.CreateHttp(url);
  18. }
  19. /// <summary>
  20. /// Gets an image stream based on a url
  21. /// </summary>
  22. public void GetImageStreamAsync(string url, Action<Stream> callback)
  23. {
  24. GetStreamAsync(url, callback);
  25. }
  26. /// <summary>
  27. /// Gets an image stream based on a url
  28. /// </summary>
  29. private void GetStreamAsync(string url, Action<Stream> callback)
  30. {
  31. HttpWebRequest request = GetNewRequest(url);
  32. request.BeginGetResponse(new AsyncCallback(result =>
  33. {
  34. using (WebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result))
  35. {
  36. Stream stream = response.GetResponseStream();
  37. callback(stream);
  38. }
  39. }), request);
  40. }
  41. /// <summary>
  42. /// Gets a BaseItem
  43. /// </summary>
  44. public void GetItemAsync(Guid id, Guid userId, Action<DTOBaseItem> callback)
  45. {
  46. string url = ApiUrl + "/item?userId=" + userId.ToString();
  47. if (id != Guid.Empty)
  48. {
  49. url += "&id=" + id.ToString();
  50. }
  51. GetDataAsync(url, callback);
  52. }
  53. /// <summary>
  54. /// Gets all users
  55. /// </summary>
  56. public void GetAllUsersAsync(Action<DTOUser[]> callback)
  57. {
  58. string url = ApiUrl + "/users";
  59. GetDataAsync(url, callback);
  60. }
  61. /// <summary>
  62. /// Gets all Genres
  63. /// </summary>
  64. public void GetAllGenresAsync(Guid userId, Action<IBNItem[]> callback)
  65. {
  66. string url = ApiUrl + "/genres?userId=" + userId.ToString();
  67. GetDataAsync(url, callback);
  68. }
  69. /// <summary>
  70. /// Gets in-progress items
  71. /// </summary>
  72. /// <param name="userId">The user id.</param>
  73. /// <param name="folderId">(Optional) Specify a folder Id to localize the search to a specific folder.</param>
  74. public void GetInProgressItemsItemsAsync(Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
  75. {
  76. string url = ApiUrl + "/itemlist?listtype=inprogressitems&userId=" + userId.ToString();
  77. if (folderId.HasValue)
  78. {
  79. url += "&id=" + folderId.ToString();
  80. }
  81. GetDataAsync(url, callback);
  82. }
  83. /// <summary>
  84. /// Gets recently added items
  85. /// </summary>
  86. /// <param name="userId">The user id.</param>
  87. /// <param name="folderId">(Optional) Specify a folder Id to localize the search to a specific folder.</param>
  88. public void GetRecentlyAddedItemsAsync(Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
  89. {
  90. string url = ApiUrl + "/itemlist?listtype=recentlyaddeditems&userId=" + userId.ToString();
  91. if (folderId.HasValue)
  92. {
  93. url += "&id=" + folderId.ToString();
  94. }
  95. GetDataAsync(url, callback);
  96. }
  97. /// <summary>
  98. /// Gets favorite items
  99. /// </summary>
  100. /// <param name="userId">The user id.</param>
  101. /// <param name="folderId">(Optional) Specify a folder Id to localize the search to a specific folder.</param>
  102. public void GetFavoriteItemsAsync(Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
  103. {
  104. string url = ApiUrl + "/itemlist?listtype=favorites&userId=" + userId.ToString();
  105. if (folderId.HasValue)
  106. {
  107. url += "&id=" + folderId.ToString();
  108. }
  109. GetDataAsync(url, callback);
  110. }
  111. /// <summary>
  112. /// Gets recently added items that are unplayed.
  113. /// </summary>
  114. /// <param name="userId">The user id.</param>
  115. /// <param name="folderId">(Optional) Specify a folder Id to localize the search to a specific folder.</param>
  116. public void GetRecentlyAddedUnplayedItemsAsync(Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
  117. {
  118. string url = ApiUrl + "/itemlist?listtype=recentlyaddedunplayeditems&userId=" + userId.ToString();
  119. if (folderId.HasValue)
  120. {
  121. url += "&id=" + folderId.ToString();
  122. }
  123. GetDataAsync(url, callback);
  124. }
  125. /// <summary>
  126. /// Gets all Years
  127. /// </summary>
  128. public void GetAllYearsAsync(Guid userId, Action<IBNItem[]> callback)
  129. {
  130. string url = ApiUrl + "/years?userId=" + userId.ToString();
  131. GetDataAsync(url, callback);
  132. }
  133. /// <summary>
  134. /// Gets all items that contain a given Year
  135. /// </summary>
  136. public void GetItemsWithYearAsync(string name, Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
  137. {
  138. string url = ApiUrl + "/itemlist?listtype=itemswithyear&userId=" + userId.ToString() + "&name=" + name;
  139. if (folderId.HasValue)
  140. {
  141. url += "&id=" + folderId.ToString();
  142. }
  143. GetDataAsync(url, callback);
  144. }
  145. /// <summary>
  146. /// Gets all items that contain a given Genre
  147. /// </summary>
  148. public void GetItemsWithGenreAsync(string name, Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
  149. {
  150. string url = ApiUrl + "/itemlist?listtype=itemswithgenre&userId=" + userId.ToString() + "&name=" + name;
  151. if (folderId.HasValue)
  152. {
  153. url += "&id=" + folderId.ToString();
  154. }
  155. GetDataAsync(url, callback);
  156. }
  157. /// <summary>
  158. /// Gets all items that contain a given Person
  159. /// </summary>
  160. public void GetItemsWithPersonAsync(string name, Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
  161. {
  162. string url = ApiUrl + "/itemlist?listtype=itemswithperson&userId=" + userId.ToString() + "&name=" + name;
  163. if (folderId.HasValue)
  164. {
  165. url += "&id=" + folderId.ToString();
  166. }
  167. GetDataAsync(url, callback);
  168. }
  169. /// <summary>
  170. /// Gets all items that contain a given Person
  171. /// </summary>
  172. public void GetItemsWithPersonAsync(string name, string personType, Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
  173. {
  174. string url = ApiUrl + "/itemlist?listtype=itemswithperson&userId=" + userId.ToString() + "&name=" + name;
  175. if (folderId.HasValue)
  176. {
  177. url += "&id=" + folderId.ToString();
  178. }
  179. url += "&persontype=" + personType;
  180. GetDataAsync(url, callback);
  181. }
  182. /// <summary>
  183. /// Gets all studious
  184. /// </summary>
  185. public void GetAllStudiosAsync(Guid userId, Action<IBNItem[]> callback)
  186. {
  187. string url = ApiUrl + "/studios?userId=" + userId.ToString();
  188. GetDataAsync(url, callback);
  189. }
  190. /// <summary>
  191. /// Gets all items that contain a given Studio
  192. /// </summary>
  193. public void GetItemsWithStudioAsync(string name, Guid userId, Action<DTOBaseItem[]> callback, Guid? folderId = null)
  194. {
  195. string url = ApiUrl + "/itemlist?listtype=itemswithstudio&userId=" + userId.ToString() + "&name=" + name;
  196. if (folderId.HasValue)
  197. {
  198. url += "&id=" + folderId.ToString();
  199. }
  200. GetDataAsync(url, callback);
  201. }
  202. /// <summary>
  203. /// Gets a studio
  204. /// </summary>
  205. public void GetStudioAsync(Guid userId, string name, Action<IBNItem> callback)
  206. {
  207. string url = ApiUrl + "/studio?userId=" + userId.ToString() + "&name=" + name;
  208. GetDataAsync(url, callback);
  209. }
  210. /// <summary>
  211. /// Gets a genre
  212. /// </summary>
  213. public void GetGenreAsync(Guid userId, string name, Action<IBNItem> callback)
  214. {
  215. string url = ApiUrl + "/genre?userId=" + userId.ToString() + "&name=" + name;
  216. GetDataAsync(url, callback);
  217. }
  218. /// <summary>
  219. /// Gets a person
  220. /// </summary>
  221. public void GetPersonAsync(Guid userId, string name, Action<IBNItem> callback)
  222. {
  223. string url = ApiUrl + "/person?userId=" + userId.ToString() + "&name=" + name;
  224. GetDataAsync(url, callback);
  225. }
  226. /// <summary>
  227. /// Gets a year
  228. /// </summary>
  229. public void GetYearAsync(Guid userId, int year, Action<IBNItem> callback)
  230. {
  231. string url = ApiUrl + "/year?userId=" + userId.ToString() + "&year=" + year;
  232. GetDataAsync(url, callback);
  233. }
  234. /// <summary>
  235. /// Gets a list of plugins installed on the server
  236. /// </summary>
  237. public void GetInstalledPluginsAsync(Action<PluginInfo[]> callback)
  238. {
  239. string url = ApiUrl + "/plugins";
  240. GetDataAsync(url, callback);
  241. }
  242. /// <summary>
  243. /// Gets a list of plugins installed on the server
  244. /// </summary>
  245. public void GetPluginAssemblyAsync(PluginInfo plugin, Action<Stream> callback)
  246. {
  247. string url = ApiUrl + "/pluginassembly?assemblyfilename=" + plugin.AssemblyFileName;
  248. GetStreamAsync(url, callback);
  249. }
  250. /// <summary>
  251. /// Gets the current server configuration
  252. /// </summary>
  253. public void GetServerConfigurationAsync(Action<ServerConfiguration> callback)
  254. {
  255. string url = ApiUrl + "/ServerConfiguration";
  256. GetDataAsync(url, callback);
  257. }
  258. /// <summary>
  259. /// Gets weather information for the default location as set in configuration
  260. /// </summary>
  261. public void GetPluginConfigurationAsync(PluginInfo plugin, Type configurationType, Action<object> callback)
  262. {
  263. string url = ApiUrl + "/PluginConfiguration?assemblyfilename=" + plugin.AssemblyFileName;
  264. // At the moment this can't be retrieved in protobuf format
  265. SerializationFormats format = DataSerializer.CanDeSerializeJsv ? SerializationFormats.Jsv : SerializationFormats.Json;
  266. GetDataAsync(url, callback, configurationType, format);
  267. }
  268. /// <summary>
  269. /// Gets the default user
  270. /// </summary>
  271. public void GetDefaultUserAsync(Action<DTOUser> callback)
  272. {
  273. string url = ApiUrl + "/user";
  274. GetDataAsync(url, callback);
  275. }
  276. /// <summary>
  277. /// Gets a user by id
  278. /// </summary>
  279. public void GetUserAsync(Guid id, Action<DTOUser> callback)
  280. {
  281. string url = ApiUrl + "/user?id=" + id.ToString();
  282. GetDataAsync(url, callback);
  283. }
  284. /// <summary>
  285. /// Gets weather information for the default location as set in configuration
  286. /// </summary>
  287. public void GetWeatherInfoAsync(Action<WeatherInfo> callback)
  288. {
  289. string url = ApiUrl + "/weather";
  290. GetDataAsync(url, callback);
  291. }
  292. /// <summary>
  293. /// Gets weather information for a specific zip code
  294. /// </summary>
  295. public void GetWeatherInfoAsync(string zipCode, Action<WeatherInfo> callback)
  296. {
  297. string url = ApiUrl + "/weather?zipcode=" + zipCode;
  298. GetDataAsync(url, callback);
  299. }
  300. /// <summary>
  301. /// Gets special features for a Movie
  302. /// </summary>
  303. public void GetMovieSpecialFeaturesAsync(Guid itemId, Guid userId, Action<DTOBaseItem[]> callback)
  304. {
  305. string url = ApiUrl + "/MovieSpecialFeatures?id=" + itemId;
  306. url += "&userid=" + userId;
  307. GetDataAsync(url, callback);
  308. }
  309. /// <summary>
  310. /// Authenticates a user and returns the result
  311. /// </summary>
  312. public void AuthenticateUserAsync(Guid userId, string password, Action<AuthenticationResult> callback)
  313. {
  314. string url = ApiUrl + "/UserAuthentication?dataformat=" + SerializationFormat.ToString();
  315. Dictionary<string, string> formValues = new Dictionary<string, string>();
  316. formValues["userid"] = userId.ToString();
  317. if (!string.IsNullOrEmpty(password))
  318. {
  319. formValues["password"] = password;
  320. }
  321. PostDataAsync(url, formValues, callback, SerializationFormat);
  322. }
  323. /// <summary>
  324. /// Updates a user's favorite status for an item and returns the updated UserItemData object.
  325. /// </summary>
  326. public void UpdateFavoriteStatusAsync(Guid itemId, Guid userId, bool isFavorite, Action<DTOUserItemData> callback)
  327. {
  328. string url = ApiUrl + "/favoritestatus?id=" + itemId;
  329. url += "&userid=" + userId;
  330. url += "&isfavorite=" + (isFavorite ? "1" : "0");
  331. GetDataAsync(url, callback);
  332. }
  333. /// <summary>
  334. /// Updates played status for an item
  335. /// </summary>
  336. public void UpdatePlayedStatusAsync(Guid itemId, Guid userId, bool wasPlayed, Action<DTOUserItemData> callback)
  337. {
  338. string url = ApiUrl + "/PlayedStatus?id=" + itemId;
  339. url += "&userid=" + userId;
  340. url += "&played=" + (wasPlayed ? "1" : "0");
  341. GetDataAsync(url, callback);
  342. }
  343. /// <summary>
  344. /// Clears a user's rating for an item
  345. /// </summary>
  346. public void ClearUserItemRatingAsync(Guid itemId, Guid userId, Action<DTOUserItemData> callback)
  347. {
  348. string url = ApiUrl + "/UserItemRating?id=" + itemId;
  349. url += "&userid=" + userId;
  350. url += "&clear=1";
  351. GetDataAsync(url, callback);
  352. }
  353. /// <summary>
  354. /// Updates a user's rating for an item, based on likes or dislikes
  355. /// </summary>
  356. public void UpdateUserItemRatingAsync(Guid itemId, Guid userId, bool likes, Action<DTOUserItemData> callback)
  357. {
  358. string url = ApiUrl + "/UserItemRating?id=" + itemId;
  359. url += "&userid=" + userId;
  360. url += "&likes=" + (likes ? "1" : "0");
  361. GetDataAsync(url, callback);
  362. }
  363. /// <summary>
  364. /// Performs a GET request, and deserializes the response stream to an object of Type T
  365. /// </summary>
  366. private void GetDataAsync<T>(string url, Action<T> callback)
  367. where T : class
  368. {
  369. GetDataAsync<T>(url, callback, SerializationFormat);
  370. }
  371. /// <summary>
  372. /// Performs a GET request, and deserializes the response stream to an object of Type T
  373. /// </summary>
  374. private void GetDataAsync<T>(string url, Action<T> callback, SerializationFormats serializationFormat)
  375. where T : class
  376. {
  377. if (url.IndexOf('?') == -1)
  378. {
  379. url += "?dataformat=" + serializationFormat.ToString();
  380. }
  381. else
  382. {
  383. url += "&dataformat=" + serializationFormat.ToString();
  384. }
  385. HttpWebRequest request = GetNewRequest(url);
  386. request.BeginGetResponse(new AsyncCallback(result =>
  387. {
  388. T value;
  389. using (WebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result))
  390. {
  391. using (Stream stream = response.GetResponseStream())
  392. {
  393. value = DeserializeFromStream<T>(stream);
  394. }
  395. }
  396. callback(value);
  397. }), request);
  398. }
  399. /// <summary>
  400. /// Performs a GET request, and deserializes the response stream to an object of Type T
  401. /// </summary>
  402. private void GetDataAsync(string url, Action<object> callback, Type type, SerializationFormats serializationFormat)
  403. {
  404. if (url.IndexOf('?') == -1)
  405. {
  406. url += "?dataformat=" + serializationFormat.ToString();
  407. }
  408. else
  409. {
  410. url += "&dataformat=" + serializationFormat.ToString();
  411. }
  412. HttpWebRequest request = GetNewRequest(url);
  413. request.BeginGetResponse(new AsyncCallback(result =>
  414. {
  415. object value;
  416. using (WebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result))
  417. {
  418. using (Stream stream = response.GetResponseStream())
  419. {
  420. value = DataSerializer.DeserializeFromStream(stream, serializationFormat, type);
  421. }
  422. }
  423. callback(value);
  424. }), request);
  425. }
  426. /// <summary>
  427. /// Performs a POST request, and deserializes the response stream to an object of Type T
  428. /// </summary>
  429. private void PostDataAsync<T>(string url, Dictionary<string, string> formValues, Action<T> callback, SerializationFormats serializationFormat)
  430. where T : class
  431. {
  432. if (url.IndexOf('?') == -1)
  433. {
  434. url += "?dataformat=" + serializationFormat.ToString();
  435. }
  436. else
  437. {
  438. url += "&dataformat=" + serializationFormat.ToString();
  439. }
  440. HttpWebRequest request = GetNewRequest(url);
  441. request.Method = "POST";
  442. request.ContentType = "application/x-www-form-urlencoded";
  443. // Begin getting request stream
  444. request.BeginGetRequestStream(new AsyncCallback(beginGetRequestStreamResult =>
  445. {
  446. // Once we have the request stream, write the post data
  447. using (Stream requestStream = request.EndGetRequestStream(beginGetRequestStreamResult))
  448. {
  449. // Construct the body
  450. string postBody = string.Join("&", formValues.Keys.Select(s => string.Format("{0}={1}", s, formValues[s])).ToArray());
  451. // Convert the string into a byte array.
  452. byte[] byteArray = Encoding.UTF8.GetBytes(postBody);
  453. // Write to the request stream.
  454. requestStream.Write(byteArray, 0, byteArray.Length);
  455. }
  456. // Begin getting response stream
  457. request.BeginGetResponse(new AsyncCallback(result =>
  458. {
  459. // Once we have it, deserialize the data and execute the callback
  460. T value;
  461. using (WebResponse response = request.EndGetResponse(result))
  462. {
  463. using (Stream responseStream = response.GetResponseStream())
  464. {
  465. value = DeserializeFromStream<T>(responseStream);
  466. }
  467. }
  468. callback(value);
  469. }), null);
  470. }), null);
  471. }
  472. }
  473. }