This repository has been archived by the owner on Dec 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathConfigPage.cs
368 lines (321 loc) · 15.7 KB
/
ConfigPage.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
using HomeSeerAPI;
using NullGuard;
using Scheduler;
using System;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using System.Globalization;
namespace Hspi
{
using static System.FormattableString;
/// <summary>
/// Helper class to generate configuration page for plugin
/// </summary>
/// <seealso cref="Scheduler.PageBuilderAndMenu.clsPageBuilder" />
[NullGuard(ValidationFlags.Arguments | ValidationFlags.NonPublic)]
internal class ConfigPage : PageBuilderAndMenu.clsPageBuilder
{
protected const string IdPrefix = "id_";
/// <summary>
/// Initializes a new instance of the <see cref="ConfigPage" /> class.
/// </summary>
/// <param name="HS">The hs.</param>
/// <param name="pluginConfig">The plugin configuration.</param>
public ConfigPage(IHSApplication HS, PluginConfig pluginConfig) : base(pageName)
{
this.HS = HS;
this.pluginConfig = pluginConfig;
}
/// <summary>
/// Gets the name of the web page.
/// </summary>
public static string Name => pageName;
/// <summary>
/// Get the web page string for the configuration page.
/// </summary>
/// <returns>
/// System.String.
/// </returns>
public string GetWebPage()
{
try
{
reset();
System.Text.StringBuilder stb = new System.Text.StringBuilder();
stb.Append(HS.GetPageHeader(Name, "Configuration", string.Empty, string.Empty, false, false));
stb.Append(PageBuilderAndMenu.clsPageBuilder.DivStart("pluginpage", ""));
stb.Append(BuildWebPageBody());
stb.Append(PageBuilderAndMenu.clsPageBuilder.DivEnd());
AddBody(stb.ToString());
AddFooter(HS.GetPageFooter());
suppressDefaultFooter = true;
return BuildPage();
}
catch (Exception)
{
return "error";
}
}
/// <summary>
/// The user has selected a control on the configuration web page.
/// The post data is provided to determine the control that initiated the post and the state of the other controls.
/// </summary>
/// <param name="data">The post data.</param>
/// <param name="user">The name of logged in user.</param>
/// <param name="userRights">The rights of the logged in user.</param>
/// <returns>Any serialized data that needs to be passed back to the web page, generated by the clsPageBuilder class.</returns>
public string PostBackProc(string data, [AllowNull]string user, int userRights)
{
NameValueCollection parts = HttpUtility.ParseQueryString(data);
string form = parts["id"];
if (form == NameToIdWithPrefix(SaveButtonName))
{
StringBuilder results = new StringBuilder();
// Validate
if (string.IsNullOrWhiteSpace(parts[APIKeyId]))
{
results.AppendLine("API Key is not Valid.<br>");
}
if (string.IsNullOrWhiteSpace(parts[StationId]))
{
results.AppendLine("Station is not Valid.<br>");
}
uint refreshIntervalMinutes = 0;
if (string.IsNullOrWhiteSpace(parts[RefreshIntervalId]) ||
!uint.TryParse(parts[RefreshIntervalId], NumberStyles.Any, CultureInfo.InvariantCulture, out refreshIntervalMinutes) ||
refreshIntervalMinutes > int.MaxValue)
{
results.AppendLine("Refresh Interval is not Valid.<br>");
}
Unit unit = Unit.US;
if (string.IsNullOrWhiteSpace(parts[UnitId]) ||
!System.Enum.TryParse<Unit>(parts[UnitId], out unit))
{
results.AppendLine("Unit is not Valid.<br>");
}
if (results.Length > 0)
{
this.divToUpdate.Add(ErrorDivId, results.ToString());
}
else
{
this.divToUpdate.Add(ErrorDivId, string.Empty);
this.pluginConfig.APIKey = parts[APIKeyId];
this.pluginConfig.RefreshIntervalMinutes = (int)refreshIntervalMinutes;
this.pluginConfig.StationId = parts[StationId];
this.pluginConfig.Unit = unit;
this.pluginConfig.DebugLogging = parts[DebugLoggingId] == "checked";
this.pluginConfig.FireConfigChanged();
}
this.divToUpdate.Add(ImageDivId, GetImageHtml());
this.divToUpdate.Add(CallsPerDayId, GetCallsPerDay());
}
else
{
bool changed = false;
foreach (var deviceDefintion in WUWeatherData.DeviceDefinitions)
{
foreach (var childDeviceDefinition in deviceDefintion.Children)
{
string id = NameToId(deviceDefintion, childDeviceDefinition);
string value = parts[id];
if (value != null)
{
this.pluginConfig.SetDeviceEnabled(deviceDefintion, childDeviceDefinition, value == "checked");
changed = true;
}
}
}
if (changed)
{
this.pluginConfig.FireConfigChanged();
}
}
return base.postBackProc(Name, data, user, userRights);
}
/// <summary>
/// Builds the web page body for the configuration page.
/// The page has separate forms so that only the data in the appropriate form is returned when a button is pressed.
/// </summary>
private string BuildWebPageBody()
{
int i = 0;
StringBuilder stb = new StringBuilder();
var tabs = new clsJQuery.jqTabs("tab1id", PageName);
var tab1 = new clsJQuery.Tab();
tab1.tabTitle = "Settings";
tab1.tabDIVID = Invariant($"tabs{i++}");
tab1.tabContent = BuildSettingTab();
tabs.tabs.Add(tab1);
foreach (var deviceDefintion in WUWeatherData.DeviceDefinitions)
{
var tab = new clsJQuery.Tab();
tab.tabTitle = deviceDefintion.Name;
tab.tabDIVID = Invariant($"tabs{i++}");
tab.tabContent = BuildTab(deviceDefintion);
tabs.tabs.Add(tab);
}
tabs.postOnTabClick = false;
stb.Append(tabs.Build());
return stb.ToString();
}
private string BuildTab(RootDeviceData root)
{
StringBuilder stb = new StringBuilder();
string idName = NameToId(root.Name);
stb.Append(@"<br>");
stb.Append(PageBuilderAndMenu.clsPageBuilder.FormStart(Invariant($"ftm{idName}"), Invariant($"Id{idName}"), "Post"));
stb.Append(DivStart(idName + "div", string.Empty));
stb.Append(@"<table class='full_width_table'>");
stb.Append("<tr height='5'><td colspan=2></td></tr>");
stb.Append("<tr><td colspan=2> </td></tr>");
stb.Append("<tr><td colspan=2><strong>Select devices to be created</strong><td></tr>");
stb.Append("<tr><td colspan=2> </td></tr>");
foreach (var childDeviceDefinition in root.Children)
{
stb.Append(Invariant($"<tr><td colspan=2>{FormCheckBox(NameToId(root, childDeviceDefinition), childDeviceDefinition.Name, pluginConfig.GetDeviceEnabled(root, childDeviceDefinition))}</td></tr>"));
}
stb.Append(@" </table>");
stb.Append(DivEnd());
stb.Append(PageBuilderAndMenu.clsPageBuilder.FormEnd());
return stb.ToString();
}
private string GetImageHtml()
{
StringBuilder stb = new StringBuilder();
if (string.IsNullOrWhiteSpace(pluginConfig.StationId))
{
stb.Append(Invariant($"<a href='http://www.wunderground.com' target='_blank'><img width='100px' alt='Powered by Weather Underground' src='http://icons.wxug.com/logos/PNG/wundergroundLogo_4c.png'></a>"));
}
else
{
stb.Append(Invariant($"<a href='http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID={pluginConfig.StationId}' target='_blank'><img src='http://banners.wunderground.com/cgi-bin/banner/ban/wxBanner?bannertype=wxstnsticker_both&weatherstationcount={pluginConfig.StationId}' height='160' width='160' border='0' alt='Weather Underground PWS {pluginConfig.StationId}'/></a>"));
}
stb.Append(" <a href='https://www.wunderground.com/wundermap' target='_blank'>Find Station</a>");
return stb.ToString();
}
private string GetCallsPerDay()
{
if (pluginConfig.RefreshIntervalMinutes != 0)
{
return Invariant($" ({ Math.Max(1, 1440 / pluginConfig.RefreshIntervalMinutes)} calls per day)");
}
else
{
return string.Empty;
}
}
private string BuildSettingTab()
{
int unitsSelection = -1;
var unitsDropDown = new NameValueCollection();
foreach (var value in Enum.GetValues(typeof(Unit)))
{
unitsDropDown.Set(EnumHelper.GetDescription((System.Enum)value), value.ToString());
if ((Unit)value == pluginConfig.Unit)
{
unitsSelection = unitsDropDown.Count - 1;
}
}
StringBuilder stb = new StringBuilder();
stb.Append(PageBuilderAndMenu.clsPageBuilder.FormStart("ftmSettings", "IdSettings", "Post"));
stb.Append(@"<br>");
stb.Append(@"<div>");
stb.Append(@"<table class='full_width_table'>");
stb.Append("<tr height='5'><td style='width:25%'></td><td style='width:20%'></td><td style='width:55%'></td></tr>");
stb.Append(Invariant($"<tr><td class='tablecell'>APIKey:</td><td class='tablecell' style='width: 50px'>{HtmlTextBox(APIKeyId, pluginConfig.APIKey)}</td><td class='tablecell'> <a href='https://www.wunderground.com/weather/api/' target='_blank'>API Home</a></td></tr>"));
stb.Append(Invariant($"<tr><td class='tablecell'>Refresh Interval(minutes):</td><td class='tablecell'>{HtmlTextBox(RefreshIntervalId, Invariant($"{pluginConfig.RefreshIntervalMinutes}"))} </td><td class='tablecell'><div id={CallsPerDayId}>{GetCallsPerDay()}</div></td></tr>"));
stb.Append(Invariant($"<tr><td class='tablecell'>Station:</td><td class='tablecell'>{HtmlTextBox(StationId, Invariant($"{pluginConfig.StationId}"))}</td ><td class='tablecell'><div id='{ImageDivId}'>{GetImageHtml()}</div></td></tr>"));
stb.Append(Invariant($"<tr><td class='tablecell'>Unit:</td><td colspan=2 class='tablecell'>{FormDropDown(UnitId, unitsDropDown, unitsSelection, 150, "Units to be used for Device")}</td></tr>"));
stb.Append(Invariant($"<tr><td class='tablecell'>Debug Logging Enabled:</td><td colspan=2 class='tablecell'>{FormCheckBox(DebugLoggingId, string.Empty, this.pluginConfig.DebugLogging)}</td></tr>"));
stb.Append(Invariant($"<tr><td colspan=3><div id='{ErrorDivId}' style='color:Red'></div></td><td></td></tr>"));
stb.Append(Invariant($"<tr><td colspan=3>{FormButton("Save", SaveButtonName, "Save Settings")}</td><td></td></tr>"));
stb.Append("<tr height='5'><td colspan=3></td></tr>");
stb.Append(Invariant($"<tr><td colspan=3></td></tr>"));
stb.Append(@"<tr><td colspan=3><div>Icons made by <a href='http://www.freepik.com' title='Freepik' target='_blank'>Freepik</a> from <a href='http://www.flaticon.com' title='Flaticon' target='_blank'>www.flaticon.com</a> is licensed by <a href='http://creativecommons.org/licenses/by/3.0/' title='Creative Commons BY 3.0' target='_blank'>CC 3.0 BY</a></div></td></tr>");
stb.Append(@"<tr height='5'><td colspan=3></td></tr>");
stb.Append(@"</table>");
stb.Append(@"</div>");
stb.Append(PageBuilderAndMenu.clsPageBuilder.FormEnd());
return stb.ToString();
}
private static string NameToId(string name)
{
return name.Replace(' ', '_');
}
private static string NameToIdWithPrefix(string name)
{
return Invariant($"{ IdPrefix}{NameToId(name)}");
}
private static string NameToId(DeviceDataBase parent, DeviceDataBase child)
{
return Invariant($"{NameToId(parent.Name)}_{NameToId(child.Name)}");
}
protected static string HtmlTextBox(string name, string defaultText, int size = 25)
{
return Invariant($"<input type=\'text\' id=\'{NameToIdWithPrefix(name)}\' size=\'{size}\' name=\'{name}\' value=\'{HtmlEncode(defaultText)}\'>");
}
protected string FormDropDown(string name, NameValueCollection options, int selected, int width, string tooltip)
{
var dropdown = new clsJQuery.jqDropList(name, PageName, false)
{
selectedItemIndex = -1,
id = NameToIdWithPrefix(name),
autoPostBack = false,
toolTip = tooltip,
style = Invariant($"width: {width}px;"),
enabled = true
};
if (options != null)
{
for (var i = 0; i < options.Count; i++)
{
var sel = i == selected;
dropdown.AddItem(options.GetKey(i), options.Get(i), sel);
}
}
return dropdown.Build();
}
protected string FormCheckBox(string name, string label, bool @checked)
{
var checkbox = new clsJQuery.jqCheckBox(name, label, PageName, true, true)
{
id = NameToIdWithPrefix(name),
@checked = @checked,
};
return checkbox.Build();
}
protected string FormButton(string name, string label, string toolTip)
{
var button = new clsJQuery.jqButton(name, label, PageName, true)
{
id = NameToIdWithPrefix(name),
toolTip = toolTip,
};
button.toolTip = toolTip;
button.enabled = true;
return button.Build();
}
public static string HtmlEncode<T>([AllowNull]T value)
{
if (value == null)
{
return string.Empty;
}
return HttpUtility.HtmlEncode(value);
}
private const string SaveButtonName = "Save";
private const string CallsPerDayId = "CallsPerDayId";
private const string DebugLoggingId = "DebugLoggingId";
private const string UnitId = "UnitId";
private const string APIKeyId = "APIKeyId";
private const string StationId = "StationId";
private const string ErrorDivId = "message_id";
private const string ImageDivId = "image_id";
private const string RefreshIntervalId = "RefreshIntervalId";
private static readonly string pageName = Invariant($"{WUWeatherData.PlugInName} Configuration").Replace(' ', '_');
private readonly IHSApplication HS;
private readonly PluginConfig pluginConfig;
}
}