67 lines
2.1 KiB
C#
67 lines
2.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using Newtonsoft.Json;
|
|
using SPT.Common.Http;
|
|
|
|
namespace UIFixes.util {
|
|
internal static class FleaPriceCache {
|
|
static Dictionary<string, CachePrice> cache = new Dictionary<string, CachePrice>();
|
|
|
|
public static double? FetchPrice(string templateId) {
|
|
Console.WriteLine($"Get price for {templateId}");
|
|
if (cache.ContainsKey(templateId)) {
|
|
double secondsSinceLastUpdate = (DateTime.Now - cache[templateId].lastUpdate).TotalSeconds;
|
|
if (secondsSinceLastUpdate > 300)
|
|
return QueryAndTryUpsertPrice(templateId, true);
|
|
return cache[templateId].price;
|
|
}
|
|
|
|
return QueryAndTryUpsertPrice(templateId, false);
|
|
}
|
|
|
|
private static string QueryPrice(string templateId) {
|
|
return RequestHandler.PostJson("/LootValue/GetItemLowestFleaPrice",
|
|
JsonConvert.SerializeObject(new FleaPriceRequest(templateId)));
|
|
}
|
|
|
|
private static double? QueryAndTryUpsertPrice(string templateId, bool update) {
|
|
string response = QueryPrice(templateId);
|
|
|
|
bool hasPlayerFleaPrice = !(string.IsNullOrEmpty(response) || response == "null");
|
|
|
|
if (hasPlayerFleaPrice) {
|
|
double price = double.Parse(response);
|
|
|
|
if (update)
|
|
cache[templateId].Update(price);
|
|
else
|
|
cache[templateId] = new CachePrice(price);
|
|
|
|
return price;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public class FleaPriceRequest {
|
|
public string templateId;
|
|
public FleaPriceRequest(string templateId) => this.templateId = templateId;
|
|
}
|
|
|
|
internal class CachePrice {
|
|
public double price { get; private set; }
|
|
public DateTime lastUpdate { get; private set; }
|
|
|
|
public CachePrice(double price) {
|
|
this.price = price;
|
|
lastUpdate = DateTime.Now;
|
|
}
|
|
|
|
public void Update(double price) {
|
|
this.price = price;
|
|
lastUpdate = DateTime.Now;
|
|
}
|
|
}
|
|
}
|