-
Notifications
You must be signed in to change notification settings - Fork 7
/
VK.Handler.pas
671 lines (610 loc) · 17.9 KB
/
VK.Handler.pas
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
unit VK.Handler;
interface
uses
System.Classes, System.SysUtils, REST.Client, REST.Json, REST.Types, Json,
VK.Types, VK.Entity.Common, REST.Authenticator.OAuth,
System.Generics.Collections;
type
TResponse = record
private
Response: string;
function AppendItemsTag(Json: string): string; inline;
public
Success: Boolean;
Json: string;
Error: record
Code: Integer;
Text: string;
end;
function ResponseText: string;
function ResponseAsItems: string;
function ResponseIsTrue: Boolean;
function ResponseIsFalse: Boolean;
function ResponseAsBool(var Value: Boolean): Boolean;
function ResponseAsInt(var Value: Integer): Boolean;
function ResponseAsInt64(var Value: Int64): Boolean;
function ResponseAsStr(var Value: string): Boolean;
function GetJSONValue: TJSONValue;
function GetJSONResponse: TJSONValue;
function GetValue<T>(const Field: string; var Value: T): Boolean; overload;
function GetValue<T: class>(var Value: T): Boolean; overload;
function GetObject<T: TVkEntity, constructor>(var Value: T): Boolean;
function GetObjects<T: TVkEntity, constructor>(var Value: T): Boolean;
function IsError: Boolean;
end;
TCallMethodCallback = reference to procedure(Respone: TResponse);
TVkHandler = class
private
FProxyServer: string;
FProxyPassword: string;
FProxyPort: Integer;
FProxyUsername: string;
FBaseURL: string;
FStartRequest: Cardinal;
FRequests: Integer;
FOnConfirm: TOnConfirm;
FOnLog: TOnLog;
FUseServiceKeyOnly: Boolean;
FOwner: TObject;
FOnCaptcha: TOnCaptcha;
FOnAuth: TOnAuthNeeded;
FExecuting: Integer;
FLogging: Boolean;
FLogResponse: Boolean;
FCaptchaWait: Boolean;
FAuthWait: Boolean;
FWaitCount: Integer;
FRequestLimit: Integer;
FQueueLock: TObject;
FAuthenticator: TOAuth2Authenticator;
FParams: TDictionary<string, string>;
FLogining: Boolean;
function DoConfirm(Answer: string): Boolean;
procedure SetOnConfirm(const Value: TOnConfirm);
procedure FLog(const Value: string);
procedure SetOnLog(const Value: TOnLog);
procedure SetUseServiceKeyOnly(const Value: Boolean);
procedure SetOwner(const Value: TObject);
procedure SetOnCaptcha(const Value: TOnCaptcha);
function FExecute(Request: TRESTRequest; IsRepeat: Boolean): TResponse;
function GetExecuting: Boolean;
procedure WaitForQueue;
function ProcessResponse(Request: TRESTRequest; IsRepeat: Boolean): TResponse;
procedure SetLogging(const Value: Boolean);
procedure SetLogResponse(const Value: Boolean);
procedure WaitTime(MS: Int64);
function GetWaiting: Boolean;
property Waiting: Boolean read GetWaiting;
function CreateRequest(Resource: string; Params: TParams; Method: TRESTRequestMethod = rmGET): TRESTRequest;
public
constructor Create(AOwner: TObject);
destructor Destroy; override;
procedure Log(Sender: TObject; const Text: string);
function AskCaptcha(Sender: TObject; const CaptchaImg: string; var Answer: string): Boolean;
function DoLogin: Boolean;
function ExecutePost(Request: string; Params: TParams): TResponse; overload;
function Execute(Request: string; Params: TParams): TResponse; overload;
function Execute(Request: string; Param: TParam): TResponse; overload;
function Execute(Request: string): TResponse; overload;
function Execute(Request: TRESTRequest; FreeRequset: Boolean = False; IsRepeat: Boolean = False): TResponse; overload;
property OnConfirm: TOnConfirm read FOnConfirm write SetOnConfirm;
property OnCaptcha: TOnCaptcha read FOnCaptcha write SetOnCaptcha;
property OnAuth: TOnAuthNeeded read FOnAuth write FOnAuth;
property OnLog: TOnLog read FOnLog write SetOnLog;
property UseServiceKeyOnly: Boolean read FUseServiceKeyOnly write SetUseServiceKeyOnly;
property Owner: TObject read FOwner write SetOwner;
property Executing: Boolean read GetExecuting;
property Logging: Boolean read FLogging write SetLogging;
property LogResponse: Boolean read FLogResponse write SetLogResponse;
property Authenticator: TOAuth2Authenticator read FAuthenticator write FAuthenticator;
/// <summary>
/// Лимит запросов в сек (по умолчанию 3)
/// </summary>
property RequestLimit: Integer read FRequestLimit write FRequestLimit;
//
procedure AddParameter(const Name, Value: string);
procedure DeleteParameter(const Name: string);
function Parameter(const Name: string): string;
property ProxyServer: string read FProxyServer write FProxyServer;
property ProxyPassword: string read FProxyPassword write FProxyPassword;
property ProxyPort: Integer read FProxyPort write FProxyPort;
property ProxyUsername: string read FProxyUsername write FProxyUsername;
property BaseURL: string read FBaseURL write FBaseURL;
end;
var
TestCaptcha: Boolean = False;
implementation
uses
VK.Errors, System.SyncObjs;
{ TVkHandler }
procedure TVkHandler.WaitTime(MS: Int64);
var
TS: Cardinal;
begin
if MS <= 0 then
Exit;
Inc(FWaitCount);
while FCaptchaWait or FAuthWait do
Sleep(100);
TS := TThread.GetTickCount;
while (TS + MS > TThread.GetTickCount) do
Sleep(100);
Dec(FWaitCount);
end;
procedure TVkHandler.AddParameter(const Name, Value: string);
begin
TMonitor.Enter(FParams);
try
FParams.Add(Name, Value);
finally
TMonitor.Exit(FParams);
end;
end;
procedure TVkHandler.DeleteParameter(const Name: string);
begin
TMonitor.Enter(FParams);
try
if FParams.ContainsKey(Name) then
FParams.Remove(Name);
finally
TMonitor.Exit(FParams);
end;
end;
function TVkHandler.Parameter(const Name: string): string;
begin
TMonitor.Enter(FParams);
try
if not FParams.TryGetValue(Name, Result) then
Result := '';
finally
TMonitor.Exit(FParams);
end;
end;
function TVkHandler.CreateRequest(Resource: string; Params: TParams; Method: TRESTRequestMethod): TRESTRequest;
var
Param: TParam;
Pair: TPair<string, string>;
begin
Result := TRESTRequest.Create(nil);
Result.SynchronizedEvents := False;
Result.ReadTimeout := 5000;
Result.ConnectTimeout := 5000;
Result.Client := TRESTClient.Create(Result);
Result.Client.SynchronizedEvents := False;
Result.Client.ConnectTimeout := 5000;
Result.Client.ReadTimeout := 5000;
Result.Response := TRESTResponse.Create(Result);
//Result.Client.Authenticator := FAuthenticator;
Result.Client.AddParameter('access_token', FAuthenticator.AccessToken);
Result.Client.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
Result.Client.AcceptCharset := 'UTF-8, *;q=0.8';
TMonitor.Enter(FParams);
try
Result.Client.BaseURL := FBaseURL;
Result.Client.ProxyPort := FProxyPort;
Result.Client.ProxyServer := FProxyServer;
Result.Client.ProxyUsername := FProxyUsername;
Result.Client.ProxyPassword := FProxyPassword;
for Pair in FParams do
Result.Client.AddParameter(Pair.Key, Pair.Value);
finally
TMonitor.Exit(FParams);
end;
Result.Resource := Resource;
Result.Method := Method;
for Param in Params do
begin
if not Param[0].IsEmpty then
Result.Params.AddItem(Param[0], Param[1]);
end;
end;
function TVkHandler.AskCaptcha(Sender: TObject; const CaptchaImg: string; var Answer: string): Boolean;
var
FRes: string;
begin
Result := False;
if Assigned(FOnCaptcha) then
begin
FRes := '';
Synchronize(
procedure
begin
FOnCaptcha(Sender, CaptchaImg, FRes);
end);
Answer := FRes;
Result := not Answer.IsEmpty;
end;
end;
function TVkHandler.DoLogin: Boolean;
var
FRes: Boolean;
begin
Result := False;
if FLogining then
Exit;
FLogining := True;
try
if Assigned(FOnAuth) then
begin
FRes := False;
Synchronize(
procedure
begin
FOnAuth(Self, FRes);
end);
Result := FRes;
end;
finally
FLogining := False;
end;
end;
constructor TVkHandler.Create(AOwner: TObject);
begin
inherited Create;
FParams := TDictionary<string, string>.Create;
FQueueLock := TObject.Create;
FRequestLimit := 3;
FOwner := AOwner;
FCaptchaWait := False;
FAuthWait := False;
FExecuting := 0;
FStartRequest := 0;
FRequests := 0;
end;
destructor TVkHandler.Destroy;
begin
FParams.Free;
FQueueLock.Free;
inherited;
end;
function TVkHandler.DoConfirm(Answer: string): Boolean;
var
FRes: Boolean;
begin
if not Assigned(FOnConfirm) then
begin
Exit(True);
end
else
begin
FRes := False;
Synchronize(
procedure
begin
FOnConfirm(Self, Answer, FRes);
end);
Result := FRes;
end;
end;
function TVkHandler.Execute(Request: string; Param: TParam): TResponse;
begin
Result := Execute(CreateRequest(Request, [Param]), True);
end;
function TVkHandler.Execute(Request: string; Params: TParams): TResponse;
begin
Result := Execute(CreateRequest(Request, Params), True);
end;
function TVkHandler.ExecutePost(Request: string; Params: TParams): TResponse;
begin
Result := Execute(CreateRequest(Request, Params, rmPOST), True);
end;
function TVkHandler.Execute(Request: string): TResponse;
begin
Result := Execute(CreateRequest(Request, []), True);
end;
function TVkHandler.Execute(Request: TRESTRequest; FreeRequset: Boolean; IsRepeat: Boolean): TResponse;
begin
try
Inc(FExecuting);
Result := FExecute(Request, IsRepeat);
finally
if not Waiting then
begin
FCaptchaWait := False;
FAuthWait := False;
end;
if FreeRequset then
Request.Free;
Dec(FExecuting);
end;
end;
procedure TVkHandler.WaitForQueue;
begin
TMonitor.Enter(FQueueLock);
try
Inc(FRequests);
// Если это первый запрос, то сохраняем метку
if FRequests = 1 then
FStartRequest := TThread.GetTickCount;
finally
TMonitor.Exit(FQueueLock);
end;
// Если уже 3 запроса было, то ждём до конца секунды FStartRequest
if FRequests > RequestLimit then
begin
FRequests := 0;
WaitTime(1300 - Int64(TThread.GetTickCount - FStartRequest));
end;
end;
function TVkHandler.FExecute(Request: TRESTRequest; IsRepeat: Boolean): TResponse;
begin
Result.Success := False;
WaitForQueue;
if FLogging then
FLog(Request.GetFullRequestURL);
Request.Execute;
if FLogging and FLogResponse then
FLog(Request.Response.JSONText);
Result := ProcessResponse(Request, IsRepeat);
end;
function TVkHandler.ProcessResponse(Request: TRESTRequest; IsRepeat: Boolean): TResponse;
var
JS: TJSONValue;
CaptchaSID: string;
CaptchaImg: string;
Answer: string;
begin
Result.Error.Code := -1;
if TestCaptcha or Request.Response.JSONValue.TryGetValue<TJSONValue>('error', JS) then
begin
Result.Success := False;
Result.Error.Code := JS.GetValue<Integer>('error_code', -1);
Result.Error.Text := JS.GetValue<string>('error_msg', VKErrors.Get(Result.Error.Code));
if TestCaptcha then
begin
Result.Error.Code := VK_ERROR_CAPTCHA;
TestCaptcha := False;
end;
case Result.Error.Code of
VK_ERROR_INVALID_TOKEN:
begin
if not DoLogin then
raise TVkInvalidTokenException.Create(VKErrors.Get(Result.Error.Code), Result.Error.Code);
end;
VK_ERROR_TOO_MANY_SIMILAR_ACTIONS:
raise TVkTooManySimilarActionException.Create(VKErrors.Get(Result.Error.Code), Result.Error.Code);
VK_ERROR_CAPTCHA: // Капча
begin
if FCaptchaWait then
Exit(Execute(Request));
FCaptchaWait := True;
CaptchaSID := JS.GetValue<string>('captcha_sid', '');
CaptchaImg := JS.GetValue<string>('captcha_img', '');
if AskCaptcha(Self, CaptchaImg, Answer) then
begin
Request.Params.AddItem('captcha_sid', CaptchaSID);
Request.Params.AddItem('captcha_key', Answer);
FCaptchaWait := False;
Result := Execute(Request);
Request.Params.Delete('captcha_sid');
Request.Params.Delete('captcha_key');
end
else
begin
FCaptchaWait := False;
raise TVkCaptchaException.Create(Result.Error.Text, Result.Error.Code);
end;
end;
VK_ERROR_CONFIRM, VK_ERROR_TOKEN_CONFIRM, VK_ERROR_MORE_CONFIRM: // Подтверждение для ВК
begin
Answer := JS.GetValue<string>('confirmation_text', '');
if DoConfirm(Answer) then
begin
Request.Params.AddItem('confirm', '1');
Result := Execute(Request);
Request.Params.Delete('confirm');
end
else
raise TVkConfirmException.Create(Result.Error.Text, Result.Error.Code);
end;
VK_ERROR_REQUESTLIMIT: // Превышено кол-во запросов в сек
begin
FLog(Format('Превышено кол-во запросов в сек. (%d/%d, StartRequest %d)', [FRequests, RequestLimit, FStartRequest]));
if not IsRepeat then
begin
WaitTime(2000);
Result := Execute(Request, False, True);
end
else
raise TVkExecuteErrorException.Create(Result.Error.Text, Result.Error.Code);
end;
VK_ERROR_INTERNAL_SERVER: // Internal Server Error
begin
if not IsRepeat then
begin
WaitTime(1000);
Result := Execute(Request, False, True);
end
else
raise TVkExecuteErrorException.Create(Result.Error.Text, Result.Error.Code);
end;
VK_ERROR_ACCESS_DENIED, VK_ERROR_ACCESS_DENIED_POST:
raise TVkAccessDeniedException.Create(Result.Error.Text, Result.Error.Code);
else
raise TVkUnknownMethodException.Create(Result.Error.Text, Result.Error.Code);
end;
end
else
begin
if Request.Response.StatusCode = 200 then
begin
if Request.Response.JSONValue.TryGetValue<TJSONValue>('response', JS) then
begin
Result.Response := JS.ToJSON;
Result.Json := Request.Response.JSONText;
Result.Success := True;
end;
end
else
raise TVkParserException.Create('Неизвестный ответ от сервера: ' + Request.Response.StatusCode.ToString);
end;
end;
procedure TVkHandler.FLog(const Value: string);
begin
if Assigned(FOnLog) then
FOnLog(Self, Value);
end;
function TVkHandler.GetExecuting: Boolean;
begin
Result := FExecuting > 0;
end;
function TVkHandler.GetWaiting: Boolean;
begin
Result := FWaitCount > 0;
end;
procedure TVkHandler.Log(Sender: TObject; const Text: string);
begin
if Assigned(FOnLog) then
FOnLog(Sender, Text);
end;
procedure TVkHandler.SetOnLog(const Value: TOnLog);
begin
FOnLog := Value;
end;
procedure TVkHandler.SetOwner(const Value: TObject);
begin
FOwner := Value;
end;
procedure TVkHandler.SetUseServiceKeyOnly(const Value: Boolean);
begin
FUseServiceKeyOnly := Value;
end;
procedure TVkHandler.SetLogging(const Value: Boolean);
begin
FLogging := Value;
end;
procedure TVkHandler.SetLogResponse(const Value: Boolean);
begin
FLogResponse := Value;
end;
procedure TVkHandler.SetOnCaptcha(const Value: TOnCaptcha);
begin
FOnCaptcha := Value;
end;
procedure TVkHandler.SetOnConfirm(const Value: TOnConfirm);
begin
FOnConfirm := Value;
end;
{ TResponse }
function TResponse.GetJSONValue: TJSONValue;
begin
if not Json.IsEmpty then
{$WARNINGS OFF}
Result := TJSONObject.ParseJSONValue(UTF8ToString(Json))
{$WARNINGS ON}
else
Result := nil;
end;
function TResponse.GetObject<T>(var Value: T): Boolean;
begin
Result := Success;
if Result then
try
Value := T.FromJsonString<T>(Response);
except
Result := False;
end;
end;
function TResponse.GetObjects<T>(var Value: T): Boolean;
begin
Result := Success;
if Result then
try
Value := T.FromJsonString<T>(ResponseAsItems);
except
Result := False;
end;
end;
function TResponse.GetValue<T>(var Value: T): Boolean;
var
JSONItem: TJSONValue;
begin
Result := Success;
if Result then
try
{$WARNINGS OFF}
JSONItem := TJSONObject.ParseJSONValue(UTF8ToString(Response));
{$WARNINGS ON}
Value := T(JSONItem);
except
JSONItem.Free;
Result := False;
end;
end;
function TResponse.GetValue<T>(const Field: string; var Value: T): Boolean;
var
JSONItem: TJSONValue;
begin
Result := Success;
if Result then
begin
Result := False;
try
{$WARNINGS OFF}
JSONItem := TJSONObject.ParseJSONValue(UTF8ToString(Response));
{$WARNINGS ON}
if Assigned(JSONItem) then
try
Result := JSONItem.TryGetValue<T>(Field, Value);
finally
JSONItem.Free;
end;
except
Result := False;
end;
end;
end;
function TResponse.IsError: Boolean;
begin
Result := (not Success) or (Error.Code <> -1);
end;
function TResponse.ResponseIsFalse: Boolean;
begin
Result := Success and (Response = '0');
end;
function TResponse.ResponseAsInt(var Value: Integer): Boolean;
begin
Result := Success and TryStrToInt(Response, Value);
end;
function TResponse.ResponseAsInt64(var Value: Int64): Boolean;
begin
Result := Success and TryStrToInt64(Response, Value);
end;
function TResponse.ResponseAsStr(var Value: string): Boolean;
begin
Result := Success;
if Result then
Value := Response;
end;
function TResponse.ResponseAsBool(var Value: Boolean): Boolean;
begin
Result := Success;
if Result then
Value := ResponseIsTrue;
end;
function TResponse.ResponseIsTrue: Boolean;
begin
Result := Success and (Response = '1');
end;
function TResponse.AppendItemsTag(Json: string): string;
begin
Result := '{"Items": ' + Json + '}';
end;
function TResponse.ResponseAsItems: string;
begin
Result := AppendItemsTag(Response);
end;
function TResponse.ResponseText: string;
begin
Result := Response;
end;
function TResponse.GetJSONResponse: TJSONValue;
begin
if not Response.IsEmpty then
{$WARNINGS OFF}
Result := TJSONObject.ParseJSONValue(UTF8ToString(Response))
{$WARNINGS ON}
else
Result := nil;
end;
end.