-
Notifications
You must be signed in to change notification settings - Fork 0
/
UnifiControllerApi.cs
236 lines (186 loc) · 7.84 KB
/
UnifiControllerApi.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using UnifiControllerCommunicator.Helpers;
namespace UnifiControllerCommunicator
{
public class UnifiControllerApi : IUnifiControllerApi
{
protected string Server { get; private set; }
protected string UserName { get; private set; }
protected SecureString Password { get; private set; }
protected string SiteName { get; set; }
/// <summary>
/// Cookie container for all operations.
/// </summary>
protected CookieContainer Cookies { get; private set; }
/// <summary>
/// Logged in variable.
/// </summary>
public bool IsLoggedIn { get; set; }
public UnifiControllerApi(string server, string username, SecureString pwd, string siteName = "default")
{
Server = server;
UserName = username;
Password = pwd;
SiteName = siteName;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
//Set our override class for checking certificate policies on SSL.
ServicePointManager.ServerCertificateValidationCallback += delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};
}
~UnifiControllerApi()
{
if (IsLoggedIn)
{
LogOut().Wait();
}
}
public async Task<bool> Login()
{
bool loggedIn = false;
try
{
if (IsLoggedIn)
{
return loggedIn;
}
Cookies = new CookieContainer();
var jsonSer = new JavaScriptSerializer();
var jsonParams = new Dictionary<string, object>();
jsonParams.Add("username", UserName);
jsonParams.Add("password", SecureStringHelper.ToInsecureString(Password));
var currentCommand = jsonSer.Serialize(jsonParams);
jsonParams.Clear();
// Create the request and setup for the post.
var strRequest = string.Format("{0}api/login", Server);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(strRequest);
httpWebRequest.ContentType = "application/json;charset=UTF-8";
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.ServicePoint.Expect100Continue = false;
httpWebRequest.CookieContainer = Cookies;
// Set the callback to handle the post of data.
var postStream = await httpWebRequest.GetRequestStreamAsync();
var byteArray = Encoding.UTF8.GetBytes(currentCommand);
// Write to the request stream.
await postStream.WriteAsync(byteArray, 0, byteArray.Length);
await postStream.FlushAsync();
postStream.Close();
// Now read the reponse and process the data.
var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string responseText = await streamReader.ReadToEndAsync();
jsonParams = jsonSer.Deserialize<Dictionary<string, object>>(responseText);
if (!jsonParams.ContainsKey("data"))
{
loggedIn = false;
}
else
{
IsLoggedIn = true;
loggedIn = true;
}
}
}
catch (Exception ex)
{
if(System.Diagnostics.Debugger.IsAttached)
{
System.Diagnostics.Trace.WriteLine(ex);
}
throw;
}
return loggedIn;
}
public async Task LogOut()
{
try
{
if (!IsLoggedIn)
{
return;
}
else
{
string strRequest = string.Format("{0}logout", Server);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(strRequest);
httpWebRequest.ContentType = "application/json;charset=UTF-8";
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.ServicePoint.Expect100Continue = false;
httpWebRequest.AllowAutoRedirect = false;
httpWebRequest.CookieContainer = Cookies;
var httpResponse = (HttpWebResponse) await httpWebRequest.GetResponseAsync();
Cookies = null;
IsLoggedIn = false;
}
}
catch (Exception)
{
throw;
}
}
public async Task<IDictionary<string, object>[]> GetClients()
{
var clients = new List<IDictionary<string, object>>();
try
{
if (!IsLoggedIn)
{
await Login();
}
var jsonSer = new JavaScriptSerializer();
var jsonParams = new Dictionary<string, object>();
var currentCommand = jsonSer.Serialize(jsonParams);
jsonParams.Clear();
// Create the request and setup for the post.
string strRequest = string.Format("{0}api/s/{1}/stat/sta", Server, SiteName);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(strRequest);
httpWebRequest.ContentType = "application/json;charset=UTF-8";
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.ServicePoint.Expect100Continue = false;
httpWebRequest.CookieContainer = Cookies;
// Set the callback to handle the post of data.
var postStream = await httpWebRequest.GetRequestStreamAsync();
byte[] byteArray = Encoding.UTF8.GetBytes(currentCommand);
// Write to the request stream.
await postStream.WriteAsync(byteArray, 0, byteArray.Length);
await postStream.FlushAsync();
postStream.Close();
// Now read the reponse and process the data.
var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string responseText = await streamReader.ReadToEndAsync();
jsonParams = jsonSer.Deserialize<Dictionary<string, object>>(responseText);
if (!jsonParams.ContainsKey("data"))
{
throw new Exception("Error getting clients");
}
var list = (ArrayList)jsonParams["data"];
foreach (Dictionary<string, object> data in list)
{
clients.Add(data);
};
}
}
catch (Exception)
{
await LogOut();
throw;
}
return clients.ToArray();
}
}
}