Subversion Repositories SmartDukaan

Rev

Rev 36253 | 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;
11
import org.openqa.selenium.*;
12
import org.openqa.selenium.chrome.ChromeDriver;
13
import org.openqa.selenium.chrome.ChromeOptions;
14
import org.openqa.selenium.interactions.Actions;
15
import org.openqa.selenium.support.ui.ExpectedConditions;
16
import org.openqa.selenium.support.ui.WebDriverWait;
30373 amit.gupta 17
import org.springframework.stereotype.Component;
30209 amit.gupta 18
 
19
import javax.imageio.ImageIO;
20
import java.awt.image.BufferedImage;
21
import java.io.File;
22
import java.time.LocalDate;
23
import java.time.format.DateTimeFormatter;
24
import java.util.HashMap;
25
import java.util.List;
26
import java.util.Map;
27
import java.util.concurrent.TimeUnit;
28
import java.util.stream.Collectors;
29
 
30373 amit.gupta 30
@Component
34416 amit.gupta 31
public class CheckRealmeWarrantyTask {
30209 amit.gupta 32
 
34416 amit.gupta 33
    private static final Logger LOGGER = LogManager.getLogger(CheckRealmeWarrantyTask.class);
30209 amit.gupta 34
 
36253 amit 35
    static {
36306 amit 36
        try {
37
            OpenCV.loadShared();
38
        } catch (Throwable t) {
39
            LogManager.getLogger(CheckRealmeWarrantyTask.class).warn("OpenCV not available on this platform: {}", t.getMessage());
40
        }
36253 amit 41
    }
42
 
32146 amit.gupta 43
    public Map<String, LocalDate> checkWarranty(List<String> imeis) {
44
        Map<String, LocalDate> dateMap = new HashMap<>();
45
        LOGGER.info("Initiating webdriver...");
30209 amit.gupta 46
 
32146 amit.gupta 47
        Map<String, Object> prefsMap = new HashMap<>();
48
        prefsMap.put("profile.default_content_settings.popups", 0);
49
        prefsMap.put("download.prompt", false);
50
        prefsMap.put("download.directory_upgrade", true);
34413 amit.gupta 51
        System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
32146 amit.gupta 52
        //I need this
34413 amit.gupta 53
        //System.setProperty("webdriver.chrome.driver", "/Users/amit/cft/chromedriver/chromedriver");
32146 amit.gupta 54
        ChromeOptions options = new ChromeOptions();
34413 amit.gupta 55
        //options.setBinary("/Users/amit/cft/chrome/Google Chrome for Testing.app/Contents/MacOS/Google Chrome For Testing");
32146 amit.gupta 56
        options.setExperimentalOption("prefs", prefsMap);
57
        //options.setExperimentalOption("detach", true);
58
        options.addArguments("--headless");
34419 amit.gupta 59
        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 60
 
32146 amit.gupta 61
        options.addArguments("--no-sandbox");
62
        options.addArguments("start-maximized");
63
        options.addArguments("disable-infobars");
64
        options.addArguments("--disable-extensions");
65
        options.addArguments("--force-device-scale-factor=1");
66
        options.addArguments("--test-type");
34420 amit.gupta 67
        options.addArguments(
68
                "--disable-blink-features=AutomationControlled",
69
                "--disable-infobars",
70
                "--disable-popup-blocking",
71
                "--disable-notifications",
72
                "--disable-extensions"
73
        );
30209 amit.gupta 74
 
34679 amit.gupta 75
        WebDriver driver = null;
30209 amit.gupta 76
 
34679 amit.gupta 77
        try {
78
            driver = new ChromeDriver(options);
79
            driver.manage().timeouts().setScriptTimeout(6, TimeUnit.SECONDS);
80
            driver.manage().window().setSize(new Dimension(1600, 900));
81
            driver.manage().window().maximize();
82
            // Deleting all the cookies
83
            driver.manage().deleteAllCookies();
84
            // Specifiying pageLoadTimeout and Implicit wait
85
            driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
86
            driver.manage().timeouts().implicitlyWait(9, TimeUnit.SECONDS);
87
 
88
            int mainCount = 0;
89
            List<String> remainingImeis = imeis;
90
            WebDriverWait wait10Sec = new WebDriverWait(driver, 15);
91
            WebDriverWait wait5Sec = new WebDriverWait(driver, 4);
92
            WebElement slideButton;
93
            Actions actionProvider = new Actions(driver);
94
            do {
95
                driver.get("https://www.realme.com/in/support/phonecheck");
34424 amit.gupta 96
            /*try {
34415 amit.gupta 97
                driver.findElement(By.cssSelector(".cp-cookie-tip a.close")).click();
98
            } catch (Exception e) {
99
                try {
100
                    System.out.println("Cookie not found");
101
                } catch (Exception e1) {
102
                }
34424 amit.gupta 103
            }*/
34415 amit.gupta 104
 
34679 amit.gupta 105
                for (int i = 0; i < remainingImeis.size(); i++) {
106
                    String imei = remainingImeis.get(i);
107
                    try {
108
                        System.out.println("Starting fresh with new IMEI " + imei);
109
                        if (driver.findElement(By.className("sn-input")).getAttribute("value").length() > 0) {
110
                            //System.out.println("Darn.. leaving" + driver.findElement(By.className("el-input__inner")).getAttribute("value"));
111
                            driver.get("https://www.realme.com/in/support/phonecheck");
112
                            break;
113
                        }
114
                        driver.findElement(By.className("sn-input")).sendKeys(imei);
30209 amit.gupta 115
 
34679 amit.gupta 116
                        //driver.findElement(By.className("el-button--primary")).click();
117
                        driver.findElement(By.cssSelector("div.check-btn")).click();
34413 amit.gupta 118
 
34679 amit.gupta 119
                        // Perform click-and-hold action on the element
120
                        int counter = 1;
121
                        boolean captchaNotBroken = true;
122
                        do {
123
                            String fileName = "/tmp/oppo-simple-i-" + counter + " " + System.currentTimeMillis() + ".png";
124
                            try {
125
                                System.out.println("Starting Do");
126
                                //Thread.sleep(5000);
127
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.tagName("canvas")));
34420 amit.gupta 128
 
34679 amit.gupta 129
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]")));
130
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
131
                                wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
132
                                slideButton = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]"));
133
                                //System.out.println("Slide button - " + slideButton);
134
                                System.out.println("Margin Left before- " + slideButton.getCssValue("margin-left"));
135
                                actionProvider.moveToElement(slideButton).clickAndHold()
136
                                        .moveByOffset(1, 0)//.pause(2000)
137
                                        .perform();
34413 amit.gupta 138
 
34679 amit.gupta 139
                                //actionProvider.moveByOffset(-1,0).pause(2000).perform();
140
                                System.out.println("Margin Left after - " + slideButton.getCssValue("margin-left"));
141
                                //Thread.sleep(5000);
142
                            } catch (Exception e) {
143
                                System.out.println(e.getMessage());
144
                                driver.get("https://www.realme.com/in/support/phonecheck");
145
                                break;
146
                            }
147
                            double[] circles = getMatCircles2(driver, fileName);
148
                            if (circles != null) {
149
                                double firstCircleX = circles[0];
150
                                double secondCircleX = circles[1];
151
                                double distance = Math.abs(firstCircleX - secondCircleX);
152
                                System.out.println("Distance is " + distance);
30209 amit.gupta 153
 
34679 amit.gupta 154
                                System.out.println("Starting Checkdistance method");
155
                                int moveByOffset = checkDistance(driver, wait10Sec, actionProvider, distance, slideButton);
156
                                if (moveByOffset > 0) {
157
                                    System.out.println("Margin Offset - " + slideButton.getCssValue("margin-left"));
158
                                    System.out.println("Ending Checkdistance method " + moveByOffset);
159
                                    actionProvider.moveByOffset(moveByOffset, 0).release().perform();
160
                                    System.out.println("Move click performed");
32146 amit.gupta 161
                                    try {
34679 amit.gupta 162
                                        try {
163
                                            wait5Sec.until(ExpectedConditions.visibilityOfElementLocated(By.className("dx_captcha_basic_bar-inform")));
164
                                            System.out.println("Failed = " + counter);
165
                                        } catch (Exception notFailedException) {
166
                                            System.out.println("Success  at attempt " + counter);
167
                                            //List<WebElement> warrantyDateElements = driver.findElements(By.className("warranty-service--result_info__dateValue"));
168
                                            //WebElement activationTimeElement = driver.findElement(By.xpath("//*[contains(text(), 'UTC+5.5')  or contains(text(), 'Non-Activate')]"));
169
                                            WebElement warrantyStatus = driver.findElement(By.xpath(
170
                                                    "//label[text()='Estimated Warranty Expiration Date']/following-sibling::div/span | //h1[contains(@class, 'title')]"));
34416 amit.gupta 171
 
34679 amit.gupta 172
                                            //TODO: IF not found activationElement
173
                                            if (warrantyStatus != null) {
174
                                                String activationDateString = warrantyStatus.getText().trim();
34415 amit.gupta 175
                                                System.out.println("Date --  " + activationDateString);
34679 amit.gupta 176
                                                try {
177
                                                    dateMap.put(imei, LocalDate.parse(activationDateString.split(" ")[0], DateTimeFormatter.ofPattern("yyyy.MM.dd")).minusYears(1));
178
                                                    System.out.println("Date --  " + activationDateString);
179
                                                } catch (Exception e) {
180
                                                    dateMap.put(imei, null);
181
                                                }
182
                                            } else {
183
                                                System.out.println("Could not capture date");
32146 amit.gupta 184
                                                dateMap.put(imei, null);
185
                                            }
34679 amit.gupta 186
                                            if (dateMap.size() == imeis.size()) {
187
                                                return dateMap;
188
                                            }
189
                                            WebElement checkAgainButton = driver.findElement(By.className("recheck-btn"));
190
                                            captchaNotBroken = false;
191
                                            checkAgainButton.click();
192
                                            break;
32146 amit.gupta 193
                                        }
34679 amit.gupta 194
                                    } catch (Throwable e) {
195
                                        System.out.println("Failed = " + counter + " ----------" + e.getMessage());
32146 amit.gupta 196
                                    }
197
                                }
198
                            }
34679 amit.gupta 199
                            System.out.println("After circles conditions");
200
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
201
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
202
                            slideButton = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]"));
203
                            actionProvider.moveToElement(slideButton).doubleClick().perform();
204
                            System.out.println("Ending Do" + counter++);
30209 amit.gupta 205
 
34679 amit.gupta 206
                        } while (captchaNotBroken && counter <= 20);
207
                        System.out.println("Counter reached upto 20");
208
                    } catch (Exception e) {
209
                        System.out.println("Caught unknown - for imei " + imei);
210
                        e.printStackTrace();
211
                    }
212
                    driver.get("https://www.realme.com/in/support/phonecheck");
213
                }
214
                mainCount++;
215
                remainingImeis = imeis.stream().filter(x -> !dateMap.containsKey(x)).collect(Collectors.toList());
36253 amit 216
                if (remainingImeis.isEmpty()) break;
34679 amit.gupta 217
            } while (mainCount < 5);
218
        } finally {
219
            if (driver != null) {
220
                try {
34681 amit.gupta 221
                    driver.quit();  // Always shuts everything down
32146 amit.gupta 222
                } catch (Exception e) {
34679 amit.gupta 223
                    System.out.println("Error closing driver: " + e.getMessage());
32146 amit.gupta 224
                }
225
            }
34679 amit.gupta 226
        }
227
 
32146 amit.gupta 228
        return dateMap;
229
    }
30352 amit.gupta 230
 
34679 amit.gupta 231
 
34413 amit.gupta 232
    private int checkDistance(WebDriver driver, WebDriverWait wait3Sec, Actions actionProvider, double distance, WebElement slideButton) throws Exception {
30209 amit.gupta 233
 
32146 amit.gupta 234
        //actionProvider.moveToElement(slideButton).clickAndHold().moveByOffset(1, 0).perform();
34413 amit.gupta 235
        actionProvider.moveByOffset(15, 0).perform();
32146 amit.gupta 236
        String fileName2 = "/tmp/" + Thread.currentThread().getName() + "-moved.png";
34413 amit.gupta 237
        double[] movedCircles = getMatCircles2(driver, fileName2);
238
        if (movedCircles == null) return 0;
239
        double movedFirst = movedCircles[0];
240
        double movedSecond = movedCircles[1];
32146 amit.gupta 241
        //System.out.println("Test Offset Move " + testMove);
242
        System.out.println("Found Moved " + movedFirst + " ," + movedSecond);
243
        double movedDistance = Math.abs(movedFirst - movedSecond);
244
        double moved = distance - movedDistance;
30209 amit.gupta 245
		/*System.out.println("Original distance " + distance);
246
		System.out.println("Moved Distance " + movedDistance);
247
		System.out.println("Moved " + moved);*/
32146 amit.gupta 248
        if (moved == 0) return 0;
249
        int moveBy = (int) ((movedDistance) * (15 / moved));
250
        //int moveBy = (int) distance - 21;
251
        return moveBy;
252
    }
30209 amit.gupta 253
 
32146 amit.gupta 254
    private Mat getMatCircles(WebDriver driver, String fileName) throws Exception {
30209 amit.gupta 255
 
32146 amit.gupta 256
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
257
        BufferedImage fullImg = ImageIO.read(screenshot);
30209 amit.gupta 258
 
32146 amit.gupta 259
        // Get the location of element on the page
260
        WebElement imageElement = driver.findElement(By.id("dx_captcha_basic_bg_1"));
261
        Point point = imageElement.getLocation();
30209 amit.gupta 262
 
32146 amit.gupta 263
        // Get width and height of the element
264
        int eleWidth = imageElement.getSize().getWidth();
265
        int eleHeight = imageElement.getSize().getHeight();
30209 amit.gupta 266
 
32146 amit.gupta 267
        // Crop the entire page screenshot to get only element screenshot
268
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
269
                eleWidth, eleHeight);
270
        ImageIO.write(eleScreenshot, "png", screenshot);
30209 amit.gupta 271
 
32146 amit.gupta 272
        // Copy the element screenshot to disk
273
        File screenshotLocation = new File(fileName);
274
        FileUtils.copyFile(screenshot, screenshotLocation);
30209 amit.gupta 275
 
32146 amit.gupta 276
        Imgcodecs imageCodecs = new Imgcodecs();
277
        Mat grayMatrix = imageCodecs.imread(fileName, Imgcodecs.IMREAD_COLOR);
278
        Imgproc.cvtColor(grayMatrix, grayMatrix, Imgproc.COLOR_BGR2GRAY);
279
        Mat medianBlur = new Mat();
280
        Imgproc.medianBlur(grayMatrix, medianBlur, 5);
281
        Mat circles = new Mat();
282
        Imgproc.HoughCircles(medianBlur, circles, Imgproc.HOUGH_GRADIENT, 1, 15, 50, 20, 17, 25);
283
        return circles;
284
    }
30209 amit.gupta 285
 
34413 amit.gupta 286
    private double[] getMatCircles2(WebDriver driver, String fileName) throws Exception {
287
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
288
        BufferedImage fullImg = ImageIO.read(screenshot);
289
 
290
        // Get the location of element on the page
291
        WebElement imageElement = driver.findElement(By.id("dx_captcha_basic_bg_1"));
292
        Point point = imageElement.getLocation();
293
 
294
        // Get width and height of the element
295
        int eleWidth = imageElement.getSize().getWidth();
296
        int eleHeight = imageElement.getSize().getHeight();
297
 
298
        // Crop the entire page screenshot to get only element screenshot
299
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
300
                eleWidth, eleHeight);
301
        ImageIO.write(eleScreenshot, "png", screenshot);
302
 
303
        // Copy the element screenshot to disk
304
        File screenshotLocation = new File(fileName);
305
        FileUtils.copyFile(screenshot, screenshotLocation);
306
 
307
        Mat src = Imgcodecs.imread(fileName);
308
        if (src.empty()) {
309
            System.err.println("Cannot read image: " + fileName);
36253 amit 310
            new File(fileName).delete();
34413 amit.gupta 311
            return null;
312
        }
313
 
314
        Mat gray = new Mat();
315
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
316
        Imgproc.GaussianBlur(gray, gray, new Size(9, 9), 2, 2);
317
 
318
        Mat circles = new Mat();
319
        Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,
320
                20, // min distance between centers
321
                100, 20, // param1 (Canny high threshold), param2 (accumulator threshold)
322
                10, 50); // minRadius, maxRadius (adjust as needed)
323
 
36253 amit 324
        if (circles.cols() < 2) {
325
            new File(fileName).delete();
326
            return null;
327
        }
34413 amit.gupta 328
 
329
        for (int i = 0; i < circles.cols(); i++) {
330
            double[] c1 = circles.get(0, i);
331
            for (int j = i + 1; j < circles.cols(); j++) {
332
                double[] c2 = circles.get(0, j);
333
                if (Math.abs(c1[2] - c2[2]) < 3) { // check similar radius
36253 amit 334
                    new File(fileName).delete();
34413 amit.gupta 335
                    return new double[] {
336
                            c1[0], c2[0] // x-coordinates
337
                    };
338
                }
339
            }
340
        }
341
 
36253 amit 342
        new File(fileName).delete();
34413 amit.gupta 343
        return null;
344
    }
345
 
346
 
30209 amit.gupta 347
}