forked from dexiio/cloudscrape-client-net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CloudScrape.cs
603 lines (525 loc) · 17.8 KB
/
CloudScrape.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
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web.Script.Serialization;
namespace CloudScrapeAPI
{
/// <summary>
/// Cloud Response details
/// </summary>
class CloudResponse
{
public string Content { get; set; }
public WebHeaderCollection Headers { get; set; }
public HttpStatusCode statusCode { get; set; }
public string StatusDescription { get; set; }
}
/// <summary>
/// Cloud Scrape class
/// </summary>
class CloudScrape
{
private CloudScrapeClient client;
/// <summary>
/// Initial method
/// </summary>
/// <param name="apiKey"></param>
/// <param name="accountId"></param>
public void Init(string apiKey, string accountId)
{
client = new CloudScrapeClient(apiKey, accountId);
}
/// <summary>
/// Default Client
/// </summary>
/// <returns></returns>
public CloudScrapeClient DefaultClient()
{
CheckState();
return client;
}
/// <summary>
/// Execute Method
/// </summary>
/// <returns></returns>
public CloudScrapeExecutions Executions()
{
CheckState();
return client.Executions();
}
/// <summary>
/// Run Method
/// </summary>
/// <returns></returns>
public CloudScrapeRuns Runs()
{
CheckState();
return client.Runs();
}
/// <summary>
/// Check State
/// </summary>
private void CheckState()
{
if (client == null)
{
throw new Exception("You must call init first before using the API");
}
}
}
/// <summary>
/// Cloud Scrape Client
/// </summary>
class CloudScrapeClient
{
private string apiKey;
private string accountId;
private string accessKey;
private string _endPoint = "https://app.cloudscrape.com/api/";
private string _userAgent = "CS-ASP-CLIENT/1.0";
private int _requestTimeout = 60*60*1000;
private CloudScrapeExecutions objExecutions;
private CloudScrapeRuns objRuns;
/// <summary>
/// Endpoint / base url of requests
/// </summary>
public string EndPoint
{
get { return _endPoint; }
set { _endPoint = value; }
}
/// <summary>
/// User agent of requests
/// </summary>
public string UserAgent
{
get { return _userAgent; }
set { _userAgent = value; }
}
/// <summary>
/// Set request timeout. Defaults to 1 hour
/// Note: If you are using the sync methods and some requests are running for very long you need to increase this value.
/// </summary>
public int RequestTimeout
{
get { return _requestTimeout; }
set { _requestTimeout = value; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="apiKey"></param>
/// <param name="accountId"></param>
public CloudScrapeClient(string apiKey, string accountId)
{
this.accountId = accountId;
this.accessKey = CreateMD5(accountId + apiKey).ToLower();
this.objExecutions = new CloudScrapeExecutions(this);
this.objRuns = new CloudScrapeRuns(this);
}
/// <summary>
/// Make a call to the CloudScrape API
/// </summary>
/// <param name="url"></param>
/// <param name="method"></param>
/// <param name="body"></param>
/// <returns></returns>
public CloudResponse Request(string url, string method = "GET", string body = null)
{
var req = System.Net.HttpWebRequest.Create(EndPoint + url) as HttpWebRequest;
req.Headers.Add("X-CloudScrape-Access", accessKey);
req.Headers.Add("X-CloudScrape-Account", accountId);
req.UserAgent = _userAgent;
req.Timeout = _requestTimeout;
req.Accept = "application/json";
req.ContentType = "application/json";
req.Method = method;
if (body != null)
{
using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
streamWriter.Write(body);
streamWriter.Flush();
}
}
CloudResponse objCloudResponse = null;
HttpWebResponse response = null;
StreamReader readStream = null;
try
{
response = (HttpWebResponse)req.GetResponse();
objCloudResponse = new CloudResponse();
objCloudResponse.statusCode = response.StatusCode;
objCloudResponse.Headers = response.Headers;
objCloudResponse.StatusDescription = response.StatusDescription;
WebHeaderCollection obj = response.Headers;
Stream receiveStream = response.GetResponseStream();
readStream = new StreamReader(receiveStream, Encoding.UTF8);
objCloudResponse.Content = readStream.ReadToEnd();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (response != null)
{
response.Close();
}
if (readStream != null)
{
readStream.Close();
}
}
return objCloudResponse;
}
/// <summary>
/// MD5 Encryption
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
private string CreateMD5(string input)
{
// Use input string to calculate MD5 hash
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);
// Convert the byte array to hexadecimal string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("X2"));
}
return sb.ToString();
}
/// <summary>
/// Execute request
/// </summary>
/// <param name="url"></param>
/// <param name="method"></param>
/// <param name="body"></param>
/// <returns></returns>
public string RequestJson(string url, string method = "GET", string body = null)
{
CloudResponse response = this.Request(url, method, body);
return response.Content;
}
/// <summary>
/// Get response boolean value
/// </summary>
/// <param name="url"></param>
/// <param name="method"></param>
/// <param name="body"></param>
/// <returns></returns>
public bool RequestBoolean(string url, string method = "GET", string body = null)
{
this.Request(url, method, body);
return true;
}
/// <summary>
/// Interact with executions.
/// </summary>
/// <returns></returns>
public CloudScrapeExecutions Executions()
{
return this.objExecutions;
}
/// <summary>
/// Interact with runs
/// </summary>
/// <returns></returns>
public CloudScrapeRuns Runs()
{
return this.objRuns;
}
}
/// <summary>
/// Execute Cloud Scrape request
/// </summary>
class CloudScrapeExecutions
{
private CloudScrapeClient client;
private JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
public CloudScrapeExecutions(CloudScrapeClient client)
{
this.client = client;
}
/// <summary>
/// Get execution
/// </summary>
/// <param name="executionId"></param>
/// <returns></returns>
public CloudScrapeExecutionDTO Get(string executionId)
{
string strResponse = this.client.RequestJson("executions/" + executionId);
var result = jsonSerializer.Deserialize<CloudScrapeExecutionDTO>(strResponse);
return result;
}
/// <summary>
/// Delete execution permanently
/// </summary>
/// <param name="executionId"></param>
/// <returns></returns>
public bool Remove(string executionId)
{
return this.client.RequestBoolean("executions/" + executionId, "DELETE");
}
/// <summary>
/// Get the entire result of an execution.
/// </summary>
/// <param name="executionId"></param>
/// <returns></returns>
public CloudScrapeResultDTO GetResult(string executionId)
{
string strResponse = this.client.RequestJson("executions/" + executionId + "/result");
var result = jsonSerializer.Deserialize<CloudScrapeResultDTO>(strResponse);
return result;
}
/// <summary>
/// Get a file from a result set
/// </summary>
/// <param name="executionId"></param>
/// <param name="fileId"></param>
/// <returns></returns>
public CloudScrapeFileDTO GetResultFile(string executionId, string fileId)
{
var response = this.client.Request("executions/" + executionId + "/file/" + fileId);
return new CloudScrapeFileDTO(response.Headers["Content-Type"], response.Content);
}
/// <summary>
/// Stop running execution
/// </summary>
/// <param name="executionId"></param>
/// <returns></returns>
public bool Stop(string executionId)
{
return this.client.RequestBoolean("executions/" + executionId + "/stop", "POST");
}
/// <summary>
/// Resume stopped execution
/// </summary>
/// <param name="executionId"></param>
/// <returns></returns>
public bool Resume(string executionId)
{
return this.client.RequestBoolean("executions/" + executionId + "/continue", "POST");
}
}
/// <summary>
/// Run Cloud Scrape robots
/// </summary>
class CloudScrapeRuns
{
private CloudScrapeClient client;
private JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
/// <summary>
/// Constructor
/// </summary>
/// <param name="client"></param>
public CloudScrapeRuns(CloudScrapeClient client)
{
this.client = client;
}
/// <summary>
/// Get Run Detail
/// </summary>
/// <param name="runId"></param>
/// <returns></returns>
public CloudScrapeRunDTO Get(string runId)
{
string strResponse = this.client.RequestJson("runs/" + runId);
var result = jsonSerializer.Deserialize<CloudScrapeRunDTO>(strResponse);
return result;
}
/// <summary>
/// Permanently delete run
/// </summary>
/// <param name="runId"></param>
/// <returns></returns>
public bool Remove(string runId)
{
return this.client.RequestBoolean("runs/" + runId, "DELETE");
}
/// <summary>
/// Start new execution of the run
/// </summary>
/// <param name="runId"></param>
/// <returns></returns>
public CloudScrapeExecutionDTO Execute(string runId)
{
string strResponse = this.client.RequestJson("runs/" + runId + "/execute", "POST");
var result = jsonSerializer.Deserialize<CloudScrapeExecutionDTO>(strResponse);
return result;
}
/// <summary>
/// Start new execution of the run, and wait for it to finish before returning the result.
/// The execution and result will be automatically deleted from CloudScrape completion
/// both successful and failed.
/// </summary>
/// <param name="runId"></param>
/// <returns></returns>
public CloudScrapeResultDTO ExecuteSync(string runId)
{
string strResponse = this.client.RequestJson("runs/" + runId + "/execute/wait", "POST");
var result = jsonSerializer.Deserialize<CloudScrapeResultDTO>(strResponse);
return result;
}
/// <summary>
/// Starts new execution of run with given inputs
/// </summary>
/// <param name="runId"></param>
/// <param name="inputs"></param>
/// <returns></returns>
public CloudScrapeExecutionDTO ExecuteWithInput(string runId, string inputs)
{
string strResponse = this.client.RequestJson("runs/" + runId + "/execute/inputs", "POST", inputs);
var result = jsonSerializer.Deserialize<CloudScrapeExecutionDTO>(strResponse);
return result;
}
/// <summary>
/// Starts new execution of run with given inputs, and wait for it to finish before returning the result.
/// The inputs, execution and result will be automatically deleted from CloudScrape upon completion - both successful and failed.
/// </summary>
/// <param name="runId"></param>
/// <param name="inputs"></param>
/// <returns></returns>
public CloudScrapeResultDTO ExecuteWithInputSync(string runId, string inputs)
{
string strResponse = this.client.RequestJson("runs/" + runId + "/execute/inputs/wait", "POST", inputs);
var result = jsonSerializer.Deserialize<CloudScrapeResultDTO>(strResponse);
return result;
}
/// <summary>
/// Get the result from the latest execution of the given run.
/// </summary>
/// <param name="runId"></param>
/// <returns></returns>
public CloudScrapeResultDTO GetLatestResult(string runId)
{
string strResponse = this.client.RequestJson("runs/" + runId + "/latest/result");
var result = jsonSerializer.Deserialize<CloudScrapeResultDTO>(strResponse);
return result;
}
/// <summary>
/// Get executions for the given run.
/// </summary>
/// <param name="runId"></param>
/// <param name="offset"></param>
/// <param name="limit"></param>
/// <returns></returns>
public CloudScrapeExecutionListDTO GetExecutions(string runId, int offset = 0, int limit = 30)
{
string strResponse = this.client.RequestJson("runs/" + runId + "/executions?offset=" + offset + "&limit=" + limit);
var result = jsonSerializer.Deserialize<CloudScrapeExecutionListDTO>(strResponse);
return result;
}
}
/// <summary>
/// Cloud Scrape Execution DTO class
/// </summary>
class CloudScrapeExecutionDTO
{
const string QUEUED = "QUEUED";
const string PENDING = "PENDING";
const string RUNNING = "RUNNING";
const string FAILED = "FAILED";
const string STOPPED = "STOPPED";
const string OK = "OK";
/// <summary>
/// The ID of the execution
/// </summary>
public string _id;
/// <summary>
/// State of the executions. See const definitions on class to see options
/// </summary>
public string _state;
/// <summary>
/// Time the executions was started - in milliseconds since unix epoch
/// </summary>
public int _starts;
/// <summary>
/// Time the executions finished - in milliseconds since unix epoch.
/// </summary>
public int _finished;
}
/// <summary>
/// Cloud Scrape Execution List DTO
/// </summary>
class CloudScrapeExecutionListDTO
{
/// <summary>
/// off set
/// </summary>
public int offset;
/// <summary>
/// total rows
/// </summary>
public int totalRows;
/// <summary>
/// array of rows
/// </summary>
public CloudScrapeExecutionDTO[] rows;
}
/// <summary>
/// Cloud Scrape Result DTO
/// </summary>
class CloudScrapeResultDTO
{
/**
* Header fields
* @var string[]
*/
public string[] headers;
/**
* An array of arrays containing each row - with each value inside it.
* @var mixed[][]
*/
public string[][] rows;
/**
* Total number of rows available
* @var int
*/
public int totalRows;
}
/// <summary>
/// Cloud Scrape File DTO
/// </summary>
class CloudScrapeFileDTO
{
/// <summary>
/// The type of file
/// </summary>
public string mimeType;
/// <summary>
/// The contents of the file
/// </summary>
public string contents;
/// <summary>
/// Constructor
/// </summary>
/// <param name="mimeType"></param>
/// <param name="contents"></param>
public CloudScrapeFileDTO(string mimeType, string contents)
{
this.mimeType = mimeType;
this.contents = contents;
}
}
/// <summary>
/// Cloud Scrape Run DTO
/// </summary>
class CloudScrapeRunDTO
{
/// <summary>
/// The ID of the run
/// </summary>
public string _id;
/// <summary>
/// Name of the run
/// </summary>
public string name;
}
}