-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainForm.cs
463 lines (384 loc) · 17.9 KB
/
MainForm.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
using Microsoft.Build.Tasks.Deployment.Bootstrapper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DotaGameAcceptor {
public partial class MainForm : Form {
private bool _hueConnected { get; set; }
public string bridgeIpAddress { get; set; }
private const string DEVICENAME = "AghanimsAcceptor";
private static HueAuthSuccess _hueAuthUser;
private static Dictionary<string, HueLightsDto> _hueBridgeLights;
private static HueUserLights _hueUserLights;
public MainForm() {
InitializeComponent();
FormBorderStyle = FormBorderStyle.FixedDialog;
// set initial image
this.pictureBox.Image = AghanimsAcceptor.Properties.Resources.IdleImage;
string infoString = "Game finder will not work without enabling Settings -> Advanced Options -> Bring Dota 2 to front when match found";
showBalloon(title: "Important", body: infoString);
System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
}
private void OnStartClick(object sender, EventArgs e) {
// show animated image
this.pictureBox.Image = AghanimsAcceptor.Properties.Resources.AnimatedImage;
// change button states
this.buttonStart.Enabled = false;
// start background operation
this.backgroundWorker.RunWorkerAsync();
}
private void OnDoWork(object sender, DoWorkEventArgs e) {
this.backgroundWorker.ReportProgress(-1, string.Format("Searching..."));
string path = Directory.GetCurrentDirectory();
int ExitCode;
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo(path + "\\Script\\DotaGameAcceptor.exe");
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = false;
Process = Process.Start(ProcessInfo);
Process.WaitForExit();
ExitCode = Process.ExitCode;
Process.Close();
if (ExitCode == 2) {
e.Cancel = true;
}
}
private void OnProgressChanged(object sender, ProgressChangedEventArgs e) {
if (e.UserState is String) {
this.labelProgress.Text = (String)e.UserState;
}
}
private void OnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
// hide animation
this.pictureBox.Image = null;
// show result indication
if (e.Cancelled) {
this.labelProgress.Text = "Operation cancelled!";
this.pictureBox.Image = AghanimsAcceptor.Properties.Resources.WarningImage;
}
else {
if (e.Error != null) {
this.labelProgress.Text = "Operation failed: " + e.Error.Message;
}
else {
this.labelProgress.Text = "Operation finish!";
this.pictureBox.Image = AghanimsAcceptor.Properties.Resources.SuccessImage;
// Fire Hue Change Lights
if (_hueConnected) {
AlertHueLights();
}
}
}
// restore button states
this.buttonStart.Enabled = true;
}
private void MainForm_Load(object sender, EventArgs e) {
}
private static void showBalloon(string title, string body) {
NotifyIcon notifyIcon = new NotifyIcon();
notifyIcon.Icon = SystemIcons.Information;
notifyIcon.Visible = true;
if (title != null) {
notifyIcon.BalloonTipTitle = title;
}
if (body != null) {
notifyIcon.BalloonTipText = body;
}
notifyIcon.ShowBalloonTip(5);
}
private async void toolStripButton1_Click(object sender, EventArgs e) {
this.hueConnectButton.Image = AghanimsAcceptor.Properties.Resources.lightbulb_waiting;
// Amazing Error Handling for Failure to Connect
try {
_hueConnected = await ConnectToHueBridge();
}
catch (HttpRequestException ex) {
WriteLog(ex.Message);
if (ex.InnerException != null) {
WriteLog(ex.InnerException.Message);
WriteLog(ex.InnerException.StackTrace);
}
showBalloon(title: "Bridge Connection Issue", body: ex.Message);
_hueConnected = false;
}
catch (Exception exAll) {
WriteLog(exAll.Message);
WriteLog(exAll.StackTrace);
showBalloon(title: "Important", body: exAll.Message);
_hueConnected = false;
}
finally {
}
if (_hueConnected) {
this.hueConnectButton.Image = AghanimsAcceptor.Properties.Resources.lightbulb_success;
TestHueLights();
}
else {
this.hueConnectButton.Image = AghanimsAcceptor.Properties.Resources.lightbulb_failed;
}
}
#region Config File
public static void SaveHueAuthXml(HueAuthSuccess hueAuthSuccess) {
System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(typeof(HueAuthSuccess));
var path = Directory.GetCurrentDirectory() + "\\Config\\HueAuthentication.xml";
System.IO.FileStream file = System.IO.File.Create(path);
writer.Serialize(file, hueAuthSuccess);
file.Close();
}
public static HueAuthSuccess ReadHueAuthXml() {
// Now we can read the serialized book ...
System.Xml.Serialization.XmlSerializer reader =
new System.Xml.Serialization.XmlSerializer(typeof(HueAuthSuccess));
var path = Directory.GetCurrentDirectory() + "\\Config\\HueAuthentication.xml";
System.IO.StreamReader file = new System.IO.StreamReader(path);
HueAuthSuccess hueAuth = (HueAuthSuccess)reader.Deserialize(file);
file.Close();
return hueAuth;
}
public static HueUserLights ReadHueUserLightsXml() {
// Now we can read the serialized book ...
System.Xml.Serialization.XmlSerializer reader =
new System.Xml.Serialization.XmlSerializer(typeof(HueUserLights));
var path = Directory.GetCurrentDirectory() + "\\Config\\HueUserLights.xml";
System.IO.StreamReader file = new System.IO.StreamReader(path);
HueUserLights hueUserLights = (HueUserLights)reader.Deserialize(file);
file.Close();
return hueUserLights;
}
#endregion
#region Connection Methods
static async Task<bool> ConnectToHueBridge() {
bool connected = false;
string hueIp = String.Empty;
try {
hueIp = await GetHueBridgeIpAddress();
}
catch {
WriteLog("Failed to get Hue Bridge Ip Address.");
return false;
}
List<BridgeIpAddressResponse> bridgeIpAddressResponse = JsonConvert.DeserializeObject<List<BridgeIpAddressResponse>>(hueIp);
HueBridgeDetails.ip = bridgeIpAddressResponse.First().internalipaddress;
HueBridgeDetails.id = bridgeIpAddressResponse.First().id;
// Try Read from config file for Hue Auth User
try {
_hueAuthUser = ReadHueAuthXml();
}
catch {
}
// If _hueAuthUser hasn't been set yet, try to connect
if (_hueAuthUser == null) {
string hueAuth = String.Empty;
hueAuth = await GetHueAuthentication();
if (hueAuth == String.Empty || hueAuth == null) {
connected = false;
}
else if (hueAuth.ToUpper().Contains("ERROR")) {
List<HueAuthError> hueAuthErrors = JsonConvert.DeserializeObject<List<HueAuthError>>(hueAuth);
showBalloon(title: "Hue Authentication Error", body: hueAuthErrors.First().error.description + ". Press Link Button on Hue Bridge and try again.");
WriteLog(hueAuthErrors.First().error.description + ". Press Link Button on Hue Bridge and try again.");
connected = false;
}
else {
List<HueAuthSuccess> hueAuthSuccesses = JsonConvert.DeserializeObject<List<HueAuthSuccess>>(hueAuth);
_hueAuthUser = hueAuthSuccesses.First();
SaveHueAuthXml(_hueAuthUser);
connected = true;
}
return connected;
}
else {
string hueLights = await GetHueLights();
if (hueLights.ToUpper().Contains("ERROR")) {
List<HueAuthError> hueAuthErrors = JsonConvert.DeserializeObject<List<HueAuthError>>(hueLights);
showBalloon(title: "Hue Authentication Token Error", body: hueAuthErrors.First().error.description + ".");
WriteLog("Hue Authentication Token Error:" + hueAuthErrors.First().error.description + ". Delete Authentication configuration file and try again or update Authentication token.");
return false;
}
else {
_hueBridgeLights = JsonConvert.DeserializeObject<Dictionary<string, HueLightsDto>>(hueLights);
_hueUserLights = ReadHueUserLightsXml();
return true;
}
}
}
private static async Task<string> GetHueLights() {
string lightsJson = String.Empty;
using (var httpClient = new HttpClient()) {
string authUri = $"https://{HueBridgeDetails.ip}/api/{_hueAuthUser.success.username}/lights";
// Build json and attach to HttpRequest
HttpResponseMessage lightsResponse = await httpClient.GetAsync(authUri);
if (lightsResponse.IsSuccessStatusCode) {
lightsJson = await lightsResponse.Content.ReadAsStringAsync();
}
}
return lightsJson;
}
private static async Task<string> GetHueAuthentication() {
string s = String.Empty;
using (var httpClient = new HttpClient()) {
string authUri = $"https://{HueBridgeDetails.ip}/api";
// Build json and attach to HttpRequest
HueAuthRequest authRequest = new HueAuthRequest() { devicetype = DEVICENAME };
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(authRequest));
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
try {
HttpResponseMessage authResponse = await httpClient.PostAsync(authUri, httpContent);
authResponse.EnsureSuccessStatusCode();
s = await authResponse.Content.ReadAsStringAsync();
}
catch (Exception e) {
WriteLog("Hue Authentication Request Error:" + e.Message);
}
}
return s;
}
private static async Task<string> GetHueBridgeIpAddress() {
string s = string.Empty;
using (var httpClient = new HttpClient()) {
HttpResponseMessage ipResponse = await httpClient.GetAsync(@"https://discovery.meethue.com/");
if (ipResponse.IsSuccessStatusCode) {
s = await ipResponse.Content.ReadAsStringAsync();
}
}
return s;
}
private static async Task<string> AlertHueLights() {
string s = String.Empty;
List<string> lightIndexes = new List<string>();
foreach (var light in _hueUserLights.Lights) {
var bridgeLight = _hueBridgeLights.Where(x => x.Value.name == light.Name).FirstOrDefault();
if (bridgeLight.Key != null)
lightIndexes.Add(bridgeLight.Key);
else
WriteLog($"Did not find Light on Hue Bridge with Name = {light.Name}");
}
using (var httpClient = new HttpClient()) {
foreach (var index in lightIndexes) {
string authUri = $"https://{HueBridgeDetails.ip}/api/{_hueAuthUser.success.username}/lights/{index}/state";
// Build json and attach to HttpRequest
var json = new { alert = "lselect" };
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(json));
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
HttpResponseMessage authResponse = await httpClient.PutAsync(authUri, httpContent);
authResponse.EnsureSuccessStatusCode();
s = await authResponse.Content.ReadAsStringAsync();
}
}
return s;
}
private static async Task<string> TestHueLights() {
string s = String.Empty;
List<string> lightIndexes = new List<string>();
foreach (var light in _hueUserLights.Lights) {
var bridgeLight = _hueBridgeLights.Where(x => x.Value.name == light.Name).FirstOrDefault();
if (bridgeLight.Key != null)
lightIndexes.Add(bridgeLight.Key);
else
WriteLog($"Did not find Light on Hue Bridge with Name = {light.Name}");
}
using (var httpClient = new HttpClient()) {
foreach (var index in lightIndexes) {
string authUri = $"https://{HueBridgeDetails.ip}/api/{_hueAuthUser.success.username}/lights/{index}/state";
// Build json and attach to HttpRequest
var json = new { alert = "select" };
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(json));
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
HttpResponseMessage authResponse = await httpClient.PutAsync(authUri, httpContent);
authResponse.EnsureSuccessStatusCode();
s = await authResponse.Content.ReadAsStringAsync();
}
}
return s;
}
#endregion
#region Hue DTOs
private class BridgeIpAddressResponse {
public string id { get; set; }
public string internalipaddress { get; set; }
}
private static class HueBridgeDetails {
public static string ip { get; set; }
public static string id { get; set; }
public static string userName { get; set; }
}
private class HueAuthRequest {
public string devicetype { get; set; }
}
private class HueAuthError {
public Error error { get; set; }
public class Error {
public int type { get; set; }
public string address { get; set; }
public string description { get; set; }
}
}
public class HueAuthSuccess {
public Success success { get; set; }
public class Success {
public string username { get; set; }
}
}
public class HueUserLights {
public List<Light> Lights;
}
public class Light {
public string Name;
}
public class State {
public bool on { get; set; }
public int bri { get; set; }
public int hue { get; set; }
public int sat { get; set; }
public string effect { get; set; }
public List<double> xy { get; set; }
public int ct { get; set; }
public string alert { get; set; }
public string colormode { get; set; }
public bool reachable { get; set; }
}
public class HueLightsDto {
public State state { get; set; }
public string type { get; set; }
public string name { get; set; }
public string modelid { get; set; }
public string manufacturername { get; set; }
public string uniqueid { get; set; }
public string swversion { get; set; }
}
#endregion
#region Logging
public static void WriteLog(string log) {
string path = Directory.GetCurrentDirectory();
using (StreamWriter w = File.AppendText(path + "\\Logs\\log.txt")) {
Log(log, w);
}
}
public static void Log(string logMessage, TextWriter w) {
w.Write("\r\nLog Entry : ");
w.WriteLine($"{DateTime.Now.ToLongTimeString()} {DateTime.Now.ToLongDateString()}");
w.WriteLine(" :");
w.WriteLine($" :{logMessage}");
w.WriteLine("-------------------------------");
}
public static void DumpLog(StreamReader r) {
string line;
while ((line = r.ReadLine()) != null) {
Console.WriteLine(line);
}
}
#endregion
}
}