/
BlockRequest.cs
633 lines (541 loc) · 25 KB
/
BlockRequest.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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
using Extreme.Net;
using RuriLib.Functions.Formats;
using RuriLib.LS;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Media;
using RuriLib.Functions.Requests;
using RuriLib.Functions.Files;
using MultipartContent = RuriLib.Functions.Requests.MultipartContent;
namespace RuriLib
{
/// <summary>
/// The types of request that can be performed.
/// </summary>
public enum RequestType
{
/// <summary>A standard request with standard content.</summary>
Standard,
/// <summary>A request which uses the 'Authentication: Basic' header.</summary>
BasicAuth,
/// <summary>A request which contains multipart content (strings and/or files).</summary>
Multipart,
/// <summary>A request which sends a raw byte stream.</summary>
Raw
}
/// <summary>
/// The available types of multipart contents.
/// </summary>
public enum MultipartContentType
{
/// <summary>A string content.</summary>
String,
/// <summary>A file content.</summary>
File
}
/// <summary>
/// The type of data expected inside the HTTP response.
/// </summary>
public enum ResponseType
{
/// <summary>A string response, e.g. an HTML page.</summary>
String,
/// <summary>A file response, e.g. an image.</summary>
File,
/// <summary>A byte array response encoded as a base64 string.</summary>
Base64String
}
/// <summary>
/// A block that can perform HTTP requests.
/// </summary>
public class BlockRequest : BlockBase
{
#region Variables
private string url = "https://google.com";
/// <summary>The URL to call, including additional GET query parameters.</summary>
public string Url { get { return url; } set { url = value; OnPropertyChanged(); } }
private RequestType requestType = RequestType.Standard;
/// <summary>The request type.</summary>
public RequestType RequestType { get { return requestType; } set { requestType = value; OnPropertyChanged(); } }
// Basic Auth
private string authUser = "";
/// <summary>The username for basic auth requests.</summary>
public string AuthUser { get { return authUser; } set { authUser = value; OnPropertyChanged(); } }
private string authPass = "";
/// <summary>The password for basic auth requests.</summary>
public string AuthPass { get { return authPass; } set { authPass = value; OnPropertyChanged(); } }
// Standard
private string postData = "";
/// <summary>The content of the request, sent after the headers. Use '\n' to input a linebreak.</summary>
public string PostData { get { return postData; } set { postData = value; OnPropertyChanged(); } }
// Raw
private string rawData = "";
/// <summary>The content of the request as a raw HEX string that will be sent as a bytestream.</summary>
public string RawData { get { return rawData; } set { rawData = value; OnPropertyChanged(); } }
private HttpMethod method = HttpMethod.GET;
/// <summary>The method of the HTTP request.</summary>
public HttpMethod Method { get { return method; } set { method = value; OnPropertyChanged(); } }
private SecurityProtocol securityProtocol = SecurityProtocol.SystemDefault;
/// <summary>The security protocol(s) to use for the HTTPS request.</summary>
public SecurityProtocol SecurityProtocol { get { return securityProtocol; } set { securityProtocol = value; OnPropertyChanged(); } }
/// <summary>The custom headers that are sent in the HTTP request.</summary>
public Dictionary<string, string> CustomHeaders { get; set; } = new Dictionary<string, string>() {
{ "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" },
{ "Pragma", "no-cache" },
{ "Accept", "*/*" }
};
/// <summary>The custom cookies that are sent in the HTTP request.</summary>
public Dictionary<string, string> CustomCookies { get; set; } = new Dictionary<string, string>() { };
private string contentType = "application/x-www-form-urlencoded";
/// <summary>The type of content the server should expect.</summary>
public string ContentType { get { return contentType; } set { contentType = value; OnPropertyChanged(); } }
private bool autoRedirect = true;
/// <summary>Whether to perform automatic redirection in the case of 3xx headers.</summary>
public bool AutoRedirect { get { return autoRedirect; } set { autoRedirect = value; OnPropertyChanged(); } }
private bool readResponseSource = true;
/// <summary>Whether to read the stream of data from the HTTP response. Set to false if only the headers are needed, in order to speed up the process.</summary>
public bool ReadResponseSource { get { return readResponseSource; } set { readResponseSource = value; OnPropertyChanged(); } }
private bool encodeContent = false;
/// <summary>Whether to URL encode the content before sending it.</summary>
public bool EncodeContent { get { return encodeContent; } set { encodeContent = value; OnPropertyChanged(); } }
private bool acceptEncoding = true;
/// <summary>Whether to automatically generate an Accept-Encoding header.</summary>
public bool AcceptEncoding { get { return acceptEncoding; } set { acceptEncoding = value; OnPropertyChanged(); } }
// Multipart
private string multipartBoundary = "";
/// <summary>The boundary that separates multipart contents.</summary>
public string MultipartBoundary { get { return multipartBoundary; } set { multipartBoundary = value; OnPropertyChanged(); } }
/// <summary>The list of contents to send in a multipart request.</summary>
public List<MultipartContent> MultipartContents { get; set; } = new List<MultipartContent>();
private ResponseType responseType = ResponseType.String;
/// <summary>The type of response expected from the server.</summary>
public ResponseType ResponseType { get { return responseType; } set { responseType = value; OnPropertyChanged(); } }
private string downloadPath = "";
/// <summary>The path of the file where a FILE response needs to be stored.</summary>
public string DownloadPath { get { return downloadPath; } set { downloadPath = value; OnPropertyChanged(); } }
private string outputVariable = "";
/// <summary>The variable name for Base64String response.</summary>
public string OutputVariable { get { return outputVariable; } set { outputVariable = value; OnPropertyChanged(); } }
private bool saveAsScreenshot = false;
/// <summary>Whether to add the downloaded image to the default screenshot path.</summary>
public bool SaveAsScreenshot { get { return saveAsScreenshot; } set { saveAsScreenshot = value; OnPropertyChanged(); } }
#endregion
/// <summary>
/// Creates a Request block.
/// </summary>
public BlockRequest()
{
Label = "REQUEST";
}
/// <inheritdoc />
public override BlockBase FromLS(string line)
{
// Trim the line
var input = line.Trim();
// Parse the label
if (input.StartsWith("#"))
Label = LineParser.ParseLabel(ref input);
Method = (HttpMethod)LineParser.ParseEnum(ref input, "METHOD", typeof(HttpMethod));
Url = LineParser.ParseLiteral(ref input, "URL");
while (LineParser.Lookahead(ref input) == TokenType.Boolean)
LineParser.SetBool(ref input, this);
CustomHeaders.Clear(); // Remove the default headers
while (input != string.Empty && !input.StartsWith("->"))
{
var parsed = LineParser.ParseToken(ref input, TokenType.Parameter, true).ToUpper();
switch (parsed)
{
case "MULTIPART":
RequestType = RequestType.Multipart;
break;
case "BASICAUTH":
RequestType = RequestType.BasicAuth;
break;
case "STANDARD":
RequestType = RequestType.Standard;
break;
case "RAW":
RequestType = RequestType.Raw;
break;
case "CONTENT":
PostData = LineParser.ParseLiteral(ref input, "POST DATA");
break;
case "RAWDATA":
RawData = LineParser.ParseLiteral(ref input, "RAW DATA");
break;
case "STRINGCONTENT":
var stringContentPair = ParseString(LineParser.ParseLiteral(ref input, "STRING CONTENT"), ':', 2);
MultipartContents.Add(new MultipartContent() { Type = MultipartContentType.String, Name = stringContentPair[0], Value = stringContentPair[1] });
break;
case "FILECONTENT":
var fileContentTriplet = ParseString(LineParser.ParseLiteral(ref input, "FILE CONTENT"), ':', 3);
MultipartContents.Add(new MultipartContent() { Type = MultipartContentType.File, Name = fileContentTriplet[0], Value = fileContentTriplet[1], ContentType = fileContentTriplet[2] });
break;
case "COOKIE":
var cookiePair = ParseString(LineParser.ParseLiteral(ref input, "COOKIE VALUE"), ':', 2);
CustomCookies[cookiePair[0]] = cookiePair[1];
break;
case "HEADER":
var headerPair = ParseString(LineParser.ParseLiteral(ref input, "HEADER VALUE"), ':', 2);
CustomHeaders[headerPair[0]] = headerPair[1];
break;
case "CONTENTTYPE":
ContentType = LineParser.ParseLiteral(ref input, "CONTENT TYPE");
break;
case "USERNAME":
AuthUser = LineParser.ParseLiteral(ref input, "USERNAME");
break;
case "PASSWORD":
AuthPass = LineParser.ParseLiteral(ref input, "PASSWORD");
break;
case "BOUNDARY":
MultipartBoundary = LineParser.ParseLiteral(ref input, "BOUNDARY");
break;
case "SECPROTO":
SecurityProtocol = LineParser.ParseEnum(ref input, "Security Protocol", typeof(SecurityProtocol));
break;
default:
break;
}
}
if (input.StartsWith("->"))
{
LineParser.EnsureIdentifier(ref input, "->");
var outType = LineParser.ParseToken(ref input, TokenType.Parameter, true);
if (outType.ToUpper() == "STRING") ResponseType = ResponseType.String;
else if (outType.ToUpper() == "FILE")
{
ResponseType = ResponseType.File;
DownloadPath = LineParser.ParseLiteral(ref input, "DOWNLOAD PATH");
while (LineParser.Lookahead(ref input) == TokenType.Boolean)
{
LineParser.SetBool(ref input, this);
}
}
else if (outType.ToUpper() == "BASE64")
{
ResponseType = ResponseType.Base64String;
OutputVariable = LineParser.ParseLiteral(ref input, "OUTPUT VARIABLE");
}
}
return this;
}
/// <summary>
/// Parses values from a string.
/// </summary>
/// <param name="input">The string to parse</param>
/// <param name="separator">The character that separates the elements</param>
/// <param name="count">The number of elements to return</param>
/// <returns>The array of the parsed elements.</returns>
public static string[] ParseString(string input, char separator, int count)
{
return input.Split(new[] { separator }, count).Select(s => s.Trim()).ToArray();
}
/// <inheritdoc />
public override string ToLS(bool indent = true)
{
var writer = new BlockWriter(GetType(), indent, Disabled);
writer
.Label(Label)
.Token("REQUEST")
.Token(Method)
.Literal(Url)
.Boolean(AcceptEncoding, "AcceptEncoding")
.Boolean(AutoRedirect, "AutoRedirect")
.Boolean(ReadResponseSource, "ReadResponseSource")
.Boolean(EncodeContent, "EncodeContent")
.Token(RequestType, "RequestType")
.Indent();
switch (RequestType)
{
case RequestType.BasicAuth:
writer
.Token("USERNAME")
.Literal(AuthUser)
.Token("PASSWORD")
.Literal(AuthPass)
.Indent();
break;
case RequestType.Standard:
if (HttpRequest.CanContainRequestBody(method))
{
writer
.Token("CONTENT")
.Literal(PostData)
.Indent()
.Token("CONTENTTYPE")
.Literal(ContentType);
}
break;
case RequestType.Multipart:
foreach(var c in MultipartContents)
{
writer
.Indent()
.Token($"{c.Type.ToString().ToUpper()}CONTENT");
if (c.Type == MultipartContentType.String)
{
writer.Literal($"{c.Name}: {c.Value}");
}
else if (c.Type == MultipartContentType.File)
{
writer.Literal($"{c.Name}: {c.Value}: {c.ContentType}");
}
}
if (!writer.CheckDefault(MultipartBoundary, "MultipartBoundary"))
{
writer
.Indent()
.Token("BOUNDARY")
.Literal(MultipartBoundary);
}
break;
case RequestType.Raw:
if (HttpRequest.CanContainRequestBody(method))
{
writer
.Token("RAWDATA")
.Literal(RawData)
.Indent()
.Token("CONTENTTYPE")
.Literal(ContentType);
}
break;
}
if (SecurityProtocol != SecurityProtocol.SystemDefault)
{
writer
.Indent()
.Token("SECPROTO")
.Token(SecurityProtocol, "SecurityProtocol");
}
foreach (var c in CustomCookies)
{
writer
.Indent()
.Token("COOKIE")
.Literal($"{c.Key}: {c.Value}");
}
foreach (var h in CustomHeaders)
{
writer
.Indent()
.Token("HEADER")
.Literal($"{h.Key}: {h.Value}");
}
if (ResponseType == ResponseType.File)
{
writer
.Indent()
.Arrow()
.Token("FILE")
.Literal(DownloadPath)
.Boolean(SaveAsScreenshot, "SaveAsScreenshot");
}
else if (ResponseType == ResponseType.Base64String)
{
writer
.Indent()
.Arrow()
.Token("BASE64")
.Literal(OutputVariable);
}
return writer.ToString();
}
/// <inheritdoc />
public override void Process(BotData data)
{
base.Process(data);
// Setup
var request = new Request();
request.Setup(data.GlobalSettings, securityProtocol, AutoRedirect, data.ConfigSettings.MaxRedirects, AcceptEncoding);
var localUrl = ReplaceValues(Url, data);
data.Log(new LogEntry($"Calling URL: {localUrl}", Colors.MediumTurquoise));
// Set content
switch (RequestType)
{
case RequestType.Standard:
request.SetStandardContent(ReplaceValues(PostData, data), ReplaceValues(ContentType, data), Method, EncodeContent, GetLogBuffer(data));
break;
case RequestType.BasicAuth:
request.SetBasicAuth(ReplaceValues(AuthUser, data), ReplaceValues(AuthPass, data));
break;
case RequestType.Multipart:
var contents = MultipartContents.Select(m =>
new MultipartContent()
{
Name = ReplaceValues(m.Name, data),
Value = ReplaceValues(m.Value, data),
ContentType = ReplaceValues(m.Value, data),
Type = m.Type
});
request.SetMultipartContent(contents, ReplaceValues(MultipartBoundary, data), GetLogBuffer(data));
break;
case RequestType.Raw:
request.SetRawContent(ReplaceValues(RawData, data), ReplaceValues(ContentType, data), Method, GetLogBuffer(data));
break;
}
// Set proxy
if (data.UseProxies)
{
request.SetProxy(data.Proxy);
}
// Set headers
data.Log(new LogEntry("Sent Headers:", Colors.DarkTurquoise));
var headers = CustomHeaders.Select( h =>
new KeyValuePair<string, string> (ReplaceValues(h.Key, data), ReplaceValues(h.Value, data))
).ToDictionary(h => h.Key, h => h.Value);
request.SetHeaders(headers, AcceptEncoding, GetLogBuffer(data));
// Set cookies
data.Log(new LogEntry("Sent Cookies:", Colors.MediumTurquoise));
foreach (var cookie in CustomCookies) // Add new user-defined custom cookies to the bot's cookie jar
data.Cookies[ReplaceValues(cookie.Key, data)] = ReplaceValues(cookie.Value, data);
request.SetCookies(data.Cookies, GetLogBuffer(data));
// End the request part
data.LogNewLine();
// Perform the request
try
{
(data.Address, data.ResponseCode, data.ResponseHeaders, data.Cookies) = request.Perform(localUrl, Method, GetLogBuffer(data));
}
catch (Exception ex)
{
if (data.ConfigSettings.IgnoreResponseErrors)
{
data.Log(new LogEntry(ex.Message, Colors.Tomato));
data.ResponseSource = ex.Message;
return;
}
throw;
}
// Save the response content
switch (ResponseType)
{
case ResponseType.String:
data.ResponseSource = request.SaveString(ReadResponseSource, data.ResponseHeaders, GetLogBuffer(data));
break;
case ResponseType.File:
if (SaveAsScreenshot)
{
Files.SaveScreenshot(request.GetResponseStream(), data); // Read the stream
data.Log(new LogEntry("File saved as screenshot", Colors.Green));
}
else
{
request.SaveFile(ReplaceValues(DownloadPath, data), GetLogBuffer(data));
}
break;
case ResponseType.Base64String:
var base64 = Convert.ToBase64String(request.GetResponseStream().ToArray());
InsertVariable(data, false, base64, OutputVariable);
break;
default:
break;
}
}
#region Custom Cookies, Headers and Multipart Contents
/// <summary>
/// Builds a string containing custom cookies.
/// </summary>
/// <returns>One cookie per line, with name and value separated by a colon</returns>
public string GetCustomCookies()
{
StringBuilder sb = new StringBuilder();
foreach (var pair in CustomCookies)
{
sb.Append($"{pair.Key}: {pair.Value}");
if (!pair.Equals(CustomCookies.Last())) sb.Append(Environment.NewLine);
}
return sb.ToString();
}
/// <summary>
/// Sets custom cookies from an array of lines.
/// </summary>
/// <param name="lines">The lines containing the colon-separated name and value of the cookies</param>
public void SetCustomCookies(string[] lines)
{
CustomCookies.Clear();
foreach (var line in lines)
{
if (line.Contains(':'))
{
var split = line.Split(new[] { ':' }, 2);
CustomCookies[split[0].Trim()] = split[1].Trim();
}
}
}
/// <summary>
/// Builds a string containing custom headers.
/// </summary>
/// <returns>One header per line, with name and value separated by a colon</returns>
public string GetCustomHeaders()
{
StringBuilder sb = new StringBuilder();
foreach (var pair in CustomHeaders)
{
sb.Append($"{pair.Key}: {pair.Value}");
if (!pair.Equals(CustomHeaders.Last())) sb.Append(Environment.NewLine);
}
return sb.ToString();
}
/// <summary>
/// Sets custom headers from an array of lines.
/// </summary>
/// <param name="lines">The lines containing the colon-separated name and value of the headers</param>
public void SetCustomHeaders(string[] lines)
{
CustomHeaders.Clear();
foreach (var line in lines)
{
if (line.Contains(':'))
{
var split = line.Split(new[] { ':' }, 2);
CustomHeaders[split[0].Trim()] = split[1].Trim();
}
}
}
/// <summary>
/// Builds a string containing multipart content.
/// </summary>
/// <returns>One content per line, with type, name and value separated by a colon</returns>
public string GetMultipartContents()
{
StringBuilder sb = new StringBuilder();
foreach (var c in MultipartContents)
{
sb.Append($"{c.Type.ToString().ToUpper()}: {c.Name}: {c.Value}");
if (!c.Equals(MultipartContents.Last())) sb.Append(Environment.NewLine);
}
return sb.ToString();
}
/// <summary>
/// Sets multipart contents from an array of lines.
/// </summary>
/// <param name="lines">The lines containing the colon-separated type, name and value of the multipart contents</param>
public void SetMultipartContents(string[] lines)
{
MultipartContents.Clear();
foreach(var line in lines)
{
try
{
var split = line.Split(new[] { ':' }, 3);
MultipartContents.Add(new MultipartContent() {
Type = (MultipartContentType)Enum.Parse(typeof(MultipartContentType), split[0].Trim(), true),
Name = split[1].Trim(),
Value = split[2].Trim()
});
}
catch { }
}
}
#endregion
private List<LogEntry> GetLogBuffer(BotData data) => data.GlobalSettings.General.EnableBotLog || data.IsDebug ? data.LogBuffer : null;
}
}