Skip to content

Commit

Permalink
Add Canvas Method
Browse files Browse the repository at this point in the history
  • Loading branch information
dzmitry-duboyski committed Oct 25, 2024
1 parent 67696a3 commit c2a7b92
Show file tree
Hide file tree
Showing 6 changed files with 109 additions and 2 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Examples of API requests for different captcha types are available on the [JavaS
- [Bounding Box Method](#bounding-box-method)
- [Grid](#grid)
- [Text Captcha](#text-captcha)
- [Canvas](#canvas)
- [Other methods](#other-methods)
- [goodReport](#goodreport)
- [badReport](#badreport)
Expand Down Expand Up @@ -520,6 +521,26 @@ solver.textCaptcha({
})
```

### Canvas

<sup>[API method description.](https://2captcha.com/2captcha-api#canvas)</sup>

The canvas method can be used when you need to draw a line around an object on an image. Returns a set of points' coordinates to draw a polygon.

```js
solver.canvas({
body: 'iVBORw0KGgoAAAANSgAAAcIA...',
imginstructions: '/9j/4AAQSkZJRgABAQEA...',
textinstructions: 'Highlight the red CIRCLE'
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})
```

## Other methods

### goodReport
Expand Down
19 changes: 19 additions & 0 deletions examples/canvas.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const TwoCaptcha = require("../dist/index.js");
require('dotenv').config();
const APIKEY = process.env.APIKEY
const solver = new TwoCaptcha.Solver(APIKEY);
const fs = require('fs')
const imageBase64 = fs.readFileSync("./media/canvas.png", "base64")
const imginstructionsBase64 = fs.readFileSync("./media/canvasImgInstructions.jpg", "base64")

solver.canvas({
body: imageBase64,
textinstructions: 'Highlight the red CIRCLE',
imginstructions: imginstructionsBase64,
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})
Binary file added examples/media/canvas.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added examples/media/canvasImgInstructions.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
65 changes: 64 additions & 1 deletion src/structs/2captcha.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,8 @@ export interface paramsBoundingBox {

export interface paramsGrid {
body: string,
recaptcha: 1,
recaptcha: number,
canvas?: number,
rows?: number,
cols?: number,
minСlicks?: number,
Expand Down Expand Up @@ -1425,6 +1426,7 @@ public async grid(params: paramsGrid): Promise<CaptchaAnswer> {
throw new APIError(data.request)
}
}

/**
* ### Text Captcha method
*
Expand Down Expand Up @@ -1479,6 +1481,67 @@ public async text(params: paramsTextcaptcha): Promise<CaptchaAnswer> {
}
}

/**
* ### Canvas method
*
* This method can be used to bypass tasks in which you need to circle an object or line in an image.
*
* @param {{ body, textinstructions, imginstructions, canSkip, lang, pingback}} params Parameters Canvas as an object.
* @param {string} params.body `Base64`- encoded captcha image.
* @param {string} params.textinstructions Text will be shown to worker to help him to select object on the image correctly. For example: "*Select cars in the image*". **Optional parameter**, if the instruction already exists in the form of the `imginstructions`.
* @param {string} params.imginstructions Image with instruction for worker to help him to select object on the image correctly. The image must be encoded in `Base64` format. **Optional parameter**, if the instruction already exists in the form of the `textinstructions`.
* @param {number} params.canSkip Set the value to `1` only if it's possible that there's no images matching to the instruction. We'll provide a button "No matching images" to worker and you will receive `No_matching_images` as answer.
* @param {string} params.lang Language code. [See the list of supported languages](https://2captcha.com/2captcha-api#language).
* @param {string} params.pingback params.pingback URL for pingback (callback) response that will be sent when captcha is solved. URL should be registered on the server. [More info here](https://2captcha.com/2captcha-api#pingback).
*
* @example
* solver.canvas({
* body: 'iVBORw0KGgoAAAANSgAAAcIA...',
* imginstructions: '/9j/4AAQSkZJRgABAQEA...',
* textinstructions: 'Highlight the red CIRCLE'
* })
* .then((res) => {
* console.log(res);
* })
* .catch((err) => {
* console.log(err);
* })
*/
public async canvas(params: paramsGrid): Promise<CaptchaAnswer> {
checkCaptchaParams(params, "canvas")

params = await renameParams(params)

const payload = {
...params,
recaptcha: 1,
canvas: 1,
method: "base64",
...this.defaultPayload,
}

const URL = this.in
const response = await fetch(URL, {
body: JSON.stringify( payload ),
method: "post",
headers: {'Content-Type': 'application/json'}
})
const result = await response.text()

let data;
try {
data = JSON.parse(result)
} catch {
throw new APIError(result)
}

if (data.status == 1) {
return this.pollResponse(data.request)
} else {
throw new APIError(data.request)
}
}

/**
* Reports a captcha as correctly solved.
*
Expand Down
6 changes: 5 additions & 1 deletion src/utils/checkCaptchaParams.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Captcha methods for which parameter checking is available
const supportedMethods = ["userrecaptcha", "hcaptcha", "geetest", "geetest_v4","yandex","funcaptcha","lemin","amazon_waf",
"turnstile", "base64", "capy","datadome", "cybersiara", "mt_captcha", "bounding_box", 'friendly_captcha', 'grid', 'textcaptcha']
"turnstile", "base64", "capy","datadome", "cybersiara", "mt_captcha", "bounding_box", 'friendly_captcha', 'grid', 'textcaptcha', 'canvas']

// Names of required fields that must be contained in the parameters captcha
const recaptchaRequiredFields = ['pageurl','googlekey']
Expand All @@ -22,6 +22,7 @@ const boundingBoxRequiredFields = ['image'] // and textinstructions or imginstru
const friendlyCaptchaFields = ['pageurl','sitekey']
const gridRequiredFields = ['body'] // and textinstructions or imginstructions
const textCaptchaRequiredFields = ['textcaptcha']
const canvasRequiredFields = ['body'] // надо проверку, если какая нибудь инструкция текст\картинка

/**
* Getting required arguments for a captcha.
Expand Down Expand Up @@ -87,6 +88,9 @@ const getRequiredFildsArr = (method: string):Array<string> => {
case "textcaptcha":
requiredFieldsArr = textCaptchaRequiredFields
break;
case "canvas":
requiredFieldsArr = canvasRequiredFields
break;
}
return requiredFieldsArr
}
Expand Down

0 comments on commit c2a7b92

Please sign in to comment.