forked from vrcx-team/VRCX
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebApi.cs
382 lines (354 loc) · 15.5 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
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
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;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
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();
SaveCookies();
}
internal void LoadCookies()
{
SQLiteLegacy.Instance.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS `cookies` (`key` TEXT PRIMARY KEY, `value` TEXT)");
SQLiteLegacy.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);
SQLiteLegacy.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()
{
_cookieDirty = true; // force cookies to be saved for lastUserLoggedIn
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);
}
_cookieDirty = true; // force cookies to be saved for lastUserLoggedIn
}
private static async Task LegacyImageUpload(HttpWebRequest request, IDictionary<string, object> options)
{
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 = Encoding.UTF8.GetBytes(item);
await requestStream.WriteAsync(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);
await requestStream.WriteAsync(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)
{
await requestStream.WriteAsync(buffer, 0, bytesRead);
}
fileStream.Close();
}
byte[] newlineBytes = Encoding.UTF8.GetBytes("\r\n");
await requestStream.WriteAsync(newlineBytes, 0, newlineBytes.Length);
byte[] endBytes = Encoding.UTF8.GetBytes("--" + boundary + "--");
await requestStream.WriteAsync(endBytes, 0, endBytes.Length);
requestStream.Close();
}
private static async Task UploadFilePut(HttpWebRequest request, IDictionary<string, object> options)
{
request.Method = "PUT";
request.ContentType = options["fileMIME"] as string;
var fileData = options["fileData"] as string;
var sentData = Convert.FromBase64CharArray(fileData.ToCharArray(), 0, fileData.Length);
request.ContentLength = sentData.Length;
using (var sendStream = request.GetRequestStream())
{
await sendStream.WriteAsync(sentData, 0, sentData.Length);
sendStream.Close();
}
}
private static async Task ImageUpload(HttpWebRequest request, IDictionary<string, object> options)
{
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))
{
var jsonPostData = (JObject)JsonConvert.DeserializeObject((string)postDataObject);
Dictionary<string, string> postData = new Dictionary<string, string>();
string formDataTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n";
if (jsonPostData != null)
{
foreach (var data in jsonPostData)
{
string item = string.Format(formDataTemplate, boundary, data.Key, data.Value);
byte[] itemBytes = Encoding.UTF8.GetBytes(item);
await requestStream.WriteAsync(itemBytes, 0, itemBytes.Length);
}
}
}
var imageData = options["imageData"] as string;
byte[] fileToUpload = Convert.FromBase64CharArray(imageData.ToCharArray(), 0, imageData.Length);
string fileFormKey = "file";
string fileName = "blob";
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);
await requestStream.WriteAsync(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)
{
await requestStream.WriteAsync(buffer, 0, bytesRead);
}
fileStream.Close();
}
byte[] newlineBytes = Encoding.UTF8.GetBytes("\r\n");
await requestStream.WriteAsync(newlineBytes, 0, newlineBytes.Length);
byte[] endBytes = Encoding.UTF8.GetBytes("--" + boundary + "--");
await requestStream.WriteAsync(endBytes, 0, endBytes.Length);
requestStream.Close();
}
#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;
request.UserAgent = Program.Version;
if (options.TryGetValue("headers", out object headers))
{
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, "Referer", StringComparison.OrdinalIgnoreCase) == 0)
{
request.Referer = value;
}
else
{
request.Headers.Add(key, value);
}
}
}
if (options.TryGetValue("method", out object method))
{
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("uploadImage", out _))
{
await ImageUpload(request, options);
}
if (options.TryGetValue("uploadFilePUT", out _))
{
await UploadFilePut(request, options);
}
if (options.TryGetValue("uploadImageLegacy", out _))
{
await LegacyImageUpload(request, options);
}
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)
{
if (response.ContentType.Contains("image/") || response.ContentType.Contains("application/octet-stream"))
{
// base64 response data for image
using (var memoryStream = new MemoryStream())
{
await stream.CopyToAsync(memoryStream);
callback.ExecuteAsync(null, new
{
data = $"data:image/png;base64,{Convert.ToBase64String(memoryStream.ToArray())}",
status = response.StatusCode
});
}
}
else
{
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
}
}