Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
30209 amit.gupta 1
package com.smartdukaan.cron.scheduled;
2
 
3
import nu.pattern.OpenCV;
4
import org.apache.commons.io.FileUtils;
5
import org.apache.logging.log4j.LogManager;
6
import org.apache.logging.log4j.Logger;
7
import org.opencv.core.Mat;
34413 amit.gupta 8
import org.opencv.core.Size;
30209 amit.gupta 9
import org.opencv.imgcodecs.Imgcodecs;
10
import org.opencv.imgproc.Imgproc;
37423 amit 11
import org.json.JSONObject;
30209 amit.gupta 12
import org.openqa.selenium.*;
13
import org.openqa.selenium.chrome.ChromeDriver;
14
import org.openqa.selenium.chrome.ChromeOptions;
15
import org.openqa.selenium.interactions.Actions;
16
import org.openqa.selenium.support.ui.ExpectedConditions;
17
import org.openqa.selenium.support.ui.WebDriverWait;
30373 amit.gupta 18
import org.springframework.stereotype.Component;
30209 amit.gupta 19
 
20
import javax.imageio.ImageIO;
21
import java.awt.image.BufferedImage;
22
import java.io.File;
23
import java.time.LocalDate;
24
import java.time.format.DateTimeFormatter;
25
import java.util.HashMap;
26
import java.util.List;
27
import java.util.Map;
28
import java.util.concurrent.TimeUnit;
29
import java.util.stream.Collectors;
30
 
30373 amit.gupta 31
@Component
34416 amit.gupta 32
public class CheckRealmeWarrantyTask {
30209 amit.gupta 33
 
34416 amit.gupta 34
    private static final Logger LOGGER = LogManager.getLogger(CheckRealmeWarrantyTask.class);
30209 amit.gupta 35
 
36253 amit 36
    static {
36306 amit 37
        try {
38
            OpenCV.loadShared();
39
        } catch (Throwable t) {
40
            LogManager.getLogger(CheckRealmeWarrantyTask.class).warn("OpenCV not available on this platform: {}", t.getMessage());
41
        }
36253 amit 42
    }
43
 
32146 amit.gupta 44
    public Map<String, LocalDate> checkWarranty(List<String> imeis) {
45
        Map<String, LocalDate> dateMap = new HashMap<>();
46
        LOGGER.info("Initiating webdriver...");
30209 amit.gupta 47
 
32146 amit.gupta 48
        Map<String, Object> prefsMap = new HashMap<>();
49
        prefsMap.put("profile.default_content_settings.popups", 0);
50
        prefsMap.put("download.prompt", false);
51
        prefsMap.put("download.directory_upgrade", true);
34413 amit.gupta 52
        System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
32146 amit.gupta 53
        //I need this
34413 amit.gupta 54
        //System.setProperty("webdriver.chrome.driver", "/Users/amit/cft/chromedriver/chromedriver");
32146 amit.gupta 55
        ChromeOptions options = new ChromeOptions();
34413 amit.gupta 56
        //options.setBinary("/Users/amit/cft/chrome/Google Chrome for Testing.app/Contents/MacOS/Google Chrome For Testing");
32146 amit.gupta 57
        options.setExperimentalOption("prefs", prefsMap);
58
        //options.setExperimentalOption("detach", true);
59
        options.addArguments("--headless");
34419 amit.gupta 60
        options.addArguments("--user-agent=\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36\"");
30209 amit.gupta 61
 
32146 amit.gupta 62
        options.addArguments("--no-sandbox");
63
        options.addArguments("start-maximized");
64
        options.addArguments("disable-infobars");
65
        options.addArguments("--disable-extensions");
66
        options.addArguments("--force-device-scale-factor=1");
67
        options.addArguments("--test-type");
34420 amit.gupta 68
        options.addArguments(
69
                "--disable-blink-features=AutomationControlled",
70
                "--disable-infobars",
71
                "--disable-popup-blocking",
72
                "--disable-notifications",
73
                "--disable-extensions"
74
        );
30209 amit.gupta 75
 
34679 amit.gupta 76
        WebDriver driver = null;
30209 amit.gupta 77
 
34679 amit.gupta 78
        try {
79
            driver = new ChromeDriver(options);
80
            driver.manage().timeouts().setScriptTimeout(6, TimeUnit.SECONDS);
81
            driver.manage().window().setSize(new Dimension(1600, 900));
82
            driver.manage().window().maximize();
83
            // Deleting all the cookies
84
            driver.manage().deleteAllCookies();
85
            // Specifiying pageLoadTimeout and Implicit wait
86
            driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
87
            driver.manage().timeouts().implicitlyWait(9, TimeUnit.SECONDS);
88
 
89
            int mainCount = 0;
90
            List<String> remainingImeis = imeis;
91
            WebDriverWait wait10Sec = new WebDriverWait(driver, 15);
92
            WebDriverWait wait5Sec = new WebDriverWait(driver, 4);
93
            WebElement slideButton;
94
            Actions actionProvider = new Actions(driver);
95
            do {
96
                driver.get("https://www.realme.com/in/support/phonecheck");
37423 amit 97
                installResponseCapture(driver);
34424 amit.gupta 98
            /*try {
34415 amit.gupta 99
                driver.findElement(By.cssSelector(".cp-cookie-tip a.close")).click();
100
            } catch (Exception e) {
101
                try {
37423 amit 102
                    LOGGER.info("Cookie not found");
34415 amit.gupta 103
                } catch (Exception e1) {
104
                }
34424 amit.gupta 105
            }*/
34415 amit.gupta 106
 
34679 amit.gupta 107
                for (int i = 0; i < remainingImeis.size(); i++) {
108
                    String imei = remainingImeis.get(i);
109
                    try {
37423 amit 110
                        LOGGER.info("Starting fresh with new IMEI " + imei);
111
                        // realme rebuilt this page: the field is no longer .sn-input and the
112
                        // submit is no longer div.check-btn but an icon inside the same box.
113
                        if (driver.findElement(By.cssSelector(IMEI_INPUT)).getAttribute("value").length() > 0) {
34679 amit.gupta 114
                            //System.out.println("Darn.. leaving" + driver.findElement(By.className("el-input__inner")).getAttribute("value"));
115
                            driver.get("https://www.realme.com/in/support/phonecheck");
37423 amit 116
                installResponseCapture(driver);
34679 amit.gupta 117
                            break;
118
                        }
37423 amit 119
                        driver.findElement(By.cssSelector(IMEI_INPUT)).sendKeys(imei);
30209 amit.gupta 120
 
34679 amit.gupta 121
                        //driver.findElement(By.className("el-button--primary")).click();
37423 amit 122
                        driver.findElement(By.cssSelector(SUBMIT_ICON)).click();
34413 amit.gupta 123
 
34679 amit.gupta 124
                        // Perform click-and-hold action on the element
125
                        int counter = 1;
126
                        boolean captchaNotBroken = true;
37435 amit 127
                        // release() is only reached on the moveByOffset > 0 path, so an attempt
128
                        // that fails detection or calibration leaves the button DOWN -- measured
129
                        // at 77% of realme presses in production. Actions is one instance per
130
                        // driver, created outside the imei loop, so the stuck press leaks into the
131
                        // next attempt and the next imei: the following clickAndHold lands on an
132
                        // already-held button and the widget never repositions the handle.
133
                        boolean pressed = false;
34679 amit.gupta 134
                        do {
135
                            String fileName = "/tmp/oppo-simple-i-" + counter + " " + System.currentTimeMillis() + ".png";
136
                            try {
37423 amit 137
                                LOGGER.info("Starting Do");
34679 amit.gupta 138
                                //Thread.sleep(5000);
139
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.tagName("canvas")));
34420 amit.gupta 140
 
34679 amit.gupta 141
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]")));
142
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
143
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
144
                                slideButton = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]"));
145
                                //System.out.println("Slide button - " + slideButton);
37423 amit 146
                                LOGGER.info("Margin Left before- " + slideButton.getCssValue("margin-left"));
34679 amit.gupta 147
                                actionProvider.moveToElement(slideButton).clickAndHold()
148
                                        .moveByOffset(1, 0)//.pause(2000)
149
                                        .perform();
37435 amit 150
                                pressed = true;
34413 amit.gupta 151
 
34679 amit.gupta 152
                                //actionProvider.moveByOffset(-1,0).pause(2000).perform();
37423 amit 153
                                LOGGER.info("Margin Left after - " + slideButton.getCssValue("margin-left"));
34679 amit.gupta 154
                                //Thread.sleep(5000);
155
                            } catch (Exception e) {
37423 amit 156
                                LOGGER.info(e.getMessage());
34679 amit.gupta 157
                                driver.get("https://www.realme.com/in/support/phonecheck");
37423 amit 158
                installResponseCapture(driver);
34679 amit.gupta 159
                                break;
160
                            }
161
                            double[] circles = getMatCircles2(driver, fileName);
162
                            if (circles != null) {
163
                                double firstCircleX = circles[0];
164
                                double secondCircleX = circles[1];
165
                                double distance = Math.abs(firstCircleX - secondCircleX);
37423 amit 166
                                LOGGER.info("Distance is " + distance);
30209 amit.gupta 167
 
37423 amit 168
                                double[] cal = calibrate(driver, actionProvider, distance);
169
                                int moveByOffset = cal == null ? 0 : (int) cal[0];
34679 amit.gupta 170
                                if (moveByOffset > 0) {
37423 amit 171
                                    // Move, measure again, close the remainder, THEN release.
172
                                    actionProvider.moveByOffset(moveByOffset, 0).perform();
173
                                    refine(driver, actionProvider, cal[1]);
174
                                    actionProvider.release().perform();
37435 amit 175
                                    pressed = false;
37423 amit 176
                                    LOGGER.info("Move click performed (main {}px)", moveByOffset);
32146 amit.gupta 177
                                    try {
37426 amit 178
                                        // Success used to mean "the dx_captcha_basic_bar-inform error element
179
                                        // did not appear". realme rebuilt this page, so that element may no
180
                                        // longer exist -- in which case the wait always times out and EVERY
181
                                        // attempt reports success while the captcha was never solved. That is
182
                                        // exactly what happened: 27 successes, 27 missed responses, 0 rows.
183
                                        //
184
                                        // The lookup response arriving is the only signal that actually proves
185
                                        // the captcha passed, so wait for that instead.
186
                                        String json = awaitResponse(driver, 8000);
187
                                        if (json == null) {
37430 amit 188
                                            LOGGER.warn("Failed = {} (captcha said: {}) urls={}",
189
                                                    counter, captchaSignal(driver), seenUrls(driver));
37426 amit 190
                                        } else {
37423 amit 191
                                            LOGGER.info("Success  at attempt " + counter);
34679 amit.gupta 192
                                            //List<WebElement> warrantyDateElements = driver.findElements(By.className("warranty-service--result_info__dateValue"));
193
                                            //WebElement activationTimeElement = driver.findElement(By.xpath("//*[contains(text(), 'UTC+5.5')  or contains(text(), 'Non-Activate')]"));
37423 amit 194
                                            // Read the JSON the page already received. The old locator
195
                                            // keyed off a label that no longer exists, and its "| //h1" branch
196
                                            // would silently grab a page heading and try to parse it as a date.
197
                                            // The API is explicit: expiryDate (yyyy.MM.dd) plus an isActivation
198
                                            // flag, so nothing has to be inferred from message text.
199
                                            LocalDate activationDate = activationFrom(json);
37426 amit 200
                                            LOGGER.info("Activation lookup for {} -> {}", imei,
201
                                                    activationDate != null ? activationDate : "not activated");
37423 amit 202
                                            // Always record, even with a null date. findElement used to THROW
203
                                            // when the element was missing, so nothing was written and the imei
204
                                            // came back on every run indefinitely.
205
                                            dateMap.put(imei, activationDate);
206
                                            clearCapture(driver);
207
 
34679 amit.gupta 208
                                            if (dateMap.size() == imeis.size()) {
209
                                                return dateMap;
210
                                            }
211
                                            WebElement checkAgainButton = driver.findElement(By.className("recheck-btn"));
212
                                            captchaNotBroken = false;
213
                                            checkAgainButton.click();
214
                                            break;
32146 amit.gupta 215
                                        }
34679 amit.gupta 216
                                    } catch (Throwable e) {
37423 amit 217
                                        LOGGER.warn("Failed = " + counter + " ----------" + e.getMessage());
32146 amit.gupta 218
                                    }
219
                                }
220
                            }
37435 amit 221
                            // Any path that got here without releasing (null circles, unusable
222
                            // calibration) must let go before the next attempt re-presses.
223
                            if (pressed) {
224
                                try {
225
                                    actionProvider.release().perform();
226
                                } catch (Exception releaseFailed) {
227
                                    LOGGER.warn("Could not release the slider: " + releaseFailed.getMessage());
228
                                }
229
                                pressed = false;
230
                            }
37423 amit 231
                            LOGGER.info("After circles conditions");
34679 amit.gupta 232
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
233
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
234
                            slideButton = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]"));
235
                            actionProvider.moveToElement(slideButton).doubleClick().perform();
37423 amit 236
                            LOGGER.info("Ending Do" + counter++);
30209 amit.gupta 237
 
37445 amit 238
                        } while (captchaNotBroken && counter <= MAX_CAPTCHA_ATTEMPTS);
37435 amit 239
                        // The widget-not-found path breaks out mid-iteration; do not carry a held
240
                        // button into the next imei.
241
                        if (pressed) {
242
                            try {
243
                                actionProvider.release().perform();
244
                            } catch (Exception releaseFailed) {
245
                                LOGGER.warn("Could not release the slider: " + releaseFailed.getMessage());
246
                            }
247
                        }
37445 amit 248
                        LOGGER.warn("Gave up after {} captcha attempts - imei stays pending for the next tick", MAX_CAPTCHA_ATTEMPTS);
34679 amit.gupta 249
                    } catch (Exception e) {
37423 amit 250
                        LOGGER.info("Caught unknown - for imei " + imei);
251
                        LOGGER.error("Realme warranty check failed for imei " + imei, e);
34679 amit.gupta 252
                    }
253
                    driver.get("https://www.realme.com/in/support/phonecheck");
37423 amit 254
                installResponseCapture(driver);
34679 amit.gupta 255
                }
256
                mainCount++;
257
                remainingImeis = imeis.stream().filter(x -> !dateMap.containsKey(x)).collect(Collectors.toList());
36253 amit 258
                if (remainingImeis.isEmpty()) break;
34679 amit.gupta 259
            } while (mainCount < 5);
260
        } finally {
261
            if (driver != null) {
262
                try {
34681 amit.gupta 263
                    driver.quit();  // Always shuts everything down
32146 amit.gupta 264
                } catch (Exception e) {
37423 amit 265
                    LOGGER.warn("Error closing driver: " + e.getMessage());
32146 amit.gupta 266
                }
267
            }
34679 amit.gupta 268
        }
269
 
32146 amit.gupta 270
        return dateMap;
271
    }
30352 amit.gupta 272
 
34679 amit.gupta 273
 
37423 amit 274
    /** realme rebuilt the page; the old .sn-input / div.check-btn no longer render. */
275
    private static final String IMEI_INPUT  = ".imei-input input";
276
    private static final String SUBMIT_ICON = ".imei-input .search-icon";
30209 amit.gupta 277
 
37423 amit 278
    /**
37424 amit 279
     * Calibration nudge, in slider px, sized from the gap rather than fixed.
280
     *
281
     * A fixed 15px was far too small: it closed only ~25px, so the ratio came from a
282
     * measurement ~20% noise and the aim landed ~30px out. A fixed 60px then proved too
283
     * large in the other direction -- production data showed 85% of attempts with a gap
284
     * under 60px ended up UNUSABLE (the piece shot past the hole and the measured gap
285
     * grew), and 45% overall.
286
     *
287
     * Aim to close about half the gap: the piece travels roughly ASSUMED_RATIO px per
288
     * slider px, so nudge ~= gap / (2 * ratio), clamped. The real ratio is still derived
289
     * from the measurement; this only sizes the probe.
37423 amit 290
     */
37433 amit 291
    /*
292
     * REALME's tuning values, deliberately independent of oppo's -- do not sync the two.
293
     * Realme currently converts ~60% of completed drags against oppo's ~12% on the same
294
     * widget, so it is the one that must not be disturbed to chase oppo.
295
     *
296
     * Left at 1.7 on purpose. Realme's measured ratio over 1,683 production calibrations
297
     * is 0.70, so this is wrong here too and the probe is smaller than intended -- but it
298
     * is wrong while converting 60%, and oppo is carrying the corrected value first. If
299
     * oppo improves, bring 0.70 over here and measure it on its own.
300
     */
37424 amit 301
    private static final double ASSUMED_RATIO = 1.7;
302
    private static final int MIN_NUDGE = 10;
303
    private static final int MAX_NUDGE = 60;
37445 amit 304
    /**
305
     * Captcha attempts per imei per tick, before giving up and letting the next tick
306
     * retry with a FRESH page and session. The imei is never abandoned -- it stays
307
     * pending and returns in ~5 minutes.
308
     *
309
     * 12, NOT oppo's 7. Realme has not had the glide change, so its successes still
310
     * spread late. Measured over 399 successes and 610 exhausted imeis:
311
     *   cap  7 -> only 83.5% of successes kept (16.5% lost), 59.2% of work saved
312
     *   cap 12 -> 96.0% kept, 35.7% saved     <- here
313
     *   cap 14 -> 97.7% kept, 26.7% saved
314
     * Realme burns more than twice oppo's captcha work, so even this gentler cap saves
315
     * more in absolute terms (4,937 attempts vs oppo's 3,648).
316
     *
317
     * If glide is ever ported here, expect the curve to shift left as oppo's did
318
     * (33% -> 2% of successes from attempts 8-20) and this can come down to ~7.
319
     */
320
    private static final int MAX_CAPTCHA_ATTEMPTS = 12;
321
 
37423 amit 322
    private static final double ALIGNED_PX = 2.0;
323
 
37424 amit 324
    private static int nudgeFor(double gap) {
325
        int n = (int) Math.round(gap / (2 * ASSUMED_RATIO));
326
        return Math.max(MIN_NUDGE, Math.min(MAX_NUDGE, n));
327
    }
328
 
37423 amit 329
    /** Stash the active/check response on window as the page receives it. */
330
    private void installResponseCapture(WebDriver driver) {
331
        try {
332
            ((JavascriptExecutor) driver).executeScript(
333
                "if (!window.__rmCapInstalled) {"
37430 amit 334
              + "  window.__rmCapInstalled = true; window.__rmResp = null; window.__rmCaptcha = null; window.__rmSeen = [];"
37431 amit 335
              // Three transports, because realme's page uses all of them and only the
336
              // prototype-level patches are reliable.
337
              //
338
              // The lookup goes through Nuxt's $fetch (ofetch), which grabs its
339
              // reference to globalThis.fetch when its bundle is evaluated -- long
340
              // before driver.get() returns and we can wrap window.fetch. So wrapping
341
              // window.fetch NEVER sees /active/check: verified on the live page, the
342
              // same $fetch call is invisible to a window.fetch wrapper and visible to
343
              // a Response.prototype one. That is why 526 solved captchas produced 0
344
              // rows: the answer arrived and we could not see it.
345
              //
346
              // Response.prototype.json / .text are resolved at call time, so patching
347
              // them catches any client no matter when it took its fetch reference.
37423 amit 348
              + "  var O = XMLHttpRequest.prototype.open;"
349
              + "  XMLHttpRequest.prototype.open = function(m,u){"
350
              + "    this.addEventListener('load', function(){"
37428 amit 351
              + "      try { var s=String(u);"
37430 amit 352
              + "        if (s.indexOf('active/check') !== -1 || s.indexOf('customer-api') !== -1) window.__rmResp = this.responseText;"
37428 amit 353
              + "        else if (s.indexOf('captcha') !== -1) window.__rmCaptcha = s + ' -> ' + (this.responseText||'').slice(0,200);"
37430 amit 354
              + "        else if (window.__rmSeen.length < 12) window.__rmSeen.push(s.slice(0,80));"
37428 amit 355
              + "      } catch(e){}"
37423 amit 356
              + "    });"
357
              + "    return O.apply(this, arguments);"
358
              + "  };"
37425 amit 359
              + "  var F = window.fetch;"
360
              + "  if (F) { window.fetch = function(){"
361
              + "    var u = arguments[0]; u = (u && u.url) ? u.url : String(u);"
362
              + "    return F.apply(this, arguments).then(function(r){"
37430 amit 363
              + "      try { if (u.indexOf('active/check') !== -1 || u.indexOf('customer-api') !== -1) { r.clone().text().then(function(t){ window.__rmResp = t; }); }"
364
              + "        else if (window.__rmSeen.length < 12) window.__rmSeen.push('F ' + u.slice(0,80)); } catch(e){}"
37425 amit 365
              + "      return r;"
366
              + "    });"
367
              + "  }; }"
37431 amit 368
              // Read the body off the Response itself. Must use the ORIGINAL reader on
369
              // the clone -- calling the patched one recurses forever (it hangs the page).
370
              + "  ['json','text'].forEach(function(name){"
371
              + "    var orig = Response.prototype[name];"
372
              + "    if (!orig) return;"
373
              + "    Response.prototype[name] = function(){"
374
              + "      try { var u = this.url || '';"
375
              + "        if ((u.indexOf('active/check') !== -1 || u.indexOf('customer-api') !== -1) && !this.__rmSeenBody) {"
376
              + "          var c = this.clone(); c.__rmSeenBody = 1;"
377
              + "          orig.call(c).then(function(t){ window.__rmResp = (typeof t === 'string') ? t : JSON.stringify(t); });"
378
              + "        } else if (u && window.__rmSeen.length < 12 && u.indexOf('captcha') === -1) {"
379
              + "          window.__rmSeen.push('R ' + u.slice(0,80));"
380
              + "        } } catch(e){}"
381
              + "      return orig.apply(this, arguments);"
382
              + "    };"
383
              + "  });"
37423 amit 384
              + "}");
385
        } catch (Exception e) {
386
            LOGGER.warn("Could not install the response capture hook: " + e.getMessage());
387
        }
388
    }
389
 
37426 amit 390
    /**
391
     * Wait for the lookup response to arrive, which is the only reliable proof that
392
     * the captcha was actually solved. Polls rather than blocking so a solved captcha
393
     * is picked up as soon as the request completes.
394
     */
395
    private String awaitResponse(WebDriver driver, long timeoutMs) {
396
        long deadline = System.currentTimeMillis() + timeoutMs;
397
        while (System.currentTimeMillis() < deadline) {
398
            String json = capturedResponse(driver);
399
            if (json != null && !json.trim().isEmpty()) return json;
400
            try {
401
                Thread.sleep(300);
402
            } catch (InterruptedException ie) {
403
                Thread.currentThread().interrupt();
404
                return null;
405
            }
406
        }
407
        return null;
408
    }
409
 
37428 amit 410
    /** Last response from the captcha widget itself -- says WHY a drag was refused. */
411
    private String captchaSignal(WebDriver driver) {
412
        try {
413
            Object v = ((JavascriptExecutor) driver).executeScript("return window.__rmCaptcha || null;");
414
            return v == null ? null : v.toString();
415
        } catch (Exception e) {
416
            return null;
417
        }
418
    }
419
 
37430 amit 420
    /** Non-captcha URLs the page called -- shows what to match on when the lookup is missed. */
421
    private String seenUrls(WebDriver driver) {
422
        try {
423
            Object v = ((JavascriptExecutor) driver).executeScript(
424
                    "return (window.__rmSeen||[]).join(' | ');");
425
            return v == null ? "" : v.toString();
426
        } catch (Exception e) {
427
            return "";
428
        }
429
    }
430
 
37423 amit 431
    private String capturedResponse(WebDriver driver) {
432
        try {
433
            Object v = ((JavascriptExecutor) driver).executeScript("return window.__rmResp || null;");
434
            return v == null ? null : v.toString();
435
        } catch (Exception e) {
436
            return null;
437
        }
438
    }
439
 
440
    private void clearCapture(WebDriver driver) {
441
        try {
442
            ((JavascriptExecutor) driver).executeScript("window.__rmResp = null;");
443
        } catch (Exception ignored) {
444
        }
445
    }
446
 
447
    /**
448
     * realme returns the WARRANTY EXPIRY, not the activation date, so a year is
449
     * subtracted -- warranty is 12 months as standard. Verified against our own
450
     * records: 41,267 of 41,289 stored Realme activation dates precede the date we
451
     * checked them, averaging 13 days before, which is only consistent with the
452
     * subtraction being applied. isActivation false means the device is not
453
     * activated yet and there is no date to derive.
454
     */
455
    private LocalDate activationFrom(String json) {
456
        if (json == null) return null;
457
        try {
458
            JSONObject root = new JSONObject(json);
459
            JSONObject data = root.optJSONObject("data");
460
            if (data == null) return null;
461
            if (!data.optBoolean("isActivation", false)) return null;
462
 
463
            String expiry = data.optString("expiryDate", "");
464
            if (expiry == null || expiry.trim().isEmpty() || "null".equals(expiry)) return null;
465
 
466
            return LocalDate.parse(expiry.trim().split(" ")[0],
467
                    DateTimeFormatter.ofPattern("yyyy.MM.dd")).minusYears(1);
468
        } catch (Exception e) {
469
            LOGGER.warn("Could not read expiryDate from the realme response: " + e.getMessage());
470
            return null;
471
        }
472
    }
473
 
474
    /** @return {sliderPxToMove, sliderPxPerCirclePx}, or null if the circles were unreadable. */
475
    private double[] calibrate(WebDriver driver, Actions actionProvider, double distance) throws Exception {
37424 amit 476
        int nudge = nudgeFor(distance);
477
        actionProvider.moveByOffset(nudge, 0).perform();
37423 amit 478
 
32146 amit.gupta 479
        String fileName2 = "/tmp/" + Thread.currentThread().getName() + "-moved.png";
34413 amit.gupta 480
        double[] movedCircles = getMatCircles2(driver, fileName2);
37423 amit 481
        if (movedCircles == null) return null;
482
 
483
        double movedDistance = Math.abs(movedCircles[0] - movedCircles[1]);
484
        double closed = distance - movedDistance;
485
        LOGGER.info("Calibration: gap {} -> {} after {}px, closed {}",
37424 amit 486
                distance, movedDistance, nudge, closed);
37423 amit 487
        if (closed <= 0) return null;
488
 
37424 amit 489
        double sliderPerCircle = nudge / closed;
37423 amit 490
        return new double[]{Math.round(movedDistance * sliderPerCircle), sliderPerCircle};
32146 amit.gupta 491
    }
30209 amit.gupta 492
 
37423 amit 493
    /** Measure again after the main move and close the remainder before releasing. */
494
    private int refine(WebDriver driver, Actions actionProvider, double sliderPerCircle) throws Exception {
495
        String fileName = "/tmp/" + Thread.currentThread().getName() + "-refine.png";
496
        double[] circles = getMatCircles2(driver, fileName);
497
        if (circles == null) return 0;
498
 
499
        double remaining = Math.abs(circles[0] - circles[1]);
500
        if (remaining <= ALIGNED_PX) return 0;
501
 
502
        int correction = (int) Math.round(remaining * sliderPerCircle);
503
        if (correction == 0) return 0;
504
        LOGGER.info("Refine: {}px of gap left -> nudging {}px", remaining, correction);
505
        actionProvider.moveByOffset(correction, 0).perform();
506
        return correction;
507
    }
508
 
32146 amit.gupta 509
    private Mat getMatCircles(WebDriver driver, String fileName) throws Exception {
30209 amit.gupta 510
 
32146 amit.gupta 511
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
512
        BufferedImage fullImg = ImageIO.read(screenshot);
30209 amit.gupta 513
 
32146 amit.gupta 514
        // Get the location of element on the page
515
        WebElement imageElement = driver.findElement(By.id("dx_captcha_basic_bg_1"));
516
        Point point = imageElement.getLocation();
30209 amit.gupta 517
 
32146 amit.gupta 518
        // Get width and height of the element
519
        int eleWidth = imageElement.getSize().getWidth();
520
        int eleHeight = imageElement.getSize().getHeight();
30209 amit.gupta 521
 
32146 amit.gupta 522
        // Crop the entire page screenshot to get only element screenshot
523
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
524
                eleWidth, eleHeight);
525
        ImageIO.write(eleScreenshot, "png", screenshot);
30209 amit.gupta 526
 
32146 amit.gupta 527
        // Copy the element screenshot to disk
528
        File screenshotLocation = new File(fileName);
529
        FileUtils.copyFile(screenshot, screenshotLocation);
30209 amit.gupta 530
 
32146 amit.gupta 531
        Imgcodecs imageCodecs = new Imgcodecs();
532
        Mat grayMatrix = imageCodecs.imread(fileName, Imgcodecs.IMREAD_COLOR);
533
        Imgproc.cvtColor(grayMatrix, grayMatrix, Imgproc.COLOR_BGR2GRAY);
534
        Mat medianBlur = new Mat();
535
        Imgproc.medianBlur(grayMatrix, medianBlur, 5);
536
        Mat circles = new Mat();
537
        Imgproc.HoughCircles(medianBlur, circles, Imgproc.HOUGH_GRADIENT, 1, 15, 50, 20, 17, 25);
538
        return circles;
539
    }
30209 amit.gupta 540
 
34413 amit.gupta 541
    private double[] getMatCircles2(WebDriver driver, String fileName) throws Exception {
542
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
543
        BufferedImage fullImg = ImageIO.read(screenshot);
544
 
545
        // Get the location of element on the page
36583 amit 546
        WebElement imageElement = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]"));
34413 amit.gupta 547
        Point point = imageElement.getLocation();
548
 
549
        // Get width and height of the element
550
        int eleWidth = imageElement.getSize().getWidth();
551
        int eleHeight = imageElement.getSize().getHeight();
552
 
553
        // Crop the entire page screenshot to get only element screenshot
554
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
555
                eleWidth, eleHeight);
556
        ImageIO.write(eleScreenshot, "png", screenshot);
557
 
558
        // Copy the element screenshot to disk
559
        File screenshotLocation = new File(fileName);
560
        FileUtils.copyFile(screenshot, screenshotLocation);
561
 
562
        Mat src = Imgcodecs.imread(fileName);
563
        if (src.empty()) {
36583 amit 564
            LOGGER.warn("Cannot read image: {}", fileName);
36253 amit 565
            new File(fileName).delete();
34413 amit.gupta 566
            return null;
567
        }
568
 
569
        Mat gray = new Mat();
570
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
571
        Imgproc.GaussianBlur(gray, gray, new Size(9, 9), 2, 2);
572
 
573
        Mat circles = new Mat();
574
        Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,
575
                20, // min distance between centers
576
                100, 20, // param1 (Canny high threshold), param2 (accumulator threshold)
577
                10, 50); // minRadius, maxRadius (adjust as needed)
578
 
36253 amit 579
        if (circles.cols() < 2) {
580
            new File(fileName).delete();
581
            return null;
582
        }
34413 amit.gupta 583
 
584
        for (int i = 0; i < circles.cols(); i++) {
585
            double[] c1 = circles.get(0, i);
586
            for (int j = i + 1; j < circles.cols(); j++) {
587
                double[] c2 = circles.get(0, j);
588
                if (Math.abs(c1[2] - c2[2]) < 3) { // check similar radius
36253 amit 589
                    new File(fileName).delete();
34413 amit.gupta 590
                    return new double[] {
591
                            c1[0], c2[0] // x-coordinates
592
                    };
593
                }
594
            }
595
        }
596
 
36253 amit 597
        new File(fileName).delete();
34413 amit.gupta 598
        return null;
599
    }
600
 
601
 
30209 amit.gupta 602
}