Subversion Repositories SmartDukaan

Rev

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