Subversion Repositories SmartDukaan

Rev

Rev 34420 | Rev 34679 | 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");
34424 amit.gupta 89
            /*try {
34415 amit.gupta 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
                }
34424 amit.gupta 96
            }*/
34415 amit.gupta 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
 
34424 amit.gupta 122
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]")));
123
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
124
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
125
                            slideButton = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]"));
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(
34424 amit.gupta 163
                                                "//label[text()='Estimated Warranty Expiration Date']/following-sibling::div/span | //h1[contains(@class, 'title')]"));
34416 amit.gupta 164
 
34420 amit.gupta 165
 
34413 amit.gupta 166
//TODO: IF not found activationElement
34420 amit.gupta 167
                                        if (warrantyStatus != null) {
168
                                            String activationDateString = warrantyStatus.getText().trim();
34413 amit.gupta 169
                                            System.out.println("Date --  " + activationDateString);
32146 amit.gupta 170
                                            try {
34419 amit.gupta 171
                                                dateMap.put(imei, LocalDate.parse(activationDateString.split(" ")[0], DateTimeFormatter.ofPattern("yyyy.MM.dd")).minusYears(1));
34415 amit.gupta 172
                                                System.out.println("Date --  " + activationDateString);
32146 amit.gupta 173
                                            } catch (Exception e) {
174
                                                dateMap.put(imei, null);
175
                                            }
176
                                        } else {
177
                                            System.out.println("Could not capture date");
178
                                            dateMap.put(imei, null);
179
                                        }
34415 amit.gupta 180
                                        if(dateMap.size()==imeis.size()) {
181
                                            driver.close();
182
                                            driver.quit();
183
                                            return dateMap;
184
                                        }
34416 amit.gupta 185
                                        WebElement checkAgainButton = driver.findElement(By.className("recheck-btn"));
32146 amit.gupta 186
                                        captchaNotBroken = false;
187
                                        checkAgainButton.click();
188
                                        break;
189
                                    }
190
                                } catch (Throwable e) {
191
                                    System.out.println("Failed = " + counter + " ----------" + e.getMessage());
192
                                }
193
                            }
194
                        }
195
                        System.out.println("After circles conditions");
34424 amit.gupta 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_')]"));
32146 amit.gupta 199
                        actionProvider.moveToElement(slideButton).doubleClick().perform();
200
                        System.out.println("Ending Do" + counter++);
30209 amit.gupta 201
 
32146 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
                }
34416 amit.gupta 208
                driver.get("https://www.realme.com/in/support/phonecheck");
32146 amit.gupta 209
            }
210
            mainCount++;
32148 amit.gupta 211
            remainingImeis = imeis.stream().filter(x -> !dateMap.containsKey(x)).collect(Collectors.toList());
32146 amit.gupta 212
        } while (mainCount < 5);
213
        driver.close();
214
        driver.quit();
215
        return dateMap;
216
    }
30352 amit.gupta 217
 
34413 amit.gupta 218
    private int checkDistance(WebDriver driver, WebDriverWait wait3Sec, Actions actionProvider, double distance, WebElement slideButton) throws Exception {
30209 amit.gupta 219
 
32146 amit.gupta 220
        //actionProvider.moveToElement(slideButton).clickAndHold().moveByOffset(1, 0).perform();
34413 amit.gupta 221
        actionProvider.moveByOffset(15, 0).perform();
32146 amit.gupta 222
        String fileName2 = "/tmp/" + Thread.currentThread().getName() + "-moved.png";
34413 amit.gupta 223
        double[] movedCircles = getMatCircles2(driver, fileName2);
224
        if (movedCircles == null) return 0;
225
        double movedFirst = movedCircles[0];
226
        double movedSecond = movedCircles[1];
32146 amit.gupta 227
        //System.out.println("Test Offset Move " + testMove);
228
        System.out.println("Found Moved " + movedFirst + " ," + movedSecond);
229
        double movedDistance = Math.abs(movedFirst - movedSecond);
230
        double moved = distance - movedDistance;
30209 amit.gupta 231
		/*System.out.println("Original distance " + distance);
232
		System.out.println("Moved Distance " + movedDistance);
233
		System.out.println("Moved " + moved);*/
32146 amit.gupta 234
        if (moved == 0) return 0;
235
        int moveBy = (int) ((movedDistance) * (15 / moved));
236
        //int moveBy = (int) distance - 21;
237
        return moveBy;
238
    }
30209 amit.gupta 239
 
32146 amit.gupta 240
    private Mat getMatCircles(WebDriver driver, String fileName) throws Exception {
30209 amit.gupta 241
 
32146 amit.gupta 242
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
243
        BufferedImage fullImg = ImageIO.read(screenshot);
30209 amit.gupta 244
 
32146 amit.gupta 245
        // Get the location of element on the page
246
        WebElement imageElement = driver.findElement(By.id("dx_captcha_basic_bg_1"));
247
        Point point = imageElement.getLocation();
30209 amit.gupta 248
 
32146 amit.gupta 249
        // Get width and height of the element
250
        int eleWidth = imageElement.getSize().getWidth();
251
        int eleHeight = imageElement.getSize().getHeight();
30209 amit.gupta 252
 
32146 amit.gupta 253
        // Crop the entire page screenshot to get only element screenshot
254
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
255
                eleWidth, eleHeight);
256
        ImageIO.write(eleScreenshot, "png", screenshot);
30209 amit.gupta 257
 
32146 amit.gupta 258
        // Copy the element screenshot to disk
259
        File screenshotLocation = new File(fileName);
260
        FileUtils.copyFile(screenshot, screenshotLocation);
30209 amit.gupta 261
 
32146 amit.gupta 262
        Imgcodecs imageCodecs = new Imgcodecs();
263
        Mat grayMatrix = imageCodecs.imread(fileName, Imgcodecs.IMREAD_COLOR);
264
        Imgproc.cvtColor(grayMatrix, grayMatrix, Imgproc.COLOR_BGR2GRAY);
265
        Mat medianBlur = new Mat();
266
        Imgproc.medianBlur(grayMatrix, medianBlur, 5);
267
        Mat circles = new Mat();
268
        Imgproc.HoughCircles(medianBlur, circles, Imgproc.HOUGH_GRADIENT, 1, 15, 50, 20, 17, 25);
269
        return circles;
270
    }
30209 amit.gupta 271
 
34413 amit.gupta 272
    private double[] getMatCircles2(WebDriver driver, String fileName) throws Exception {
273
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
274
        BufferedImage fullImg = ImageIO.read(screenshot);
275
 
276
        // Get the location of element on the page
277
        WebElement imageElement = driver.findElement(By.id("dx_captcha_basic_bg_1"));
278
        Point point = imageElement.getLocation();
279
 
280
        // Get width and height of the element
281
        int eleWidth = imageElement.getSize().getWidth();
282
        int eleHeight = imageElement.getSize().getHeight();
283
 
284
        // Crop the entire page screenshot to get only element screenshot
285
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
286
                eleWidth, eleHeight);
287
        ImageIO.write(eleScreenshot, "png", screenshot);
288
 
289
        // Copy the element screenshot to disk
290
        File screenshotLocation = new File(fileName);
291
        FileUtils.copyFile(screenshot, screenshotLocation);
292
 
293
        Mat src = Imgcodecs.imread(fileName);
294
        if (src.empty()) {
295
            System.err.println("Cannot read image: " + fileName);
296
            return null;
297
        }
298
 
299
        Mat gray = new Mat();
300
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
301
        Imgproc.GaussianBlur(gray, gray, new Size(9, 9), 2, 2);
302
 
303
        Mat circles = new Mat();
304
        Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,
305
                20, // min distance between centers
306
                100, 20, // param1 (Canny high threshold), param2 (accumulator threshold)
307
                10, 50); // minRadius, maxRadius (adjust as needed)
308
 
309
        if (circles.cols() < 2) return null;
310
 
311
        for (int i = 0; i < circles.cols(); i++) {
312
            double[] c1 = circles.get(0, i);
313
            for (int j = i + 1; j < circles.cols(); j++) {
314
                double[] c2 = circles.get(0, j);
315
                if (Math.abs(c1[2] - c2[2]) < 3) { // check similar radius
316
                    return new double[] {
317
                            c1[0], c2[0] // x-coordinates
318
                    };
319
                }
320
            }
321
        }
322
 
323
        return null;
324
    }
325
 
326
 
30209 amit.gupta 327
}