Subversion Repositories SmartDukaan

Rev

Rev 37434 | Rev 37436 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
30209 amit.gupta 1
package com.smartdukaan.cron.scheduled;
2
 
3
import nu.pattern.OpenCV;
4
import org.apache.commons.io.FileUtils;
5
import org.apache.logging.log4j.LogManager;
6
import org.apache.logging.log4j.Logger;
7
import org.opencv.core.Mat;
34413 amit.gupta 8
import org.opencv.core.Size;
30209 amit.gupta 9
import org.opencv.imgcodecs.Imgcodecs;
10
import org.opencv.imgproc.Imgproc;
37420 amit 11
import org.json.JSONObject;
30209 amit.gupta 12
import org.openqa.selenium.*;
13
import org.openqa.selenium.chrome.ChromeDriver;
14
import org.openqa.selenium.chrome.ChromeOptions;
15
import org.openqa.selenium.interactions.Actions;
16
import org.openqa.selenium.support.ui.ExpectedConditions;
17
import org.openqa.selenium.support.ui.WebDriverWait;
30373 amit.gupta 18
import org.springframework.stereotype.Component;
30209 amit.gupta 19
 
20
import javax.imageio.ImageIO;
21
import java.awt.image.BufferedImage;
22
import java.io.File;
23
import java.time.LocalDate;
24
import java.time.format.DateTimeFormatter;
37420 amit 25
import java.time.Instant;
26
import java.time.ZoneId;
30209 amit.gupta 27
import java.util.HashMap;
28
import java.util.List;
29
import java.util.Map;
30
import java.util.concurrent.TimeUnit;
31
import java.util.stream.Collectors;
32
 
30373 amit.gupta 33
@Component
34
public class CheckOppoWarrantyTask {
30209 amit.gupta 35
 
32146 amit.gupta 36
    private static final Logger LOGGER = LogManager.getLogger(CheckOppoWarrantyTask.class);
30209 amit.gupta 37
 
36253 amit 38
    static {
36306 amit 39
        try {
40
            OpenCV.loadShared();
41
        } catch (Throwable t) {
42
            LogManager.getLogger(CheckOppoWarrantyTask.class).warn("OpenCV not available on this platform: {}", t.getMessage());
43
        }
36253 amit 44
    }
45
 
32146 amit.gupta 46
    public Map<String, LocalDate> checkWarranty(List<String> imeis) {
47
        Map<String, LocalDate> dateMap = new HashMap<>();
48
        LOGGER.info("Initiating webdriver...");
30209 amit.gupta 49
 
32146 amit.gupta 50
        Map<String, Object> prefsMap = new HashMap<>();
51
        prefsMap.put("profile.default_content_settings.popups", 0);
52
        prefsMap.put("download.prompt", false);
53
        prefsMap.put("download.directory_upgrade", true);
34413 amit.gupta 54
        System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
32146 amit.gupta 55
        //I need this
34413 amit.gupta 56
        //System.setProperty("webdriver.chrome.driver", "/Users/amit/cft/chromedriver/chromedriver");
32146 amit.gupta 57
        ChromeOptions options = new ChromeOptions();
34413 amit.gupta 58
        //options.setBinary("/Users/amit/cft/chrome/Google Chrome for Testing.app/Contents/MacOS/Google Chrome For Testing");
32146 amit.gupta 59
        options.setExperimentalOption("prefs", prefsMap);
60
        //options.setExperimentalOption("detach", true);
61
        options.addArguments("--headless");
62
        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\"");
30209 amit.gupta 63
 
32146 amit.gupta 64
        options.addArguments("--no-sandbox");
65
        options.addArguments("start-maximized");
66
        options.addArguments("disable-infobars");
67
        options.addArguments("--disable-extensions");
68
        options.addArguments("--force-device-scale-factor=1");
69
        options.addArguments("--test-type");
30209 amit.gupta 70
 
34680 amit.gupta 71
        WebDriver driver = null;
30209 amit.gupta 72
 
34680 amit.gupta 73
        try {
74
            driver = new ChromeDriver(options);
75
            driver.manage().timeouts().setScriptTimeout(6, TimeUnit.SECONDS);
76
            driver.manage().window().setSize(new Dimension(1600, 900));
77
            driver.manage().window().maximize();
78
            // Deleting all the cookies
79
            driver.manage().deleteAllCookies();
80
            // Specifiying pageLoadTimeout and Implicit wait
81
            driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
82
            driver.manage().timeouts().implicitlyWait(9, TimeUnit.SECONDS);
34415 amit.gupta 83
 
34680 amit.gupta 84
            int mainCount = 0;
85
            List<String> remainingImeis = imeis;
86
            WebDriverWait wait10Sec = new WebDriverWait(driver, 8);
87
            WebDriverWait wait5Sec = new WebDriverWait(driver, 4);
88
            WebElement slideButton;
89
            Actions actionProvider = new Actions(driver);
90
            do {
91
                driver.get("https://support.oppo.com/in/warranty-check/");
37420 amit 92
                installResponseCapture(driver);
32146 amit.gupta 93
                try {
34680 amit.gupta 94
                    driver.findElement(By.cssSelector(".cp-cookie-tip a.close")).click();
95
                } catch (Exception e) {
96
                }
30209 amit.gupta 97
 
34680 amit.gupta 98
                for (int i = 0; i < remainingImeis.size(); i++) {
99
                    String imei = remainingImeis.get(i);
100
                    try {
37410 amit 101
                        LOGGER.info("Starting fresh with new IMEI " + imei);
34680 amit.gupta 102
                        if (driver.findElement(By.className("el-input__inner")).getAttribute("value").length() > 0) {
37410 amit 103
                            LOGGER.info("Darn.. leaving" + driver.findElement(By.className("el-input__inner")).getAttribute("value"));
32146 amit.gupta 104
                            driver.get("https://support.oppo.com/in/warranty-check/");
37432 amit 105
                            installResponseCapture(driver);
32146 amit.gupta 106
                            break;
107
                        }
34680 amit.gupta 108
                        driver.findElement(By.className("el-input__inner")).sendKeys(imei);
30209 amit.gupta 109
 
34680 amit.gupta 110
                        //driver.findElement(By.className("el-button--primary")).click();
111
                        driver.findElement(By.cssSelector("div.searchBtn")).click();
112
 
113
                        // Perform click-and-hold action on the element
114
                        int counter = 1;
115
                        boolean captchaNotBroken = true;
37435 amit 116
                        // release() is only reached on the moveByOffset > 0 path, so an attempt
117
                        // that fails detection or calibration leaves the button DOWN. Measured in
118
                        // production: 79% of presses were never released. Actions is one instance
119
                        // per driver, created outside the imei loop, so the stuck press leaks into
120
                        // the next attempt AND the next imei -- the following clickAndHold lands on
121
                        // an already-held button, so the widget never repositions the handle and the
122
                        // drag continues from wherever the pointer was abandoned.
123
                        boolean pressed = false;
34680 amit.gupta 124
                        do {
125
                            String fileName = "/tmp/oppo-simple-i-" + counter + " " + System.currentTimeMillis() + ".png";
126
                            try {
37410 amit 127
                                LOGGER.info("Starting Do");
36583 amit 128
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
129
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
130
                                slideButton = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]"));
34680 amit.gupta 131
                                //System.out.println("Slide button - " + slideButton);
37410 amit 132
                                LOGGER.info("Margin Left before- " + slideButton.getCssValue("margin-left"));
34680 amit.gupta 133
                                actionProvider.moveToElement(slideButton).clickAndHold()
134
                                        .moveByOffset(1, 0)//.pause(2000)
135
                                        .perform();
37435 amit 136
                                pressed = true;
34680 amit.gupta 137
 
138
                                //actionProvider.moveByOffset(-1,0).pause(2000).perform();
37410 amit 139
                                LOGGER.info("Margin Left after - " + slideButton.getCssValue("margin-left"));
34680 amit.gupta 140
                                //Thread.sleep(5000);
141
                            } catch (Exception e) {
37410 amit 142
                                LOGGER.warn("Slider captcha widget (dx_captcha_basic_*) not found or not draggable"
143
                                        + " - reloading. Cause: " + e.getMessage());
34680 amit.gupta 144
                                driver.get("https://support.oppo.com/in/warranty-check/");
37432 amit 145
                                installResponseCapture(driver);
34680 amit.gupta 146
                                break;
147
                            }
148
                            double[] circles = getMatCircles2(driver, fileName);
149
                            if (circles != null) {
150
                                double firstCircleX = circles[0];
151
                                double secondCircleX = circles[1];
152
                                double distance = Math.abs(firstCircleX - secondCircleX);
37410 amit 153
                                LOGGER.info("Distance is " + distance);
34680 amit.gupta 154
 
37422 amit 155
                                double[] cal = calibrate(driver, actionProvider, distance);
156
                                int moveByOffset = cal == null ? 0 : (int) cal[0];
34680 amit.gupta 157
                                if (moveByOffset > 0) {
37422 amit 158
                                    // Move, then measure again and close the remainder BEFORE
159
                                    // releasing. Releasing on the first computed offset committed
160
                                    // the whole calibration error to the final position.
161
                                    actionProvider.moveByOffset(moveByOffset, 0).perform();
162
                                    refine(driver, actionProvider, cal[1]);
163
                                    actionProvider.release().perform();
37435 amit 164
                                    pressed = false;
37422 amit 165
                                    LOGGER.info("Move click performed (main {}px)", moveByOffset);
32146 amit.gupta 166
                                    try {
34680 amit.gupta 167
                                        try {
168
                                            wait5Sec.until(ExpectedConditions.visibilityOfElementLocated(By.className("dx_captcha_basic_bar-inform")));
37433 amit 169
                                            // realme logs the widget's own verdict here and oppo did not,
170
                                            // which is why realme's failures name POSITION_MISMATCH and
171
                                            // oppo's 85% say nothing at all. Same line, oppo's variables.
172
                                            LOGGER.warn("Failed = {} (captcha said: {})", counter, captchaSignal(driver));
34680 amit.gupta 173
                                        } catch (Exception notFailedException) {
37410 amit 174
                                            LOGGER.info("Success  at attempt " + counter);
37420 amit 175
 
176
                                            // Read the JSON the page itself received rather than the
177
                                            // rendered text. The DOM value is built from two text nodes -- the
178
                                            // date plus a "(UTC+x)" suffix derived from the browser timezone --
179
                                            // and the old locator tested only the first, so it matched nothing.
180
                                            // The API carries regDate as epoch millis, which has no format or
181
                                            // timezone ambiguity at all.
37429 amit 182
                                            String json = awaitResponse(driver, 8000);
37420 amit 183
                                            LocalDate activationDate = regDateFrom(json);
184
 
185
                                            if (json == null) {
37429 amit 186
                                                LOGGER.warn("No getDeviceInfo response for imei {} (captcha said: {})",
187
                                                        imei, captchaSignal(driver));
34680 amit.gupta 188
                                            } else {
37420 amit 189
                                                LOGGER.info("Activation lookup for {} -> {}", imei,
190
                                                        activationDate != null ? activationDate : "no activation date");
32146 amit.gupta 191
                                            }
37420 amit 192
                                            // Always record the imei, even with a null date: findElement used to
193
                                            // throw here, so the row was never written and came back every run.
194
                                            dateMap.put(imei, activationDate);
195
                                            clearCapture(driver);
196
 
34680 amit.gupta 197
                                            if (dateMap.size() == imeis.size()) {
198
                                                return dateMap;
199
                                            }
200
                                            WebElement checkAgainButton = driver.findElement(By.className("c-btn"));
201
                                            captchaNotBroken = false;
202
                                            checkAgainButton.click();
203
                                            break;
32146 amit.gupta 204
                                        }
34680 amit.gupta 205
                                    } catch (Throwable e) {
37410 amit 206
                                        LOGGER.warn("Failed = " + counter + " ----------" + e.getMessage());
32146 amit.gupta 207
                                    }
208
                                }
209
                            }
37435 amit 210
                            // Any path that got here without releasing (null circles, unusable
211
                            // calibration) must let go before the next attempt re-presses.
212
                            if (pressed) {
213
                                try {
214
                                    actionProvider.release().perform();
215
                                } catch (Exception releaseFailed) {
216
                                    LOGGER.warn("Could not release the slider: " + releaseFailed.getMessage());
217
                                }
218
                                pressed = false;
219
                            }
37410 amit 220
                            LOGGER.info("After circles conditions");
36583 amit 221
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
222
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
223
                            slideButton = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]"));
34680 amit.gupta 224
                            actionProvider.moveToElement(slideButton).doubleClick().perform();
37410 amit 225
                            LOGGER.info("Ending Do" + counter++);
30209 amit.gupta 226
 
34680 amit.gupta 227
                        } while (captchaNotBroken && counter <= 20);
37435 amit 228
                        // The widget-not-found path breaks out mid-iteration; do not carry a held
229
                        // button into the next imei.
230
                        if (pressed) {
231
                            try {
232
                                actionProvider.release().perform();
233
                            } catch (Exception releaseFailed) {
234
                                LOGGER.warn("Could not release the slider: " + releaseFailed.getMessage());
235
                            }
236
                        }
37410 amit 237
                        LOGGER.warn("Counter reached upto 20");
34680 amit.gupta 238
                    } catch (Exception e) {
37410 amit 239
                        LOGGER.error("Oppo warranty check failed for imei " + imei, e);
34680 amit.gupta 240
                    }
241
                    driver.get("https://support.oppo.com/in/warranty-check/");
37432 amit 242
                    // Every navigation destroys the JS context, taking the capture hook
243
                    // with it. Miss one of these and the page is blind from the second
244
                    // imei onwards: __oppoResp and __oppoCaptcha both come back null,
245
                    // which reads as "the captcha failed" when it may well have passed.
246
                    installResponseCapture(driver);
34680 amit.gupta 247
                }
248
                mainCount++;
249
                remainingImeis = imeis.stream().filter(x -> !dateMap.containsKey(x)).collect(Collectors.toList());
36253 amit 250
                if (remainingImeis.isEmpty()) break;
34680 amit.gupta 251
            } while (mainCount < 5);
252
        } finally {
253
            if (driver != null) {
254
                try {
255
                    driver.quit(); //Ensures cleanup even on return or error
32146 amit.gupta 256
                } catch (Exception e) {
37410 amit 257
                    LOGGER.warn("Error closing driver: " + e.getMessage());
32146 amit.gupta 258
                }
259
            }
34680 amit.gupta 260
        }
261
 
32146 amit.gupta 262
        return dateMap;
263
    }
30352 amit.gupta 264
 
34680 amit.gupta 265
 
37420 amit 266
    /** Stash the getDeviceInfo response on window as the page receives it. */
267
    private void installResponseCapture(WebDriver driver) {
268
        try {
269
            ((JavascriptExecutor) driver).executeScript(
270
                "if (!window.__oppoCapInstalled) {"
37428 amit 271
              + "  window.__oppoCapInstalled = true; window.__oppoResp = null; window.__oppoCaptcha = null;"
37434 amit 272
              // __oppoCaptcha is last-captcha-call-wins, and the widget refetches a puzzle
273
              // (/api/a) straight after a rejected verify (/api/v1). We then wait up to 5s
274
              // for the error element before reading it, which is ample time for the
275
              // refetch to overwrite the verdict -- so "all failures show /api/a" cannot
276
              // distinguish "never verified" from "verified, rejected, then overwritten".
277
              // Keep the verify separately, and a count, so the two are distinguishable.
278
              + "  window.__oppoVerify = null; window.__oppoVerifyCount = 0;"
37425 amit 279
              // axios can sit on either transport, and realme's page uses fetch --
280
              // an XHR-only hook silently captures nothing, which is exactly what
281
              // 'no getDeviceInfo response captured' was reporting.
37420 amit 282
              + "  var O = XMLHttpRequest.prototype.open;"
283
              + "  XMLHttpRequest.prototype.open = function(m,u){"
284
              + "    this.addEventListener('load', function(){"
37428 amit 285
              + "      try { var s=String(u);"
286
              + "        if (s.indexOf('getDeviceInfo') !== -1) window.__oppoResp = this.responseText;"
37434 amit 287
              + "        else if (s.indexOf('/api/v1') !== -1) { window.__oppoVerifyCount++; window.__oppoVerify = (this.responseText||'').slice(0,160); window.__oppoCaptcha = s + ' -> ' + (this.responseText||'').slice(0,200); }"
37428 amit 288
              + "        else if (s.indexOf('captcha') !== -1) window.__oppoCaptcha = s + ' -> ' + (this.responseText||'').slice(0,200);"
289
              + "      } catch(e){}"
37420 amit 290
              + "    });"
291
              + "    return O.apply(this, arguments);"
292
              + "  };"
37425 amit 293
              + "  var F = window.fetch;"
294
              + "  if (F) { window.fetch = function(){"
295
              + "    var u = arguments[0]; u = (u && u.url) ? u.url : String(u);"
296
              + "    return F.apply(this, arguments).then(function(r){"
297
              + "      try { if (u.indexOf('getDeviceInfo') !== -1) { r.clone().text().then(function(t){ window.__oppoResp = t; }); } } catch(e){}"
298
              + "      return r;"
299
              + "    });"
300
              + "  }; }"
37431 amit 301
              // A window.fetch wrapper only catches clients that resolve fetch at call
302
              // time. Anything that captured globalThis.fetch when its bundle loaded --
303
              // Nuxt's $fetch/ofetch does exactly this, and it is what hid realme's
304
              // lookup from us -- sails straight past it. Response.prototype is resolved
305
              // per call, so it catches every client regardless.
306
              // Read the clone with the ORIGINAL reader; the patched one recurses forever.
307
              + "  ['json','text'].forEach(function(name){"
308
              + "    var orig = Response.prototype[name];"
309
              + "    if (!orig) return;"
310
              + "    Response.prototype[name] = function(){"
311
              + "      try { var u = this.url || '';"
312
              + "        if (u.indexOf('getDeviceInfo') !== -1 && !this.__oppoSeenBody) {"
313
              + "          var c = this.clone(); c.__oppoSeenBody = 1;"
314
              + "          orig.call(c).then(function(t){ window.__oppoResp = (typeof t === 'string') ? t : JSON.stringify(t); });"
315
              + "        } } catch(e){}"
316
              + "      return orig.apply(this, arguments);"
317
              + "    };"
318
              + "  });"
37420 amit 319
              + "}");
320
        } catch (Exception e) {
321
            LOGGER.warn("Could not install the response capture hook: " + e.getMessage());
322
        }
323
    }
324
 
37428 amit 325
    /** Last response from the captcha widget itself -- says WHY a drag was refused. */
326
    private String captchaSignal(WebDriver driver) {
327
        try {
37434 amit 328
            Object v = ((JavascriptExecutor) driver).executeScript(
329
                    "return 'verifies=' + (window.__oppoVerifyCount||0)"
330
                  + " + ' lastVerify=' + (window.__oppoVerify || 'NONE')"
331
                  + " + ' | ' + (window.__oppoCaptcha || 'none');");
37428 amit 332
            return v == null ? null : v.toString();
333
        } catch (Exception e) {
334
            return null;
335
        }
336
    }
337
 
37429 amit 338
    /** Poll for the response instead of reading once: the success signal can fire
339
     *  before the lookup request has completed, which loses the payload. */
340
    private String awaitResponse(WebDriver driver, long timeoutMs) {
341
        long deadline = System.currentTimeMillis() + timeoutMs;
342
        while (System.currentTimeMillis() < deadline) {
343
            String json = capturedResponse(driver);
344
            if (json != null && !json.trim().isEmpty()) return json;
345
            try {
346
                Thread.sleep(300);
347
            } catch (InterruptedException ie) {
348
                Thread.currentThread().interrupt();
349
                return null;
350
            }
351
        }
352
        return null;
353
    }
354
 
37420 amit 355
    private String capturedResponse(WebDriver driver) {
356
        try {
357
            Object v = ((JavascriptExecutor) driver).executeScript("return window.__oppoResp || null;");
358
            return v == null ? null : v.toString();
359
        } catch (Exception e) {
360
            return null;
361
        }
362
    }
363
 
364
    private void clearCapture(WebDriver driver) {
365
        try {
366
            ((JavascriptExecutor) driver).executeScript("window.__oppoResp = null;");
367
        } catch (Exception ignored) {
368
        }
369
    }
370
 
371
    /** data.regDate is epoch millis; absent or blank means the device is not activated yet. */
372
    private LocalDate regDateFrom(String json) {
373
        if (json == null) return null;
374
        try {
375
            JSONObject data = new JSONObject(json).optJSONObject("data");
376
            if (data == null) return null;
377
            String reg = data.optString("regDate", "");
378
            if (reg == null || reg.trim().isEmpty() || "null".equals(reg)) return null;
379
            return Instant.ofEpochMilli(Long.parseLong(reg.trim()))
380
                    .atZone(ZoneId.of("Asia/Kolkata")).toLocalDate();
381
        } catch (Exception e) {
382
            LOGGER.warn("Could not read regDate from the Oppo response: " + e.getMessage());
383
            return null;
384
        }
385
    }
386
 
37422 amit 387
    /**
37424 amit 388
     * Calibration nudge, in slider px, sized from the gap rather than fixed.
37422 amit 389
     *
37424 amit 390
     * A fixed 15px was far too small: it closed only ~25px, so the ratio came from a
391
     * measurement ~20% noise and the aim landed ~30px out. A fixed 60px then proved too
392
     * large in the other direction -- production data showed 85% of attempts with a gap
393
     * under 60px ended up UNUSABLE (the piece shot past the hole and the measured gap
394
     * grew), and 45% overall.
37422 amit 395
     *
37424 amit 396
     * Aim to close about half the gap: the piece travels roughly ASSUMED_RATIO px per
397
     * slider px, so nudge ~= gap / (2 * ratio), clamped. The real ratio is still derived
398
     * from the measurement; this only sizes the probe.
37422 amit 399
     */
37433 amit 400
    /*
401
     * These are OPPO's tuning values and are deliberately independent of realme's.
402
     * The two classes drive the same dingxiang widget but convert very differently
403
     * (oppo ~12%, realme ~60% of completed drags), so a change proven on one is NOT
404
     * evidence for the other. Tune and measure them separately.
405
     *
406
     * 1.7 was a guess carried over from a single hand measurement. Measured over 3,694
407
     * real oppo calibrations in production the ratio is 0.67 (realme's is 0.70, on its
408
     * own 1,683). At 1.7 the probe closes about a fifth of the gap instead of the half
409
     * it is meant to, so the ratio is derived from a needlessly small, noisy sample.
410
     */
411
    private static final double ASSUMED_RATIO = 0.67;
37424 amit 412
    private static final int MIN_NUDGE = 10;
413
    private static final int MAX_NUDGE = 60;
37422 amit 414
    private static final double ALIGNED_PX = 2.0;
415
 
37424 amit 416
    private static int nudgeFor(double gap) {
417
        int n = (int) Math.round(gap / (2 * ASSUMED_RATIO));
418
        return Math.max(MIN_NUDGE, Math.min(MAX_NUDGE, n));
419
    }
420
 
37422 amit 421
    /**
422
     * @return {sliderPxToMove, sliderPxPerCirclePx}, or null when the circles could not
423
     *         be read. Returned rather than stored on a field: this is a singleton and
424
     *         the Oppo secondary and tertiary jobs run it concurrently.
425
     */
426
    private double[] calibrate(WebDriver driver, Actions actionProvider, double distance) throws Exception {
37424 amit 427
        int nudge = nudgeFor(distance);
428
        actionProvider.moveByOffset(nudge, 0).perform();
37422 amit 429
 
32146 amit.gupta 430
        String fileName2 = "/tmp/" + Thread.currentThread().getName() + "-moved.png";
34413 amit.gupta 431
        double[] movedCircles = getMatCircles2(driver, fileName2);
37422 amit 432
        if (movedCircles == null) return null;
433
 
434
        double movedDistance = Math.abs(movedCircles[0] - movedCircles[1]);
435
        double closed = distance - movedDistance;
436
        LOGGER.info("Calibration: gap {} -> {} after {}px, closed {}",
37424 amit 437
                distance, movedDistance, nudge, closed);
37422 amit 438
 
439
        // A non-positive value means the piece did not move, or moved away from the
440
        // hole -- either way the ratio is meaningless and guessing would waste the try.
441
        if (closed <= 0) return null;
442
 
37424 amit 443
        double sliderPerCircle = nudge / closed;
37422 amit 444
        int moveBy = (int) Math.round(movedDistance * sliderPerCircle);
445
        return new double[]{moveBy, sliderPerCircle};
32146 amit.gupta 446
    }
30209 amit.gupta 447
 
37422 amit 448
    /**
449
     * Measure again after the main move and close whatever is left. The old code
450
     * committed its single computed offset blind, so any calibration error went
451
     * straight into the final position with nothing to catch it.
452
     */
453
    private int refine(WebDriver driver, Actions actionProvider, double sliderPerCircle) throws Exception {
454
        String fileName = "/tmp/" + Thread.currentThread().getName() + "-refine.png";
455
        double[] circles = getMatCircles2(driver, fileName);
456
        if (circles == null) return 0;
457
 
458
        double remaining = Math.abs(circles[0] - circles[1]);
459
        if (remaining <= ALIGNED_PX) return 0;
460
 
461
        int correction = (int) Math.round(remaining * sliderPerCircle);
462
        if (correction == 0) return 0;
463
        LOGGER.info("Refine: {}px of gap left -> nudging {}px", remaining, correction);
464
        actionProvider.moveByOffset(correction, 0).perform();
465
        return correction;
466
    }
467
 
32146 amit.gupta 468
    private Mat getMatCircles(WebDriver driver, String fileName) throws Exception {
30209 amit.gupta 469
 
32146 amit.gupta 470
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
471
        BufferedImage fullImg = ImageIO.read(screenshot);
30209 amit.gupta 472
 
32146 amit.gupta 473
        // Get the location of element on the page
36583 amit 474
        WebElement imageElement = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]"));
32146 amit.gupta 475
        Point point = imageElement.getLocation();
30209 amit.gupta 476
 
32146 amit.gupta 477
        // Get width and height of the element
478
        int eleWidth = imageElement.getSize().getWidth();
479
        int eleHeight = imageElement.getSize().getHeight();
30209 amit.gupta 480
 
32146 amit.gupta 481
        // Crop the entire page screenshot to get only element screenshot
482
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
483
                eleWidth, eleHeight);
484
        ImageIO.write(eleScreenshot, "png", screenshot);
30209 amit.gupta 485
 
32146 amit.gupta 486
        // Copy the element screenshot to disk
487
        File screenshotLocation = new File(fileName);
488
        FileUtils.copyFile(screenshot, screenshotLocation);
30209 amit.gupta 489
 
32146 amit.gupta 490
        Imgcodecs imageCodecs = new Imgcodecs();
491
        Mat grayMatrix = imageCodecs.imread(fileName, Imgcodecs.IMREAD_COLOR);
492
        Imgproc.cvtColor(grayMatrix, grayMatrix, Imgproc.COLOR_BGR2GRAY);
493
        Mat medianBlur = new Mat();
494
        Imgproc.medianBlur(grayMatrix, medianBlur, 5);
495
        Mat circles = new Mat();
496
        Imgproc.HoughCircles(medianBlur, circles, Imgproc.HOUGH_GRADIENT, 1, 15, 50, 20, 17, 25);
497
        return circles;
498
    }
30209 amit.gupta 499
 
34413 amit.gupta 500
    private double[] getMatCircles2(WebDriver driver, String fileName) throws Exception {
501
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
502
        BufferedImage fullImg = ImageIO.read(screenshot);
503
 
504
        // Get the location of element on the page
36583 amit 505
        WebElement imageElement = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]"));
34413 amit.gupta 506
        Point point = imageElement.getLocation();
507
 
508
        // Get width and height of the element
509
        int eleWidth = imageElement.getSize().getWidth();
510
        int eleHeight = imageElement.getSize().getHeight();
511
 
512
        // Crop the entire page screenshot to get only element screenshot
513
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
514
                eleWidth, eleHeight);
515
        ImageIO.write(eleScreenshot, "png", screenshot);
516
 
517
        // Copy the element screenshot to disk
518
        File screenshotLocation = new File(fileName);
519
        FileUtils.copyFile(screenshot, screenshotLocation);
520
 
521
        Mat src = Imgcodecs.imread(fileName);
522
        if (src.empty()) {
523
            System.err.println("Cannot read image: " + fileName);
36253 amit 524
            new File(fileName).delete();
34413 amit.gupta 525
            return null;
526
        }
527
 
528
        Mat gray = new Mat();
529
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
530
        Imgproc.GaussianBlur(gray, gray, new Size(9, 9), 2, 2);
531
 
532
        Mat circles = new Mat();
533
        Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,
534
                20, // min distance between centers
535
                100, 20, // param1 (Canny high threshold), param2 (accumulator threshold)
536
                10, 50); // minRadius, maxRadius (adjust as needed)
537
 
36253 amit 538
        if (circles.cols() < 2) {
539
            new File(fileName).delete();
540
            return null;
541
        }
34413 amit.gupta 542
 
543
        for (int i = 0; i < circles.cols(); i++) {
544
            double[] c1 = circles.get(0, i);
545
            for (int j = i + 1; j < circles.cols(); j++) {
546
                double[] c2 = circles.get(0, j);
547
                if (Math.abs(c1[2] - c2[2]) < 3) { // check similar radius
36253 amit 548
                    new File(fileName).delete();
34413 amit.gupta 549
                    return new double[] {
550
                            c1[0], c2[0] // x-coordinates
551
                    };
552
                }
553
            }
554
        }
555
 
36253 amit 556
        new File(fileName).delete();
34413 amit.gupta 557
        return null;
558
    }
559
 
560
 
30209 amit.gupta 561
}