Subversion Repositories SmartDukaan

Rev

Rev 37446 | Rev 37472 | 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;
37450 amit 7
import org.opencv.core.Core;
30209 amit.gupta 8
import org.opencv.core.Mat;
37450 amit 9
import org.opencv.core.Scalar;
34413 amit.gupta 10
import org.opencv.core.Size;
30209 amit.gupta 11
import org.opencv.imgcodecs.Imgcodecs;
12
import org.opencv.imgproc.Imgproc;
37420 amit 13
import org.json.JSONObject;
30209 amit.gupta 14
import org.openqa.selenium.*;
15
import org.openqa.selenium.chrome.ChromeDriver;
16
import org.openqa.selenium.chrome.ChromeOptions;
17
import org.openqa.selenium.interactions.Actions;
18
import org.openqa.selenium.support.ui.ExpectedConditions;
19
import org.openqa.selenium.support.ui.WebDriverWait;
30373 amit.gupta 20
import org.springframework.stereotype.Component;
30209 amit.gupta 21
 
22
import javax.imageio.ImageIO;
23
import java.awt.image.BufferedImage;
24
import java.io.File;
25
import java.time.LocalDate;
26
import java.time.format.DateTimeFormatter;
37420 amit 27
import java.time.Instant;
28
import java.time.ZoneId;
30209 amit.gupta 29
import java.util.HashMap;
30
import java.util.List;
31
import java.util.Map;
32
import java.util.concurrent.TimeUnit;
33
import java.util.stream.Collectors;
34
 
30373 amit.gupta 35
@Component
36
public class CheckOppoWarrantyTask {
30209 amit.gupta 37
 
32146 amit.gupta 38
    private static final Logger LOGGER = LogManager.getLogger(CheckOppoWarrantyTask.class);
30209 amit.gupta 39
 
36253 amit 40
    static {
36306 amit 41
        try {
42
            OpenCV.loadShared();
43
        } catch (Throwable t) {
44
            LogManager.getLogger(CheckOppoWarrantyTask.class).warn("OpenCV not available on this platform: {}", t.getMessage());
45
        }
36253 amit 46
    }
47
 
32146 amit.gupta 48
    public Map<String, LocalDate> checkWarranty(List<String> imeis) {
49
        Map<String, LocalDate> dateMap = new HashMap<>();
50
        LOGGER.info("Initiating webdriver...");
30209 amit.gupta 51
 
32146 amit.gupta 52
        Map<String, Object> prefsMap = new HashMap<>();
53
        prefsMap.put("profile.default_content_settings.popups", 0);
54
        prefsMap.put("download.prompt", false);
55
        prefsMap.put("download.directory_upgrade", true);
34413 amit.gupta 56
        System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
32146 amit.gupta 57
        //I need this
34413 amit.gupta 58
        //System.setProperty("webdriver.chrome.driver", "/Users/amit/cft/chromedriver/chromedriver");
32146 amit.gupta 59
        ChromeOptions options = new ChromeOptions();
34413 amit.gupta 60
        //options.setBinary("/Users/amit/cft/chrome/Google Chrome for Testing.app/Contents/MacOS/Google Chrome For Testing");
32146 amit.gupta 61
        options.setExperimentalOption("prefs", prefsMap);
62
        //options.setExperimentalOption("detach", true);
63
        options.addArguments("--headless");
64
        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 65
 
32146 amit.gupta 66
        options.addArguments("--no-sandbox");
67
        options.addArguments("start-maximized");
68
        options.addArguments("disable-infobars");
69
        options.addArguments("--disable-extensions");
70
        options.addArguments("--force-device-scale-factor=1");
71
        options.addArguments("--test-type");
37446 amit 72
        // Headless needs no GPU, yet chrome still forks a gpu-process per browser (6 were
73
        // alive across the fleet). --disable-gpu removes them; --disable-dev-shm-usage
74
        // keeps chrome off the small /dev/shm on this box. Both are pure overhead removal,
75
        // no behaviour change. This box co-hosts a 9.4GB tomcat with ~3GB available and
76
        // has been OOM-killed twice this month, and tomcat was the victim both times.
77
        options.addArguments("--disable-gpu");
78
        options.addArguments("--disable-dev-shm-usage");
79
        options.addArguments("--disable-software-rasterizer");
30209 amit.gupta 80
 
34680 amit.gupta 81
        WebDriver driver = null;
30209 amit.gupta 82
 
34680 amit.gupta 83
        try {
84
            driver = new ChromeDriver(options);
85
            driver.manage().timeouts().setScriptTimeout(6, TimeUnit.SECONDS);
86
            driver.manage().window().setSize(new Dimension(1600, 900));
87
            driver.manage().window().maximize();
88
            // Deleting all the cookies
89
            driver.manage().deleteAllCookies();
90
            // Specifiying pageLoadTimeout and Implicit wait
91
            driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
92
            driver.manage().timeouts().implicitlyWait(9, TimeUnit.SECONDS);
34415 amit.gupta 93
 
34680 amit.gupta 94
            int mainCount = 0;
95
            List<String> remainingImeis = imeis;
96
            WebDriverWait wait10Sec = new WebDriverWait(driver, 8);
97
            WebDriverWait wait5Sec = new WebDriverWait(driver, 4);
98
            WebElement slideButton;
99
            Actions actionProvider = new Actions(driver);
100
            do {
101
                driver.get("https://support.oppo.com/in/warranty-check/");
37420 amit 102
                installResponseCapture(driver);
32146 amit.gupta 103
                try {
34680 amit.gupta 104
                    driver.findElement(By.cssSelector(".cp-cookie-tip a.close")).click();
105
                } catch (Exception e) {
106
                }
30209 amit.gupta 107
 
34680 amit.gupta 108
                for (int i = 0; i < remainingImeis.size(); i++) {
109
                    String imei = remainingImeis.get(i);
110
                    try {
37410 amit 111
                        LOGGER.info("Starting fresh with new IMEI " + imei);
34680 amit.gupta 112
                        if (driver.findElement(By.className("el-input__inner")).getAttribute("value").length() > 0) {
37410 amit 113
                            LOGGER.info("Darn.. leaving" + driver.findElement(By.className("el-input__inner")).getAttribute("value"));
32146 amit.gupta 114
                            driver.get("https://support.oppo.com/in/warranty-check/");
37432 amit 115
                            installResponseCapture(driver);
32146 amit.gupta 116
                            break;
117
                        }
34680 amit.gupta 118
                        driver.findElement(By.className("el-input__inner")).sendKeys(imei);
30209 amit.gupta 119
 
34680 amit.gupta 120
                        //driver.findElement(By.className("el-button--primary")).click();
121
                        driver.findElement(By.cssSelector("div.searchBtn")).click();
122
 
123
                        // Perform click-and-hold action on the element
124
                        int counter = 1;
125
                        boolean captchaNotBroken = true;
37435 amit 126
                        // release() is only reached on the moveByOffset > 0 path, so an attempt
127
                        // that fails detection or calibration leaves the button DOWN. Measured in
128
                        // production: 79% of presses were never released. Actions is one instance
129
                        // per driver, created outside the imei loop, so the stuck press leaks into
130
                        // the next attempt AND the next imei -- the following clickAndHold lands on
131
                        // an already-held button, so the widget never repositions the handle and the
132
                        // drag continues from wherever the pointer was abandoned.
133
                        boolean pressed = false;
34680 amit.gupta 134
                        do {
135
                            String fileName = "/tmp/oppo-simple-i-" + counter + " " + System.currentTimeMillis() + ".png";
136
                            try {
37410 amit 137
                                LOGGER.info("Starting Do");
36583 amit 138
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
139
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
37437 amit 140
                                By sliderBy = By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]");
141
                                slideButton = driver.findElement(sliderBy);
142
                                LOGGER.info("Margin Left before- " + marginLeftOf(slideButton));
143
                                try {
144
                                    actionProvider.moveToElement(slideButton).clickAndHold()
145
                                            .moveByOffset(1, 0)
146
                                            .perform();
147
                                } catch (StaleElementReferenceException stale) {
148
                                    // The retry refresh (doubleClick at the end of the previous
149
                                    // attempt) swaps the widget's DOM, so the handle located at the
150
                                    // top of THIS attempt can already be detached by the time we act
151
                                    // on it. Re-find and try once, rather than abandoning the imei
152
                                    // and reloading the page: this killed 19% of oppo attempts
153
                                    // (54 of 284), against 0 on realme.
154
                                    LOGGER.info("Slider went stale before the drag - re-finding and retrying once");
155
                                    slideButton = driver.findElement(sliderBy);
156
                                    actionProvider.moveToElement(slideButton).clickAndHold()
157
                                            .moveByOffset(1, 0)
158
                                            .perform();
159
                                }
37435 amit 160
                                pressed = true;
37437 amit 161
                                LOGGER.info("Margin Left after - " + marginLeftOf(slideButton));
34680 amit.gupta 162
                                //Thread.sleep(5000);
163
                            } catch (Exception e) {
37410 amit 164
                                LOGGER.warn("Slider captcha widget (dx_captcha_basic_*) not found or not draggable"
165
                                        + " - reloading. Cause: " + e.getMessage());
34680 amit.gupta 166
                                driver.get("https://support.oppo.com/in/warranty-check/");
37432 amit 167
                                installResponseCapture(driver);
34680 amit.gupta 168
                                break;
169
                            }
37450 amit 170
                            Double ringPageX = pieceCentreX(driver);
171
                            double[] circles = null;
172
                            if (ringPageX == null) {
173
                                LOGGER.warn("No ring element to anchor detection on");
174
                            } else {
175
                                int bgLeft = driver.findElement(
176
                                        By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]")).getLocation().getX();
177
                                circles = getMatCircles2(driver, fileName, ringPageX - bgLeft);
178
                            }
34680 amit.gupta 179
                            if (circles != null) {
180
                                double firstCircleX = circles[0];
181
                                double secondCircleX = circles[1];
182
                                double distance = Math.abs(firstCircleX - secondCircleX);
37410 amit 183
                                LOGGER.info("Distance is " + distance);
34680 amit.gupta 184
 
37438 amit 185
                                // Closed loop on the ring's own position; no assumed ratio.
186
                                int moveByOffset = aim(driver, actionProvider, circles);
34680 amit.gupta 187
                                if (moveByOffset > 0) {
37422 amit 188
                                    actionProvider.release().perform();
37435 amit 189
                                    pressed = false;
37422 amit 190
                                    LOGGER.info("Move click performed (main {}px)", moveByOffset);
32146 amit.gupta 191
                                    try {
34680 amit.gupta 192
                                        try {
193
                                            wait5Sec.until(ExpectedConditions.visibilityOfElementLocated(By.className("dx_captcha_basic_bar-inform")));
37433 amit 194
                                            // realme logs the widget's own verdict here and oppo did not,
195
                                            // which is why realme's failures name POSITION_MISMATCH and
196
                                            // oppo's 85% say nothing at all. Same line, oppo's variables.
197
                                            LOGGER.warn("Failed = {} (captcha said: {})", counter, captchaSignal(driver));
34680 amit.gupta 198
                                        } catch (Exception notFailedException) {
37410 amit 199
                                            LOGGER.info("Success  at attempt " + counter);
37420 amit 200
 
201
                                            // Read the JSON the page itself received rather than the
202
                                            // rendered text. The DOM value is built from two text nodes -- the
203
                                            // date plus a "(UTC+x)" suffix derived from the browser timezone --
204
                                            // and the old locator tested only the first, so it matched nothing.
205
                                            // The API carries regDate as epoch millis, which has no format or
206
                                            // timezone ambiguity at all.
37429 amit 207
                                            String json = awaitResponse(driver, 8000);
37420 amit 208
                                            LocalDate activationDate = regDateFrom(json);
209
 
210
                                            if (json == null) {
37429 amit 211
                                                LOGGER.warn("No getDeviceInfo response for imei {} (captcha said: {})",
212
                                                        imei, captchaSignal(driver));
34680 amit.gupta 213
                                            } else {
37420 amit 214
                                                LOGGER.info("Activation lookup for {} -> {}", imei,
215
                                                        activationDate != null ? activationDate : "no activation date");
32146 amit.gupta 216
                                            }
37420 amit 217
                                            // Always record the imei, even with a null date: findElement used to
218
                                            // throw here, so the row was never written and came back every run.
219
                                            dateMap.put(imei, activationDate);
220
                                            clearCapture(driver);
221
 
34680 amit.gupta 222
                                            if (dateMap.size() == imeis.size()) {
223
                                                return dateMap;
224
                                            }
225
                                            WebElement checkAgainButton = driver.findElement(By.className("c-btn"));
226
                                            captchaNotBroken = false;
227
                                            checkAgainButton.click();
228
                                            break;
32146 amit.gupta 229
                                        }
34680 amit.gupta 230
                                    } catch (Throwable e) {
37410 amit 231
                                        LOGGER.warn("Failed = " + counter + " ----------" + e.getMessage());
32146 amit.gupta 232
                                    }
233
                                }
234
                            }
37435 amit 235
                            // Any path that got here without releasing (null circles, unusable
236
                            // calibration) must let go before the next attempt re-presses.
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
                                pressed = false;
244
                            }
37410 amit 245
                            LOGGER.info("After circles conditions");
36583 amit 246
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
247
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
248
                            slideButton = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]"));
34680 amit.gupta 249
                            actionProvider.moveToElement(slideButton).doubleClick().perform();
37410 amit 250
                            LOGGER.info("Ending Do" + counter++);
30209 amit.gupta 251
 
37445 amit 252
                        } while (captchaNotBroken && counter <= MAX_CAPTCHA_ATTEMPTS);
37435 amit 253
                        // The widget-not-found path breaks out mid-iteration; do not carry a held
254
                        // button into the next imei.
255
                        if (pressed) {
256
                            try {
257
                                actionProvider.release().perform();
258
                            } catch (Exception releaseFailed) {
259
                                LOGGER.warn("Could not release the slider: " + releaseFailed.getMessage());
260
                            }
261
                        }
37445 amit 262
                        LOGGER.warn("Gave up after {} captcha attempts - imei stays pending for the next tick", MAX_CAPTCHA_ATTEMPTS);
34680 amit.gupta 263
                    } catch (Exception e) {
37410 amit 264
                        LOGGER.error("Oppo warranty check failed for imei " + imei, e);
34680 amit.gupta 265
                    }
266
                    driver.get("https://support.oppo.com/in/warranty-check/");
37432 amit 267
                    // Every navigation destroys the JS context, taking the capture hook
268
                    // with it. Miss one of these and the page is blind from the second
269
                    // imei onwards: __oppoResp and __oppoCaptcha both come back null,
270
                    // which reads as "the captcha failed" when it may well have passed.
271
                    installResponseCapture(driver);
34680 amit.gupta 272
                }
273
                mainCount++;
274
                remainingImeis = imeis.stream().filter(x -> !dateMap.containsKey(x)).collect(Collectors.toList());
36253 amit 275
                if (remainingImeis.isEmpty()) break;
34680 amit.gupta 276
            } while (mainCount < 5);
277
        } finally {
278
            if (driver != null) {
279
                try {
280
                    driver.quit(); //Ensures cleanup even on return or error
32146 amit.gupta 281
                } catch (Exception e) {
37410 amit 282
                    LOGGER.warn("Error closing driver: " + e.getMessage());
32146 amit.gupta 283
                }
284
            }
34680 amit.gupta 285
        }
286
 
32146 amit.gupta 287
        return dateMap;
288
    }
30352 amit.gupta 289
 
34680 amit.gupta 290
 
37420 amit 291
    /** Stash the getDeviceInfo response on window as the page receives it. */
292
    private void installResponseCapture(WebDriver driver) {
293
        try {
294
            ((JavascriptExecutor) driver).executeScript(
295
                "if (!window.__oppoCapInstalled) {"
37428 amit 296
              + "  window.__oppoCapInstalled = true; window.__oppoResp = null; window.__oppoCaptcha = null;"
37434 amit 297
              // __oppoCaptcha is last-captcha-call-wins, and the widget refetches a puzzle
298
              // (/api/a) straight after a rejected verify (/api/v1). We then wait up to 5s
299
              // for the error element before reading it, which is ample time for the
300
              // refetch to overwrite the verdict -- so "all failures show /api/a" cannot
301
              // distinguish "never verified" from "verified, rejected, then overwritten".
302
              // Keep the verify separately, and a count, so the two are distinguishable.
303
              + "  window.__oppoVerify = null; window.__oppoVerifyCount = 0;"
37425 amit 304
              // axios can sit on either transport, and realme's page uses fetch --
305
              // an XHR-only hook silently captures nothing, which is exactly what
306
              // 'no getDeviceInfo response captured' was reporting.
37420 amit 307
              + "  var O = XMLHttpRequest.prototype.open;"
308
              + "  XMLHttpRequest.prototype.open = function(m,u){"
309
              + "    this.addEventListener('load', function(){"
37428 amit 310
              + "      try { var s=String(u);"
311
              + "        if (s.indexOf('getDeviceInfo') !== -1) window.__oppoResp = this.responseText;"
37434 amit 312
              + "        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 313
              + "        else if (s.indexOf('captcha') !== -1) window.__oppoCaptcha = s + ' -> ' + (this.responseText||'').slice(0,200);"
314
              + "      } catch(e){}"
37420 amit 315
              + "    });"
316
              + "    return O.apply(this, arguments);"
317
              + "  };"
37425 amit 318
              + "  var F = window.fetch;"
319
              + "  if (F) { window.fetch = function(){"
320
              + "    var u = arguments[0]; u = (u && u.url) ? u.url : String(u);"
321
              + "    return F.apply(this, arguments).then(function(r){"
322
              + "      try { if (u.indexOf('getDeviceInfo') !== -1) { r.clone().text().then(function(t){ window.__oppoResp = t; }); } } catch(e){}"
323
              + "      return r;"
324
              + "    });"
325
              + "  }; }"
37431 amit 326
              // A window.fetch wrapper only catches clients that resolve fetch at call
327
              // time. Anything that captured globalThis.fetch when its bundle loaded --
328
              // Nuxt's $fetch/ofetch does exactly this, and it is what hid realme's
329
              // lookup from us -- sails straight past it. Response.prototype is resolved
330
              // per call, so it catches every client regardless.
331
              // Read the clone with the ORIGINAL reader; the patched one recurses forever.
332
              + "  ['json','text'].forEach(function(name){"
333
              + "    var orig = Response.prototype[name];"
334
              + "    if (!orig) return;"
335
              + "    Response.prototype[name] = function(){"
336
              + "      try { var u = this.url || '';"
337
              + "        if (u.indexOf('getDeviceInfo') !== -1 && !this.__oppoSeenBody) {"
338
              + "          var c = this.clone(); c.__oppoSeenBody = 1;"
339
              + "          orig.call(c).then(function(t){ window.__oppoResp = (typeof t === 'string') ? t : JSON.stringify(t); });"
340
              + "        } } catch(e){}"
341
              + "      return orig.apply(this, arguments);"
342
              + "    };"
343
              + "  });"
37420 amit 344
              + "}");
345
        } catch (Exception e) {
346
            LOGGER.warn("Could not install the response capture hook: " + e.getMessage());
347
        }
348
    }
349
 
37428 amit 350
    /** Last response from the captcha widget itself -- says WHY a drag was refused. */
351
    private String captchaSignal(WebDriver driver) {
352
        try {
37434 amit 353
            Object v = ((JavascriptExecutor) driver).executeScript(
354
                    "return 'verifies=' + (window.__oppoVerifyCount||0)"
355
                  + " + ' lastVerify=' + (window.__oppoVerify || 'NONE')"
356
                  + " + ' | ' + (window.__oppoCaptcha || 'none');");
37428 amit 357
            return v == null ? null : v.toString();
358
        } catch (Exception e) {
359
            return null;
360
        }
361
    }
362
 
37429 amit 363
    /** Poll for the response instead of reading once: the success signal can fire
364
     *  before the lookup request has completed, which loses the payload. */
365
    private String awaitResponse(WebDriver driver, long timeoutMs) {
366
        long deadline = System.currentTimeMillis() + timeoutMs;
367
        while (System.currentTimeMillis() < deadline) {
368
            String json = capturedResponse(driver);
369
            if (json != null && !json.trim().isEmpty()) return json;
370
            try {
371
                Thread.sleep(300);
372
            } catch (InterruptedException ie) {
373
                Thread.currentThread().interrupt();
374
                return null;
375
            }
376
        }
377
        return null;
378
    }
379
 
37420 amit 380
    private String capturedResponse(WebDriver driver) {
381
        try {
382
            Object v = ((JavascriptExecutor) driver).executeScript("return window.__oppoResp || null;");
383
            return v == null ? null : v.toString();
384
        } catch (Exception e) {
385
            return null;
386
        }
387
    }
388
 
389
    private void clearCapture(WebDriver driver) {
390
        try {
391
            ((JavascriptExecutor) driver).executeScript("window.__oppoResp = null;");
392
        } catch (Exception ignored) {
393
        }
394
    }
395
 
396
    /** data.regDate is epoch millis; absent or blank means the device is not activated yet. */
397
    private LocalDate regDateFrom(String json) {
398
        if (json == null) return null;
399
        try {
400
            JSONObject data = new JSONObject(json).optJSONObject("data");
401
            if (data == null) return null;
402
            String reg = data.optString("regDate", "");
403
            if (reg == null || reg.trim().isEmpty() || "null".equals(reg)) return null;
404
            return Instant.ofEpochMilli(Long.parseLong(reg.trim()))
405
                    .atZone(ZoneId.of("Asia/Kolkata")).toLocalDate();
406
        } catch (Exception e) {
407
            LOGGER.warn("Could not read regDate from the Oppo response: " + e.getMessage());
408
            return null;
409
        }
410
    }
411
 
37422 amit 412
    /**
37439 amit 413
     * How close the ring must get to the hole before we release, in px.
37422 amit 414
     *
37439 amit 415
     * There is deliberately NO assumed ratio anywhere in this class. px-per-px is derived
416
     * from real movement on every attempt and re-derived on every step within it -- see
417
     * aim(). Earlier revisions carried an ASSUMED_RATIO constant, it was tuned twice
418
     * (1.7 -> 0.67 -> 1.7) against contaminated measurements, and it never helped. Do not
419
     * reintroduce one: the widget's px-per-px genuinely varies by environment (1.4-1.5 in
420
     * production, 1.1-1.2 locally) and by brand, which is exactly why it must be measured.
37422 amit 421
     */
37445 amit 422
    /**
423
     * Captcha attempts per imei per tick, before giving up and letting the next tick
424
     * retry with a FRESH page and session.
425
     *
426
     * A captcha failure is a technical failure, not an answer, so the imei is never
427
     * abandoned -- it stays pending and comes back in ~5 minutes. What this caps is how
428
     * many times we grind on it inside one already-refused session.
429
     *
430
     * 20 was right before the drag was fixed: pre-glide, 33% of oppo's successes came
431
     * from attempts 8-20. Post-glide (r37440) the drag lands first or second try and the
432
     * tail stopped paying. Measured over 308 post-glide successes and 279 exhausted imeis:
433
     *   cap  5 -> 95.5% of successes kept, 67.7% of captcha work saved
434
     *   cap  7 -> 97.7% kept, 58.4% saved   <- here
435
     *   cap 10 -> 99.0% kept, 44.8% saved
436
     * Realme keeps its own, higher cap: it has no glide yet, so its successes still
437
     * spread to attempt 10+ and 7 would cost it 16.5%. Re-check the histogram after a
438
     * day; if the distribution shifts, so should this.
439
     */
440
    private static final int MAX_CAPTCHA_ATTEMPTS = 7;
441
 
37422 amit 442
    private static final double ALIGNED_PX = 2.0;
443
 
37437 amit 444
    /**
445
     * margin-left for logging only. Reading it off a detached element throws, and this is
446
     * a diagnostic -- it must never be the reason an attempt is abandoned.
447
     */
448
    private String marginLeftOf(WebElement el) {
449
        try {
450
            return el.getCssValue("margin-left");
451
        } catch (Exception e) {
452
            return "?";
453
        }
37424 amit 454
    }
455
 
37437 amit 456
    /** Seed probe, in slider px. Deliberately small: it only has to produce a first
457
     *  measurable movement, and it must be too small to cross the hole. */
458
    private static final int SEED_NUDGE = 12;
37440 amit 459
    /** Sub-moves per leg, and the pause between them. A leg is traversed as many small
460
     *  eased steps rather than one jump, so the pointer describes a continuous path. */
461
    private static final int MAX_GLIDE_STEPS = 18;
462
    private static final int GLIDE_PX_PER_STEP = 8;
463
    private static final long GLIDE_PAUSE_MS = 45;
37437 amit 464
    private static final int MAX_AIM_STEPS = 5;
465
    private static final int MAX_STEP = 140;
466
 
37440 amit 467
    /**
468
     * Traverse one leg as many small eased sub-moves instead of a single jump.
469
     *
470
     * Nothing about the distance changes -- it is still whatever the derived ratio says.
471
     * Only the path does. The widget scores trajectory as well as final position, and
472
     * returns POSITION_MISMATCH for either, so a drag that teleports in 2 jumps and one
473
     * that slides in over 15 are not equally credible. Realme holds ~1.93s and converts
474
     * 54-74%; oppo held 0.91s in 2-3 jumps and converts 15%. That is suggestive, not
475
     * proof -- this change is the test.
476
     *
477
     * Ease-out (1-(1-t)^2) so it starts quickly and settles, which is how a hand moves.
478
     */
479
    private void glide(Actions actionProvider, int distance) throws InterruptedException {
480
        int steps = Math.abs(distance) / GLIDE_PX_PER_STEP;
481
        if (steps > MAX_GLIDE_STEPS) steps = MAX_GLIDE_STEPS;
482
        if (steps <= 1) {
483
            actionProvider.moveByOffset(distance, 0).perform();
484
            return;
485
        }
486
        int done = 0;
487
        for (int i = 1; i <= steps; i++) {
488
            double t = (double) i / steps;
489
            int cumulative = (int) Math.round(distance * (1 - Math.pow(1 - t, 2)));
490
            int delta = cumulative - done;
491
            if (delta != 0) {
492
                actionProvider.moveByOffset(delta, 0).perform();
493
                done += delta;
494
            }
495
            Thread.sleep(GLIDE_PAUSE_MS);
496
        }
497
        if (done != distance) {
498
            actionProvider.moveByOffset(distance - done, 0).perform();
499
        }
500
    }
501
 
37438 amit 502
    /** Centre of the draggable ring, in page CSS px, or null if it is not there. */
503
    private Double pieceCentreX(WebDriver driver) {
504
        try {
505
            WebElement piece = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_sub-slider_')]"));
506
            return piece.getLocation().getX() + (piece.getSize().getWidth() / 2.0);
507
        } catch (Exception e) {
508
            return null;
509
        }
510
    }
511
 
37422 amit 512
    /**
37438 amit 513
     * Drag the ring onto the hole, deriving px-per-px as we go.
37437 amit 514
     *
37438 amit 515
     * Why this does not re-run circle detection: it cannot. Hough needs to resolve TWO
516
     * circles of similar radius, and as the ring closes on the hole they overlap and stop
517
     * being two -- so the measurement dies exactly at convergence. Measured in production
518
     * after r37437: 25 of 36 attempts lost the circles on the very step after the main
519
     * move, and NOT ONE ever reported aligned. The old refine() hit the same wall and
520
     * silently released. Any loop built on "distance between two detected circles" is
521
     * blind at the only moment that matters.
37437 amit 522
     *
37438 amit 523
     * So the target is fixed ONCE, from the detection already done while the two are far
524
     * apart and resolvable, and from then on we track the RING'S OWN ELEMENT, which stays
525
     * readable however close it gets. Verified locally against the live widget: the ring's
526
     * rect tracks the drag cleanly the whole way in (+10 mouse -> +11 ring, repeatably).
37437 amit 527
     *
37438 amit 528
     * The circle x's are already CSS px relative to the bg element -- the crop in
529
     * getMatCircles2 uses CSS coordinates and chrome runs with
530
     * --force-device-scale-factor=1 -- so the only conversion needed is the bg offset.
531
     *
532
     * Every move is also a measurement: the ratio is re-derived from what that move
533
     * actually achieved, and it is signed, so overshoot corrects itself instead of needing
534
     * to be detected.
535
     *
536
     * @return total slider px moved, or 0 if the ring could not be located at all.
37422 amit 537
     */
37438 amit 538
    private int aim(WebDriver driver, Actions actionProvider, double[] circleXs) throws Exception {
539
        Double piece = pieceCentreX(driver);
540
        if (piece == null) {
541
            LOGGER.warn("Aim: no ring element to track");
542
            return 0;
543
        }
544
        int bgX;
545
        try {
546
            bgX = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]")).getLocation().getX();
547
        } catch (Exception e) {
548
            LOGGER.warn("Aim: bg element gone - " + e.getMessage());
549
            return 0;
550
        }
551
 
552
        // Of the two detected circles the ring is whichever sits at the ring element; the
553
        // other one is the hole we are aiming at.
554
        double a = bgX + circleXs[0], b = bgX + circleXs[1];
555
        double target = (Math.abs(a - piece) <= Math.abs(b - piece)) ? b : a;
556
        LOGGER.info("Aim: ring at {} target at {} ({}px to close)",
557
                Math.round(piece), Math.round(target), Math.round(target - piece));
558
 
559
        double ratio = 0;               // ring px per mouse px, signed, derived from real moves
37437 amit 560
        int total = 0;
561
        int step = SEED_NUDGE;
37422 amit 562
 
37437 amit 563
        for (int i = 0; i < MAX_AIM_STEPS; i++) {
37440 amit 564
            glide(actionProvider, step);
37437 amit 565
            total += step;
37422 amit 566
 
37438 amit 567
            Double now = pieceCentreX(driver);
568
            if (now == null) {
569
                LOGGER.warn("Aim step {}: lost the ring after {}px", i, total);
37437 amit 570
                return total;
571
            }
37438 amit 572
            double moved = now - piece;
573
            if (Math.abs(moved) > 0.5) {
574
                double observed = moved / step;
575
                ratio = (ratio == 0) ? observed : (ratio + observed) / 2;
37437 amit 576
            }
37438 amit 577
            double remaining = target - now;
578
            LOGGER.info("Aim step {}: mouse {}px -> ring moved {}px, {}px left, ratio {}",
579
                    i, step, Math.round(moved), Math.round(remaining), String.format("%.2f", ratio));
37422 amit 580
 
37438 amit 581
            if (Math.abs(remaining) <= ALIGNED_PX) {
582
                LOGGER.info("Aim: aligned to {}px after {} step(s), {}px of slider",
583
                        Math.round(remaining), i + 1, total);
37437 amit 584
                return total;
585
            }
37438 amit 586
            piece = now;
587
            if (ratio == 0) {           // nothing measurable yet, probe again
37437 amit 588
                step = SEED_NUDGE;
589
                continue;
590
            }
37438 amit 591
            int next = (int) Math.round(remaining / ratio);
592
            if (next == 0) next = (remaining > 0 ? 1 : -1);
37437 amit 593
            if (next > MAX_STEP) next = MAX_STEP;
37438 amit 594
            if (next < -MAX_STEP) next = -MAX_STEP;
595
            step = next;
37437 amit 596
        }
37438 amit 597
        LOGGER.info("Aim: {} steps used, {}px of slider, still short", MAX_AIM_STEPS, total);
37437 amit 598
        return total;
32146 amit.gupta 599
    }
30209 amit.gupta 600
 
32146 amit.gupta 601
    private Mat getMatCircles(WebDriver driver, String fileName) throws Exception {
30209 amit.gupta 602
 
32146 amit.gupta 603
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
604
        BufferedImage fullImg = ImageIO.read(screenshot);
30209 amit.gupta 605
 
32146 amit.gupta 606
        // Get the location of element on the page
36583 amit 607
        WebElement imageElement = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]"));
32146 amit.gupta 608
        Point point = imageElement.getLocation();
30209 amit.gupta 609
 
32146 amit.gupta 610
        // Get width and height of the element
611
        int eleWidth = imageElement.getSize().getWidth();
612
        int eleHeight = imageElement.getSize().getHeight();
30209 amit.gupta 613
 
32146 amit.gupta 614
        // Crop the entire page screenshot to get only element screenshot
615
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
616
                eleWidth, eleHeight);
617
        ImageIO.write(eleScreenshot, "png", screenshot);
30209 amit.gupta 618
 
32146 amit.gupta 619
        // Copy the element screenshot to disk
620
        File screenshotLocation = new File(fileName);
621
        FileUtils.copyFile(screenshot, screenshotLocation);
30209 amit.gupta 622
 
32146 amit.gupta 623
        Imgcodecs imageCodecs = new Imgcodecs();
624
        Mat grayMatrix = imageCodecs.imread(fileName, Imgcodecs.IMREAD_COLOR);
625
        Imgproc.cvtColor(grayMatrix, grayMatrix, Imgproc.COLOR_BGR2GRAY);
626
        Mat medianBlur = new Mat();
627
        Imgproc.medianBlur(grayMatrix, medianBlur, 5);
628
        Mat circles = new Mat();
629
        Imgproc.HoughCircles(medianBlur, circles, Imgproc.HOUGH_GRADIENT, 1, 15, 50, 20, 17, 25);
630
        return circles;
631
    }
30209 amit.gupta 632
 
37450 amit 633
    /** Anything within this many px of the ring's known centre IS the ring, not the hole. */
634
    private static final double RING_EXCLUSION_PX = 30;
635
    /** A real hole sits at least this far below the frame's mean luminance. */
636
    private static final double MIN_HOLE_DARKNESS = 15;
637
 
638
    /** Mean luminance inside a detected circle, clamped to the image. */
639
    private double meanInside(Mat gray, double[] circle) {
640
        int r = (int) Math.max(3, circle[2] * 0.6);            // inner core, avoids the rim
641
        int x0 = (int) Math.max(0, circle[0] - r), y0 = (int) Math.max(0, circle[1] - r);
642
        int x1 = (int) Math.min(gray.cols(), circle[0] + r), y1 = (int) Math.min(gray.rows(), circle[1] + r);
643
        if (x1 - x0 < 2 || y1 - y0 < 2) return Double.MAX_VALUE;
644
        return Core.mean(gray.submat(y0, y1, x0, x1)).val[0];
645
    }
646
 
647
    /**
648
     * Locate the hole. The RING is not detected -- its exact position comes from the DOM
649
     * (dx_captcha_basic_sub-slider_), so hough only has to find one thing instead of two.
650
     *
651
     * The old version demanded TWO circles whose radii matched within 3px and returned
652
     * null otherwise, so a puzzle where the hole was found perfectly well still failed if
653
     * the ring was missed or the radii differed by 4px. It was also re-detecting something
654
     * already known exactly.
655
     *
656
     * param1 is the Canny HIGH threshold: edges weaker than it are discarded before circle
657
     * finding begins. At 100 a low-contrast hole produces no edge at all. Measured on four
658
     * live puzzles, hole-vs-background contrast was 98, 103, 28 and 117 -- the 28 (a pale
659
     * lilac background) cannot survive 100, which is the mechanism behind "60% of attempts
660
     * never find the circles". Dropped to 50.
661
     *
662
     * @param ringRelX ring centre in px relative to the bg element's left edge
663
     * @return {ringRelX, holeRelX} -- shape kept so callers are unchanged -- or null
664
     */
665
    private double[] getMatCircles2(WebDriver driver, String fileName, double ringRelX) throws Exception {
34413 amit.gupta 666
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
667
        BufferedImage fullImg = ImageIO.read(screenshot);
668
 
669
        // Get the location of element on the page
36583 amit 670
        WebElement imageElement = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]"));
34413 amit.gupta 671
        Point point = imageElement.getLocation();
672
 
673
        // Get width and height of the element
674
        int eleWidth = imageElement.getSize().getWidth();
675
        int eleHeight = imageElement.getSize().getHeight();
676
 
677
        // Crop the entire page screenshot to get only element screenshot
678
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
679
                eleWidth, eleHeight);
680
        ImageIO.write(eleScreenshot, "png", screenshot);
681
 
682
        // Copy the element screenshot to disk
683
        File screenshotLocation = new File(fileName);
684
        FileUtils.copyFile(screenshot, screenshotLocation);
685
 
686
        Mat src = Imgcodecs.imread(fileName);
687
        if (src.empty()) {
688
            System.err.println("Cannot read image: " + fileName);
36253 amit 689
            new File(fileName).delete();
34413 amit.gupta 690
            return null;
691
        }
692
 
693
        Mat gray = new Mat();
694
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
695
        Imgproc.GaussianBlur(gray, gray, new Size(9, 9), 2, 2);
696
 
697
        Mat circles = new Mat();
698
        Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,
699
                20, // min distance between centers
37450 amit 700
                50, 20, // param1 (Canny high threshold), param2 (accumulator threshold)
701
                10, 50); // minRadius, maxRadius
34413 amit.gupta 702
 
37450 amit 703
        if (circles.cols() < 1) {
36253 amit 704
            new File(fileName).delete();
705
            return null;
706
        }
34413 amit.gupta 707
 
37450 amit 708
        // Dropping param1 to 50 lets weak edges through, which also lets textured
709
        // backgrounds (the sand images especially) produce spurious circles. Without the
710
        // old two-circle pairing there is nothing else to reject them, so verify the
711
        // candidate is actually a HOLE: it must be materially darker than the picture as
712
        // a whole. Measured on live puzzles the hole runs 28-117 luminance below the
713
        // median, so 15 rejects noise while keeping even the faintest real hole.
714
        Scalar frameMean = Core.mean(gray);
715
        // OpenCV returns circles strongest-accumulator first, so take the first candidate
716
        // that is not the ring and does look like a hole.
34413 amit.gupta 717
        for (int i = 0; i < circles.cols(); i++) {
37450 amit 718
            double[] c = circles.get(0, i);
719
            if (Math.abs(c[0] - ringRelX) < RING_EXCLUSION_PX) continue; // that is the ring
720
            double darkness = frameMean.val[0] - meanInside(gray, c);
721
            if (darkness < MIN_HOLE_DARKNESS) {
722
                LOGGER.info("Rejecting circle at {}px: only {} darker than the frame",
723
                        Math.round(c[0]), Math.round(darkness));
724
                continue;
34413 amit.gupta 725
            }
37450 amit 726
            new File(fileName).delete();
727
            return new double[] { ringRelX, c[0] };
34413 amit.gupta 728
        }
729
 
37450 amit 730
        LOGGER.info("Detected {} circle(s) but all sat on the ring at {}px", circles.cols(), Math.round(ringRelX));
36253 amit 731
        new File(fileName).delete();
34413 amit.gupta 732
        return null;
733
    }
734
 
735
 
30209 amit.gupta 736
}