/* eslint-disable linebreak-style */ import 'codeceptjs'; import { createWorker } from 'tesseract.js'; import { logger } from '../Logger/logger'; import { Wait } from './dewWait'; import { Screenshot } from './screenshot'; const fs = require(`fs`); /** * Read Captcha Component */ export class ReadCaptcha { /** * The method is used to read the captcha and perform mathematical operation which is displayed in captcha and return the final output. * * ```js * await ReadCaptcha.readCaptcha(`//img[@id='captcha_image_register']`,"saveCaptchaScreenshot"); * ``` * * @param {string}locator * @param {string}filename */ static async readCaptcha(locator: string, filename: string) { let returnNumber: number; try { await Wait.waitForDefaultTimeout(10); await Screenshot.saveElementScreenshot(locator, filename); // await Wait.waitForDefaultTimeout(5); const worker = await createWorker({ logger: (m) => console.log(m), }); await worker.load(); await worker.loadLanguage(`eng`); await worker.initialize(`eng`); const { data: { text } } = await worker.recognize(filename + `.png`); console.log(`OCR read the image value as: ` + text); returnNumber = await this.performOperation(text); console.log(`Returning value after mathematical operation: ` + returnNumber); fs.unlinkSync(filename + `.png`); await worker.terminate(); return returnNumber; } catch (err) { logger.log(`Issue while performing operation in DDCC: Error while reading captcha`); logger.log(err); throw err; } } /** * The method perform mathematical operation on output given by OCR. * @param {string}text */ static async performOperation(text: string) { let numOperation: number; try { if (text.includes(`+`)) { const num1 = text.split(`+`)[0]; const num2 = text.split(`+`)[1]; numOperation = await Number(num1) + Number(num2); } else if (text.includes(`-`)) { const num1 = text.split(`-`)[0]; const num2 = text.split(`-`)[1]; numOperation = await Number(num1) - Number(num2); } else { throw Error(`Error in reading,OCR has recognized Alphabets or special characters`); } return numOperation; } catch (err) { logger.log(`Issue while performing operation in DDCC: Unable to perform mathematical operation`); throw err; } } }