Subversion Repositories SmartDukaan

Rev

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