123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- using System;
- using System.Net;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Threading.Tasks;
- using Newtonsoft.Json;
- using BlizzSharp.Data;
- using System.Collections.Generic;
-
- namespace BlizzSharp
- {
- public class BlizzSharpClient
- {
- private readonly Dictionary<long, Item> _itemLookup;
- private string _key;
- private HttpClient _http;
- private long _latestTimeStamp;
- public AuctionResponse CurrentAuctionResponse {get;set;}
- public AuctionResponse PreviousAuctionResponse {get;set;}
-
- public BlizzSharpClient(string key)
- {
- _itemLookup = new Dictionary<long, Item>();
- _http = new HttpClient();
- _http.BaseAddress = new Uri("https://eu.api.battle.net/wow/");
- _http.DefaultRequestHeaders.Accept.Clear();
- _http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- _key = key;
- _latestTimeStamp = -1;
- }
-
- //TODO: Exception handling
- public async Task<AuctionResponse> GetAuctionsAsync(string realm, string locale)
- {
- HttpResponseMessage response = await _http.GetAsync($"auction/data/{realm}?locale={locale}&apikey={_key}");
- if(response.IsSuccessStatusCode)
- {
- string auctionsLocatorResponse = await response.Content.ReadAsStringAsync();
- AuctionLocator locator = JsonConvert.DeserializeObject<Data.AuctionLocatorList>(auctionsLocatorResponse).Locators[0];
- if((locator.Timestamp > _latestTimeStamp) || CurrentAuctionResponse == null)
- {
- using(HttpClient auctionClient = new HttpClient())
- {
- HttpResponseMessage auctionResponse = await auctionClient.GetAsync(locator.Url);
- if(auctionResponse.IsSuccessStatusCode)
- {
- string auctionsResponse = await auctionResponse.Content.ReadAsStringAsync();
- PreviousAuctionResponse = CurrentAuctionResponse;
- CurrentAuctionResponse = JsonConvert.DeserializeObject<AuctionResponse>(auctionsResponse);
- return CurrentAuctionResponse;
- }
- }
-
- }
- }
-
- return null;
- }
-
- public async Task<Item> GetItemInfoAsync(long itemId, string locale)
- {
- if(_itemLookup.ContainsKey(itemId))
- return _itemLookup[itemId];
- HttpResponseMessage response = await _http.GetAsync($"item/{itemId}?locale={locale}&apikey={_key}");
- if(response.IsSuccessStatusCode)
- {
- string itemResponse = await response.Content.ReadAsStringAsync();
- Item item = JsonConvert.DeserializeObject<Item>(itemResponse);
- _itemLookup[itemId] = item;
- return item;
- }
- return null;
- }
- }
- }
|