-
-
Notifications
You must be signed in to change notification settings - Fork 347
/
JsonConfiguration.cs
441 lines (391 loc) · 13.3 KB
/
JsonConfiguration.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using CKAN.Games;
namespace CKAN.Configuration
{
public class JsonConfiguration : IConfiguration
{
#region JSON Structures
[JsonConverter(typeof(ConfigConverter))]
private class Config
{
public string AutoStartInstance { get; set; }
public string DownloadCacheDir { get; set; }
public long? CacheSizeLimit { get; set; }
public int? RefreshRate { get; set; }
public string Language { get; set; }
public IList<GameInstanceEntry> GameInstances { get; set; } = new List<GameInstanceEntry>();
public IDictionary<string, string> AuthTokens { get; set; } = new Dictionary<string, string>();
public string[] GlobalInstallFilters { get; set; } = new string[] { };
}
public class ConfigConverter : JsonPropertyNamesChangedConverter
{
protected override Dictionary<string, string> mapping
{
get
{
return new Dictionary<string, string>
{
{ "KspInstances", "GameInstances" }
};
}
}
}
private class GameInstanceEntry
{
public string Name { get; set; }
public string Path { get; set; }
public string Game { get; set; }
}
#endregion
// The standard location of the config file. Where this actually points is platform dependent,
// but it's the same place as the downloads folder. The location can be overwritten with the
// CKAN_CONFIG_FILE environment variable.
public static readonly string defaultConfigFile =
Environment.GetEnvironmentVariable("CKAN_CONFIG_FILE")
?? Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CKAN",
"config.json"
);
public static readonly string DefaultDownloadCacheDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CKAN",
"downloads"
);
// The actual config file state, and its location on the disk (we allow
// the location to be changed for unit tests). Note that these are static
// because we only want to have one copy of the config file in memory. This
// version is considered authoritative, and we save it to the disk every time
// it gets changed.
//
// If you have multiple instances of CKAN running at the same time, each will
// believe that their copy of the config file in memory is authoritative, so
// changes made by one copy will not be respected by the other.
//
// Since we only have one copy in memory, we need to use _lock in order to
// keep things consistent. Depending on performance needs, it may make sense
// to switch to a read/write lock---but only do that after profiling. It is
// almost certainly more effort than it's worth, and may not actually provide
// any performance gains.
private static readonly object _lock = new object();
private static string configFile = defaultConfigFile;
private static Config config = null;
// <summary>
// Where the config file is located.
// </summary>
public string ConfigFile
{
get => configFile;
}
public string DownloadCacheDir
{
get
{
lock (_lock)
{
return config.DownloadCacheDir ?? DefaultDownloadCacheDir;
}
}
set
{
lock (_lock)
{
if (string.IsNullOrEmpty(value))
{
config.DownloadCacheDir = null;
}
else
{
if (!Path.IsPathRooted(value))
{
value = Path.GetFullPath(value);
}
config.DownloadCacheDir = value;
}
SaveConfig();
}
}
}
public long? CacheSizeLimit
{
get
{
lock (_lock)
{
return config.CacheSizeLimit;
}
}
set
{
lock (_lock)
{
if (value < 0)
{
config.CacheSizeLimit = null;
}
else
{
config.CacheSizeLimit = value;
}
SaveConfig();
}
}
}
public int RefreshRate
{
get
{
lock (_lock)
{
return config.RefreshRate ?? 0;
}
}
set
{
lock (_lock)
{
if (value <= 0)
{
config.RefreshRate = null;
}
else
{
config.RefreshRate = value;
}
SaveConfig();
}
}
}
public string Language
{
get
{
lock (_lock)
{
return config.Language;
}
}
set
{
lock (_lock)
{
if (Utilities.AvailableLanguages.Contains(value))
{
config.Language = value;
SaveConfig();
}
}
}
}
public string AutoStartInstance
{
get
{
lock (_lock)
{
return config.AutoStartInstance ?? "";
}
}
set
{
lock (_lock)
{
config.AutoStartInstance = value ?? "";
SaveConfig();
}
}
}
// <summary>
// For testing purposes only. This constructor discards the global configuration
// state, and recreates it from the specified file.
// </summary>
//
// N.B., if you're adding the ability to specify a config file from the CLI, this
// might be the way to do it. However, you need to ensure that the configuration
// doesn't get loaded from the default location first, as that might end up
// creating files and directories that the user is trying to avoid creating by
// specifying the configuration file on the command line.
public JsonConfiguration(string newConfig = null)
{
lock (_lock)
{
configFile = newConfig ?? defaultConfigFile;
LoadConfig();
}
}
public IEnumerable<Tuple<string, string, string>> GetInstances()
{
lock (_lock)
{
return config.GameInstances.Select(instance =>
new Tuple<string, string, string>(
instance.Name,
instance.Path,
instance.Game)
);
}
}
public void SetRegistryToInstances(SortedList<string, GameInstance> instances)
{
lock (_lock)
{
config.GameInstances = instances.Select(instance => new GameInstanceEntry
{
Name = instance.Key,
Path = instance.Value.GameDir(),
Game = instance.Value.game.ShortName
}).ToList();
SaveConfig();
}
}
public IEnumerable<string> GetAuthTokenHosts()
{
lock (_lock)
{
return config.AuthTokens.Keys;
}
}
public bool TryGetAuthToken(string host, out string token)
{
lock (_lock)
{
return config.AuthTokens.TryGetValue(host, out token);
}
}
public void SetAuthToken(string host, string token)
{
lock (_lock)
{
if (string.IsNullOrEmpty(token))
{
config.AuthTokens.Remove(host);
}
else
{
config.AuthTokens[host] = token;
}
SaveConfig();
}
}
public string[] GlobalInstallFilters
{
get
{
lock (_lock)
{
return config.GlobalInstallFilters;
}
}
set
{
lock (_lock)
{
config.GlobalInstallFilters = value;
SaveConfig();
}
}
}
// <summary>
// Save the JSON configuration file.
// </summary>
private static void SaveConfig()
{
lock (_lock)
{
string json = JsonConvert.SerializeObject(config, Formatting.Indented);
File.WriteAllText(configFile, json);
}
}
// <summary>
// Load the JSON configuration file. This will replace the current state.
//
// If the configuration file does not exist, this will create it and then
// try to populate it with values in the registry left from the old system.
// </summary>
private void LoadConfig()
{
lock (_lock)
{
try
{
string json = File.ReadAllText(configFile);
config = JsonConvert.DeserializeObject<Config>(json);
if (config == null)
{
config = new Config();
}
if (config.GameInstances == null)
{
config.GameInstances = new List<GameInstanceEntry>();
}
else
{
var game = new KerbalSpaceProgram();
foreach (GameInstanceEntry e in config.GameInstances)
{
if (e.Game == null)
{
e.Game = game.ShortName;
}
}
}
if (config.AuthTokens == null)
{
config.AuthTokens = new Dictionary<string, string>();
}
}
catch (Exception ex) when (ex is FileNotFoundException || ex is DirectoryNotFoundException)
{
// This runs if the configuration does not exist. We will create a new configuration and
// try to migrate from the registry.
config = new Config();
// Ensure the directory exists
new FileInfo(configFile).Directory.Create();
#if !NETCOREAPP
// If we are not running on .NET Core, try to migrate from the real registry
if (Win32RegistryConfiguration.DoesRegistryConfigurationExist())
{
Migrate();
// TODO: At some point, we can uncomment this to clean up after ourselves.
// Win32RegistryConfiguration.DeleteAllKeys();
}
#endif
SaveConfig();
}
}
}
// <summary>
// Copy the configuration from the registry here.
// </summary>
private void Migrate()
{
Win32RegistryConfiguration registry = new Win32RegistryConfiguration();
lock (_lock)
{
var instances = registry.GetInstances();
config.GameInstances = instances.Select(instance => new GameInstanceEntry
{
Name = instance.Item1,
Path = instance.Item2,
Game = instance.Item3
}).ToList();
config.AutoStartInstance = registry.AutoStartInstance;
config.DownloadCacheDir = registry.DownloadCacheDir;
config.CacheSizeLimit = registry.CacheSizeLimit;
config.RefreshRate = registry.RefreshRate;
foreach (string host in registry.GetAuthTokenHosts())
{
if (registry.TryGetAuthToken(host, out string token))
{
config.AuthTokens[host] = token;
}
}
SaveConfig();
}
}
}
}