forked from vrcx-team/VRCX
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebApi.cs
297 lines (277 loc) · 11.6 KB
/
WebApi.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
using CefSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
namespace VRCX
{
public class WebApi
{
public static readonly WebApi Instance;
public CookieContainer _cookieContainer;
private bool _cookieDirty;
private Timer _timer;
static WebApi()
{
Instance = new WebApi();
ServicePointManager.DefaultConnectionLimit = 10;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}
public WebApi()
{
_cookieContainer = new CookieContainer();
_timer = new Timer(TimerCallback, null, -1, -1);
}
private void TimerCallback(object state)
{
try
{
SaveCookies();
}
catch
{
}
}
internal void Init()
{
LoadCookies();
_timer.Change(1000, 1000);
}
internal void Exit()
{
_timer.Change(-1, -1);
SaveCookies();
}
public void ClearCookies()
{
_cookieContainer = new CookieContainer();
}
internal void LoadCookies()
{
SQLite.Instance.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS `cookies` (`key` TEXT PRIMARY KEY, `value` TEXT)");
SQLite.Instance.Execute((values) =>
{
try
{
using (var stream = new MemoryStream(Convert.FromBase64String((string)values[0])))
{
_cookieContainer = (CookieContainer)new BinaryFormatter().Deserialize(stream);
}
}
catch
{
}
},
"SELECT `value` FROM `cookies` WHERE `key` = @key",
new Dictionary<string, object>() {
{"@key", "default"}
}
);
}
internal void SaveCookies()
{
if (_cookieDirty == false)
{
return;
}
try
{
using (var memoryStream = new MemoryStream())
{
new BinaryFormatter().Serialize(memoryStream, _cookieContainer);
SQLite.Instance.ExecuteNonQuery(
"INSERT OR REPLACE INTO `cookies` (`key`, `value`) VALUES (@key, @value)",
new Dictionary<string, object>() {
{"@key", "default"},
{"@value", Convert.ToBase64String(memoryStream.ToArray())}
}
);
}
_cookieDirty = false;
}
catch
{
}
}
public string GetCookies()
{
using (var memoryStream = new MemoryStream())
{
new BinaryFormatter().Serialize(memoryStream, _cookieContainer);
return Convert.ToBase64String(memoryStream.ToArray());
}
}
public void SetCookies(string cookies)
{
using (var stream = new MemoryStream(Convert.FromBase64String(cookies)))
{
_cookieContainer = (CookieContainer)new BinaryFormatter().Deserialize(stream);
}
}
#pragma warning disable CS4014
public async void Execute(IDictionary<string, object> options, IJavascriptCallback callback)
{
try
{
var request = WebRequest.CreateHttp((string)options["url"]);
request.CookieContainer = _cookieContainer;
request.KeepAlive = true;
if (options.TryGetValue("headers", out object headers) == true)
{
foreach (var header in (IEnumerable<KeyValuePair<string, object>>)headers)
{
var key = header.Key;
var value = header.Value.ToString();
if (string.Compare(key, "Content-Type", StringComparison.OrdinalIgnoreCase) == 0)
{
request.ContentType = value;
}
else if (string.Compare(key, "User-Agent", StringComparison.OrdinalIgnoreCase) == 0)
{
request.UserAgent = value;
}
else if (string.Compare(key, "Referer", StringComparison.OrdinalIgnoreCase) == 0)
{
request.Referer = value;
}
else
{
request.Headers.Add(key, value);
}
}
}
if (options.TryGetValue("method", out object method) == true)
{
var _method = (string)method;
request.Method = _method;
if (string.Compare(_method, "GET", StringComparison.OrdinalIgnoreCase) != 0 &&
options.TryGetValue("body", out object body) == true)
{
using (var stream = await request.GetRequestStreamAsync())
using (var streamWriter = new StreamWriter(stream))
{
await streamWriter.WriteAsync((string)body);
}
}
}
if (options.TryGetValue("uploadFilePUT", out object uploadImagePUT) == true)
{
request.Method = "PUT";
request.ContentType = options["fileMIME"] as string;
var imageData = options["fileData"] as string;
byte[] sentData = Convert.FromBase64CharArray(imageData.ToCharArray(), 0, imageData.Length);
request.ContentLength = sentData.Length;
using (System.IO.Stream sendStream = request.GetRequestStream())
{
sendStream.Write(sentData, 0, sentData.Length);
sendStream.Close();
}
}
if (options.TryGetValue("uploadImage", out object uploadImage) == true)
{
request.Method = "POST";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
request.ContentType = "multipart/form-data; boundary=" + boundary;
Stream requestStream = request.GetRequestStream();
if (options.TryGetValue("postData", out object postDataObject) == true)
{
Dictionary<string, string> postData = new Dictionary<string, string>();
postData.Add("data", (string)postDataObject);
string FormDataTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n";
foreach (string key in postData.Keys)
{
string item = String.Format(FormDataTemplate, boundary, key, postData[key]);
byte[] itemBytes = System.Text.Encoding.UTF8.GetBytes(item);
requestStream.Write(itemBytes, 0, itemBytes.Length);
}
}
var imageData = options["imageData"] as string;
byte[] fileToUpload = Convert.FromBase64CharArray(imageData.ToCharArray(), 0, imageData.Length);
string fileFormKey = "image";
string fileName = "image.png";
string fileMimeType = "image/png";
string HeaderTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n";
string header = String.Format(HeaderTemplate, boundary, fileFormKey, fileName, fileMimeType);
byte[] headerbytes = Encoding.UTF8.GetBytes(header);
requestStream.Write(headerbytes, 0, headerbytes.Length);
using (MemoryStream fileStream = new MemoryStream(fileToUpload))
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
}
byte[] newlineBytes = Encoding.UTF8.GetBytes("\r\n");
requestStream.Write(newlineBytes, 0, newlineBytes.Length);
byte[] endBytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "--");
requestStream.Write(endBytes, 0, endBytes.Length);
requestStream.Close();
}
try
{
using (var response = await request.GetResponseAsync() as HttpWebResponse)
{
if (response.Headers["Set-Cookie"] != null)
{
_cookieDirty = true;
}
using (var stream = response.GetResponseStream())
using (var streamReader = new StreamReader(stream))
{
if (callback.CanExecute == true)
{
callback.ExecuteAsync(null, new
{
data = await streamReader.ReadToEndAsync(),
status = response.StatusCode
});
}
}
}
}
catch (WebException webException)
{
if (webException.Response is HttpWebResponse response)
{
if (response.Headers["Set-Cookie"] != null)
{
_cookieDirty = true;
}
using (var stream = response.GetResponseStream())
using (var streamReader = new StreamReader(stream))
{
if (callback.CanExecute == true)
{
callback.ExecuteAsync(null, new
{
data = await streamReader.ReadToEndAsync(),
status = response.StatusCode
});
}
}
}
else if (callback.CanExecute == true)
{
callback.ExecuteAsync(webException.Message, null);
}
}
}
catch (Exception e)
{
if (callback.CanExecute == true)
{
// FIXME: 브라우저는 종료되었는데 얘는 이후에 실행되면 터짐
callback.ExecuteAsync(e.Message, null);
}
}
callback.Dispose();
}
#pragma warning restore CS4014
}
}