forked from RoliSoft/RS-TV-Show-Tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Settings.cs
424 lines (354 loc) · 14 KB
/
Settings.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
namespace RoliSoft.TVShowTracker
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RoliSoft.TVShowTracker.Parsers.Subtitles;
/// <summary>
/// Provides access to the default JSON settings file.
/// </summary>
public static class Settings
{
/// <summary>
/// Gets or sets the key-value container.
/// </summary>
/// <value>The key-value container.</value>
public static Dictionary<string, object> Keys { get; set; }
private static readonly string _jsFile;
/// <summary>
/// Initializes the <see cref="Database"/> class.
/// </summary>
static Settings()
{
if (string.IsNullOrWhiteSpace(Signature.InstallPath))
{
Log.Fatal("Stopping settings initialization because $InstallPath is null or empty.");
return;
}
_jsFile = Path.Combine(Signature.InstallPath, "Settings.json");
var tmp = Path.Combine(Signature.UACVirtualPath, "Settings.json");
if (!File.Exists(_jsFile) && File.Exists(tmp))
{
Log.Info("$UACVirtualPath\\Settings.json exists, initiating migration to $InstallPath...");
try
{
File.Copy(tmp, _jsFile);
File.Delete(tmp);
}
catch (Exception ex)
{
Log.Error("Error while migrating settings file from $UACVirtualPath to $InstallPath.", ex);
}
}
LoadSettings();
}
/// <summary>
/// Loads the settings.
/// </summary>
public static void LoadSettings()
{
Log.Info("Loading settings...");
var st = DateTime.Now;
try
{
Keys = (Dictionary<string, object>)ConvertJToNet(
JObject.Parse(
File.ReadAllText(_jsFile)
)
);
}
catch (Exception ex)
{
Log.Error("Error while loading settings file, resetting all settings to default.", ex);
Keys = new Dictionary<string, object> { { "Revision", 2 } };
}
try
{
Log.SetLevel(Get("Logging Level", Log.Level.Info));
}
catch (Exception ex)
{
Log.Warn("Error while getting logging level from settings. Level will remain on Trace.", ex);
}
Log.Debug("Settings loaded in " + (DateTime.Now - st).TotalSeconds + "s, containing " + Keys.Count + " entries.");
// set defaults, if they're missing
if (!Keys.ContainsKey("Active Trackers"))
{
Keys["Active Trackers"] = new List<string>
{
"The Pirate Bay", "DirectDownload.tv", "Zunox", "NBIndex", "NZBClub"
};
}
if (!Keys.ContainsKey("Tracker Order"))
{
Keys["Tracker Order"] = new List<string>
{
"BroadcasTheNet", "Tv Torrents Ro", "TvStore", "BitMeTV", "TvTorrents", "FileList", "nCore", "bitHUmen"
};
}
if (!Keys.ContainsKey("Active Subtitle Sites"))
{
Keys["Active Subtitle Sites"] = Extensibility.GetNewInstances<SubtitleSearchEngine>(inclExternal: false, inclScripts: false)
.Select(inst => inst.Name)
.ToList();
}
if (!Keys.ContainsKey("Active Subtitle Languages"))
{
Keys["Active Subtitle Languages"] = new List<string> { "en" };
}
// update download path to an array
// -> revision bd869ed9836a6d1c846a17586855d51b5ce092c2
if (Keys.ContainsKey("Download Path"))
{
Log.Info("Updating settings file to revision 0...");
Keys["Download Paths"] = new List<string>
{
(string)Keys["Download Path"]
};
Keys.Remove("Download Path");
}
// update encryption on logins and encrypt cookies
// -> revision 9465c36466739ade0ad556d498d7e17aec379bbb
if (!Keys.ContainsKey("Revision") || (int)Keys["Revision"] < 1)
{
Log.Info("Updating settings file to revision 1...");
var keys = Keys.Keys.ToList();
var plugins = Extensibility.GetNewInstances<IPlugin>().ToList();
foreach (var key in keys)
{
if (key.EndsWith(" Login"))
{
try
{
var plugin = plugins.FirstOrDefault(p => p.Name == key.Substring(0, key.Length - 6));
if (plugin == null)
{
Keys.Remove(key);
continue;
}
var ua = Utils.Decrypt((string)Keys[key], plugin.GetType().FullName + Environment.NewLine + Utils.GetUUID()).Split(new[] { '\0' }, 2);
Keys[key] = Utils.Encrypt(plugin, ua[0], ua[1]);
}
catch
{
continue;
}
}
else if (key.EndsWith(" Cookies"))
{
try
{
var plugin = plugins.FirstOrDefault(p => p.Name == key.Substring(0, key.Length - 8));
if (plugin == null)
{
Keys.Remove(key);
continue;
}
Keys[key] = Utils.Encrypt(plugin, (string)Keys[key]);
}
catch
{
continue;
}
}
}
Set("Revision", 1);
}
if ((int)Keys["Revision"] < 2)
{
Log.Info("Updating settings file to revision 2...");
var altdl = Get<Dictionary<string, List<string>>>("Alternative Associations");
if (Keys.ContainsKey("Torrent Downloader") && !string.IsNullOrWhiteSpace((string)Keys["Torrent Downloader"]))
{
if (altdl.ContainsKey(".torrent"))
{
altdl[".torrent"].Add((string)Keys["Torrent Downloader"]);
}
else
{
altdl[".torrent"] = new List<string> { (string)Keys["Torrent Downloader"] };
}
Keys.Remove("Torrent Downloader");
}
if (Keys.ContainsKey("Usenet Downloader") && !string.IsNullOrWhiteSpace((string)Keys["Usenet Downloader"]))
{
if (altdl.ContainsKey(".nzb"))
{
altdl[".nzb"].Add((string)Keys["Usenet Downloader"]);
}
else
{
altdl[".nzb"] = new List<string> { (string)Keys["Usenet Downloader"] };
}
Keys.Remove("Usenet Downloader");
}
if (Keys.ContainsKey("JDownloader") && !string.IsNullOrWhiteSpace((string)Keys["JDownloader"]))
{
if (altdl.ContainsKey(".dlc"))
{
altdl[".dlc"].Add((string)Keys["JDownloader"]);
}
else
{
altdl[".dlc"] = new List<string> { (string)Keys["JDownloader"] };
}
Keys.Remove("JDownloader");
}
Set("Alternative Associations", altdl);
Set("Revision", 2);
}
}
/// <summary>
/// Converts a <c>JObject</c> to a CLR object.
/// Consult the source code for the list of supported <c>JTokenType</c>s.
/// </summary>
/// <param name="obj">The deserialized JavaScript object.</param>
/// <returns>
/// Matching CLR object.
/// </returns>
private static object ConvertJToNet(JToken obj)
{
switch (obj.Type)
{
case JTokenType.String:
return (string)obj;
case JTokenType.Boolean:
return (bool)obj;
case JTokenType.Integer:
return (int)obj;
case JTokenType.Float:
return (double)obj;
case JTokenType.Array:
Type lastType = null;
bool typeDiff = false;
var array = new List<object>();
foreach (var item in (JArray)obj)
{
var nitem = ConvertJToNet(item);
var ntype = nitem.GetType();
array.Add(nitem);
if (lastType != null && lastType != ntype)
{
typeDiff = true;
}
lastType = ntype;
}
if (array.Count == 0)
{
return null;
}
if (!typeDiff && lastType != null)
{
switch (lastType.FullName)
{
case "System.String":
return array.Cast<string>().ToList();
case "System.Int32":
return array.Cast<int>().ToList();
case "System.Double":
return array.Cast<double>().ToList();
}
if (lastType.FullName == typeof(Dictionary<string, object>).FullName)
{
return array.Cast<Dictionary<string, object>>().ToList();
}
}
return array;
case JTokenType.Object:
var dict = new Dictionary<string, object>();
foreach (var item in (JObject)obj)
{
dict.Add(item.Key, ConvertJToNet(item.Value));
}
return dict;
case JTokenType.None:
case JTokenType.Null:
case JTokenType.Undefined:
return null;
default:
return null;
}
}
/// <summary>
/// Retrieves the key from the JSON settings.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Stored value or empty string.</returns>
public static string Get(string key)
{
return Get<string>(key);
}
/// <summary>
/// Retrieves the key from the JSON settings casting it to type <c>T</c>,
/// or if the key doesn't exist, the default value will be returned for value types
/// and a new instance will be returned for reference types.
/// </summary>
/// <typeparam name="T">The type in which to return the setting's value.</typeparam>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value to return if key was not found.</param>
/// <returns>
/// Stored value or default value/new instance.
/// </returns>
public static T Get<T>(string key, T defaultValue = default(T))
{
object value;
if (Keys.TryGetValue(key, out value) && value != null)
{
return (T)value;
}
if (!typeof(T).IsValueType && typeof(T) != typeof(string) && defaultValue == null)
{
return Activator.CreateInstance<T>();
}
return defaultValue;
}
/// <summary>
/// Stores the key and value into the JSON settings.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public static void Set<T>(string key, T value)
{
if (value is string && string.IsNullOrWhiteSpace(value as string))
{
Keys.Remove(key);
}
else
{
Keys[key] = value;
}
Save();
}
/// <summary>
/// Toggles the key's current boolean value in the JSON settings.
/// </summary>
/// <param name="key">The key.</param>
public static void Toggle(string key)
{
Keys[key] = !Get<bool>(key);
Save();
}
/// <summary>
/// Removes the key and value from the JSON settings.
/// </summary>
/// <param name="key">The key.</param>
public static void Remove(string key)
{
Keys.Remove(key);
Save();
}
/// <summary>
/// Saves the XML settings into the file.
/// </summary>
public static void Save()
{
File.WriteAllText(
_jsFile,
JsonConvert.SerializeObject(new SortedDictionary<string, object>(Keys), Formatting.Indented)
);
}
}
}