Subversion Repositories SmartDukaan

Rev

Rev 37410 | Rev 37422 | 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;
37420 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;
37420 amit 25
import java.time.Instant;
26
import java.time.ZoneId;
30209 amit.gupta 27
import java.util.HashMap;
28
import java.util.List;
29
import java.util.Map;
30
import java.util.concurrent.TimeUnit;
31
import java.util.stream.Collectors;
32
 
30373 amit.gupta 33
@Component
34
public class CheckOppoWarrantyTask {
30209 amit.gupta 35
 
32146 amit.gupta 36
    private static final Logger LOGGER = LogManager.getLogger(CheckOppoWarrantyTask.class);
30209 amit.gupta 37
 
36253 amit 38
    static {
36306 amit 39
        try {
40
            OpenCV.loadShared();
41
        } catch (Throwable t) {
42
            LogManager.getLogger(CheckOppoWarrantyTask.class).warn("OpenCV not available on this platform: {}", t.getMessage());
43
        }
36253 amit 44
    }
45
 
32146 amit.gupta 46
    public Map<String, LocalDate> checkWarranty(List<String> imeis) {
47
        Map<String, LocalDate> dateMap = new HashMap<>();
48
        LOGGER.info("Initiating webdriver...");
30209 amit.gupta 49
 
32146 amit.gupta 50
        Map<String, Object> prefsMap = new HashMap<>();
51
        prefsMap.put("profile.default_content_settings.popups", 0);
52
        prefsMap.put("download.prompt", false);
53
        prefsMap.put("download.directory_upgrade", true);
34413 amit.gupta 54
        System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
32146 amit.gupta 55
        //I need this
34413 amit.gupta 56
        //System.setProperty("webdriver.chrome.driver", "/Users/amit/cft/chromedriver/chromedriver");
32146 amit.gupta 57
        ChromeOptions options = new ChromeOptions();
34413 amit.gupta 58
        //options.setBinary("/Users/amit/cft/chrome/Google Chrome for Testing.app/Contents/MacOS/Google Chrome For Testing");
32146 amit.gupta 59
        options.setExperimentalOption("prefs", prefsMap);
60
        //options.setExperimentalOption("detach", true);
61
        options.addArguments("--headless");
62
        options.addArguments("--user-agent=\"Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166\"");
30209 amit.gupta 63
 
32146 amit.gupta 64
        options.addArguments("--no-sandbox");
65
        options.addArguments("start-maximized");
66
        options.addArguments("disable-infobars");
67
        options.addArguments("--disable-extensions");
68
        options.addArguments("--force-device-scale-factor=1");
69
        options.addArguments("--test-type");
30209 amit.gupta 70
 
34680 amit.gupta 71
        WebDriver driver = null;
30209 amit.gupta 72
 
34680 amit.gupta 73
        try {
74
            driver = new ChromeDriver(options);
75
            driver.manage().timeouts().setScriptTimeout(6, TimeUnit.SECONDS);
76
            driver.manage().window().setSize(new Dimension(1600, 900));
77
            driver.manage().window().maximize();
78
            // Deleting all the cookies
79
            driver.manage().deleteAllCookies();
80
            // Specifiying pageLoadTimeout and Implicit wait
81
            driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
82
            driver.manage().timeouts().implicitlyWait(9, TimeUnit.SECONDS);
34415 amit.gupta 83
 
34680 amit.gupta 84
            int mainCount = 0;
85
            List<String> remainingImeis = imeis;
86
            WebDriverWait wait10Sec = new WebDriverWait(driver, 8);
87
            WebDriverWait wait5Sec = new WebDriverWait(driver, 4);
88
            WebElement slideButton;
89
            Actions actionProvider = new Actions(driver);
90
            do {
91
                driver.get("https://support.oppo.com/in/warranty-check/");
37420 amit 92
                installResponseCapture(driver);
32146 amit.gupta 93
                try {
34680 amit.gupta 94
                    driver.findElement(By.cssSelector(".cp-cookie-tip a.close")).click();
95
                } catch (Exception e) {
96
                }
30209 amit.gupta 97
 
34680 amit.gupta 98
                for (int i = 0; i < remainingImeis.size(); i++) {
99
                    String imei = remainingImeis.get(i);
100
                    try {
37410 amit 101
                        LOGGER.info("Starting fresh with new IMEI " + imei);
34680 amit.gupta 102
                        if (driver.findElement(By.className("el-input__inner")).getAttribute("value").length() > 0) {
37410 amit 103
                            LOGGER.info("Darn.. leaving" + driver.findElement(By.className("el-input__inner")).getAttribute("value"));
32146 amit.gupta 104
                            driver.get("https://support.oppo.com/in/warranty-check/");
105
                            break;
106
                        }
34680 amit.gupta 107
                        driver.findElement(By.className("el-input__inner")).sendKeys(imei);
30209 amit.gupta 108
 
34680 amit.gupta 109
                        //driver.findElement(By.className("el-button--primary")).click();
110
                        driver.findElement(By.cssSelector("div.searchBtn")).click();
111
 
112
                        // Perform click-and-hold action on the element
113
                        int counter = 1;
114
                        boolean captchaNotBroken = true;
115
                        do {
116
                            String fileName = "/tmp/oppo-simple-i-" + counter + " " + System.currentTimeMillis() + ".png";
117
                            try {
37410 amit 118
                                LOGGER.info("Starting Do");
36583 amit 119
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
120
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
121
                                slideButton = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]"));
34680 amit.gupta 122
                                //System.out.println("Slide button - " + slideButton);
37410 amit 123
                                LOGGER.info("Margin Left before- " + slideButton.getCssValue("margin-left"));
34680 amit.gupta 124
                                actionProvider.moveToElement(slideButton).clickAndHold()
125
                                        .moveByOffset(1, 0)//.pause(2000)
126
                                        .perform();
127
 
128
                                //actionProvider.moveByOffset(-1,0).pause(2000).perform();
37410 amit 129
                                LOGGER.info("Margin Left after - " + slideButton.getCssValue("margin-left"));
34680 amit.gupta 130
                                //Thread.sleep(5000);
131
                            } catch (Exception e) {
37410 amit 132
                                LOGGER.warn("Slider captcha widget (dx_captcha_basic_*) not found or not draggable"
133
                                        + " - reloading. Cause: " + e.getMessage());
34680 amit.gupta 134
                                driver.get("https://support.oppo.com/in/warranty-check/");
135
                                break;
136
                            }
137
                            double[] circles = getMatCircles2(driver, fileName);
138
                            if (circles != null) {
139
                                double firstCircleX = circles[0];
140
                                double secondCircleX = circles[1];
141
                                double distance = Math.abs(firstCircleX - secondCircleX);
37410 amit 142
                                LOGGER.info("Distance is " + distance);
34680 amit.gupta 143
 
37410 amit 144
                                LOGGER.info("Starting Checkdistance method");
34680 amit.gupta 145
                                int moveByOffset = checkDistance(driver, wait10Sec, actionProvider, distance, slideButton);
146
                                if (moveByOffset > 0) {
37410 amit 147
                                    LOGGER.info("Margin Offset - " + slideButton.getCssValue("margin-left"));
148
                                    LOGGER.info("Ending Checkdistance method " + moveByOffset);
34680 amit.gupta 149
                                    actionProvider.moveByOffset(moveByOffset, 0).release().perform();
37410 amit 150
                                    LOGGER.info("Move click performed");
32146 amit.gupta 151
                                    try {
34680 amit.gupta 152
                                        try {
153
                                            wait5Sec.until(ExpectedConditions.visibilityOfElementLocated(By.className("dx_captcha_basic_bar-inform")));
37410 amit 154
                                            LOGGER.warn("Failed = " + counter);
34680 amit.gupta 155
                                        } catch (Exception notFailedException) {
37410 amit 156
                                            LOGGER.info("Success  at attempt " + counter);
37420 amit 157
 
158
                                            // Read the JSON the page itself received rather than the
159
                                            // rendered text. The DOM value is built from two text nodes -- the
160
                                            // date plus a "(UTC+x)" suffix derived from the browser timezone --
161
                                            // and the old locator tested only the first, so it matched nothing.
162
                                            // The API carries regDate as epoch millis, which has no format or
163
                                            // timezone ambiguity at all.
164
                                            String json = capturedResponse(driver);
165
                                            LocalDate activationDate = regDateFrom(json);
166
 
167
                                            if (json == null) {
168
                                                LOGGER.warn("Result shown but no getDeviceInfo response captured for imei {}", imei);
34680 amit.gupta 169
                                            } else {
37420 amit 170
                                                LOGGER.info("Activation lookup for {} -> {}", imei,
171
                                                        activationDate != null ? activationDate : "no activation date");
32146 amit.gupta 172
                                            }
37420 amit 173
                                            // Always record the imei, even with a null date: findElement used to
174
                                            // throw here, so the row was never written and came back every run.
175
                                            dateMap.put(imei, activationDate);
176
                                            clearCapture(driver);
177
 
34680 amit.gupta 178
                                            if (dateMap.size() == imeis.size()) {
179
                                                return dateMap;
180
                                            }
181
                                            WebElement checkAgainButton = driver.findElement(By.className("c-btn"));
182
                                            captchaNotBroken = false;
183
                                            checkAgainButton.click();
184
                                            break;
32146 amit.gupta 185
                                        }
34680 amit.gupta 186
                                    } catch (Throwable e) {
37410 amit 187
                                        LOGGER.warn("Failed = " + counter + " ----------" + e.getMessage());
32146 amit.gupta 188
                                    }
189
                                }
190
                            }
37410 amit 191
                            LOGGER.info("After circles conditions");
36583 amit 192
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
193
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
194
                            slideButton = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]"));
34680 amit.gupta 195
                            actionProvider.moveToElement(slideButton).doubleClick().perform();
37410 amit 196
                            LOGGER.info("Ending Do" + counter++);
30209 amit.gupta 197
 
34680 amit.gupta 198
                        } while (captchaNotBroken && counter <= 20);
37410 amit 199
                        LOGGER.warn("Counter reached upto 20");
34680 amit.gupta 200
                    } catch (Exception e) {
37410 amit 201
                        LOGGER.error("Oppo warranty check failed for imei " + imei, e);
34680 amit.gupta 202
                    }
203
                    driver.get("https://support.oppo.com/in/warranty-check/");
204
                }
205
                mainCount++;
206
                remainingImeis = imeis.stream().filter(x -> !dateMap.containsKey(x)).collect(Collectors.toList());
36253 amit 207
                if (remainingImeis.isEmpty()) break;
34680 amit.gupta 208
            } while (mainCount < 5);
209
        } finally {
210
            if (driver != null) {
211
                try {
212
                    driver.quit(); //Ensures cleanup even on return or error
32146 amit.gupta 213
                } catch (Exception e) {
37410 amit 214
                    LOGGER.warn("Error closing driver: " + e.getMessage());
32146 amit.gupta 215
                }
216
            }
34680 amit.gupta 217
        }
218
 
32146 amit.gupta 219
        return dateMap;
220
    }
30352 amit.gupta 221
 
34680 amit.gupta 222
 
37420 amit 223
    /** Stash the getDeviceInfo response on window as the page receives it. */
224
    private void installResponseCapture(WebDriver driver) {
225
        try {
226
            ((JavascriptExecutor) driver).executeScript(
227
                "if (!window.__oppoCapInstalled) {"
228
              + "  window.__oppoCapInstalled = true; window.__oppoResp = null;"
229
              + "  var O = XMLHttpRequest.prototype.open;"
230
              + "  XMLHttpRequest.prototype.open = function(m,u){"
231
              + "    this.addEventListener('load', function(){"
232
              + "      try { if (String(u).indexOf('getDeviceInfo') !== -1) window.__oppoResp = this.responseText; } catch(e){}"
233
              + "    });"
234
              + "    return O.apply(this, arguments);"
235
              + "  };"
236
              + "}");
237
        } catch (Exception e) {
238
            LOGGER.warn("Could not install the response capture hook: " + e.getMessage());
239
        }
240
    }
241
 
242
    private String capturedResponse(WebDriver driver) {
243
        try {
244
            Object v = ((JavascriptExecutor) driver).executeScript("return window.__oppoResp || null;");
245
            return v == null ? null : v.toString();
246
        } catch (Exception e) {
247
            return null;
248
        }
249
    }
250
 
251
    private void clearCapture(WebDriver driver) {
252
        try {
253
            ((JavascriptExecutor) driver).executeScript("window.__oppoResp = null;");
254
        } catch (Exception ignored) {
255
        }
256
    }
257
 
258
    /** data.regDate is epoch millis; absent or blank means the device is not activated yet. */
259
    private LocalDate regDateFrom(String json) {
260
        if (json == null) return null;
261
        try {
262
            JSONObject data = new JSONObject(json).optJSONObject("data");
263
            if (data == null) return null;
264
            String reg = data.optString("regDate", "");
265
            if (reg == null || reg.trim().isEmpty() || "null".equals(reg)) return null;
266
            return Instant.ofEpochMilli(Long.parseLong(reg.trim()))
267
                    .atZone(ZoneId.of("Asia/Kolkata")).toLocalDate();
268
        } catch (Exception e) {
269
            LOGGER.warn("Could not read regDate from the Oppo response: " + e.getMessage());
270
            return null;
271
        }
272
    }
273
 
34413 amit.gupta 274
    private int checkDistance(WebDriver driver, WebDriverWait wait3Sec, Actions actionProvider, double distance, WebElement slideButton) throws Exception {
30209 amit.gupta 275
 
32146 amit.gupta 276
        //actionProvider.moveToElement(slideButton).clickAndHold().moveByOffset(1, 0).perform();
34413 amit.gupta 277
        actionProvider.moveByOffset(15, 0).perform();
32146 amit.gupta 278
        String fileName2 = "/tmp/" + Thread.currentThread().getName() + "-moved.png";
34413 amit.gupta 279
        double[] movedCircles = getMatCircles2(driver, fileName2);
280
        if (movedCircles == null) return 0;
281
        double movedFirst = movedCircles[0];
282
        double movedSecond = movedCircles[1];
32146 amit.gupta 283
        //System.out.println("Test Offset Move " + testMove);
37410 amit 284
        LOGGER.info("Found Moved " + movedFirst + " ," + movedSecond);
32146 amit.gupta 285
        double movedDistance = Math.abs(movedFirst - movedSecond);
286
        double moved = distance - movedDistance;
37410 amit 287
		/*LOGGER.info("Original distance " + distance);
288
		LOGGER.info("Moved Distance " + movedDistance);
289
		LOGGER.info("Moved " + moved);*/
32146 amit.gupta 290
        if (moved == 0) return 0;
291
        int moveBy = (int) ((movedDistance) * (15 / moved));
292
        //int moveBy = (int) distance - 21;
293
        return moveBy;
294
    }
30209 amit.gupta 295
 
32146 amit.gupta 296
    private Mat getMatCircles(WebDriver driver, String fileName) throws Exception {
30209 amit.gupta 297
 
32146 amit.gupta 298
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
299
        BufferedImage fullImg = ImageIO.read(screenshot);
30209 amit.gupta 300
 
32146 amit.gupta 301
        // Get the location of element on the page
36583 amit 302
        WebElement imageElement = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]"));
32146 amit.gupta 303
        Point point = imageElement.getLocation();
30209 amit.gupta 304
 
32146 amit.gupta 305
        // Get width and height of the element
306
        int eleWidth = imageElement.getSize().getWidth();
307
        int eleHeight = imageElement.getSize().getHeight();
30209 amit.gupta 308
 
32146 amit.gupta 309
        // Crop the entire page screenshot to get only element screenshot
310
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
311
                eleWidth, eleHeight);
312
        ImageIO.write(eleScreenshot, "png", screenshot);
30209 amit.gupta 313
 
32146 amit.gupta 314
        // Copy the element screenshot to disk
315
        File screenshotLocation = new File(fileName);
316
        FileUtils.copyFile(screenshot, screenshotLocation);
30209 amit.gupta 317
 
32146 amit.gupta 318
        Imgcodecs imageCodecs = new Imgcodecs();
319
        Mat grayMatrix = imageCodecs.imread(fileName, Imgcodecs.IMREAD_COLOR);
320
        Imgproc.cvtColor(grayMatrix, grayMatrix, Imgproc.COLOR_BGR2GRAY);
321
        Mat medianBlur = new Mat();
322
        Imgproc.medianBlur(grayMatrix, medianBlur, 5);
323
        Mat circles = new Mat();
324
        Imgproc.HoughCircles(medianBlur, circles, Imgproc.HOUGH_GRADIENT, 1, 15, 50, 20, 17, 25);
325
        return circles;
326
    }
30209 amit.gupta 327
 
34413 amit.gupta 328
    private double[] getMatCircles2(WebDriver driver, String fileName) throws Exception {
329
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
330
        BufferedImage fullImg = ImageIO.read(screenshot);
331
 
332
        // Get the location of element on the page
36583 amit 333
        WebElement imageElement = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]"));
34413 amit.gupta 334
        Point point = imageElement.getLocation();
335
 
336
        // Get width and height of the element
337
        int eleWidth = imageElement.getSize().getWidth();
338
        int eleHeight = imageElement.getSize().getHeight();
339
 
340
        // Crop the entire page screenshot to get only element screenshot
341
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
342
                eleWidth, eleHeight);
343
        ImageIO.write(eleScreenshot, "png", screenshot);
344
 
345
        // Copy the element screenshot to disk
346
        File screenshotLocation = new File(fileName);
347
        FileUtils.copyFile(screenshot, screenshotLocation);
348
 
349
        Mat src = Imgcodecs.imread(fileName);
350
        if (src.empty()) {
351
            System.err.println("Cannot read image: " + fileName);
36253 amit 352
            new File(fileName).delete();
34413 amit.gupta 353
            return null;
354
        }
355
 
356
        Mat gray = new Mat();
357
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
358
        Imgproc.GaussianBlur(gray, gray, new Size(9, 9), 2, 2);
359
 
360
        Mat circles = new Mat();
361
        Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,
362
                20, // min distance between centers
363
                100, 20, // param1 (Canny high threshold), param2 (accumulator threshold)
364
                10, 50); // minRadius, maxRadius (adjust as needed)
365
 
36253 amit 366
        if (circles.cols() < 2) {
367
            new File(fileName).delete();
368
            return null;
369
        }
34413 amit.gupta 370
 
371
        for (int i = 0; i < circles.cols(); i++) {
372
            double[] c1 = circles.get(0, i);
373
            for (int j = i + 1; j < circles.cols(); j++) {
374
                double[] c2 = circles.get(0, j);
375
                if (Math.abs(c1[2] - c2[2]) < 3) { // check similar radius
36253 amit 376
                    new File(fileName).delete();
34413 amit.gupta 377
                    return new double[] {
378
                            c1[0], c2[0] // x-coordinates
379
                    };
380
                }
381
            }
382
        }
383
 
36253 amit 384
        new File(fileName).delete();
34413 amit.gupta 385
        return null;
386
    }
387
 
388
 
30209 amit.gupta 389
}