Subversion Repositories SmartDukaan

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
37459 amit 1
package com.smartdukaan.cron.scheduled;
2
 
3
import org.apache.logging.log4j.LogManager;
4
import org.apache.logging.log4j.Logger;
5
import org.json.JSONObject;
6
import org.openqa.selenium.By;
7
import org.openqa.selenium.Dimension;
8
import org.openqa.selenium.JavascriptExecutor;
9
import org.openqa.selenium.WebDriver;
10
import org.openqa.selenium.chrome.ChromeDriver;
11
import org.openqa.selenium.chrome.ChromeOptions;
12
import org.openqa.selenium.support.ui.ExpectedConditions;
13
import org.openqa.selenium.support.ui.WebDriverWait;
14
import org.springframework.beans.factory.annotation.Autowired;
15
import org.springframework.stereotype.Component;
16
 
17
import java.time.Instant;
18
import java.time.LocalDate;
19
import java.time.ZoneId;
20
import java.time.format.DateTimeFormatter;
21
import java.util.HashMap;
22
import java.util.Iterator;
23
import java.util.List;
24
import java.util.Map;
25
import java.util.concurrent.TimeUnit;
26
 
27
/**
28
 * Website-based activation-date pull for Motorola, mirroring
29
 * CheckOppoWarrantyTask / CheckRealmeWarrantyTask.
30
 *
31
 * Differs from those two in one important way: there is no slider. The page
32
 * (https://en-in.support.motorola.com/app/warranty/check) is Oracle Service
33
 * Cloud, so there is no DingXiang widget, no canvas, and OpenCV is not needed
34
 * at all. The lookup is a single AJAX call and the whole job is to read its
35
 * JSON -- the same "read the JSON, not the DOM" lesson that realme taught.
36
 *
37
 * What gates it instead is reCAPTCHA v2, raised by the endpoint itself as an
38
 * "==CHALLENGE REQUIRED==" body. See MotorolaChallengeSolver.
39
 */
40
@Component
41
public class CheckMotorolaWarrantyTask {
42
 
43
    private static final Logger LOGGER = LogManager.getLogger(CheckMotorolaWarrantyTask.class);
44
 
45
    private static final String PAGE_URL = "https://en-in.support.motorola.com/app/warranty/check";
46
 
47
    /** Field and submit, confirmed against the live page. The submit is a
48
     *  type=button; the only type=submit on the page is a FOOTER control. */
49
    private static final String IMEI_INPUT = "#rn_warrantylookup_3_serial";
50
    private static final String SUBMIT_BTN = ".my-products__detect-device-button";
51
 
52
    /** RightNow routes the lookup through this widget endpoint. */
53
    private static final String LOOKUP_ENDPOINT = "/ci/ajax/widget/custom/warranty/warrantylookup";
54
 
55
    private static final String CHALLENGE_MARKER = "==CHALLENGE REQUIRED==";
56
 
57
    /** Optional: no bean supplied means challenges cannot be answered. */
58
    @Autowired(required = false)
59
    private MotorolaChallengeSolver challengeSolver;
60
 
61
    /** Logged once per batch so a first successful payload reveals its shape
62
     *  without spamming the log for every imei. */
63
    private boolean loggedSamplePayload = false;
64
 
65
    public Map<String, LocalDate> checkWarranty(List<String> imeis) {
66
        Map<String, LocalDate> dateMap = new HashMap<>();
67
        if (imeis == null || imeis.isEmpty()) {
68
            return dateMap;
69
        }
70
        loggedSamplePayload = false;
71
 
72
        ChromeOptions options = new ChromeOptions();
73
        Map<String, Object> prefsMap = new HashMap<>();
74
        prefsMap.put("profile.default_content_settings.popups", 0);
75
        prefsMap.put("download.prompt", false);
76
        options.setExperimentalOption("prefs", prefsMap);
77
        // Prod path, same as the oppo/realme drivers. Left overridable so the job
78
        // can be exercised on a dev box against Chrome for Testing without
79
        // editing the file:
80
        //   -Dwebdriver.chrome.driver=/Users/<u>/cft/chromedriver/chromedriver
81
        //   -Dwebdriver.chrome.binary="/Users/<u>/cft/chrome/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
82
        if (System.getProperty("webdriver.chrome.driver") == null) {
83
            System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
84
        }
85
        String binary = System.getProperty("webdriver.chrome.binary");
86
        if (binary != null && !binary.isEmpty()) {
87
            options.setBinary(binary);
88
        }
89
        options.addArguments("--headless");
90
        options.addArguments("--no-sandbox");
91
        options.addArguments("--disable-extensions");
92
        options.addArguments("--test-type");
93
        // Same memory posture as the oppo/realme drivers: this box co-hosts a
94
        // 9.4GB tomcat with ~3GB available and has been OOM-killed twice, with
95
        // tomcat the victim both times. Each driver tree is roughly 850MB, so
96
        // do not let this job overlap the oppo/realme window.
97
        options.addArguments("--disable-gpu");
98
        options.addArguments("--disable-dev-shm-usage");
99
        options.addArguments("--disable-software-rasterizer");
100
 
101
        WebDriver driver = null;
102
        try {
103
            driver = new ChromeDriver(options);
104
            driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
105
            driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
106
            driver.manage().window().setSize(new Dimension(1600, 900));
107
            driver.manage().deleteAllCookies();
108
 
109
            WebDriverWait wait = new WebDriverWait(driver, 12);
110
 
111
            driver.get(PAGE_URL);
112
            installResponseCapture(driver);
113
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(IMEI_INPUT)));
114
 
115
            for (Iterator<String> it = imeis.iterator(); it.hasNext(); ) {
116
                String imei = it.next();
117
                try {
118
                    LocalDate date = lookupOne(driver, wait, imei);
119
                    // A null date is still a result: the caller writes it back
120
                    // as a null activation, which bumps createTimestamp and so
121
                    // defers this imei to the next pool sweep.
122
                    dateMap.put(imei, date);
123
                } catch (ChallengeUnansweredException ce) {
124
                    // Abandon the whole batch. Every subsequent lookup in this
125
                    // session would hit the same wall, and continuing would be
126
                    // pure load on Motorola for no data.
127
                    LOGGER.warn("Motorola raised a reCAPTCHA challenge and no solver is configured "
128
                            + "- abandoning the batch after {} of {} imeis", dateMap.size(), imeis.size());
129
                    break;
130
                } catch (Exception e) {
131
                    LOGGER.warn("Motorola lookup failed for {} - {}", imei, e.getMessage());
132
                }
133
            }
134
        } catch (Exception e) {
135
            LOGGER.error("Motorola warranty run failed", e);
136
        } finally {
137
            if (driver != null) {
138
                try {
139
                    driver.quit();
140
                } catch (Exception ignored) {
141
                }
142
            }
143
        }
144
        LOGGER.info("Motorola: resolved {} of {} imeis", dateMap.size(), imeis.size());
145
        return dateMap;
146
    }
147
 
148
    /** One imei: clear, type, submit, wait for the widget's JSON. */
149
    private LocalDate lookupOne(WebDriver driver, WebDriverWait wait, String imei) throws Exception {
150
        clearCapture(driver);
151
 
152
        // Re-navigating per imei is what oppo/realme do, and it is what keeps a
153
        // stale previous result from being read as this imei's answer.
154
        driver.get(PAGE_URL);
155
        installResponseCapture(driver);
156
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(IMEI_INPUT)));
157
 
158
        // The field is React-backed: a plain sendKeys can be discarded on
159
        // re-render, so drive the native setter and fire the events the widget
160
        // actually listens for.
161
        ((JavascriptExecutor) driver).executeScript(
162
                "var f = document.querySelector(arguments[0]);"
163
              + "var s = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,'value').set;"
164
              + "s.call(f, arguments[1]);"
165
              + "f.dispatchEvent(new Event('input',{bubbles:true}));"
166
              + "f.dispatchEvent(new Event('change',{bubbles:true}));",
167
                IMEI_INPUT, imei);
168
 
169
        driver.findElement(By.cssSelector(SUBMIT_BTN)).click();
170
 
171
        String body = awaitResponse(driver, 15000);
172
        if (body == null) {
173
            LOGGER.info("Motorola: no lookup response captured for {}", imei);
174
            return null;
175
        }
176
 
177
        if (body.contains(CHALLENGE_MARKER)) {
178
            String siteKey = extractSiteKey(body);
179
            if (challengeSolver == null) {
180
                throw new ChallengeUnansweredException(siteKey);
181
            }
182
            String token = challengeSolver.solve(siteKey, PAGE_URL);
183
            if (token == null || token.isEmpty()) {
184
                throw new ChallengeUnansweredException(siteKey);
185
            }
186
            body = submitWithToken(driver, wait, token);
187
            if (body == null || body.contains(CHALLENGE_MARKER)) {
188
                LOGGER.warn("Motorola rejected the supplied challenge token for {}", imei);
189
                return null;
190
            }
191
        }
192
 
193
        if (!loggedSamplePayload) {
194
            // The success payload shape is unverified -- every observed response
195
            // so far has been the challenge, so no real warranty body has been
196
            // seen. Log the first one in full so the parser can be tightened to
197
            // the actual field names instead of guessing.
198
            LOGGER.info("Motorola sample lookup payload for {}: {}", imei,
199
                    body.substring(0, Math.min(body.length(), 1500)));
200
            loggedSamplePayload = true;
201
        }
202
        return parseActivationDate(body);
203
    }
204
 
205
    /** Replays the lookup with a challenge token attached. */
206
    private String submitWithToken(WebDriver driver, WebDriverWait wait, String token) {
207
        try {
208
            clearCapture(driver);
209
            ((JavascriptExecutor) driver).executeScript(
210
                    "var el = document.getElementById('g-recaptcha-response');"
211
                  + "if (!el) { el = document.createElement('textarea');"
212
                  + "  el.id = 'g-recaptcha-response'; el.name = 'g-recaptcha-response';"
213
                  + "  el.style.display='none'; document.body.appendChild(el); }"
214
                  + "el.value = arguments[0];", token);
215
            driver.findElement(By.cssSelector(SUBMIT_BTN)).click();
216
            return awaitResponse(driver, 15000);
217
        } catch (Exception e) {
218
            LOGGER.warn("Challenge replay failed - {}", e.getMessage());
219
            return null;
220
        }
221
    }
222
 
223
    /** reCAPTCHA sitekey out of the challenge blob, for the solver. */
224
    private String extractSiteKey(String body) {
225
        try {
226
            int i = body.indexOf("publicKey:");
227
            if (i < 0) return null;
228
            int q1 = body.indexOf('"', i);
229
            int q2 = body.indexOf('"', q1 + 1);
230
            if (q1 < 0 || q2 < 0) return null;
231
            return body.substring(q1 + 1, q2).replace("\\", "");
232
        } catch (Exception e) {
233
            return null;
234
        }
235
    }
236
 
237
    /**
238
     * Pulls an activation/warranty-start date out of the payload.
239
     *
240
     * Deliberately tolerant about field names and formats: the real response
241
     * has never been observed past the challenge, so this tries the keys such
242
     * payloads normally carry and falls back to logging rather than guessing
243
     * wrong. Tighten it once the sample payload above appears in the log.
244
     */
245
    LocalDate parseActivationDate(String json) {
246
        if (json == null || json.trim().isEmpty()) return null;
247
        String[] keys = {"activationDate", "warrantyStartDate", "startDate",
248
                         "purchaseDate", "regDate", "inWarrantyStartDate", "shipDate"};
249
        try {
250
            JSONObject root = new JSONObject(json);
251
            JSONObject scope = root.optJSONObject("data") != null ? root.optJSONObject("data") : root;
252
            for (String key : keys) {
253
                if (!scope.has(key) || scope.isNull(key)) continue;
254
                LocalDate d = toLocalDate(scope.get(key).toString());
255
                if (d != null) return d;
256
            }
257
        } catch (Exception e) {
258
            LOGGER.debug("Motorola payload was not the JSON shape expected - {}", e.getMessage());
259
        }
260
        return null;
261
    }
262
 
263
    /** Epoch millis, or the date formats these portals typically emit. */
264
    private LocalDate toLocalDate(String raw) {
265
        if (raw == null) return null;
266
        String v = raw.trim();
267
        if (v.isEmpty() || "null".equalsIgnoreCase(v)) return null;
268
        try {
269
            if (v.matches("\\d{10,13}")) {
270
                long epoch = Long.parseLong(v);
271
                if (v.length() == 10) epoch *= 1000L;
272
                return Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()).toLocalDate();
273
            }
274
        } catch (Exception ignored) {
275
        }
276
        String[] patterns = {"yyyy-MM-dd", "dd-MM-yyyy", "MM/dd/yyyy", "dd/MM/yyyy", "yyyy/MM/dd"};
277
        for (String p : patterns) {
278
            try {
279
                return LocalDate.parse(v.length() > 10 ? v.substring(0, 10) : v,
280
                        DateTimeFormatter.ofPattern(p));
281
            } catch (Exception ignored) {
282
            }
283
        }
284
        return null;
285
    }
286
 
287
    /**
288
     * Captures the widget's AJAX body.
289
     *
290
     * Hooks XHR, fetch AND Response.prototype. The last one matters: a client
291
     * that grabbed globalThis.fetch when its bundle loaded sails straight past
292
     * a window.fetch wrapper, which is exactly what hid realme's lookup.
293
     */
294
    private void installResponseCapture(WebDriver driver) {
295
        try {
296
            ((JavascriptExecutor) driver).executeScript(
297
                "if (!window.__motoCapInstalled) {"
298
              + "  window.__motoCapInstalled = true; window.__motoResp = null;"
299
              + "  var hit = function(u){ return String(u).indexOf('" + LOOKUP_ENDPOINT + "') !== -1; };"
300
              + "  var O = XMLHttpRequest.prototype.open;"
301
              + "  XMLHttpRequest.prototype.open = function(m,u){"
302
              + "    var self=this;"
303
              + "    this.addEventListener('load', function(){"
304
              + "      try { if (hit(u)) window.__motoResp = self.responseText; } catch(e){}"
305
              + "    });"
306
              + "    return O.apply(this, arguments);"
307
              + "  };"
308
              + "  var F = window.fetch;"
309
              + "  if (F) { window.fetch = function(){"
310
              + "    var u = arguments[0]; u = (u && u.url) ? u.url : String(u);"
311
              + "    return F.apply(this, arguments).then(function(r){"
312
              + "      try { if (hit(u)) r.clone().text().then(function(t){ window.__motoResp = t; }); } catch(e){}"
313
              + "      return r;"
314
              + "    });"
315
              + "  }; }"
316
              + "  ['json','text'].forEach(function(name){"
317
              + "    var orig = Response.prototype[name];"
318
              + "    if (!orig) return;"
319
              + "    Response.prototype[name] = function(){"
320
              + "      try { var u = this.url || '';"
321
              + "        if (hit(u) && !this.__motoSeen) {"
322
              + "          var c = this.clone(); this.__motoSeen = 1;"
323
              + "          orig.call(c).then(function(t){"
324
              + "            window.__motoResp = (typeof t === 'string') ? t : JSON.stringify(t); });"
325
              + "        } } catch(e){}"
326
              + "      return orig.apply(this, arguments);"
327
              + "    };"
328
              + "  });"
329
              + "}");
330
        } catch (Exception e) {
331
            LOGGER.warn("Could not install the Motorola response capture hook: {}", e.getMessage());
332
        }
333
    }
334
 
335
    /** Poll rather than read once: the click can return before the AJAX lands. */
336
    private String awaitResponse(WebDriver driver, long timeoutMs) {
337
        long deadline = System.currentTimeMillis() + timeoutMs;
338
        while (System.currentTimeMillis() < deadline) {
339
            try {
340
                Object v = ((JavascriptExecutor) driver).executeScript("return window.__motoResp || null;");
341
                if (v != null && !v.toString().trim().isEmpty()) {
342
                    return v.toString();
343
                }
344
            } catch (Exception ignored) {
345
            }
346
            try {
347
                Thread.sleep(300);
348
            } catch (InterruptedException ie) {
349
                Thread.currentThread().interrupt();
350
                return null;
351
            }
352
        }
353
        return null;
354
    }
355
 
356
    private void clearCapture(WebDriver driver) {
357
        try {
358
            ((JavascriptExecutor) driver).executeScript("window.__motoResp = null;");
359
        } catch (Exception ignored) {
360
        }
361
    }
362
 
363
    /** Raised when the page challenges and nothing can answer it. */
364
    static class ChallengeUnansweredException extends Exception {
365
        ChallengeUnansweredException(String siteKey) {
366
            super("reCAPTCHA challenge raised (sitekey=" + siteKey + ") and no solver is configured");
367
        }
368
    }
369
}