Subversion Repositories SmartDukaan

Rev

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