ApiClient.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. /// Authenticates a user and returns the result
  302. /// </summary>
  303. public void AuthenticateUserAsync(Guid userId, string password, Action<AuthenticationResult> callback)
  304. {
  305. string url = ApiUrl + "/UserAuthentication?dataformat=" + SerializationFormat.ToString();
  306. Dictionary<string, string> formValues = new Dictionary<string, string>();
  307. formValues["userid"] = userId.ToString();
  308. if (!string.IsNullOrEmpty(password))
  309. {
  310. formValues["password"] = password;
  311. }
  312. PostDataAsync(url, formValues, callback, SerializationFormat);
  313. }
  314. /// <summary>
  315. /// Updates a user's favorite status for an item and returns the updated UserItemData object.
  316. /// </summary>
  317. public void UpdateFavoriteStatusAsync(Guid itemId, Guid userId, bool isFavorite, Action<DTOUserItemData> callback)
  318. {
  319. string url = ApiUrl + "/favoritestatus?id=" + itemId;
  320. url += "&userid=" + userId;
  321. url += "&isfavorite=" + (isFavorite ? "1" : "0");
  322. GetDataAsync(url, callback);
  323. }
  324. /// <summary>
  325. /// Clears a user's rating for an item
  326. /// </summary>
  327. public void ClearUserItemRatingAsync(Guid itemId, Guid userId, Action<DTOUserItemData> callback)
  328. {
  329. string url = ApiUrl + "/UserItemRating?id=" + itemId;
  330. url += "&userid=" + userId;
  331. url += "&clear=1";
  332. GetDataAsync(url, callback);
  333. }
  334. /// <summary>
  335. /// Updates a user's rating for an item, based on likes or dislikes
  336. /// </summary>
  337. public void UpdateUserItemRatingAsync(Guid itemId, Guid userId, bool likes, Action<DTOUserItemData> callback)
  338. {
  339. string url = ApiUrl + "/UserItemRating?id=" + itemId;
  340. url += "&userid=" + userId;
  341. url += "&likes=" + (likes ? "1" : "0");
  342. GetDataAsync(url, callback);
  343. }
  344. /// <summary>
  345. /// Performs a GET request, and deserializes the response stream to an object of Type T
  346. /// </summary>
  347. private void GetDataAsync<T>(string url, Action<T> callback)
  348. where T : class
  349. {
  350. GetDataAsync<T>(url, callback, SerializationFormat);
  351. }
  352. /// <summary>
  353. /// Performs a GET request, and deserializes the response stream to an object of Type T
  354. /// </summary>
  355. private void GetDataAsync<T>(string url, Action<T> callback, SerializationFormats serializationFormat)
  356. where T : class
  357. {
  358. if (url.IndexOf('?') == -1)
  359. {
  360. url += "?dataformat=" + serializationFormat.ToString();
  361. }
  362. else
  363. {
  364. url += "&dataformat=" + serializationFormat.ToString();
  365. }
  366. HttpWebRequest request = GetNewRequest(url);
  367. request.BeginGetResponse(new AsyncCallback(result =>
  368. {
  369. T value;
  370. using (WebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result))
  371. {
  372. using (Stream stream = response.GetResponseStream())
  373. {
  374. value = DeserializeFromStream<T>(stream);
  375. }
  376. }
  377. callback(value);
  378. }), request);
  379. }
  380. /// <summary>
  381. /// Performs a GET request, and deserializes the response stream to an object of Type T
  382. /// </summary>
  383. private void GetDataAsync(string url, Action<object> callback, Type type, SerializationFormats serializationFormat)
  384. {
  385. if (url.IndexOf('?') == -1)
  386. {
  387. url += "?dataformat=" + serializationFormat.ToString();
  388. }
  389. else
  390. {
  391. url += "&dataformat=" + serializationFormat.ToString();
  392. }
  393. HttpWebRequest request = GetNewRequest(url);
  394. request.BeginGetResponse(new AsyncCallback(result =>
  395. {
  396. object value;
  397. using (WebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result))
  398. {
  399. using (Stream stream = response.GetResponseStream())
  400. {
  401. value = DataSerializer.DeserializeFromStream(stream, serializationFormat, type);
  402. }
  403. }
  404. callback(value);
  405. }), request);
  406. }
  407. /// <summary>
  408. /// Performs a POST request, and deserializes the response stream to an object of Type T
  409. /// </summary>
  410. private void PostDataAsync<T>(string url, Dictionary<string, string> formValues, Action<T> callback, SerializationFormats serializationFormat)
  411. where T : class
  412. {
  413. if (url.IndexOf('?') == -1)
  414. {
  415. url += "?dataformat=" + serializationFormat.ToString();
  416. }
  417. else
  418. {
  419. url += "&dataformat=" + serializationFormat.ToString();
  420. }
  421. HttpWebRequest request = GetNewRequest(url);
  422. request.Method = "POST";
  423. request.ContentType = "application/x-www-form-urlencoded";
  424. // Begin getting request stream
  425. request.BeginGetRequestStream(new AsyncCallback(beginGetRequestStreamResult =>
  426. {
  427. // Once we have the request stream, write the post data
  428. using (Stream requestStream = request.EndGetRequestStream(beginGetRequestStreamResult))
  429. {
  430. // Construct the body
  431. string postBody = string.Join("&", formValues.Keys.Select(s => string.Format("{0}={1}", s, formValues[s])).ToArray());
  432. // Convert the string into a byte array.
  433. byte[] byteArray = Encoding.UTF8.GetBytes(postBody);
  434. // Write to the request stream.
  435. requestStream.Write(byteArray, 0, byteArray.Length);
  436. }
  437. // Begin getting response stream
  438. request.BeginGetResponse(new AsyncCallback(result =>
  439. {
  440. // Once we have it, deserialize the data and execute the callback
  441. T value;
  442. using (WebResponse response = request.EndGetResponse(result))
  443. {
  444. using (Stream responseStream = response.GetResponseStream())
  445. {
  446. value = DeserializeFromStream<T>(responseStream);
  447. }
  448. }
  449. callback(value);
  450. }), null);
  451. }), null);
  452. }
  453. }
  454. }