-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPluginInfoLoader.cs
More file actions
87 lines (77 loc) · 2.88 KB
/
PluginInfoLoader.cs
File metadata and controls
87 lines (77 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using Newtonsoft.Json;
using Rocket.Core.Logging;
using SpeedMann.PluginChecker.Models;
using SpeedMann.PluginChecker.Models.UStore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SpeedMann.PluginChecker
{
public class PluginInfoLoader
{
private const string ApiUrl = "https://unturnedstore.com/api/products/";
public delegate void PluginQuerryCompletion(bool success, Product pluginInfo);
private static Dictionary<uint, Product> LoadedProducts = new Dictionary<uint, Product>();
public static bool tryGetPluginInfo(uint pluginId, out Product pluginInfo)
{
pluginInfo = null;
if (isPluginInfoLoaded(pluginId))
{
pluginInfo = LoadedProducts[pluginId];
return true;
}
return false;
}
public static bool isPluginInfoLoaded(uint pluginId)
{
return LoadedProducts.ContainsKey(pluginId);
}
public static void loadPluginInfo(PluginQuerryCompletion calledMethod, uint productId, int retries = 2)
{
if (isPluginInfoLoaded(productId))
{
calledMethod.Invoke(true, LoadedProducts[productId]);
return;
}
loadProductAsync(calledMethod, productId, retries);
}
private static async void loadProductAsync(PluginQuerryCompletion calledFunction, uint productId, int retries)
{
WebRequest wr = WebRequest.Create(ApiUrl + productId);
wr.Method = "GET";
Product deserializedProduct;
int currentRetry = 0;
while(true)
{
try
{
WebResponse response = await wr.GetResponseAsync();
Stream dataStream = response.GetResponseStream();
JsonTextReader reader = new JsonTextReader(new StreamReader(dataStream));
var serializer = new JsonSerializer();
deserializedProduct = serializer.Deserialize<Product>(reader);
}
catch (Exception e)
{
currentRetry++;
if (currentRetry <= retries)
{
Thread.Sleep(1000);
continue;
}
calledFunction?.Invoke(false, null);
Logger.LogWarning($"Could not load product {productId} from UnturnedStore.com after {retries} retries!");
return;
}
LoadedProducts.Add(productId, deserializedProduct);
calledFunction?.Invoke(true, deserializedProduct);
return;
}
}
}
}