Subversion Repositories SmartDukaan

Rev

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