Subversion Repositories SmartDukaan

Rev

Rev 37440 | Rev 37446 | 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_')]")));
37437 amit 130
                                By sliderBy = By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]");
131
                                slideButton = driver.findElement(sliderBy);
132
                                LOGGER.info("Margin Left before- " + marginLeftOf(slideButton));
133
                                try {
134
                                    actionProvider.moveToElement(slideButton).clickAndHold()
135
                                            .moveByOffset(1, 0)
136
                                            .perform();
137
                                } catch (StaleElementReferenceException stale) {
138
                                    // The retry refresh (doubleClick at the end of the previous
139
                                    // attempt) swaps the widget's DOM, so the handle located at the
140
                                    // top of THIS attempt can already be detached by the time we act
141
                                    // on it. Re-find and try once, rather than abandoning the imei
142
                                    // and reloading the page: this killed 19% of oppo attempts
143
                                    // (54 of 284), against 0 on realme.
144
                                    LOGGER.info("Slider went stale before the drag - re-finding and retrying once");
145
                                    slideButton = driver.findElement(sliderBy);
146
                                    actionProvider.moveToElement(slideButton).clickAndHold()
147
                                            .moveByOffset(1, 0)
148
                                            .perform();
149
                                }
37435 amit 150
                                pressed = true;
37437 amit 151
                                LOGGER.info("Margin Left after - " + marginLeftOf(slideButton));
34680 amit.gupta 152
                                //Thread.sleep(5000);
153
                            } catch (Exception e) {
37410 amit 154
                                LOGGER.warn("Slider captcha widget (dx_captcha_basic_*) not found or not draggable"
155
                                        + " - reloading. Cause: " + e.getMessage());
34680 amit.gupta 156
                                driver.get("https://support.oppo.com/in/warranty-check/");
37432 amit 157
                                installResponseCapture(driver);
34680 amit.gupta 158
                                break;
159
                            }
160
                            double[] circles = getMatCircles2(driver, fileName);
161
                            if (circles != null) {
162
                                double firstCircleX = circles[0];
163
                                double secondCircleX = circles[1];
164
                                double distance = Math.abs(firstCircleX - secondCircleX);
37410 amit 165
                                LOGGER.info("Distance is " + distance);
34680 amit.gupta 166
 
37438 amit 167
                                // Closed loop on the ring's own position; no assumed ratio.
168
                                int moveByOffset = aim(driver, actionProvider, circles);
34680 amit.gupta 169
                                if (moveByOffset > 0) {
37422 amit 170
                                    actionProvider.release().perform();
37435 amit 171
                                    pressed = false;
37422 amit 172
                                    LOGGER.info("Move click performed (main {}px)", moveByOffset);
32146 amit.gupta 173
                                    try {
34680 amit.gupta 174
                                        try {
175
                                            wait5Sec.until(ExpectedConditions.visibilityOfElementLocated(By.className("dx_captcha_basic_bar-inform")));
37433 amit 176
                                            // realme logs the widget's own verdict here and oppo did not,
177
                                            // which is why realme's failures name POSITION_MISMATCH and
178
                                            // oppo's 85% say nothing at all. Same line, oppo's variables.
179
                                            LOGGER.warn("Failed = {} (captcha said: {})", counter, captchaSignal(driver));
34680 amit.gupta 180
                                        } catch (Exception notFailedException) {
37410 amit 181
                                            LOGGER.info("Success  at attempt " + counter);
37420 amit 182
 
183
                                            // Read the JSON the page itself received rather than the
184
                                            // rendered text. The DOM value is built from two text nodes -- the
185
                                            // date plus a "(UTC+x)" suffix derived from the browser timezone --
186
                                            // and the old locator tested only the first, so it matched nothing.
187
                                            // The API carries regDate as epoch millis, which has no format or
188
                                            // timezone ambiguity at all.
37429 amit 189
                                            String json = awaitResponse(driver, 8000);
37420 amit 190
                                            LocalDate activationDate = regDateFrom(json);
191
 
192
                                            if (json == null) {
37429 amit 193
                                                LOGGER.warn("No getDeviceInfo response for imei {} (captcha said: {})",
194
                                                        imei, captchaSignal(driver));
34680 amit.gupta 195
                                            } else {
37420 amit 196
                                                LOGGER.info("Activation lookup for {} -> {}", imei,
197
                                                        activationDate != null ? activationDate : "no activation date");
32146 amit.gupta 198
                                            }
37420 amit 199
                                            // Always record the imei, even with a null date: findElement used to
200
                                            // throw here, so the row was never written and came back every run.
201
                                            dateMap.put(imei, activationDate);
202
                                            clearCapture(driver);
203
 
34680 amit.gupta 204
                                            if (dateMap.size() == imeis.size()) {
205
                                                return dateMap;
206
                                            }
207
                                            WebElement checkAgainButton = driver.findElement(By.className("c-btn"));
208
                                            captchaNotBroken = false;
209
                                            checkAgainButton.click();
210
                                            break;
32146 amit.gupta 211
                                        }
34680 amit.gupta 212
                                    } catch (Throwable e) {
37410 amit 213
                                        LOGGER.warn("Failed = " + counter + " ----------" + e.getMessage());
32146 amit.gupta 214
                                    }
215
                                }
216
                            }
37435 amit 217
                            // Any path that got here without releasing (null circles, unusable
218
                            // calibration) must let go before the next attempt re-presses.
219
                            if (pressed) {
220
                                try {
221
                                    actionProvider.release().perform();
222
                                } catch (Exception releaseFailed) {
223
                                    LOGGER.warn("Could not release the slider: " + releaseFailed.getMessage());
224
                                }
225
                                pressed = false;
226
                            }
37410 amit 227
                            LOGGER.info("After circles conditions");
36583 amit 228
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
229
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
230
                            slideButton = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]"));
34680 amit.gupta 231
                            actionProvider.moveToElement(slideButton).doubleClick().perform();
37410 amit 232
                            LOGGER.info("Ending Do" + counter++);
30209 amit.gupta 233
 
37445 amit 234
                        } while (captchaNotBroken && counter <= MAX_CAPTCHA_ATTEMPTS);
37435 amit 235
                        // The widget-not-found path breaks out mid-iteration; do not carry a held
236
                        // button into the next imei.
237
                        if (pressed) {
238
                            try {
239
                                actionProvider.release().perform();
240
                            } catch (Exception releaseFailed) {
241
                                LOGGER.warn("Could not release the slider: " + releaseFailed.getMessage());
242
                            }
243
                        }
37445 amit 244
                        LOGGER.warn("Gave up after {} captcha attempts - imei stays pending for the next tick", MAX_CAPTCHA_ATTEMPTS);
34680 amit.gupta 245
                    } catch (Exception e) {
37410 amit 246
                        LOGGER.error("Oppo warranty check failed for imei " + imei, e);
34680 amit.gupta 247
                    }
248
                    driver.get("https://support.oppo.com/in/warranty-check/");
37432 amit 249
                    // Every navigation destroys the JS context, taking the capture hook
250
                    // with it. Miss one of these and the page is blind from the second
251
                    // imei onwards: __oppoResp and __oppoCaptcha both come back null,
252
                    // which reads as "the captcha failed" when it may well have passed.
253
                    installResponseCapture(driver);
34680 amit.gupta 254
                }
255
                mainCount++;
256
                remainingImeis = imeis.stream().filter(x -> !dateMap.containsKey(x)).collect(Collectors.toList());
36253 amit 257
                if (remainingImeis.isEmpty()) break;
34680 amit.gupta 258
            } while (mainCount < 5);
259
        } finally {
260
            if (driver != null) {
261
                try {
262
                    driver.quit(); //Ensures cleanup even on return or error
32146 amit.gupta 263
                } catch (Exception e) {
37410 amit 264
                    LOGGER.warn("Error closing driver: " + e.getMessage());
32146 amit.gupta 265
                }
266
            }
34680 amit.gupta 267
        }
268
 
32146 amit.gupta 269
        return dateMap;
270
    }
30352 amit.gupta 271
 
34680 amit.gupta 272
 
37420 amit 273
    /** Stash the getDeviceInfo response on window as the page receives it. */
274
    private void installResponseCapture(WebDriver driver) {
275
        try {
276
            ((JavascriptExecutor) driver).executeScript(
277
                "if (!window.__oppoCapInstalled) {"
37428 amit 278
              + "  window.__oppoCapInstalled = true; window.__oppoResp = null; window.__oppoCaptcha = null;"
37434 amit 279
              // __oppoCaptcha is last-captcha-call-wins, and the widget refetches a puzzle
280
              // (/api/a) straight after a rejected verify (/api/v1). We then wait up to 5s
281
              // for the error element before reading it, which is ample time for the
282
              // refetch to overwrite the verdict -- so "all failures show /api/a" cannot
283
              // distinguish "never verified" from "verified, rejected, then overwritten".
284
              // Keep the verify separately, and a count, so the two are distinguishable.
285
              + "  window.__oppoVerify = null; window.__oppoVerifyCount = 0;"
37425 amit 286
              // axios can sit on either transport, and realme's page uses fetch --
287
              // an XHR-only hook silently captures nothing, which is exactly what
288
              // 'no getDeviceInfo response captured' was reporting.
37420 amit 289
              + "  var O = XMLHttpRequest.prototype.open;"
290
              + "  XMLHttpRequest.prototype.open = function(m,u){"
291
              + "    this.addEventListener('load', function(){"
37428 amit 292
              + "      try { var s=String(u);"
293
              + "        if (s.indexOf('getDeviceInfo') !== -1) window.__oppoResp = this.responseText;"
37434 amit 294
              + "        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 295
              + "        else if (s.indexOf('captcha') !== -1) window.__oppoCaptcha = s + ' -> ' + (this.responseText||'').slice(0,200);"
296
              + "      } catch(e){}"
37420 amit 297
              + "    });"
298
              + "    return O.apply(this, arguments);"
299
              + "  };"
37425 amit 300
              + "  var F = window.fetch;"
301
              + "  if (F) { window.fetch = function(){"
302
              + "    var u = arguments[0]; u = (u && u.url) ? u.url : String(u);"
303
              + "    return F.apply(this, arguments).then(function(r){"
304
              + "      try { if (u.indexOf('getDeviceInfo') !== -1) { r.clone().text().then(function(t){ window.__oppoResp = t; }); } } catch(e){}"
305
              + "      return r;"
306
              + "    });"
307
              + "  }; }"
37431 amit 308
              // A window.fetch wrapper only catches clients that resolve fetch at call
309
              // time. Anything that captured globalThis.fetch when its bundle loaded --
310
              // Nuxt's $fetch/ofetch does exactly this, and it is what hid realme's
311
              // lookup from us -- sails straight past it. Response.prototype is resolved
312
              // per call, so it catches every client regardless.
313
              // Read the clone with the ORIGINAL reader; the patched one recurses forever.
314
              + "  ['json','text'].forEach(function(name){"
315
              + "    var orig = Response.prototype[name];"
316
              + "    if (!orig) return;"
317
              + "    Response.prototype[name] = function(){"
318
              + "      try { var u = this.url || '';"
319
              + "        if (u.indexOf('getDeviceInfo') !== -1 && !this.__oppoSeenBody) {"
320
              + "          var c = this.clone(); c.__oppoSeenBody = 1;"
321
              + "          orig.call(c).then(function(t){ window.__oppoResp = (typeof t === 'string') ? t : JSON.stringify(t); });"
322
              + "        } } catch(e){}"
323
              + "      return orig.apply(this, arguments);"
324
              + "    };"
325
              + "  });"
37420 amit 326
              + "}");
327
        } catch (Exception e) {
328
            LOGGER.warn("Could not install the response capture hook: " + e.getMessage());
329
        }
330
    }
331
 
37428 amit 332
    /** Last response from the captcha widget itself -- says WHY a drag was refused. */
333
    private String captchaSignal(WebDriver driver) {
334
        try {
37434 amit 335
            Object v = ((JavascriptExecutor) driver).executeScript(
336
                    "return 'verifies=' + (window.__oppoVerifyCount||0)"
337
                  + " + ' lastVerify=' + (window.__oppoVerify || 'NONE')"
338
                  + " + ' | ' + (window.__oppoCaptcha || 'none');");
37428 amit 339
            return v == null ? null : v.toString();
340
        } catch (Exception e) {
341
            return null;
342
        }
343
    }
344
 
37429 amit 345
    /** Poll for the response instead of reading once: the success signal can fire
346
     *  before the lookup request has completed, which loses the payload. */
347
    private String awaitResponse(WebDriver driver, long timeoutMs) {
348
        long deadline = System.currentTimeMillis() + timeoutMs;
349
        while (System.currentTimeMillis() < deadline) {
350
            String json = capturedResponse(driver);
351
            if (json != null && !json.trim().isEmpty()) return json;
352
            try {
353
                Thread.sleep(300);
354
            } catch (InterruptedException ie) {
355
                Thread.currentThread().interrupt();
356
                return null;
357
            }
358
        }
359
        return null;
360
    }
361
 
37420 amit 362
    private String capturedResponse(WebDriver driver) {
363
        try {
364
            Object v = ((JavascriptExecutor) driver).executeScript("return window.__oppoResp || null;");
365
            return v == null ? null : v.toString();
366
        } catch (Exception e) {
367
            return null;
368
        }
369
    }
370
 
371
    private void clearCapture(WebDriver driver) {
372
        try {
373
            ((JavascriptExecutor) driver).executeScript("window.__oppoResp = null;");
374
        } catch (Exception ignored) {
375
        }
376
    }
377
 
378
    /** data.regDate is epoch millis; absent or blank means the device is not activated yet. */
379
    private LocalDate regDateFrom(String json) {
380
        if (json == null) return null;
381
        try {
382
            JSONObject data = new JSONObject(json).optJSONObject("data");
383
            if (data == null) return null;
384
            String reg = data.optString("regDate", "");
385
            if (reg == null || reg.trim().isEmpty() || "null".equals(reg)) return null;
386
            return Instant.ofEpochMilli(Long.parseLong(reg.trim()))
387
                    .atZone(ZoneId.of("Asia/Kolkata")).toLocalDate();
388
        } catch (Exception e) {
389
            LOGGER.warn("Could not read regDate from the Oppo response: " + e.getMessage());
390
            return null;
391
        }
392
    }
393
 
37422 amit 394
    /**
37439 amit 395
     * How close the ring must get to the hole before we release, in px.
37422 amit 396
     *
37439 amit 397
     * There is deliberately NO assumed ratio anywhere in this class. px-per-px is derived
398
     * from real movement on every attempt and re-derived on every step within it -- see
399
     * aim(). Earlier revisions carried an ASSUMED_RATIO constant, it was tuned twice
400
     * (1.7 -> 0.67 -> 1.7) against contaminated measurements, and it never helped. Do not
401
     * reintroduce one: the widget's px-per-px genuinely varies by environment (1.4-1.5 in
402
     * production, 1.1-1.2 locally) and by brand, which is exactly why it must be measured.
37422 amit 403
     */
37445 amit 404
    /**
405
     * Captcha attempts per imei per tick, before giving up and letting the next tick
406
     * retry with a FRESH page and session.
407
     *
408
     * A captcha failure is a technical failure, not an answer, so the imei is never
409
     * abandoned -- it stays pending and comes back in ~5 minutes. What this caps is how
410
     * many times we grind on it inside one already-refused session.
411
     *
412
     * 20 was right before the drag was fixed: pre-glide, 33% of oppo's successes came
413
     * from attempts 8-20. Post-glide (r37440) the drag lands first or second try and the
414
     * tail stopped paying. Measured over 308 post-glide successes and 279 exhausted imeis:
415
     *   cap  5 -> 95.5% of successes kept, 67.7% of captcha work saved
416
     *   cap  7 -> 97.7% kept, 58.4% saved   <- here
417
     *   cap 10 -> 99.0% kept, 44.8% saved
418
     * Realme keeps its own, higher cap: it has no glide yet, so its successes still
419
     * spread to attempt 10+ and 7 would cost it 16.5%. Re-check the histogram after a
420
     * day; if the distribution shifts, so should this.
421
     */
422
    private static final int MAX_CAPTCHA_ATTEMPTS = 7;
423
 
37422 amit 424
    private static final double ALIGNED_PX = 2.0;
425
 
37437 amit 426
    /**
427
     * margin-left for logging only. Reading it off a detached element throws, and this is
428
     * a diagnostic -- it must never be the reason an attempt is abandoned.
429
     */
430
    private String marginLeftOf(WebElement el) {
431
        try {
432
            return el.getCssValue("margin-left");
433
        } catch (Exception e) {
434
            return "?";
435
        }
37424 amit 436
    }
437
 
37437 amit 438
    /** Seed probe, in slider px. Deliberately small: it only has to produce a first
439
     *  measurable movement, and it must be too small to cross the hole. */
440
    private static final int SEED_NUDGE = 12;
37440 amit 441
    /** Sub-moves per leg, and the pause between them. A leg is traversed as many small
442
     *  eased steps rather than one jump, so the pointer describes a continuous path. */
443
    private static final int MAX_GLIDE_STEPS = 18;
444
    private static final int GLIDE_PX_PER_STEP = 8;
445
    private static final long GLIDE_PAUSE_MS = 45;
37437 amit 446
    private static final int MAX_AIM_STEPS = 5;
447
    private static final int MAX_STEP = 140;
448
 
37440 amit 449
    /**
450
     * Traverse one leg as many small eased sub-moves instead of a single jump.
451
     *
452
     * Nothing about the distance changes -- it is still whatever the derived ratio says.
453
     * Only the path does. The widget scores trajectory as well as final position, and
454
     * returns POSITION_MISMATCH for either, so a drag that teleports in 2 jumps and one
455
     * that slides in over 15 are not equally credible. Realme holds ~1.93s and converts
456
     * 54-74%; oppo held 0.91s in 2-3 jumps and converts 15%. That is suggestive, not
457
     * proof -- this change is the test.
458
     *
459
     * Ease-out (1-(1-t)^2) so it starts quickly and settles, which is how a hand moves.
460
     */
461
    private void glide(Actions actionProvider, int distance) throws InterruptedException {
462
        int steps = Math.abs(distance) / GLIDE_PX_PER_STEP;
463
        if (steps > MAX_GLIDE_STEPS) steps = MAX_GLIDE_STEPS;
464
        if (steps <= 1) {
465
            actionProvider.moveByOffset(distance, 0).perform();
466
            return;
467
        }
468
        int done = 0;
469
        for (int i = 1; i <= steps; i++) {
470
            double t = (double) i / steps;
471
            int cumulative = (int) Math.round(distance * (1 - Math.pow(1 - t, 2)));
472
            int delta = cumulative - done;
473
            if (delta != 0) {
474
                actionProvider.moveByOffset(delta, 0).perform();
475
                done += delta;
476
            }
477
            Thread.sleep(GLIDE_PAUSE_MS);
478
        }
479
        if (done != distance) {
480
            actionProvider.moveByOffset(distance - done, 0).perform();
481
        }
482
    }
483
 
37438 amit 484
    /** Centre of the draggable ring, in page CSS px, or null if it is not there. */
485
    private Double pieceCentreX(WebDriver driver) {
486
        try {
487
            WebElement piece = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_sub-slider_')]"));
488
            return piece.getLocation().getX() + (piece.getSize().getWidth() / 2.0);
489
        } catch (Exception e) {
490
            return null;
491
        }
492
    }
493
 
37422 amit 494
    /**
37438 amit 495
     * Drag the ring onto the hole, deriving px-per-px as we go.
37437 amit 496
     *
37438 amit 497
     * Why this does not re-run circle detection: it cannot. Hough needs to resolve TWO
498
     * circles of similar radius, and as the ring closes on the hole they overlap and stop
499
     * being two -- so the measurement dies exactly at convergence. Measured in production
500
     * after r37437: 25 of 36 attempts lost the circles on the very step after the main
501
     * move, and NOT ONE ever reported aligned. The old refine() hit the same wall and
502
     * silently released. Any loop built on "distance between two detected circles" is
503
     * blind at the only moment that matters.
37437 amit 504
     *
37438 amit 505
     * So the target is fixed ONCE, from the detection already done while the two are far
506
     * apart and resolvable, and from then on we track the RING'S OWN ELEMENT, which stays
507
     * readable however close it gets. Verified locally against the live widget: the ring's
508
     * rect tracks the drag cleanly the whole way in (+10 mouse -> +11 ring, repeatably).
37437 amit 509
     *
37438 amit 510
     * The circle x's are already CSS px relative to the bg element -- the crop in
511
     * getMatCircles2 uses CSS coordinates and chrome runs with
512
     * --force-device-scale-factor=1 -- so the only conversion needed is the bg offset.
513
     *
514
     * Every move is also a measurement: the ratio is re-derived from what that move
515
     * actually achieved, and it is signed, so overshoot corrects itself instead of needing
516
     * to be detected.
517
     *
518
     * @return total slider px moved, or 0 if the ring could not be located at all.
37422 amit 519
     */
37438 amit 520
    private int aim(WebDriver driver, Actions actionProvider, double[] circleXs) throws Exception {
521
        Double piece = pieceCentreX(driver);
522
        if (piece == null) {
523
            LOGGER.warn("Aim: no ring element to track");
524
            return 0;
525
        }
526
        int bgX;
527
        try {
528
            bgX = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]")).getLocation().getX();
529
        } catch (Exception e) {
530
            LOGGER.warn("Aim: bg element gone - " + e.getMessage());
531
            return 0;
532
        }
533
 
534
        // Of the two detected circles the ring is whichever sits at the ring element; the
535
        // other one is the hole we are aiming at.
536
        double a = bgX + circleXs[0], b = bgX + circleXs[1];
537
        double target = (Math.abs(a - piece) <= Math.abs(b - piece)) ? b : a;
538
        LOGGER.info("Aim: ring at {} target at {} ({}px to close)",
539
                Math.round(piece), Math.round(target), Math.round(target - piece));
540
 
541
        double ratio = 0;               // ring px per mouse px, signed, derived from real moves
37437 amit 542
        int total = 0;
543
        int step = SEED_NUDGE;
37422 amit 544
 
37437 amit 545
        for (int i = 0; i < MAX_AIM_STEPS; i++) {
37440 amit 546
            glide(actionProvider, step);
37437 amit 547
            total += step;
37422 amit 548
 
37438 amit 549
            Double now = pieceCentreX(driver);
550
            if (now == null) {
551
                LOGGER.warn("Aim step {}: lost the ring after {}px", i, total);
37437 amit 552
                return total;
553
            }
37438 amit 554
            double moved = now - piece;
555
            if (Math.abs(moved) > 0.5) {
556
                double observed = moved / step;
557
                ratio = (ratio == 0) ? observed : (ratio + observed) / 2;
37437 amit 558
            }
37438 amit 559
            double remaining = target - now;
560
            LOGGER.info("Aim step {}: mouse {}px -> ring moved {}px, {}px left, ratio {}",
561
                    i, step, Math.round(moved), Math.round(remaining), String.format("%.2f", ratio));
37422 amit 562
 
37438 amit 563
            if (Math.abs(remaining) <= ALIGNED_PX) {
564
                LOGGER.info("Aim: aligned to {}px after {} step(s), {}px of slider",
565
                        Math.round(remaining), i + 1, total);
37437 amit 566
                return total;
567
            }
37438 amit 568
            piece = now;
569
            if (ratio == 0) {           // nothing measurable yet, probe again
37437 amit 570
                step = SEED_NUDGE;
571
                continue;
572
            }
37438 amit 573
            int next = (int) Math.round(remaining / ratio);
574
            if (next == 0) next = (remaining > 0 ? 1 : -1);
37437 amit 575
            if (next > MAX_STEP) next = MAX_STEP;
37438 amit 576
            if (next < -MAX_STEP) next = -MAX_STEP;
577
            step = next;
37437 amit 578
        }
37438 amit 579
        LOGGER.info("Aim: {} steps used, {}px of slider, still short", MAX_AIM_STEPS, total);
37437 amit 580
        return total;
32146 amit.gupta 581
    }
30209 amit.gupta 582
 
32146 amit.gupta 583
    private Mat getMatCircles(WebDriver driver, String fileName) throws Exception {
30209 amit.gupta 584
 
32146 amit.gupta 585
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
586
        BufferedImage fullImg = ImageIO.read(screenshot);
30209 amit.gupta 587
 
32146 amit.gupta 588
        // Get the location of element on the page
36583 amit 589
        WebElement imageElement = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]"));
32146 amit.gupta 590
        Point point = imageElement.getLocation();
30209 amit.gupta 591
 
32146 amit.gupta 592
        // Get width and height of the element
593
        int eleWidth = imageElement.getSize().getWidth();
594
        int eleHeight = imageElement.getSize().getHeight();
30209 amit.gupta 595
 
32146 amit.gupta 596
        // Crop the entire page screenshot to get only element screenshot
597
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
598
                eleWidth, eleHeight);
599
        ImageIO.write(eleScreenshot, "png", screenshot);
30209 amit.gupta 600
 
32146 amit.gupta 601
        // Copy the element screenshot to disk
602
        File screenshotLocation = new File(fileName);
603
        FileUtils.copyFile(screenshot, screenshotLocation);
30209 amit.gupta 604
 
32146 amit.gupta 605
        Imgcodecs imageCodecs = new Imgcodecs();
606
        Mat grayMatrix = imageCodecs.imread(fileName, Imgcodecs.IMREAD_COLOR);
607
        Imgproc.cvtColor(grayMatrix, grayMatrix, Imgproc.COLOR_BGR2GRAY);
608
        Mat medianBlur = new Mat();
609
        Imgproc.medianBlur(grayMatrix, medianBlur, 5);
610
        Mat circles = new Mat();
611
        Imgproc.HoughCircles(medianBlur, circles, Imgproc.HOUGH_GRADIENT, 1, 15, 50, 20, 17, 25);
612
        return circles;
613
    }
30209 amit.gupta 614
 
34413 amit.gupta 615
    private double[] getMatCircles2(WebDriver driver, String fileName) throws Exception {
616
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
617
        BufferedImage fullImg = ImageIO.read(screenshot);
618
 
619
        // Get the location of element on the page
36583 amit 620
        WebElement imageElement = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]"));
34413 amit.gupta 621
        Point point = imageElement.getLocation();
622
 
623
        // Get width and height of the element
624
        int eleWidth = imageElement.getSize().getWidth();
625
        int eleHeight = imageElement.getSize().getHeight();
626
 
627
        // Crop the entire page screenshot to get only element screenshot
628
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
629
                eleWidth, eleHeight);
630
        ImageIO.write(eleScreenshot, "png", screenshot);
631
 
632
        // Copy the element screenshot to disk
633
        File screenshotLocation = new File(fileName);
634
        FileUtils.copyFile(screenshot, screenshotLocation);
635
 
636
        Mat src = Imgcodecs.imread(fileName);
637
        if (src.empty()) {
638
            System.err.println("Cannot read image: " + fileName);
36253 amit 639
            new File(fileName).delete();
34413 amit.gupta 640
            return null;
641
        }
642
 
643
        Mat gray = new Mat();
644
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
645
        Imgproc.GaussianBlur(gray, gray, new Size(9, 9), 2, 2);
646
 
647
        Mat circles = new Mat();
648
        Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,
649
                20, // min distance between centers
650
                100, 20, // param1 (Canny high threshold), param2 (accumulator threshold)
651
                10, 50); // minRadius, maxRadius (adjust as needed)
652
 
36253 amit 653
        if (circles.cols() < 2) {
654
            new File(fileName).delete();
655
            return null;
656
        }
34413 amit.gupta 657
 
658
        for (int i = 0; i < circles.cols(); i++) {
659
            double[] c1 = circles.get(0, i);
660
            for (int j = i + 1; j < circles.cols(); j++) {
661
                double[] c2 = circles.get(0, j);
662
                if (Math.abs(c1[2] - c2[2]) < 3) { // check similar radius
36253 amit 663
                    new File(fileName).delete();
34413 amit.gupta 664
                    return new double[] {
665
                            c1[0], c2[0] // x-coordinates
666
                    };
667
                }
668
            }
669
        }
670
 
36253 amit 671
        new File(fileName).delete();
34413 amit.gupta 672
        return null;
673
    }
674
 
675
 
30209 amit.gupta 676
}