1const Apify = require('apify');
2const fetch = require('node-fetch');
3
4const postJson = async (url, body) => {
5 const opt = {
6 method: 'POST',
7 body: JSON.stringify(body),
8 headers: {'Content-Type': 'application/json'}
9 };
10 const response = await fetch(url, opt);
11 return await response.json();
12};
13
14class AntiCaptchaTask {
15
16 constructor(input){
17 this.input = input;
18 this.taskId = null;
19 this.clientKey = input.clientKey;
20 }
21
22 async create(){
23 const data = await postJson('http://api.anti-captcha.com/createTask', this.input);
24 if(data.errorId > 0){throw new Error(data.errorDescription);}
25 this.taskId = data.taskId;
26 return data.taskId;
27 }
28
29 async getResult(){
30 const body = {
31 taskId: this.taskId,
32 clientKey: this.clientKey,
33 };
34 const data = await postJson('http://api.anti-captcha.com/getTaskResult', body);
35 if(data.errorId > 0){throw new Error(data.errorDescription);}
36 return data;
37 }
38
39 async waitForResult(timeout = 600000){
40 return new Promise((resolve, reject) => {
41 const startedAt = new Date();
42 const waitLoop = () => {
43 if((new Date() - startedAt) > timeout){
44 reject(new Error("Waiting for result timed out."));
45 }
46 this.getResult().then((response) => {
47 if(response.errorId !== 0){
48 reject(new Error(response.errorDescription));
49 }
50 else{
51 console.log(response);
52 if(response.status === 'ready'){resolve(response);}
53 else{
54 console.log('...');
55 setTimeout(waitLoop, 1000);
56 }
57 }
58 }).catch((e) => reject(e));
59 };
60 waitLoop();
61 });
62 }
63
64}
65
66Apify.main(async () => {
67
68 const input = await Apify.getValue('INPUT');
69 if(!input.clientKey){
70 throw new Error('ERROR: missing "clientKey" attribute in INPUT');
71 }
72 if(!input.task){
73 throw new Error('ERROR: missing "task" attribute in INPUT');
74 }
75 if(!input.task.type){
76 throw new Error('ERROR: missing "task.type" attribute in INPUT');
77 }
78
79 console.log('Solving captcha, type: ' + input.task.type);
80
81 const task = new AntiCaptchaTask(input);
82 console.log('Creating AntiCaptcha task...');
83 await task.create();
84 console.log('Waiting for result...');
85 const result = await task.waitForResult();
86 console.log('Captcha solving succesful.');
87 await Apify.setValue('OUTPUT', result.solution);
88 console.log('Solution: ');
89 console.dir(result.solution);
90});