Subversion Repositories SmartDukaan

Rev

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