-
Notifications
You must be signed in to change notification settings - Fork 0
/
Config.cs
126 lines (114 loc) · 3.43 KB
/
Config.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
using Newtonsoft.Json;
using System.Runtime.CompilerServices;
namespace CherryDDNS
{
[Serializable]
public class Config
{
public string Secret { get; set; } = string.Empty;
public string Key { get; set; } = string.Empty;
public List<Record> Records { get; set; } = new List<Record>();
private const string FILENAME = "config.json";
private static Config _instance;
public static Config Instance
{
get
{
if (_instance == null)
{
_instance = Load();
}
return _instance;
}
}
public static string Model
{
get
{
Config model = new Config().ToString();
model.Records.Add(new Record());
return model.ToString();
}
}
[JsonIgnore]
public static string FilePath
{
get
{
return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FILENAME);
}
}
[JsonIgnore]
public string AuthHeader
{
get
{
return $"{Key}:{Secret}";
}
}
private Config() { }
private static Config Load()
{
try
{
if (!File.Exists(FilePath)) new Config().Save();
string json = string.Empty;
using (StreamReader reader = new StreamReader(FilePath))
{
json = reader.ReadToEnd();
}
return json;
}
catch (Exception ex)
{
LogManager.Error(ex);
return null;
}
}
public void Save()
{
try
{
if (this.Records.Count == 0) this.Records.Add(new Record()); //if there are no records, we want to create a blank one in the file for users to see/edit
using (StreamWriter sw = new StreamWriter(FILENAME, false))
{
string body = this.ToString();
sw.WriteLine(body);
sw.Close();
}
}
catch (Exception ex)
{
LogManager.Error(ex);
}
}
public override string ToString()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
public string ToMaskedString()
{
Config maskedConfig = this.ToString();
if (!string.IsNullOrWhiteSpace(maskedConfig.Secret)) maskedConfig.Secret = "[redacted]";
if (!string.IsNullOrWhiteSpace(maskedConfig.Key)) maskedConfig.Key = "[redacted]";
return maskedConfig.ToString();
}
public static implicit operator Config(string json)
{
return JsonConvert.DeserializeObject<Config>(json);
}
}
public class Record
{
public string HostName { get; set; } = string.Empty;
public string DomainName { get; set; } = string.Empty;
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
public static implicit operator Record(string json)
{
return JsonConvert.DeserializeObject<Record>(json);
}
}
}