Subversion Repositories SmartDukaan

Rev

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