Subversion Repositories SmartDukaan

Rev

Rev 34679 | 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
 
33
 
34416 amit.gupta 34
    private static final Logger LOGGER = LogManager.getLogger(CheckRealmeWarrantyTask.class);
30209 amit.gupta 35
 
32146 amit.gupta 36
    public Map<String, LocalDate> checkWarranty(List<String> imeis) {
37
        Map<String, LocalDate> dateMap = new HashMap<>();
38
        //System.out.println(System.getProperty("os.name"));
39
        //System.out.println(System.getProperty("os.arch"));
40
        OpenCV.loadShared();
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());
212
            } while (mainCount < 5);
213
        } finally {
214
            if (driver != null) {
215
                try {
34681 amit.gupta 216
                    driver.quit();  // Always shuts everything down
32146 amit.gupta 217
                } catch (Exception e) {
34679 amit.gupta 218
                    System.out.println("Error closing driver: " + e.getMessage());
32146 amit.gupta 219
                }
220
            }
34679 amit.gupta 221
        }
222
 
32146 amit.gupta 223
        return dateMap;
224
    }
30352 amit.gupta 225
 
34679 amit.gupta 226
 
34413 amit.gupta 227
    private int checkDistance(WebDriver driver, WebDriverWait wait3Sec, Actions actionProvider, double distance, WebElement slideButton) throws Exception {
30209 amit.gupta 228
 
32146 amit.gupta 229
        //actionProvider.moveToElement(slideButton).clickAndHold().moveByOffset(1, 0).perform();
34413 amit.gupta 230
        actionProvider.moveByOffset(15, 0).perform();
32146 amit.gupta 231
        String fileName2 = "/tmp/" + Thread.currentThread().getName() + "-moved.png";
34413 amit.gupta 232
        double[] movedCircles = getMatCircles2(driver, fileName2);
233
        if (movedCircles == null) return 0;
234
        double movedFirst = movedCircles[0];
235
        double movedSecond = movedCircles[1];
32146 amit.gupta 236
        //System.out.println("Test Offset Move " + testMove);
237
        System.out.println("Found Moved " + movedFirst + " ," + movedSecond);
238
        double movedDistance = Math.abs(movedFirst - movedSecond);
239
        double moved = distance - movedDistance;
30209 amit.gupta 240
		/*System.out.println("Original distance " + distance);
241
		System.out.println("Moved Distance " + movedDistance);
242
		System.out.println("Moved " + moved);*/
32146 amit.gupta 243
        if (moved == 0) return 0;
244
        int moveBy = (int) ((movedDistance) * (15 / moved));
245
        //int moveBy = (int) distance - 21;
246
        return moveBy;
247
    }
30209 amit.gupta 248
 
32146 amit.gupta 249
    private Mat getMatCircles(WebDriver driver, String fileName) throws Exception {
30209 amit.gupta 250
 
32146 amit.gupta 251
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
252
        BufferedImage fullImg = ImageIO.read(screenshot);
30209 amit.gupta 253
 
32146 amit.gupta 254
        // Get the location of element on the page
255
        WebElement imageElement = driver.findElement(By.id("dx_captcha_basic_bg_1"));
256
        Point point = imageElement.getLocation();
30209 amit.gupta 257
 
32146 amit.gupta 258
        // Get width and height of the element
259
        int eleWidth = imageElement.getSize().getWidth();
260
        int eleHeight = imageElement.getSize().getHeight();
30209 amit.gupta 261
 
32146 amit.gupta 262
        // Crop the entire page screenshot to get only element screenshot
263
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
264
                eleWidth, eleHeight);
265
        ImageIO.write(eleScreenshot, "png", screenshot);
30209 amit.gupta 266
 
32146 amit.gupta 267
        // Copy the element screenshot to disk
268
        File screenshotLocation = new File(fileName);
269
        FileUtils.copyFile(screenshot, screenshotLocation);
30209 amit.gupta 270
 
32146 amit.gupta 271
        Imgcodecs imageCodecs = new Imgcodecs();
272
        Mat grayMatrix = imageCodecs.imread(fileName, Imgcodecs.IMREAD_COLOR);
273
        Imgproc.cvtColor(grayMatrix, grayMatrix, Imgproc.COLOR_BGR2GRAY);
274
        Mat medianBlur = new Mat();
275
        Imgproc.medianBlur(grayMatrix, medianBlur, 5);
276
        Mat circles = new Mat();
277
        Imgproc.HoughCircles(medianBlur, circles, Imgproc.HOUGH_GRADIENT, 1, 15, 50, 20, 17, 25);
278
        return circles;
279
    }
30209 amit.gupta 280
 
34413 amit.gupta 281
    private double[] getMatCircles2(WebDriver driver, String fileName) throws Exception {
282
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
283
        BufferedImage fullImg = ImageIO.read(screenshot);
284
 
285
        // Get the location of element on the page
286
        WebElement imageElement = driver.findElement(By.id("dx_captcha_basic_bg_1"));
287
        Point point = imageElement.getLocation();
288
 
289
        // Get width and height of the element
290
        int eleWidth = imageElement.getSize().getWidth();
291
        int eleHeight = imageElement.getSize().getHeight();
292
 
293
        // Crop the entire page screenshot to get only element screenshot
294
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
295
                eleWidth, eleHeight);
296
        ImageIO.write(eleScreenshot, "png", screenshot);
297
 
298
        // Copy the element screenshot to disk
299
        File screenshotLocation = new File(fileName);
300
        FileUtils.copyFile(screenshot, screenshotLocation);
301
 
302
        Mat src = Imgcodecs.imread(fileName);
303
        if (src.empty()) {
304
            System.err.println("Cannot read image: " + fileName);
305
            return null;
306
        }
307
 
308
        Mat gray = new Mat();
309
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
310
        Imgproc.GaussianBlur(gray, gray, new Size(9, 9), 2, 2);
311
 
312
        Mat circles = new Mat();
313
        Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,
314
                20, // min distance between centers
315
                100, 20, // param1 (Canny high threshold), param2 (accumulator threshold)
316
                10, 50); // minRadius, maxRadius (adjust as needed)
317
 
318
        if (circles.cols() < 2) return null;
319
 
320
        for (int i = 0; i < circles.cols(); i++) {
321
            double[] c1 = circles.get(0, i);
322
            for (int j = i + 1; j < circles.cols(); j++) {
323
                double[] c2 = circles.get(0, j);
324
                if (Math.abs(c1[2] - c2[2]) < 3) { // check similar radius
325
                    return new double[] {
326
                            c1[0], c2[0] // x-coordinates
327
                    };
328
                }
329
            }
330
        }
331
 
332
        return null;
333
    }
334
 
335
 
30209 amit.gupta 336
}