Subversion Repositories SmartDukaan

Rev

Rev 34419 | Rev 34424 | 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
 
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
 
32146 amit.gupta 71
        WebDriver driver = new ChromeDriver(options);
34413 amit.gupta 72
        driver.manage().timeouts().setScriptTimeout(6, TimeUnit.SECONDS);
32146 amit.gupta 73
        driver.manage().window().setSize(new Dimension(1600, 900));
74
        driver.manage().window().maximize();
75
        // Deleting all the cookies
76
        driver.manage().deleteAllCookies();
77
        // Specifiying pageLoadTimeout and Implicit wait
34413 amit.gupta 78
        driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
79
        driver.manage().timeouts().implicitlyWait(9, TimeUnit.SECONDS);
30209 amit.gupta 80
 
32146 amit.gupta 81
        int mainCount = 0;
82
        List<String> remainingImeis = imeis;
34416 amit.gupta 83
        WebDriverWait wait10Sec = new WebDriverWait(driver, 15);
34413 amit.gupta 84
        WebDriverWait wait5Sec = new WebDriverWait(driver, 4);
32146 amit.gupta 85
        WebElement slideButton;
86
        Actions actionProvider = new Actions(driver);
87
        do {
34416 amit.gupta 88
            driver.get("https://www.realme.com/in/support/phonecheck");
34415 amit.gupta 89
            try {
90
                driver.findElement(By.cssSelector(".cp-cookie-tip a.close")).click();
91
            } catch (Exception e) {
92
                try {
93
                    System.out.println("Cookie not found");
94
                } catch (Exception e1) {
95
                }
96
            }
97
 
32146 amit.gupta 98
            for (int i = 0; i < remainingImeis.size(); i++) {
99
                String imei = remainingImeis.get(i);
100
                try {
101
                    System.out.println("Starting fresh with new IMEI " + imei);
34416 amit.gupta 102
                    if (driver.findElement(By.className("sn-input")).getAttribute("value").length() > 0) {
34420 amit.gupta 103
                        //System.out.println("Darn.. leaving" + driver.findElement(By.className("el-input__inner")).getAttribute("value"));
34416 amit.gupta 104
                        driver.get("https://www.realme.com/in/support/phonecheck");
32146 amit.gupta 105
                        break;
106
                    }
34416 amit.gupta 107
                    driver.findElement(By.className("sn-input")).sendKeys(imei);
30209 amit.gupta 108
 
34413 amit.gupta 109
                    //driver.findElement(By.className("el-button--primary")).click();
34416 amit.gupta 110
                    driver.findElement(By.cssSelector("div.check-btn")).click();
34413 amit.gupta 111
 
32146 amit.gupta 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 {
118
                            System.out.println("Starting Do");
34416 amit.gupta 119
                            //Thread.sleep(5000);
120
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.tagName("canvas")));
34420 amit.gupta 121
 
122
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='dx_captcha_basic_bg_1' or @id='dx_captcha_basic_bg_2' or @id='dx_captcha_basic_bg_3' or @id='dx_captcha_basic_bg_4' or @id='dx_captcha_basic_bg_5' or @id='dx_captcha_basic_bg_6' or @id='dx_captcha_basic_bg_7' or @id='dx_captcha_basic_bg_8']")));
123
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='dx_captcha_basic_wrapper_1' or @id='dx_captcha_basic_wrapper_2' or @id='dx_captcha_basic_wrapper_3' or @id='dx_captcha_basic_wrapper_4' or @id='dx_captcha_basic_wrapper_5' or @id='dx_captcha_basic_wrapper_6' or @id='dx_captcha_basic_wrapper_7' or @id='dx_captcha_basic_wrapper_8']")));
124
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='dx_captcha_basic_slider_1' or @id='dx_captcha_basic_slider_2' or @id='dx_captcha_basic_slider_3' or @id='dx_captcha_basic_slider_4' or @id='dx_captcha_basic_slider_5' or @id='dx_captcha_basic_slider_6' or @id='dx_captcha_basic_slider_7' or @id='dx_captcha_basic_slider_8']")));
125
                            slideButton = driver.findElement(By.xpath("//*[@id='dx_captcha_basic_slider_1' or @id='dx_captcha_basic_slider_2' or @id='dx_captcha_basic_slider_3' or @id='dx_captcha_basic_slider_4' or @id='dx_captcha_basic_slider_5' or @id='dx_captcha_basic_slider_6' or @id='dx_captcha_basic_slider_7' or @id='dx_captcha_basic_slider_8']"));
34413 amit.gupta 126
                            //System.out.println("Slide button - " + slideButton);
127
                            System.out.println("Margin Left before- " + slideButton.getCssValue("margin-left"));
128
                            actionProvider.moveToElement(slideButton).clickAndHold()
129
                                    .moveByOffset(1, 0)//.pause(2000)
130
                                    .perform();
131
 
132
                            //actionProvider.moveByOffset(-1,0).pause(2000).perform();
133
                            System.out.println("Margin Left after - " + slideButton.getCssValue("margin-left"));
134
                            //Thread.sleep(5000);
32146 amit.gupta 135
                        } catch (Exception e) {
136
                            System.out.println(e.getMessage());
34416 amit.gupta 137
                            driver.get("https://www.realme.com/in/support/phonecheck");
32146 amit.gupta 138
                            break;
139
                        }
34413 amit.gupta 140
                        double[] circles = getMatCircles2(driver, fileName);
141
                        if (circles != null) {
142
                            double firstCircleX = circles[0];
143
                            double secondCircleX = circles[1];
32146 amit.gupta 144
                            double distance = Math.abs(firstCircleX - secondCircleX);
34413 amit.gupta 145
                            System.out.println("Distance is " + distance);
30209 amit.gupta 146
 
32146 amit.gupta 147
                            System.out.println("Starting Checkdistance method");
34413 amit.gupta 148
                            int moveByOffset = checkDistance(driver, wait10Sec, actionProvider, distance, slideButton);
149
                            if (moveByOffset > 0) {
150
                                System.out.println("Margin Offset - " + slideButton.getCssValue("margin-left"));
151
                                System.out.println("Ending Checkdistance method " + moveByOffset);
152
                                actionProvider.moveByOffset(moveByOffset, 0).release().perform();
32146 amit.gupta 153
                                System.out.println("Move click performed");
154
                                try {
155
                                    try {
156
                                        wait5Sec.until(ExpectedConditions.visibilityOfElementLocated(By.className("dx_captcha_basic_bar-inform")));
157
                                        System.out.println("Failed = " + counter);
158
                                    } catch (Exception notFailedException) {
159
                                        System.out.println("Success  at attempt " + counter);
34413 amit.gupta 160
                                        //List<WebElement> warrantyDateElements = driver.findElements(By.className("warranty-service--result_info__dateValue"));
34416 amit.gupta 161
                                        //WebElement activationTimeElement = driver.findElement(By.xpath("//*[contains(text(), 'UTC+5.5')  or contains(text(), 'Non-Activate')]"));
34420 amit.gupta 162
                                        WebElement warrantyStatus = driver.findElement(By.xpath(
163
                                                "//label[text()='Estimated Warranty Expiration Date']/following-sibling::div/span"
164
                                        ));
34416 amit.gupta 165
 
34420 amit.gupta 166
 
34413 amit.gupta 167
//TODO: IF not found activationElement
34420 amit.gupta 168
                                        if (warrantyStatus != null) {
169
                                            String activationDateString = warrantyStatus.getText().trim();
34413 amit.gupta 170
                                            System.out.println("Date --  " + activationDateString);
32146 amit.gupta 171
                                            try {
34419 amit.gupta 172
                                                dateMap.put(imei, LocalDate.parse(activationDateString.split(" ")[0], DateTimeFormatter.ofPattern("yyyy.MM.dd")).minusYears(1));
34415 amit.gupta 173
                                                System.out.println("Date --  " + activationDateString);
32146 amit.gupta 174
                                            } catch (Exception e) {
175
                                                dateMap.put(imei, null);
176
                                            }
177
                                        } else {
178
                                            System.out.println("Could not capture date");
179
                                            dateMap.put(imei, null);
180
                                        }
34415 amit.gupta 181
                                        if(dateMap.size()==imeis.size()) {
182
                                            driver.close();
183
                                            driver.quit();
184
                                            return dateMap;
185
                                        }
34416 amit.gupta 186
                                        WebElement checkAgainButton = driver.findElement(By.className("recheck-btn"));
32146 amit.gupta 187
                                        captchaNotBroken = false;
188
                                        checkAgainButton.click();
189
                                        break;
190
                                    }
191
                                } catch (Throwable e) {
192
                                    System.out.println("Failed = " + counter + " ----------" + e.getMessage());
193
                                }
194
                            }
195
                        }
196
                        System.out.println("After circles conditions");
197
                        wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.id("dx_captcha_basic_wrapper_1")));
198
                        wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.id("dx_captcha_basic_slider_1")));
199
                        slideButton = driver.findElement(By.id("dx_captcha_basic_slider_1"));
200
                        actionProvider.moveToElement(slideButton).doubleClick().perform();
201
                        System.out.println("Ending Do" + counter++);
30209 amit.gupta 202
 
32146 amit.gupta 203
                    } while (captchaNotBroken && counter <= 20);
204
                    System.out.println("Counter reached upto 20");
205
                } catch (Exception e) {
206
                    System.out.println("Caught unknown - for imei " + imei);
207
                    e.printStackTrace();
208
                }
34416 amit.gupta 209
                driver.get("https://www.realme.com/in/support/phonecheck");
32146 amit.gupta 210
            }
211
            mainCount++;
32148 amit.gupta 212
            remainingImeis = imeis.stream().filter(x -> !dateMap.containsKey(x)).collect(Collectors.toList());
32146 amit.gupta 213
        } while (mainCount < 5);
214
        driver.close();
215
        driver.quit();
216
        return dateMap;
217
    }
30352 amit.gupta 218
 
34413 amit.gupta 219
    private int checkDistance(WebDriver driver, WebDriverWait wait3Sec, Actions actionProvider, double distance, WebElement slideButton) throws Exception {
30209 amit.gupta 220
 
32146 amit.gupta 221
        //actionProvider.moveToElement(slideButton).clickAndHold().moveByOffset(1, 0).perform();
34413 amit.gupta 222
        actionProvider.moveByOffset(15, 0).perform();
32146 amit.gupta 223
        String fileName2 = "/tmp/" + Thread.currentThread().getName() + "-moved.png";
34413 amit.gupta 224
        double[] movedCircles = getMatCircles2(driver, fileName2);
225
        if (movedCircles == null) return 0;
226
        double movedFirst = movedCircles[0];
227
        double movedSecond = movedCircles[1];
32146 amit.gupta 228
        //System.out.println("Test Offset Move " + testMove);
229
        System.out.println("Found Moved " + movedFirst + " ," + movedSecond);
230
        double movedDistance = Math.abs(movedFirst - movedSecond);
231
        double moved = distance - movedDistance;
30209 amit.gupta 232
		/*System.out.println("Original distance " + distance);
233
		System.out.println("Moved Distance " + movedDistance);
234
		System.out.println("Moved " + moved);*/
32146 amit.gupta 235
        if (moved == 0) return 0;
236
        int moveBy = (int) ((movedDistance) * (15 / moved));
237
        //int moveBy = (int) distance - 21;
238
        return moveBy;
239
    }
30209 amit.gupta 240
 
32146 amit.gupta 241
    private Mat getMatCircles(WebDriver driver, String fileName) throws Exception {
30209 amit.gupta 242
 
32146 amit.gupta 243
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
244
        BufferedImage fullImg = ImageIO.read(screenshot);
30209 amit.gupta 245
 
32146 amit.gupta 246
        // Get the location of element on the page
247
        WebElement imageElement = driver.findElement(By.id("dx_captcha_basic_bg_1"));
248
        Point point = imageElement.getLocation();
30209 amit.gupta 249
 
32146 amit.gupta 250
        // Get width and height of the element
251
        int eleWidth = imageElement.getSize().getWidth();
252
        int eleHeight = imageElement.getSize().getHeight();
30209 amit.gupta 253
 
32146 amit.gupta 254
        // Crop the entire page screenshot to get only element screenshot
255
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
256
                eleWidth, eleHeight);
257
        ImageIO.write(eleScreenshot, "png", screenshot);
30209 amit.gupta 258
 
32146 amit.gupta 259
        // Copy the element screenshot to disk
260
        File screenshotLocation = new File(fileName);
261
        FileUtils.copyFile(screenshot, screenshotLocation);
30209 amit.gupta 262
 
32146 amit.gupta 263
        Imgcodecs imageCodecs = new Imgcodecs();
264
        Mat grayMatrix = imageCodecs.imread(fileName, Imgcodecs.IMREAD_COLOR);
265
        Imgproc.cvtColor(grayMatrix, grayMatrix, Imgproc.COLOR_BGR2GRAY);
266
        Mat medianBlur = new Mat();
267
        Imgproc.medianBlur(grayMatrix, medianBlur, 5);
268
        Mat circles = new Mat();
269
        Imgproc.HoughCircles(medianBlur, circles, Imgproc.HOUGH_GRADIENT, 1, 15, 50, 20, 17, 25);
270
        return circles;
271
    }
30209 amit.gupta 272
 
34413 amit.gupta 273
    private double[] getMatCircles2(WebDriver driver, String fileName) throws Exception {
274
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
275
        BufferedImage fullImg = ImageIO.read(screenshot);
276
 
277
        // Get the location of element on the page
278
        WebElement imageElement = driver.findElement(By.id("dx_captcha_basic_bg_1"));
279
        Point point = imageElement.getLocation();
280
 
281
        // Get width and height of the element
282
        int eleWidth = imageElement.getSize().getWidth();
283
        int eleHeight = imageElement.getSize().getHeight();
284
 
285
        // Crop the entire page screenshot to get only element screenshot
286
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
287
                eleWidth, eleHeight);
288
        ImageIO.write(eleScreenshot, "png", screenshot);
289
 
290
        // Copy the element screenshot to disk
291
        File screenshotLocation = new File(fileName);
292
        FileUtils.copyFile(screenshot, screenshotLocation);
293
 
294
        Mat src = Imgcodecs.imread(fileName);
295
        if (src.empty()) {
296
            System.err.println("Cannot read image: " + fileName);
297
            return null;
298
        }
299
 
300
        Mat gray = new Mat();
301
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
302
        Imgproc.GaussianBlur(gray, gray, new Size(9, 9), 2, 2);
303
 
304
        Mat circles = new Mat();
305
        Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,
306
                20, // min distance between centers
307
                100, 20, // param1 (Canny high threshold), param2 (accumulator threshold)
308
                10, 50); // minRadius, maxRadius (adjust as needed)
309
 
310
        if (circles.cols() < 2) return null;
311
 
312
        for (int i = 0; i < circles.cols(); i++) {
313
            double[] c1 = circles.get(0, i);
314
            for (int j = i + 1; j < circles.cols(); j++) {
315
                double[] c2 = circles.get(0, j);
316
                if (Math.abs(c1[2] - c2[2]) < 3) { // check similar radius
317
                    return new double[] {
318
                            c1[0], c2[0] // x-coordinates
319
                    };
320
                }
321
            }
322
        }
323
 
324
        return null;
325
    }
326
 
327
 
30209 amit.gupta 328
}