-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountryCache.cs
140 lines (127 loc) · 4.53 KB
/
CountryCache.cs
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
using System.Collections.Concurrent;
using System.Text.Json;
namespace MyApp
{
public sealed class CountryCache
{
class ApiKeysFile
{
public string? ipgeolocation_key { get; set; }
}
public string? ipgeolocation_key { get; private set; } = null;
public Dictionary<string, string> Cache = new Dictionary<string, string>();
private readonly object cachelock = new object();
private ConcurrentDictionary<string, Task<GeoInfo?>> apiQueries = new ConcurrentDictionary<string, Task<GeoInfo?>>();
private CountryCache()
{
try
{
var text = File.ReadAllText(getConfigPath());
var config = JsonSerializer.Deserialize<ApiKeysFile>(text);
if (config != null)
{
ipgeolocation_key = config.ipgeolocation_key;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception while trying to read apikeys:\n" + ex);
}
try
{
var text = File.ReadAllText(getCachePath());
var countrycache = JsonSerializer.Deserialize<Dictionary<string, string>>(text);
if (countrycache != null)
{
Cache = countrycache;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception while trying to read geocache:\n" + ex);
}
}
private static string getConfigPath()
{
var configPath = Environment.GetEnvironmentVariable("CONFIGPATH");
var configDir = "config";
if (Directory.Exists(configPath)) configDir = configPath;
return Path.Join(configDir, "apikeys.json");
}
private static string getCachePath()
{
var configPath = Environment.GetEnvironmentVariable("CONFIGPATH");
var configDir = "config";
if (Directory.Exists(configPath)) configDir = configPath;
return Path.Join(configDir, "geocache.json");
}
private void SaveCache()
{
Console.WriteLine("Saving Country Cache");
JsonSerializerOptions jsonConfig = new()
{
WriteIndented = true,
};
lock (cachelock)
{
var json = JsonSerializer.Serialize(Cache, jsonConfig);
File.WriteAllText(getCachePath(), json);
}
}
private class GeoInfo
{
public string ip { get; set; }
public string country_code2 { get; set; }
public GeoInfo(string ip, string country_code2)
{
this.ip = ip;
this.country_code2 = country_code2;
}
}
internal async Task<string?> GetCountryCode(string hostname)
{
// Look in cache
lock (cachelock)
{
var value = Cache.GetValueOrDefault(hostname);
if (value != null) return value;
}
if (ipgeolocation_key == null || ipgeolocation_key.Length == 0)
{
return null;
}
using (var client = new HttpClient())
{
Console.WriteLine("Retrieving country code for ip: " + hostname);
// Check if there already is a request in flight for this mod
string geoUrl = $"https://api.ipgeolocation.io/ipgeo?apiKey={ipgeolocation_key}&fields=country_code2&ip={hostname}";
// Guard against multiple concurrent queries for the same url
var task = apiQueries.GetOrAdd(geoUrl, client.GetFromJsonAsync<GeoInfo>(geoUrl));
var resp = await task;
if (resp != null)
{
bool modified = false;
lock (cachelock)
{
modified = Cache.TryAdd(hostname, resp.country_code2);
}
if (modified) SaveCache();
return resp.country_code2;
}
}
return null;
}
private static CountryCache? instance = null;
public static CountryCache Instance
{
get
{
if (instance == null)
{
instance = new CountryCache();
}
return instance;
}
}
}
}