Blizzard Api Wrapper for C#

BlizzSharpClient.cs 3.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Net;
  3. using System.Net.Http;
  4. using System.Net.Http.Headers;
  5. using System.Threading.Tasks;
  6. using Newtonsoft.Json;
  7. using BlizzSharp.Data;
  8. using System.Collections.Generic;
  9. namespace BlizzSharp
  10. {
  11. public class BlizzSharpClient
  12. {
  13. private readonly Dictionary<long, Item> _itemLookup;
  14. private string _key;
  15. private HttpClient _http;
  16. private long _latestTimeStamp;
  17. public AuctionResponse CurrentAuctionResponse {get;set;}
  18. public AuctionResponse PreviousAuctionResponse {get;set;}
  19. public BlizzSharpClient(string key)
  20. {
  21. _itemLookup = new Dictionary<long, Item>();
  22. _http = new HttpClient();
  23. _http.BaseAddress = new Uri("https://eu.api.battle.net/wow/");
  24. _http.DefaultRequestHeaders.Accept.Clear();
  25. _http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  26. _key = key;
  27. _latestTimeStamp = -1;
  28. }
  29. //TODO: Exception handling
  30. public async Task<AuctionResponse> GetAuctionsAsync(string realm, string locale)
  31. {
  32. HttpResponseMessage response = await _http.GetAsync($"auction/data/{realm}?locale={locale}&apikey={_key}");
  33. if(response.IsSuccessStatusCode)
  34. {
  35. string auctionsLocatorResponse = await response.Content.ReadAsStringAsync();
  36. AuctionLocator locator = JsonConvert.DeserializeObject<Data.AuctionLocatorList>(auctionsLocatorResponse).Locators[0];
  37. if((locator.Timestamp > _latestTimeStamp) || CurrentAuctionResponse == null)
  38. {
  39. using(HttpClient auctionClient = new HttpClient())
  40. {
  41. HttpResponseMessage auctionResponse = await auctionClient.GetAsync(locator.Url);
  42. if(auctionResponse.IsSuccessStatusCode)
  43. {
  44. string auctionsResponse = await auctionResponse.Content.ReadAsStringAsync();
  45. PreviousAuctionResponse = CurrentAuctionResponse;
  46. CurrentAuctionResponse = JsonConvert.DeserializeObject<AuctionResponse>(auctionsResponse);
  47. return CurrentAuctionResponse;
  48. }
  49. }
  50. }
  51. }
  52. return null;
  53. }
  54. public async Task<Item> GetItemInfoAsync(long itemId, string locale)
  55. {
  56. if(_itemLookup.ContainsKey(itemId))
  57. return _itemLookup[itemId];
  58. HttpResponseMessage response = await _http.GetAsync($"item/{itemId}?locale={locale}&apikey={_key}");
  59. if(response.IsSuccessStatusCode)
  60. {
  61. string itemResponse = await response.Content.ReadAsStringAsync();
  62. Item item = JsonConvert.DeserializeObject<Item>(itemResponse);
  63. _itemLookup[itemId] = item;
  64. return item;
  65. }
  66. return null;
  67. }
  68. }
  69. }