Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

package com.smartdukaan.cron.scheduled;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Website-based activation-date pull for Motorola, mirroring
 * CheckOppoWarrantyTask / CheckRealmeWarrantyTask.
 *
 * Differs from those two in one important way: there is no slider. The page
 * (https://en-in.support.motorola.com/app/warranty/check) is Oracle Service
 * Cloud, so there is no DingXiang widget, no canvas, and OpenCV is not needed
 * at all. The lookup is a single AJAX call and the whole job is to read its
 * JSON -- the same "read the JSON, not the DOM" lesson that realme taught.
 *
 * What gates it instead is reCAPTCHA v2, raised by the endpoint itself as an
 * "==CHALLENGE REQUIRED==" body. See MotorolaChallengeSolver.
 */
@Component
public class CheckMotorolaWarrantyTask {

    private static final Logger LOGGER = LogManager.getLogger(CheckMotorolaWarrantyTask.class);

    private static final String PAGE_URL = "https://en-in.support.motorola.com/app/warranty/check";

    /** Field and submit, confirmed against the live page. The submit is a
     *  type=button; the only type=submit on the page is a FOOTER control. */
    private static final String IMEI_INPUT = "#rn_warrantylookup_3_serial";
    private static final String SUBMIT_BTN = ".my-products__detect-device-button";

    /** RightNow routes the lookup through this widget endpoint. */
    private static final String LOOKUP_ENDPOINT = "/ci/ajax/widget/custom/warranty/warrantylookup";

    private static final String CHALLENGE_MARKER = "==CHALLENGE REQUIRED==";

    /** Optional: no bean supplied means challenges cannot be answered. */
    @Autowired(required = false)
    private MotorolaChallengeSolver challengeSolver;

    /** Logged once per batch so a first successful payload reveals its shape
     *  without spamming the log for every imei. */
    private boolean loggedSamplePayload = false;

    public Map<String, LocalDate> checkWarranty(List<String> imeis) {
        Map<String, LocalDate> dateMap = new HashMap<>();
        if (imeis == null || imeis.isEmpty()) {
            return dateMap;
        }
        loggedSamplePayload = false;

        ChromeOptions options = new ChromeOptions();
        Map<String, Object> prefsMap = new HashMap<>();
        prefsMap.put("profile.default_content_settings.popups", 0);
        prefsMap.put("download.prompt", false);
        options.setExperimentalOption("prefs", prefsMap);
        // Prod path, same as the oppo/realme drivers. Left overridable so the job
        // can be exercised on a dev box against Chrome for Testing without
        // editing the file:
        //   -Dwebdriver.chrome.driver=/Users/<u>/cft/chromedriver/chromedriver
        //   -Dwebdriver.chrome.binary="/Users/<u>/cft/chrome/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
        if (System.getProperty("webdriver.chrome.driver") == null) {
            System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
        }
        String binary = System.getProperty("webdriver.chrome.binary");
        if (binary != null && !binary.isEmpty()) {
            options.setBinary(binary);
        }
        options.addArguments("--headless");
        options.addArguments("--no-sandbox");
        options.addArguments("--disable-extensions");
        options.addArguments("--test-type");
        // Same memory posture as the oppo/realme drivers: this box co-hosts a
        // 9.4GB tomcat with ~3GB available and has been OOM-killed twice, with
        // tomcat the victim both times. Each driver tree is roughly 850MB, so
        // do not let this job overlap the oppo/realme window.
        options.addArguments("--disable-gpu");
        options.addArguments("--disable-dev-shm-usage");
        options.addArguments("--disable-software-rasterizer");

        WebDriver driver = null;
        try {
            driver = new ChromeDriver(options);
            driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
            driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
            driver.manage().window().setSize(new Dimension(1600, 900));
            driver.manage().deleteAllCookies();

            WebDriverWait wait = new WebDriverWait(driver, 12);

            driver.get(PAGE_URL);
            installResponseCapture(driver);
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(IMEI_INPUT)));

            for (Iterator<String> it = imeis.iterator(); it.hasNext(); ) {
                String imei = it.next();
                try {
                    LocalDate date = lookupOne(driver, wait, imei);
                    // A null date is still a result: the caller writes it back
                    // as a null activation, which bumps createTimestamp and so
                    // defers this imei to the next pool sweep.
                    dateMap.put(imei, date);
                } catch (ChallengeUnansweredException ce) {
                    // Abandon the whole batch. Every subsequent lookup in this
                    // session would hit the same wall, and continuing would be
                    // pure load on Motorola for no data.
                    LOGGER.warn("Motorola raised a reCAPTCHA challenge and no solver is configured "
                            + "- abandoning the batch after {} of {} imeis", dateMap.size(), imeis.size());
                    break;
                } catch (Exception e) {
                    LOGGER.warn("Motorola lookup failed for {} - {}", imei, e.getMessage());
                }
            }
        } catch (Exception e) {
            LOGGER.error("Motorola warranty run failed", e);
        } finally {
            if (driver != null) {
                try {
                    driver.quit();
                } catch (Exception ignored) {
                }
            }
        }
        LOGGER.info("Motorola: resolved {} of {} imeis", dateMap.size(), imeis.size());
        return dateMap;
    }

    /** One imei: clear, type, submit, wait for the widget's JSON. */
    private LocalDate lookupOne(WebDriver driver, WebDriverWait wait, String imei) throws Exception {
        clearCapture(driver);

        // Re-navigating per imei is what oppo/realme do, and it is what keeps a
        // stale previous result from being read as this imei's answer.
        driver.get(PAGE_URL);
        installResponseCapture(driver);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(IMEI_INPUT)));

        // The field is React-backed: a plain sendKeys can be discarded on
        // re-render, so drive the native setter and fire the events the widget
        // actually listens for.
        ((JavascriptExecutor) driver).executeScript(
                "var f = document.querySelector(arguments[0]);"
              + "var s = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,'value').set;"
              + "s.call(f, arguments[1]);"
              + "f.dispatchEvent(new Event('input',{bubbles:true}));"
              + "f.dispatchEvent(new Event('change',{bubbles:true}));",
                IMEI_INPUT, imei);

        driver.findElement(By.cssSelector(SUBMIT_BTN)).click();

        String body = awaitResponse(driver, 15000);
        if (body == null) {
            LOGGER.info("Motorola: no lookup response captured for {}", imei);
            return null;
        }

        if (body.contains(CHALLENGE_MARKER)) {
            String siteKey = extractSiteKey(body);
            if (challengeSolver == null) {
                throw new ChallengeUnansweredException(siteKey);
            }
            String token = challengeSolver.solve(siteKey, PAGE_URL);
            if (token == null || token.isEmpty()) {
                throw new ChallengeUnansweredException(siteKey);
            }
            body = submitWithToken(driver, wait, token);
            if (body == null || body.contains(CHALLENGE_MARKER)) {
                LOGGER.warn("Motorola rejected the supplied challenge token for {}", imei);
                return null;
            }
        }

        if (!loggedSamplePayload) {
            // The success payload shape is unverified -- every observed response
            // so far has been the challenge, so no real warranty body has been
            // seen. Log the first one in full so the parser can be tightened to
            // the actual field names instead of guessing.
            LOGGER.info("Motorola sample lookup payload for {}: {}", imei,
                    body.substring(0, Math.min(body.length(), 1500)));
            loggedSamplePayload = true;
        }
        return parseActivationDate(body);
    }

    /** Replays the lookup with a challenge token attached. */
    private String submitWithToken(WebDriver driver, WebDriverWait wait, String token) {
        try {
            clearCapture(driver);
            ((JavascriptExecutor) driver).executeScript(
                    "var el = document.getElementById('g-recaptcha-response');"
                  + "if (!el) { el = document.createElement('textarea');"
                  + "  el.id = 'g-recaptcha-response'; el.name = 'g-recaptcha-response';"
                  + "  el.style.display='none'; document.body.appendChild(el); }"
                  + "el.value = arguments[0];", token);
            driver.findElement(By.cssSelector(SUBMIT_BTN)).click();
            return awaitResponse(driver, 15000);
        } catch (Exception e) {
            LOGGER.warn("Challenge replay failed - {}", e.getMessage());
            return null;
        }
    }

    /** reCAPTCHA sitekey out of the challenge blob, for the solver. */
    private String extractSiteKey(String body) {
        try {
            int i = body.indexOf("publicKey:");
            if (i < 0) return null;
            int q1 = body.indexOf('"', i);
            int q2 = body.indexOf('"', q1 + 1);
            if (q1 < 0 || q2 < 0) return null;
            return body.substring(q1 + 1, q2).replace("\\", "");
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Pulls an activation/warranty-start date out of the payload.
     *
     * Deliberately tolerant about field names and formats: the real response
     * has never been observed past the challenge, so this tries the keys such
     * payloads normally carry and falls back to logging rather than guessing
     * wrong. Tighten it once the sample payload above appears in the log.
     */
    LocalDate parseActivationDate(String json) {
        if (json == null || json.trim().isEmpty()) return null;
        String[] keys = {"activationDate", "warrantyStartDate", "startDate",
                         "purchaseDate", "regDate", "inWarrantyStartDate", "shipDate"};
        try {
            JSONObject root = new JSONObject(json);
            JSONObject scope = root.optJSONObject("data") != null ? root.optJSONObject("data") : root;
            for (String key : keys) {
                if (!scope.has(key) || scope.isNull(key)) continue;
                LocalDate d = toLocalDate(scope.get(key).toString());
                if (d != null) return d;
            }
        } catch (Exception e) {
            LOGGER.debug("Motorola payload was not the JSON shape expected - {}", e.getMessage());
        }
        return null;
    }

    /** Epoch millis, or the date formats these portals typically emit. */
    private LocalDate toLocalDate(String raw) {
        if (raw == null) return null;
        String v = raw.trim();
        if (v.isEmpty() || "null".equalsIgnoreCase(v)) return null;
        try {
            if (v.matches("\\d{10,13}")) {
                long epoch = Long.parseLong(v);
                if (v.length() == 10) epoch *= 1000L;
                return Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()).toLocalDate();
            }
        } catch (Exception ignored) {
        }
        String[] patterns = {"yyyy-MM-dd", "dd-MM-yyyy", "MM/dd/yyyy", "dd/MM/yyyy", "yyyy/MM/dd"};
        for (String p : patterns) {
            try {
                return LocalDate.parse(v.length() > 10 ? v.substring(0, 10) : v,
                        DateTimeFormatter.ofPattern(p));
            } catch (Exception ignored) {
            }
        }
        return null;
    }

    /**
     * Captures the widget's AJAX body.
     *
     * Hooks XHR, fetch AND Response.prototype. The last one matters: a client
     * that grabbed globalThis.fetch when its bundle loaded sails straight past
     * a window.fetch wrapper, which is exactly what hid realme's lookup.
     */
    private void installResponseCapture(WebDriver driver) {
        try {
            ((JavascriptExecutor) driver).executeScript(
                "if (!window.__motoCapInstalled) {"
              + "  window.__motoCapInstalled = true; window.__motoResp = null;"
              + "  var hit = function(u){ return String(u).indexOf('" + LOOKUP_ENDPOINT + "') !== -1; };"
              + "  var O = XMLHttpRequest.prototype.open;"
              + "  XMLHttpRequest.prototype.open = function(m,u){"
              + "    var self=this;"
              + "    this.addEventListener('load', function(){"
              + "      try { if (hit(u)) window.__motoResp = self.responseText; } catch(e){}"
              + "    });"
              + "    return O.apply(this, arguments);"
              + "  };"
              + "  var F = window.fetch;"
              + "  if (F) { window.fetch = function(){"
              + "    var u = arguments[0]; u = (u && u.url) ? u.url : String(u);"
              + "    return F.apply(this, arguments).then(function(r){"
              + "      try { if (hit(u)) r.clone().text().then(function(t){ window.__motoResp = t; }); } catch(e){}"
              + "      return r;"
              + "    });"
              + "  }; }"
              + "  ['json','text'].forEach(function(name){"
              + "    var orig = Response.prototype[name];"
              + "    if (!orig) return;"
              + "    Response.prototype[name] = function(){"
              + "      try { var u = this.url || '';"
              + "        if (hit(u) && !this.__motoSeen) {"
              + "          var c = this.clone(); this.__motoSeen = 1;"
              + "          orig.call(c).then(function(t){"
              + "            window.__motoResp = (typeof t === 'string') ? t : JSON.stringify(t); });"
              + "        } } catch(e){}"
              + "      return orig.apply(this, arguments);"
              + "    };"
              + "  });"
              + "}");
        } catch (Exception e) {
            LOGGER.warn("Could not install the Motorola response capture hook: {}", e.getMessage());
        }
    }

    /** Poll rather than read once: the click can return before the AJAX lands. */
    private String awaitResponse(WebDriver driver, long timeoutMs) {
        long deadline = System.currentTimeMillis() + timeoutMs;
        while (System.currentTimeMillis() < deadline) {
            try {
                Object v = ((JavascriptExecutor) driver).executeScript("return window.__motoResp || null;");
                if (v != null && !v.toString().trim().isEmpty()) {
                    return v.toString();
                }
            } catch (Exception ignored) {
            }
            try {
                Thread.sleep(300);
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                return null;
            }
        }
        return null;
    }

    private void clearCapture(WebDriver driver) {
        try {
            ((JavascriptExecutor) driver).executeScript("window.__motoResp = null;");
        } catch (Exception ignored) {
        }
    }

    /** Raised when the page challenges and nothing can answer it. */
    static class ChallengeUnansweredException extends Exception {
        ChallengeUnansweredException(String siteKey) {
            super("reCAPTCHA challenge raised (sitekey=" + siteKey + ") and no solver is configured");
        }
    }
}