-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathClient.php
More file actions
104 lines (78 loc) · 3.09 KB
/
Client.php
File metadata and controls
104 lines (78 loc) · 3.09 KB
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
<?php
include_once './client/src/Networker.php';
include_once './client/src/CaptchaRequest.php';
include_once './client/src/Result.php';
include_once './client/src/Timeouts.php';
class Client extends Networker {
private $clientKey;
private $startTime;
private $endTime;
private $totalTimeToTask;
private $apiEndpoint = "https://api.capmonster.cloud/";
private $userAgent = "Zennolab.CapMonsterCloud.Client.PHP/1.2";
private function startTask() : void {
$this->startTime = date_create()->format('Uv');
$this->endTime = $this->startTime + $this->totalTimeToTask;
}
private function isTimeExpired() {
$currentTime = date_create()->format('Uv');
return $currentTime >= $this->endTime;
}
private function tryParseGetBalanceError(string $rawError) : string {
$parsed = json_decode($rawError, true);
if(json_last_error() === JSON_ERROR_NONE) {
return $parsed['errorCode'];
} else {
return 'Curl: ' . $rawError;
}
}
public function __construct(string $clientKey) {
$this->clientKey = $clientKey;
}
public function solve(CaptchaRequest $request) : Result {
if(!$request->isValid()) {
return $request->getTrouble();
}
$this->totalTimeToTask = $request->getTotalTime();
$request->setClientKey($this->clientKey);
try {
$request->createTask();
} catch (Exception $e) {
return new Result(false, $e->getMessage());
}
$this->startTask();
usleep($request->getFirstDelay());
while(!$this->isTimeExpired()) {
try {
$request->getTaskResult(); //помним, что 503 ошибка игнорируется
} catch (Exception $e) {
return new Result(false, $e->getMessage());
}
if($request->isReady) {
return new Result(true, $request->solution);
}
//если интервал до следующего запроса больше времени, оставшегося на выполнение
if($request->getInterval() > $this->endTime - date_create()->format('Uv')) {
return new Result(false, 'Timeout');
}
usleep($request->getInterval());
}
return new Result(false, 'Timeout');
}
public function getBalance() : Result {
$url = $this->apiEndpoint . 'getBalance';
$response = null;
try {
$response = $this->postRequest($url, ["clientKey" => $this->clientKey], $this->userAgent);
} catch (Exception $e) {
$message = $this->tryParseGetBalanceError($e->getMessage());
return new Result(false, $message);
}
$jsonResponse = json_decode($response, true);
if($jsonResponse['errorId'] == 1) {
$message = $jsonResponse['errorDescription'];
return new Result(false, $message);
}
return new Result(true, $jsonResponse['balance']);
}
}