Blizzard Api Wrapper for C#

BlizzSharpClient.cs 3.2KB

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