Subversion Repositories SmartDukaan

Rev

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

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