Rev 37436 | Rev 37438 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
package com.smartdukaan.cron.scheduled;import nu.pattern.OpenCV;import org.apache.commons.io.FileUtils;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.opencv.core.Mat;import org.opencv.core.Size;import org.opencv.imgcodecs.Imgcodecs;import org.opencv.imgproc.Imgproc;import org.json.JSONObject;import org.openqa.selenium.*;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.chrome.ChromeOptions;import org.openqa.selenium.interactions.Actions;import org.openqa.selenium.support.ui.ExpectedConditions;import org.openqa.selenium.support.ui.WebDriverWait;import org.springframework.stereotype.Component;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.File;import java.time.LocalDate;import java.time.format.DateTimeFormatter;import java.time.Instant;import java.time.ZoneId;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.concurrent.TimeUnit;import java.util.stream.Collectors;@Componentpublic class CheckOppoWarrantyTask {private static final Logger LOGGER = LogManager.getLogger(CheckOppoWarrantyTask.class);static {try {OpenCV.loadShared();} catch (Throwable t) {LogManager.getLogger(CheckOppoWarrantyTask.class).warn("OpenCV not available on this platform: {}", t.getMessage());}}public Map<String, LocalDate> checkWarranty(List<String> imeis) {Map<String, LocalDate> dateMap = new HashMap<>();LOGGER.info("Initiating webdriver...");Map<String, Object> prefsMap = new HashMap<>();prefsMap.put("profile.default_content_settings.popups", 0);prefsMap.put("download.prompt", false);prefsMap.put("download.directory_upgrade", true);System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");//I need this//System.setProperty("webdriver.chrome.driver", "/Users/amit/cft/chromedriver/chromedriver");ChromeOptions options = new ChromeOptions();//options.setBinary("/Users/amit/cft/chrome/Google Chrome for Testing.app/Contents/MacOS/Google Chrome For Testing");options.setExperimentalOption("prefs", prefsMap);//options.setExperimentalOption("detach", true);options.addArguments("--headless");options.addArguments("--user-agent=\"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166\"");options.addArguments("--no-sandbox");options.addArguments("start-maximized");options.addArguments("disable-infobars");options.addArguments("--disable-extensions");options.addArguments("--force-device-scale-factor=1");options.addArguments("--test-type");WebDriver driver = null;try {driver = new ChromeDriver(options);driver.manage().timeouts().setScriptTimeout(6, TimeUnit.SECONDS);driver.manage().window().setSize(new Dimension(1600, 900));driver.manage().window().maximize();// Deleting all the cookiesdriver.manage().deleteAllCookies();// Specifiying pageLoadTimeout and Implicit waitdriver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);driver.manage().timeouts().implicitlyWait(9, TimeUnit.SECONDS);int mainCount = 0;List<String> remainingImeis = imeis;WebDriverWait wait10Sec = new WebDriverWait(driver, 8);WebDriverWait wait5Sec = new WebDriverWait(driver, 4);WebElement slideButton;Actions actionProvider = new Actions(driver);do {driver.get("https://support.oppo.com/in/warranty-check/");installResponseCapture(driver);try {driver.findElement(By.cssSelector(".cp-cookie-tip a.close")).click();} catch (Exception e) {}for (int i = 0; i < remainingImeis.size(); i++) {String imei = remainingImeis.get(i);try {LOGGER.info("Starting fresh with new IMEI " + imei);if (driver.findElement(By.className("el-input__inner")).getAttribute("value").length() > 0) {LOGGER.info("Darn.. leaving" + driver.findElement(By.className("el-input__inner")).getAttribute("value"));driver.get("https://support.oppo.com/in/warranty-check/");installResponseCapture(driver);break;}driver.findElement(By.className("el-input__inner")).sendKeys(imei);//driver.findElement(By.className("el-button--primary")).click();driver.findElement(By.cssSelector("div.searchBtn")).click();// Perform click-and-hold action on the elementint counter = 1;boolean captchaNotBroken = true;// release() is only reached on the moveByOffset > 0 path, so an attempt// that fails detection or calibration leaves the button DOWN. Measured in// production: 79% of presses were never released. Actions is one instance// per driver, created outside the imei loop, so the stuck press leaks into// the next attempt AND the next imei -- the following clickAndHold lands on// an already-held button, so the widget never repositions the handle and the// drag continues from wherever the pointer was abandoned.boolean pressed = false;do {String fileName = "/tmp/oppo-simple-i-" + counter + " " + System.currentTimeMillis() + ".png";try {LOGGER.info("Starting Do");wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));By sliderBy = By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]");slideButton = driver.findElement(sliderBy);LOGGER.info("Margin Left before- " + marginLeftOf(slideButton));try {actionProvider.moveToElement(slideButton).clickAndHold().moveByOffset(1, 0).perform();} catch (StaleElementReferenceException stale) {// The retry refresh (doubleClick at the end of the previous// attempt) swaps the widget's DOM, so the handle located at the// top of THIS attempt can already be detached by the time we act// on it. Re-find and try once, rather than abandoning the imei// and reloading the page: this killed 19% of oppo attempts// (54 of 284), against 0 on realme.LOGGER.info("Slider went stale before the drag - re-finding and retrying once");slideButton = driver.findElement(sliderBy);actionProvider.moveToElement(slideButton).clickAndHold().moveByOffset(1, 0).perform();}pressed = true;LOGGER.info("Margin Left after - " + marginLeftOf(slideButton));//Thread.sleep(5000);} catch (Exception e) {LOGGER.warn("Slider captcha widget (dx_captcha_basic_*) not found or not draggable"+ " - reloading. Cause: " + e.getMessage());driver.get("https://support.oppo.com/in/warranty-check/");installResponseCapture(driver);break;}double[] circles = getMatCircles2(driver, fileName);if (circles != null) {double firstCircleX = circles[0];double secondCircleX = circles[1];double distance = Math.abs(firstCircleX - secondCircleX);LOGGER.info("Distance is " + distance);// Closed loop: no assumed ratio, every move re-measures.int moveByOffset = aim(driver, actionProvider, distance);if (moveByOffset > 0) {actionProvider.release().perform();pressed = false;LOGGER.info("Move click performed (main {}px)", moveByOffset);try {try {wait5Sec.until(ExpectedConditions.visibilityOfElementLocated(By.className("dx_captcha_basic_bar-inform")));// realme logs the widget's own verdict here and oppo did not,// which is why realme's failures name POSITION_MISMATCH and// oppo's 85% say nothing at all. Same line, oppo's variables.LOGGER.warn("Failed = {} (captcha said: {})", counter, captchaSignal(driver));} catch (Exception notFailedException) {LOGGER.info("Success at attempt " + counter);// Read the JSON the page itself received rather than the// rendered text. The DOM value is built from two text nodes -- the// date plus a "(UTC+x)" suffix derived from the browser timezone --// and the old locator tested only the first, so it matched nothing.// The API carries regDate as epoch millis, which has no format or// timezone ambiguity at all.String json = awaitResponse(driver, 8000);LocalDate activationDate = regDateFrom(json);if (json == null) {LOGGER.warn("No getDeviceInfo response for imei {} (captcha said: {})",imei, captchaSignal(driver));} else {LOGGER.info("Activation lookup for {} -> {}", imei,activationDate != null ? activationDate : "no activation date");}// Always record the imei, even with a null date: findElement used to// throw here, so the row was never written and came back every run.dateMap.put(imei, activationDate);clearCapture(driver);if (dateMap.size() == imeis.size()) {return dateMap;}WebElement checkAgainButton = driver.findElement(By.className("c-btn"));captchaNotBroken = false;checkAgainButton.click();break;}} catch (Throwable e) {LOGGER.warn("Failed = " + counter + " ----------" + e.getMessage());}}}// Any path that got here without releasing (null circles, unusable// calibration) must let go before the next attempt re-presses.if (pressed) {try {actionProvider.release().perform();} catch (Exception releaseFailed) {LOGGER.warn("Could not release the slider: " + releaseFailed.getMessage());}pressed = false;}LOGGER.info("After circles conditions");wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));slideButton = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]"));actionProvider.moveToElement(slideButton).doubleClick().perform();LOGGER.info("Ending Do" + counter++);} while (captchaNotBroken && counter <= 20);// The widget-not-found path breaks out mid-iteration; do not carry a held// button into the next imei.if (pressed) {try {actionProvider.release().perform();} catch (Exception releaseFailed) {LOGGER.warn("Could not release the slider: " + releaseFailed.getMessage());}}LOGGER.warn("Counter reached upto 20");} catch (Exception e) {LOGGER.error("Oppo warranty check failed for imei " + imei, e);}driver.get("https://support.oppo.com/in/warranty-check/");// Every navigation destroys the JS context, taking the capture hook// with it. Miss one of these and the page is blind from the second// imei onwards: __oppoResp and __oppoCaptcha both come back null,// which reads as "the captcha failed" when it may well have passed.installResponseCapture(driver);}mainCount++;remainingImeis = imeis.stream().filter(x -> !dateMap.containsKey(x)).collect(Collectors.toList());if (remainingImeis.isEmpty()) break;} while (mainCount < 5);} finally {if (driver != null) {try {driver.quit(); //Ensures cleanup even on return or error} catch (Exception e) {LOGGER.warn("Error closing driver: " + e.getMessage());}}}return dateMap;}/** Stash the getDeviceInfo response on window as the page receives it. */private void installResponseCapture(WebDriver driver) {try {((JavascriptExecutor) driver).executeScript("if (!window.__oppoCapInstalled) {"+ " window.__oppoCapInstalled = true; window.__oppoResp = null; window.__oppoCaptcha = null;"// __oppoCaptcha is last-captcha-call-wins, and the widget refetches a puzzle// (/api/a) straight after a rejected verify (/api/v1). We then wait up to 5s// for the error element before reading it, which is ample time for the// refetch to overwrite the verdict -- so "all failures show /api/a" cannot// distinguish "never verified" from "verified, rejected, then overwritten".// Keep the verify separately, and a count, so the two are distinguishable.+ " window.__oppoVerify = null; window.__oppoVerifyCount = 0;"// axios can sit on either transport, and realme's page uses fetch --// an XHR-only hook silently captures nothing, which is exactly what// 'no getDeviceInfo response captured' was reporting.+ " var O = XMLHttpRequest.prototype.open;"+ " XMLHttpRequest.prototype.open = function(m,u){"+ " this.addEventListener('load', function(){"+ " try { var s=String(u);"+ " if (s.indexOf('getDeviceInfo') !== -1) window.__oppoResp = this.responseText;"+ " else if (s.indexOf('/api/v1') !== -1) { window.__oppoVerifyCount++; window.__oppoVerify = (this.responseText||'').slice(0,160); window.__oppoCaptcha = s + ' -> ' + (this.responseText||'').slice(0,200); }"+ " else if (s.indexOf('captcha') !== -1) window.__oppoCaptcha = s + ' -> ' + (this.responseText||'').slice(0,200);"+ " } catch(e){}"+ " });"+ " return O.apply(this, arguments);"+ " };"+ " var F = window.fetch;"+ " if (F) { window.fetch = function(){"+ " var u = arguments[0]; u = (u && u.url) ? u.url : String(u);"+ " return F.apply(this, arguments).then(function(r){"+ " try { if (u.indexOf('getDeviceInfo') !== -1) { r.clone().text().then(function(t){ window.__oppoResp = t; }); } } catch(e){}"+ " return r;"+ " });"+ " }; }"// A window.fetch wrapper only catches clients that resolve fetch at call// time. Anything that captured globalThis.fetch when its bundle loaded --// Nuxt's $fetch/ofetch does exactly this, and it is what hid realme's// lookup from us -- sails straight past it. Response.prototype is resolved// per call, so it catches every client regardless.// Read the clone with the ORIGINAL reader; the patched one recurses forever.+ " ['json','text'].forEach(function(name){"+ " var orig = Response.prototype[name];"+ " if (!orig) return;"+ " Response.prototype[name] = function(){"+ " try { var u = this.url || '';"+ " if (u.indexOf('getDeviceInfo') !== -1 && !this.__oppoSeenBody) {"+ " var c = this.clone(); c.__oppoSeenBody = 1;"+ " orig.call(c).then(function(t){ window.__oppoResp = (typeof t === 'string') ? t : JSON.stringify(t); });"+ " } } catch(e){}"+ " return orig.apply(this, arguments);"+ " };"+ " });"+ "}");} catch (Exception e) {LOGGER.warn("Could not install the response capture hook: " + e.getMessage());}}/** Last response from the captcha widget itself -- says WHY a drag was refused. */private String captchaSignal(WebDriver driver) {try {Object v = ((JavascriptExecutor) driver).executeScript("return 'verifies=' + (window.__oppoVerifyCount||0)"+ " + ' lastVerify=' + (window.__oppoVerify || 'NONE')"+ " + ' | ' + (window.__oppoCaptcha || 'none');");return v == null ? null : v.toString();} catch (Exception e) {return null;}}/** Poll for the response instead of reading once: the success signal can fire* before the lookup request has completed, which loses the payload. */private String awaitResponse(WebDriver driver, long timeoutMs) {long deadline = System.currentTimeMillis() + timeoutMs;while (System.currentTimeMillis() < deadline) {String json = capturedResponse(driver);if (json != null && !json.trim().isEmpty()) return json;try {Thread.sleep(300);} catch (InterruptedException ie) {Thread.currentThread().interrupt();return null;}}return null;}private String capturedResponse(WebDriver driver) {try {Object v = ((JavascriptExecutor) driver).executeScript("return window.__oppoResp || null;");return v == null ? null : v.toString();} catch (Exception e) {return null;}}private void clearCapture(WebDriver driver) {try {((JavascriptExecutor) driver).executeScript("window.__oppoResp = null;");} catch (Exception ignored) {}}/** data.regDate is epoch millis; absent or blank means the device is not activated yet. */private LocalDate regDateFrom(String json) {if (json == null) return null;try {JSONObject data = new JSONObject(json).optJSONObject("data");if (data == null) return null;String reg = data.optString("regDate", "");if (reg == null || reg.trim().isEmpty() || "null".equals(reg)) return null;return Instant.ofEpochMilli(Long.parseLong(reg.trim())).atZone(ZoneId.of("Asia/Kolkata")).toLocalDate();} catch (Exception e) {LOGGER.warn("Could not read regDate from the Oppo response: " + e.getMessage());return null;}}/*** Calibration nudge, in slider px, sized from the gap rather than fixed.** A fixed 15px was far too small: it closed only ~25px, so the ratio came from a* measurement ~20% noise and the aim landed ~30px out. A fixed 60px then proved too* large in the other direction -- production data showed 85% of attempts with a gap* under 60px ended up UNUSABLE (the piece shot past the hole and the measured gap* grew), and 45% overall.** Aim to close about half the gap: the piece travels roughly ASSUMED_RATIO px per* slider px, so nudge ~= gap / (2 * ratio), clamped. The real ratio is still derived* from the measurement; this only sizes the probe.*/private static final double ALIGNED_PX = 2.0;/*** margin-left for logging only. Reading it off a detached element throws, and this is* a diagnostic -- it must never be the reason an attempt is abandoned.*/private String marginLeftOf(WebElement el) {try {return el.getCssValue("margin-left");} catch (Exception e) {return "?";}}/** Seed probe, in slider px. Deliberately small: it only has to produce a first* measurable movement, and it must be too small to cross the hole. */private static final int SEED_NUDGE = 12;private static final int MAX_AIM_STEPS = 5;private static final int MAX_STEP = 140;/*** Drag onto the hole without ever assuming a ratio.** The old path derived px-per-px ONCE from a single probe and then trusted it for* the main move and the correction alike, so one noisy probe poisoned everything* downstream. Here every move is also a measurement: after each one the ratio is* re-derived from what that move actually achieved, so the estimate improves as the* piece approaches instead of being fixed at its least informed point.** It also gets to see overshoot, which a single pass cannot. The gap is |c1 - c2|,* so it cannot tell "not there yet" from "gone past" -- but if a move makes the gap* GROW, we crossed the hole, and the sign of the next step flips.** @return total slider px moved, or 0 if the circles could not be read at all.*/private int aim(WebDriver driver, Actions actionProvider, double gap) throws Exception {double ratio = 0; // slider px per gap px, derived from real movesint total = 0;int step = SEED_NUDGE;for (int i = 0; i < MAX_AIM_STEPS; i++) {actionProvider.moveByOffset(step, 0).perform();total += step;double[] c = getMatCircles2(driver, "/tmp/" + Thread.currentThread().getName() + "-aim" + i + ".png");if (c == null) {LOGGER.warn("Aim step {}: lost the circles after {}px", i, total);return total;}double now = Math.abs(c[0] - c[1]);double closed = gap - now;if (closed != 0) {// What this move actually bought us, in slider px per gap px.double observed = Math.abs(step) / Math.abs(closed);// Blend once an estimate exists, so a single bad frame cannot swing it.ratio = (ratio <= 0) ? observed : (ratio + observed) / 2;}LOGGER.info("Aim step {}: moved {}px, gap {} -> {}, ratio now {}",i, step, gap, now, String.format("%.2f", ratio));if (now <= ALIGNED_PX) {LOGGER.info("Aim: aligned within {}px after {} step(s), {}px total", ALIGNED_PX, i + 1, total);return total;}if (ratio <= 0) { // nothing measurable yet, probe againgap = now;step = SEED_NUDGE;continue;}int next = (int) Math.round(now * ratio);if (next == 0) next = 1;if (next > MAX_STEP) next = MAX_STEP;// Gap grew => we are past the hole; go back instead of further away.step = (closed < 0) ? -next : next;gap = now;}LOGGER.info("Aim: {} steps used, {}px total", MAX_AIM_STEPS, total);return total;}private Mat getMatCircles(WebDriver driver, String fileName) throws Exception {File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);BufferedImage fullImg = ImageIO.read(screenshot);// Get the location of element on the pageWebElement imageElement = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]"));Point point = imageElement.getLocation();// Get width and height of the elementint eleWidth = imageElement.getSize().getWidth();int eleHeight = imageElement.getSize().getHeight();// Crop the entire page screenshot to get only element screenshotBufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),eleWidth, eleHeight);ImageIO.write(eleScreenshot, "png", screenshot);// Copy the element screenshot to diskFile screenshotLocation = new File(fileName);FileUtils.copyFile(screenshot, screenshotLocation);Imgcodecs imageCodecs = new Imgcodecs();Mat grayMatrix = imageCodecs.imread(fileName, Imgcodecs.IMREAD_COLOR);Imgproc.cvtColor(grayMatrix, grayMatrix, Imgproc.COLOR_BGR2GRAY);Mat medianBlur = new Mat();Imgproc.medianBlur(grayMatrix, medianBlur, 5);Mat circles = new Mat();Imgproc.HoughCircles(medianBlur, circles, Imgproc.HOUGH_GRADIENT, 1, 15, 50, 20, 17, 25);return circles;}private double[] getMatCircles2(WebDriver driver, String fileName) throws Exception {File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);BufferedImage fullImg = ImageIO.read(screenshot);// Get the location of element on the pageWebElement imageElement = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]"));Point point = imageElement.getLocation();// Get width and height of the elementint eleWidth = imageElement.getSize().getWidth();int eleHeight = imageElement.getSize().getHeight();// Crop the entire page screenshot to get only element screenshotBufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),eleWidth, eleHeight);ImageIO.write(eleScreenshot, "png", screenshot);// Copy the element screenshot to diskFile screenshotLocation = new File(fileName);FileUtils.copyFile(screenshot, screenshotLocation);Mat src = Imgcodecs.imread(fileName);if (src.empty()) {System.err.println("Cannot read image: " + fileName);new File(fileName).delete();return null;}Mat gray = new Mat();Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);Imgproc.GaussianBlur(gray, gray, new Size(9, 9), 2, 2);Mat circles = new Mat();Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,20, // min distance between centers100, 20, // param1 (Canny high threshold), param2 (accumulator threshold)10, 50); // minRadius, maxRadius (adjust as needed)if (circles.cols() < 2) {new File(fileName).delete();return null;}for (int i = 0; i < circles.cols(); i++) {double[] c1 = circles.get(0, i);for (int j = i + 1; j < circles.cols(); j++) {double[] c2 = circles.get(0, j);if (Math.abs(c1[2] - c2[2]) < 3) { // check similar radiusnew File(fileName).delete();return new double[] {c1[0], c2[0] // x-coordinates};}}}new File(fileName).delete();return null;}}