Subversion Repositories SmartDukaan

Rev

Rev 34415 | Rev 34419 | 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");
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;
34416 amit.gupta 76
        WebDriverWait wait10Sec = new WebDriverWait(driver, 15);
34413 amit.gupta 77
        WebDriverWait wait5Sec = new WebDriverWait(driver, 4);
32146 amit.gupta 78
        WebElement slideButton;
79
        Actions actionProvider = new Actions(driver);
80
        do {
34416 amit.gupta 81
            driver.get("https://www.realme.com/in/support/phonecheck");
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);
34416 amit.gupta 95
                    if (driver.findElement(By.className("sn-input")).getAttribute("value").length() > 0) {
32146 amit.gupta 96
                        System.out.println("Darn.. leaving" + driver.findElement(By.className("el-input__inner")).getAttribute("value"));
34416 amit.gupta 97
                        driver.get("https://www.realme.com/in/support/phonecheck");
32146 amit.gupta 98
                        break;
99
                    }
34416 amit.gupta 100
                    driver.findElement(By.className("sn-input")).sendKeys(imei);
30209 amit.gupta 101
 
34413 amit.gupta 102
                    //driver.findElement(By.className("el-button--primary")).click();
34416 amit.gupta 103
                    driver.findElement(By.cssSelector("div.check-btn")).click();
34413 amit.gupta 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");
34416 amit.gupta 112
                            //Thread.sleep(5000);
113
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.tagName("canvas")));
114
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='dx_captcha_basic_bg_1' or @id='dx_captcha_basic_bg_2']")));
115
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='dx_captcha_basic_wrapper_1' or @id='dx_captcha_basic_wrapper_2']")));
116
                            wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='dx_captcha_basic_slider_1' or @id='dx_captcha_basic_slider_2']")));
117
                            slideButton = driver.findElement(By.xpath("//*[@id='dx_captcha_basic_slider_1' or @id='dx_captcha_basic_slider_2']"));
34413 amit.gupta 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);
32146 amit.gupta 127
                        } catch (Exception e) {
128
                            System.out.println(e.getMessage());
34416 amit.gupta 129
                            driver.get("https://www.realme.com/in/support/phonecheck");
32146 amit.gupta 130
                            break;
131
                        }
34413 amit.gupta 132
                        double[] circles = getMatCircles2(driver, fileName);
133
                        if (circles != null) {
134
                            double firstCircleX = circles[0];
135
                            double secondCircleX = circles[1];
32146 amit.gupta 136
                            double distance = Math.abs(firstCircleX - secondCircleX);
34413 amit.gupta 137
                            System.out.println("Distance is " + distance);
30209 amit.gupta 138
 
32146 amit.gupta 139
                            System.out.println("Starting Checkdistance method");
34413 amit.gupta 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();
32146 amit.gupta 145
                                System.out.println("Move click performed");
146
                                try {
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);
34413 amit.gupta 152
                                        //List<WebElement> warrantyDateElements = driver.findElements(By.className("warranty-service--result_info__dateValue"));
34416 amit.gupta 153
                                        //WebElement activationTimeElement = driver.findElement(By.xpath("//*[contains(text(), 'UTC+5.5')  or contains(text(), 'Non-Activate')]"));
154
                                        WebElement activationTimeElement = driver.findElement(By.xpath("//*[matches(text(), '\\d{4}\\.\\d{2}\\.\\d{2}') or contains(text(), 'not activate')]"));
155
 
34413 amit.gupta 156
//TODO: IF not found activationElement
157
                                        if (activationTimeElement != null) {
158
                                            String activationDateString = activationTimeElement.getText().trim();
159
                                            System.out.println("Date --  " + activationDateString);
32146 amit.gupta 160
                                            try {
34416 amit.gupta 161
                                                dateMap.put(imei, LocalDate.parse(activationDateString.split(" ")[0], DateTimeFormatter.ofPattern("yyyy/MM/dd")).minusYears(1));
34415 amit.gupta 162
                                                System.out.println("Date --  " + activationDateString);
32146 amit.gupta 163
                                            } catch (Exception e) {
164
                                                dateMap.put(imei, null);
165
                                            }
166
                                        } else {
167
                                            System.out.println("Could not capture date");
168
                                            dateMap.put(imei, null);
169
                                        }
34415 amit.gupta 170
                                        if(dateMap.size()==imeis.size()) {
171
                                            driver.close();
172
                                            driver.quit();
173
                                            return dateMap;
174
                                        }
34416 amit.gupta 175
                                        WebElement checkAgainButton = driver.findElement(By.className("recheck-btn"));
32146 amit.gupta 176
                                        captchaNotBroken = false;
177
                                        checkAgainButton.click();
178
                                        break;
179
                                    }
180
                                } catch (Throwable e) {
181
                                    System.out.println("Failed = " + counter + " ----------" + e.getMessage());
182
                                }
183
                            }
184
                        }
185
                        System.out.println("After circles conditions");
186
                        wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.id("dx_captcha_basic_wrapper_1")));
187
                        wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.id("dx_captcha_basic_slider_1")));
188
                        slideButton = driver.findElement(By.id("dx_captcha_basic_slider_1"));
189
                        actionProvider.moveToElement(slideButton).doubleClick().perform();
190
                        System.out.println("Ending Do" + counter++);
30209 amit.gupta 191
 
32146 amit.gupta 192
                    } while (captchaNotBroken && counter <= 20);
193
                    System.out.println("Counter reached upto 20");
194
                } catch (Exception e) {
195
                    System.out.println("Caught unknown - for imei " + imei);
196
                    e.printStackTrace();
197
                }
34416 amit.gupta 198
                driver.get("https://www.realme.com/in/support/phonecheck");
32146 amit.gupta 199
            }
200
            mainCount++;
32148 amit.gupta 201
            remainingImeis = imeis.stream().filter(x -> !dateMap.containsKey(x)).collect(Collectors.toList());
32146 amit.gupta 202
        } while (mainCount < 5);
203
        driver.close();
204
        driver.quit();
205
        return dateMap;
206
    }
30352 amit.gupta 207
 
34413 amit.gupta 208
    private int checkDistance(WebDriver driver, WebDriverWait wait3Sec, Actions actionProvider, double distance, WebElement slideButton) throws Exception {
30209 amit.gupta 209
 
32146 amit.gupta 210
        //actionProvider.moveToElement(slideButton).clickAndHold().moveByOffset(1, 0).perform();
34413 amit.gupta 211
        actionProvider.moveByOffset(15, 0).perform();
32146 amit.gupta 212
        String fileName2 = "/tmp/" + Thread.currentThread().getName() + "-moved.png";
34413 amit.gupta 213
        double[] movedCircles = getMatCircles2(driver, fileName2);
214
        if (movedCircles == null) return 0;
215
        double movedFirst = movedCircles[0];
216
        double movedSecond = movedCircles[1];
32146 amit.gupta 217
        //System.out.println("Test Offset Move " + testMove);
218
        System.out.println("Found Moved " + movedFirst + " ," + movedSecond);
219
        double movedDistance = Math.abs(movedFirst - movedSecond);
220
        double moved = distance - movedDistance;
30209 amit.gupta 221
		/*System.out.println("Original distance " + distance);
222
		System.out.println("Moved Distance " + movedDistance);
223
		System.out.println("Moved " + moved);*/
32146 amit.gupta 224
        if (moved == 0) return 0;
225
        int moveBy = (int) ((movedDistance) * (15 / moved));
226
        //int moveBy = (int) distance - 21;
227
        return moveBy;
228
    }
30209 amit.gupta 229
 
32146 amit.gupta 230
    private Mat getMatCircles(WebDriver driver, String fileName) throws Exception {
30209 amit.gupta 231
 
32146 amit.gupta 232
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
233
        BufferedImage fullImg = ImageIO.read(screenshot);
30209 amit.gupta 234
 
32146 amit.gupta 235
        // Get the location of element on the page
236
        WebElement imageElement = driver.findElement(By.id("dx_captcha_basic_bg_1"));
237
        Point point = imageElement.getLocation();
30209 amit.gupta 238
 
32146 amit.gupta 239
        // Get width and height of the element
240
        int eleWidth = imageElement.getSize().getWidth();
241
        int eleHeight = imageElement.getSize().getHeight();
30209 amit.gupta 242
 
32146 amit.gupta 243
        // Crop the entire page screenshot to get only element screenshot
244
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
245
                eleWidth, eleHeight);
246
        ImageIO.write(eleScreenshot, "png", screenshot);
30209 amit.gupta 247
 
32146 amit.gupta 248
        // Copy the element screenshot to disk
249
        File screenshotLocation = new File(fileName);
250
        FileUtils.copyFile(screenshot, screenshotLocation);
30209 amit.gupta 251
 
32146 amit.gupta 252
        Imgcodecs imageCodecs = new Imgcodecs();
253
        Mat grayMatrix = imageCodecs.imread(fileName, Imgcodecs.IMREAD_COLOR);
254
        Imgproc.cvtColor(grayMatrix, grayMatrix, Imgproc.COLOR_BGR2GRAY);
255
        Mat medianBlur = new Mat();
256
        Imgproc.medianBlur(grayMatrix, medianBlur, 5);
257
        Mat circles = new Mat();
258
        Imgproc.HoughCircles(medianBlur, circles, Imgproc.HOUGH_GRADIENT, 1, 15, 50, 20, 17, 25);
259
        return circles;
260
    }
30209 amit.gupta 261
 
34413 amit.gupta 262
    private double[] getMatCircles2(WebDriver driver, String fileName) throws Exception {
263
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
264
        BufferedImage fullImg = ImageIO.read(screenshot);
265
 
266
        // Get the location of element on the page
267
        WebElement imageElement = driver.findElement(By.id("dx_captcha_basic_bg_1"));
268
        Point point = imageElement.getLocation();
269
 
270
        // Get width and height of the element
271
        int eleWidth = imageElement.getSize().getWidth();
272
        int eleHeight = imageElement.getSize().getHeight();
273
 
274
        // Crop the entire page screenshot to get only element screenshot
275
        BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
276
                eleWidth, eleHeight);
277
        ImageIO.write(eleScreenshot, "png", screenshot);
278
 
279
        // Copy the element screenshot to disk
280
        File screenshotLocation = new File(fileName);
281
        FileUtils.copyFile(screenshot, screenshotLocation);
282
 
283
        Mat src = Imgcodecs.imread(fileName);
284
        if (src.empty()) {
285
            System.err.println("Cannot read image: " + fileName);
286
            return null;
287
        }
288
 
289
        Mat gray = new Mat();
290
        Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
291
        Imgproc.GaussianBlur(gray, gray, new Size(9, 9), 2, 2);
292
 
293
        Mat circles = new Mat();
294
        Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,
295
                20, // min distance between centers
296
                100, 20, // param1 (Canny high threshold), param2 (accumulator threshold)
297
                10, 50); // minRadius, maxRadius (adjust as needed)
298
 
299
        if (circles.cols() < 2) return null;
300
 
301
        for (int i = 0; i < circles.cols(); i++) {
302
            double[] c1 = circles.get(0, i);
303
            for (int j = i + 1; j < circles.cols(); j++) {
304
                double[] c2 = circles.get(0, j);
305
                if (Math.abs(c1[2] - c2[2]) < 3) { // check similar radius
306
                    return new double[] {
307
                            c1[0], c2[0] // x-coordinates
308
                    };
309
                }
310
            }
311
        }
312
 
313
        return null;
314
    }
315
 
316
 
30209 amit.gupta 317
}