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