|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- import axios from 'axios'
-
- import { ICaptchaResolver } from '../interfaces/ICaptchaResolver';
-
- export class CapMonster implements ICaptchaResolver {
- private readonly CAPTCHA_KEY: string = process.env.CAP_MONSTER_KEY
- private readonly CAPTCHA_BALANCE: string =
- 'https://api.capmonster.cloud/getBalance'
- private readonly CAPTCHA_CREATE: string =
- 'https://api.capmonster.cloud/createTask'
- private readonly CAPTCHA_RESULT: string =
- 'https://api.capmonster.cloud/getTaskResult'
-
- public async temSaldoDisponivel (): Promise<boolean> {
- try {
- const balanceData = {
- clientKey: this.CAPTCHA_KEY
- }
-
- const { data } = await axios.post(this.CAPTCHA_BALANCE, balanceData)
-
- if (data.errorId > 0) {
- console.log(`[consultar-saldo-captcha] - ${data.errorCode}`)
- return false
- }
-
- return data.balance > 0
- } catch (error) {
- console.log(`[consultar-saldo-captcha] - ${error.message}`)
-
- return false
- }
- }
-
- public async resolver (imageData: string): Promise<string> {
- const taskId = await this.criar(imageData)
-
- if (taskId === 0) return null
-
- return await this.resultado(taskId)
- }
-
- private async criar (imageData: string): Promise<number> {
- try {
- const createTask = {
- clientKey: this.CAPTCHA_KEY,
- task: {
- type: 'ImageToTextTask',
- body: imageData
- }
- }
-
- const { data } = await axios.post(this.CAPTCHA_CREATE, createTask)
-
- if (data.errorId > 0) {
- console.log(`[criar-captcha] - ${data.errorCode}`)
- return 0
- }
-
- return data.taskId
- } catch (error) {
- console.log(`[criar-captcha] - ${error.message}`)
-
- return 0
- }
- }
-
- private async resultado (taskId: number): Promise<string> {
- let tentativas = 0
- let error: boolean = false
- let captchaData = null
-
- const getResultTask = {
- clientKey: this.CAPTCHA_KEY,
- taskId: taskId
- }
-
- do {
- try {
- const {
- data: { errorId, errorCode, solution, status }
- } = await axios.post(this.CAPTCHA_RESULT, getResultTask)
-
- if (errorId > 0) {
- console.log(
- `[resultado-captcha] - Task: ${taskId} Erro: ${errorCode} Tentativas: ${tentativas}`
- )
- error = true
- break
- }
-
- if (status === 'ready') {
- captchaData = solution.text
- break
- }
-
- tentativas += 1
- await new Promise(r => setTimeout(r, 10 * 1000))
- } catch (error) {
- console.log(
- `[resultado-captcha] - Task: ${taskId} Erro: ${error.message} Tentativas: ${tentativas}`
- )
- error = true
- break
- }
- } while (tentativas < 20)
-
- if (error) return null
-
- return captchaData
- }
- }
-
- export default new CapMonster()
|