Subversion Repositories SmartDukaan

Rev

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