| 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;
|
| 37420 |
amit |
11 |
import org.json.JSONObject;
|
| 30209 |
amit.gupta |
12 |
import org.openqa.selenium.*;
|
|
|
13 |
import org.openqa.selenium.chrome.ChromeDriver;
|
|
|
14 |
import org.openqa.selenium.chrome.ChromeOptions;
|
|
|
15 |
import org.openqa.selenium.interactions.Actions;
|
|
|
16 |
import org.openqa.selenium.support.ui.ExpectedConditions;
|
|
|
17 |
import org.openqa.selenium.support.ui.WebDriverWait;
|
| 30373 |
amit.gupta |
18 |
import org.springframework.stereotype.Component;
|
| 30209 |
amit.gupta |
19 |
|
|
|
20 |
import javax.imageio.ImageIO;
|
|
|
21 |
import java.awt.image.BufferedImage;
|
|
|
22 |
import java.io.File;
|
|
|
23 |
import java.time.LocalDate;
|
|
|
24 |
import java.time.format.DateTimeFormatter;
|
| 37420 |
amit |
25 |
import java.time.Instant;
|
|
|
26 |
import java.time.ZoneId;
|
| 30209 |
amit.gupta |
27 |
import java.util.HashMap;
|
|
|
28 |
import java.util.List;
|
|
|
29 |
import java.util.Map;
|
|
|
30 |
import java.util.concurrent.TimeUnit;
|
|
|
31 |
import java.util.stream.Collectors;
|
|
|
32 |
|
| 30373 |
amit.gupta |
33 |
@Component
|
|
|
34 |
public class CheckOppoWarrantyTask {
|
| 30209 |
amit.gupta |
35 |
|
| 32146 |
amit.gupta |
36 |
private static final Logger LOGGER = LogManager.getLogger(CheckOppoWarrantyTask.class);
|
| 30209 |
amit.gupta |
37 |
|
| 36253 |
amit |
38 |
static {
|
| 36306 |
amit |
39 |
try {
|
|
|
40 |
OpenCV.loadShared();
|
|
|
41 |
} catch (Throwable t) {
|
|
|
42 |
LogManager.getLogger(CheckOppoWarrantyTask.class).warn("OpenCV not available on this platform: {}", t.getMessage());
|
|
|
43 |
}
|
| 36253 |
amit |
44 |
}
|
|
|
45 |
|
| 32146 |
amit.gupta |
46 |
public Map<String, LocalDate> checkWarranty(List<String> imeis) {
|
|
|
47 |
Map<String, LocalDate> dateMap = new HashMap<>();
|
|
|
48 |
LOGGER.info("Initiating webdriver...");
|
| 30209 |
amit.gupta |
49 |
|
| 32146 |
amit.gupta |
50 |
Map<String, Object> prefsMap = new HashMap<>();
|
|
|
51 |
prefsMap.put("profile.default_content_settings.popups", 0);
|
|
|
52 |
prefsMap.put("download.prompt", false);
|
|
|
53 |
prefsMap.put("download.directory_upgrade", true);
|
| 34413 |
amit.gupta |
54 |
System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
|
| 32146 |
amit.gupta |
55 |
//I need this
|
| 34413 |
amit.gupta |
56 |
//System.setProperty("webdriver.chrome.driver", "/Users/amit/cft/chromedriver/chromedriver");
|
| 32146 |
amit.gupta |
57 |
ChromeOptions options = new ChromeOptions();
|
| 34413 |
amit.gupta |
58 |
//options.setBinary("/Users/amit/cft/chrome/Google Chrome for Testing.app/Contents/MacOS/Google Chrome For Testing");
|
| 32146 |
amit.gupta |
59 |
options.setExperimentalOption("prefs", prefsMap);
|
|
|
60 |
//options.setExperimentalOption("detach", true);
|
|
|
61 |
options.addArguments("--headless");
|
|
|
62 |
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 |
63 |
|
| 32146 |
amit.gupta |
64 |
options.addArguments("--no-sandbox");
|
|
|
65 |
options.addArguments("start-maximized");
|
|
|
66 |
options.addArguments("disable-infobars");
|
|
|
67 |
options.addArguments("--disable-extensions");
|
|
|
68 |
options.addArguments("--force-device-scale-factor=1");
|
|
|
69 |
options.addArguments("--test-type");
|
| 30209 |
amit.gupta |
70 |
|
| 34680 |
amit.gupta |
71 |
WebDriver driver = null;
|
| 30209 |
amit.gupta |
72 |
|
| 34680 |
amit.gupta |
73 |
try {
|
|
|
74 |
driver = new ChromeDriver(options);
|
|
|
75 |
driver.manage().timeouts().setScriptTimeout(6, TimeUnit.SECONDS);
|
|
|
76 |
driver.manage().window().setSize(new Dimension(1600, 900));
|
|
|
77 |
driver.manage().window().maximize();
|
|
|
78 |
// Deleting all the cookies
|
|
|
79 |
driver.manage().deleteAllCookies();
|
|
|
80 |
// Specifiying pageLoadTimeout and Implicit wait
|
|
|
81 |
driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
|
|
|
82 |
driver.manage().timeouts().implicitlyWait(9, TimeUnit.SECONDS);
|
| 34415 |
amit.gupta |
83 |
|
| 34680 |
amit.gupta |
84 |
int mainCount = 0;
|
|
|
85 |
List<String> remainingImeis = imeis;
|
|
|
86 |
WebDriverWait wait10Sec = new WebDriverWait(driver, 8);
|
|
|
87 |
WebDriverWait wait5Sec = new WebDriverWait(driver, 4);
|
|
|
88 |
WebElement slideButton;
|
|
|
89 |
Actions actionProvider = new Actions(driver);
|
|
|
90 |
do {
|
|
|
91 |
driver.get("https://support.oppo.com/in/warranty-check/");
|
| 37420 |
amit |
92 |
installResponseCapture(driver);
|
| 32146 |
amit.gupta |
93 |
try {
|
| 34680 |
amit.gupta |
94 |
driver.findElement(By.cssSelector(".cp-cookie-tip a.close")).click();
|
|
|
95 |
} catch (Exception e) {
|
|
|
96 |
}
|
| 30209 |
amit.gupta |
97 |
|
| 34680 |
amit.gupta |
98 |
for (int i = 0; i < remainingImeis.size(); i++) {
|
|
|
99 |
String imei = remainingImeis.get(i);
|
|
|
100 |
try {
|
| 37410 |
amit |
101 |
LOGGER.info("Starting fresh with new IMEI " + imei);
|
| 34680 |
amit.gupta |
102 |
if (driver.findElement(By.className("el-input__inner")).getAttribute("value").length() > 0) {
|
| 37410 |
amit |
103 |
LOGGER.info("Darn.. leaving" + driver.findElement(By.className("el-input__inner")).getAttribute("value"));
|
| 32146 |
amit.gupta |
104 |
driver.get("https://support.oppo.com/in/warranty-check/");
|
| 37432 |
amit |
105 |
installResponseCapture(driver);
|
| 32146 |
amit.gupta |
106 |
break;
|
|
|
107 |
}
|
| 34680 |
amit.gupta |
108 |
driver.findElement(By.className("el-input__inner")).sendKeys(imei);
|
| 30209 |
amit.gupta |
109 |
|
| 34680 |
amit.gupta |
110 |
//driver.findElement(By.className("el-button--primary")).click();
|
|
|
111 |
driver.findElement(By.cssSelector("div.searchBtn")).click();
|
|
|
112 |
|
|
|
113 |
// Perform click-and-hold action on the element
|
|
|
114 |
int counter = 1;
|
|
|
115 |
boolean captchaNotBroken = true;
|
| 37435 |
amit |
116 |
// release() is only reached on the moveByOffset > 0 path, so an attempt
|
|
|
117 |
// that fails detection or calibration leaves the button DOWN. Measured in
|
|
|
118 |
// production: 79% of presses were never released. Actions is one instance
|
|
|
119 |
// per driver, created outside the imei loop, so the stuck press leaks into
|
|
|
120 |
// the next attempt AND the next imei -- the following clickAndHold lands on
|
|
|
121 |
// an already-held button, so the widget never repositions the handle and the
|
|
|
122 |
// drag continues from wherever the pointer was abandoned.
|
|
|
123 |
boolean pressed = false;
|
| 34680 |
amit.gupta |
124 |
do {
|
|
|
125 |
String fileName = "/tmp/oppo-simple-i-" + counter + " " + System.currentTimeMillis() + ".png";
|
|
|
126 |
try {
|
| 37410 |
amit |
127 |
LOGGER.info("Starting Do");
|
| 36583 |
amit |
128 |
wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
|
|
|
129 |
wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
|
| 37437 |
amit |
130 |
By sliderBy = By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]");
|
|
|
131 |
slideButton = driver.findElement(sliderBy);
|
|
|
132 |
LOGGER.info("Margin Left before- " + marginLeftOf(slideButton));
|
|
|
133 |
try {
|
|
|
134 |
actionProvider.moveToElement(slideButton).clickAndHold()
|
|
|
135 |
.moveByOffset(1, 0)
|
|
|
136 |
.perform();
|
|
|
137 |
} catch (StaleElementReferenceException stale) {
|
|
|
138 |
// The retry refresh (doubleClick at the end of the previous
|
|
|
139 |
// attempt) swaps the widget's DOM, so the handle located at the
|
|
|
140 |
// top of THIS attempt can already be detached by the time we act
|
|
|
141 |
// on it. Re-find and try once, rather than abandoning the imei
|
|
|
142 |
// and reloading the page: this killed 19% of oppo attempts
|
|
|
143 |
// (54 of 284), against 0 on realme.
|
|
|
144 |
LOGGER.info("Slider went stale before the drag - re-finding and retrying once");
|
|
|
145 |
slideButton = driver.findElement(sliderBy);
|
|
|
146 |
actionProvider.moveToElement(slideButton).clickAndHold()
|
|
|
147 |
.moveByOffset(1, 0)
|
|
|
148 |
.perform();
|
|
|
149 |
}
|
| 37435 |
amit |
150 |
pressed = true;
|
| 37437 |
amit |
151 |
LOGGER.info("Margin Left after - " + marginLeftOf(slideButton));
|
| 34680 |
amit.gupta |
152 |
//Thread.sleep(5000);
|
|
|
153 |
} catch (Exception e) {
|
| 37410 |
amit |
154 |
LOGGER.warn("Slider captcha widget (dx_captcha_basic_*) not found or not draggable"
|
|
|
155 |
+ " - reloading. Cause: " + e.getMessage());
|
| 34680 |
amit.gupta |
156 |
driver.get("https://support.oppo.com/in/warranty-check/");
|
| 37432 |
amit |
157 |
installResponseCapture(driver);
|
| 34680 |
amit.gupta |
158 |
break;
|
|
|
159 |
}
|
|
|
160 |
double[] circles = getMatCircles2(driver, fileName);
|
|
|
161 |
if (circles != null) {
|
|
|
162 |
double firstCircleX = circles[0];
|
|
|
163 |
double secondCircleX = circles[1];
|
|
|
164 |
double distance = Math.abs(firstCircleX - secondCircleX);
|
| 37410 |
amit |
165 |
LOGGER.info("Distance is " + distance);
|
| 34680 |
amit.gupta |
166 |
|
| 37438 |
amit |
167 |
// Closed loop on the ring's own position; no assumed ratio.
|
|
|
168 |
int moveByOffset = aim(driver, actionProvider, circles);
|
| 34680 |
amit.gupta |
169 |
if (moveByOffset > 0) {
|
| 37422 |
amit |
170 |
actionProvider.release().perform();
|
| 37435 |
amit |
171 |
pressed = false;
|
| 37422 |
amit |
172 |
LOGGER.info("Move click performed (main {}px)", moveByOffset);
|
| 32146 |
amit.gupta |
173 |
try {
|
| 34680 |
amit.gupta |
174 |
try {
|
|
|
175 |
wait5Sec.until(ExpectedConditions.visibilityOfElementLocated(By.className("dx_captcha_basic_bar-inform")));
|
| 37433 |
amit |
176 |
// realme logs the widget's own verdict here and oppo did not,
|
|
|
177 |
// which is why realme's failures name POSITION_MISMATCH and
|
|
|
178 |
// oppo's 85% say nothing at all. Same line, oppo's variables.
|
|
|
179 |
LOGGER.warn("Failed = {} (captcha said: {})", counter, captchaSignal(driver));
|
| 34680 |
amit.gupta |
180 |
} catch (Exception notFailedException) {
|
| 37410 |
amit |
181 |
LOGGER.info("Success at attempt " + counter);
|
| 37420 |
amit |
182 |
|
|
|
183 |
// Read the JSON the page itself received rather than the
|
|
|
184 |
// rendered text. The DOM value is built from two text nodes -- the
|
|
|
185 |
// date plus a "(UTC+x)" suffix derived from the browser timezone --
|
|
|
186 |
// and the old locator tested only the first, so it matched nothing.
|
|
|
187 |
// The API carries regDate as epoch millis, which has no format or
|
|
|
188 |
// timezone ambiguity at all.
|
| 37429 |
amit |
189 |
String json = awaitResponse(driver, 8000);
|
| 37420 |
amit |
190 |
LocalDate activationDate = regDateFrom(json);
|
|
|
191 |
|
|
|
192 |
if (json == null) {
|
| 37429 |
amit |
193 |
LOGGER.warn("No getDeviceInfo response for imei {} (captcha said: {})",
|
|
|
194 |
imei, captchaSignal(driver));
|
| 34680 |
amit.gupta |
195 |
} else {
|
| 37420 |
amit |
196 |
LOGGER.info("Activation lookup for {} -> {}", imei,
|
|
|
197 |
activationDate != null ? activationDate : "no activation date");
|
| 32146 |
amit.gupta |
198 |
}
|
| 37420 |
amit |
199 |
// Always record the imei, even with a null date: findElement used to
|
|
|
200 |
// throw here, so the row was never written and came back every run.
|
|
|
201 |
dateMap.put(imei, activationDate);
|
|
|
202 |
clearCapture(driver);
|
|
|
203 |
|
| 34680 |
amit.gupta |
204 |
if (dateMap.size() == imeis.size()) {
|
|
|
205 |
return dateMap;
|
|
|
206 |
}
|
|
|
207 |
WebElement checkAgainButton = driver.findElement(By.className("c-btn"));
|
|
|
208 |
captchaNotBroken = false;
|
|
|
209 |
checkAgainButton.click();
|
|
|
210 |
break;
|
| 32146 |
amit.gupta |
211 |
}
|
| 34680 |
amit.gupta |
212 |
} catch (Throwable e) {
|
| 37410 |
amit |
213 |
LOGGER.warn("Failed = " + counter + " ----------" + e.getMessage());
|
| 32146 |
amit.gupta |
214 |
}
|
|
|
215 |
}
|
|
|
216 |
}
|
| 37435 |
amit |
217 |
// Any path that got here without releasing (null circles, unusable
|
|
|
218 |
// calibration) must let go before the next attempt re-presses.
|
|
|
219 |
if (pressed) {
|
|
|
220 |
try {
|
|
|
221 |
actionProvider.release().perform();
|
|
|
222 |
} catch (Exception releaseFailed) {
|
|
|
223 |
LOGGER.warn("Could not release the slider: " + releaseFailed.getMessage());
|
|
|
224 |
}
|
|
|
225 |
pressed = false;
|
|
|
226 |
}
|
| 37410 |
amit |
227 |
LOGGER.info("After circles conditions");
|
| 36583 |
amit |
228 |
wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_wrapper_')]")));
|
|
|
229 |
wait10Sec.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]")));
|
|
|
230 |
slideButton = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_slider_')]"));
|
| 34680 |
amit.gupta |
231 |
actionProvider.moveToElement(slideButton).doubleClick().perform();
|
| 37410 |
amit |
232 |
LOGGER.info("Ending Do" + counter++);
|
| 30209 |
amit.gupta |
233 |
|
| 34680 |
amit.gupta |
234 |
} while (captchaNotBroken && counter <= 20);
|
| 37435 |
amit |
235 |
// The widget-not-found path breaks out mid-iteration; do not carry a held
|
|
|
236 |
// button into the next imei.
|
|
|
237 |
if (pressed) {
|
|
|
238 |
try {
|
|
|
239 |
actionProvider.release().perform();
|
|
|
240 |
} catch (Exception releaseFailed) {
|
|
|
241 |
LOGGER.warn("Could not release the slider: " + releaseFailed.getMessage());
|
|
|
242 |
}
|
|
|
243 |
}
|
| 37410 |
amit |
244 |
LOGGER.warn("Counter reached upto 20");
|
| 34680 |
amit.gupta |
245 |
} catch (Exception e) {
|
| 37410 |
amit |
246 |
LOGGER.error("Oppo warranty check failed for imei " + imei, e);
|
| 34680 |
amit.gupta |
247 |
}
|
|
|
248 |
driver.get("https://support.oppo.com/in/warranty-check/");
|
| 37432 |
amit |
249 |
// Every navigation destroys the JS context, taking the capture hook
|
|
|
250 |
// with it. Miss one of these and the page is blind from the second
|
|
|
251 |
// imei onwards: __oppoResp and __oppoCaptcha both come back null,
|
|
|
252 |
// which reads as "the captcha failed" when it may well have passed.
|
|
|
253 |
installResponseCapture(driver);
|
| 34680 |
amit.gupta |
254 |
}
|
|
|
255 |
mainCount++;
|
|
|
256 |
remainingImeis = imeis.stream().filter(x -> !dateMap.containsKey(x)).collect(Collectors.toList());
|
| 36253 |
amit |
257 |
if (remainingImeis.isEmpty()) break;
|
| 34680 |
amit.gupta |
258 |
} while (mainCount < 5);
|
|
|
259 |
} finally {
|
|
|
260 |
if (driver != null) {
|
|
|
261 |
try {
|
|
|
262 |
driver.quit(); //Ensures cleanup even on return or error
|
| 32146 |
amit.gupta |
263 |
} catch (Exception e) {
|
| 37410 |
amit |
264 |
LOGGER.warn("Error closing driver: " + e.getMessage());
|
| 32146 |
amit.gupta |
265 |
}
|
|
|
266 |
}
|
| 34680 |
amit.gupta |
267 |
}
|
|
|
268 |
|
| 32146 |
amit.gupta |
269 |
return dateMap;
|
|
|
270 |
}
|
| 30352 |
amit.gupta |
271 |
|
| 34680 |
amit.gupta |
272 |
|
| 37420 |
amit |
273 |
/** Stash the getDeviceInfo response on window as the page receives it. */
|
|
|
274 |
private void installResponseCapture(WebDriver driver) {
|
|
|
275 |
try {
|
|
|
276 |
((JavascriptExecutor) driver).executeScript(
|
|
|
277 |
"if (!window.__oppoCapInstalled) {"
|
| 37428 |
amit |
278 |
+ " window.__oppoCapInstalled = true; window.__oppoResp = null; window.__oppoCaptcha = null;"
|
| 37434 |
amit |
279 |
// __oppoCaptcha is last-captcha-call-wins, and the widget refetches a puzzle
|
|
|
280 |
// (/api/a) straight after a rejected verify (/api/v1). We then wait up to 5s
|
|
|
281 |
// for the error element before reading it, which is ample time for the
|
|
|
282 |
// refetch to overwrite the verdict -- so "all failures show /api/a" cannot
|
|
|
283 |
// distinguish "never verified" from "verified, rejected, then overwritten".
|
|
|
284 |
// Keep the verify separately, and a count, so the two are distinguishable.
|
|
|
285 |
+ " window.__oppoVerify = null; window.__oppoVerifyCount = 0;"
|
| 37425 |
amit |
286 |
// axios can sit on either transport, and realme's page uses fetch --
|
|
|
287 |
// an XHR-only hook silently captures nothing, which is exactly what
|
|
|
288 |
// 'no getDeviceInfo response captured' was reporting.
|
| 37420 |
amit |
289 |
+ " var O = XMLHttpRequest.prototype.open;"
|
|
|
290 |
+ " XMLHttpRequest.prototype.open = function(m,u){"
|
|
|
291 |
+ " this.addEventListener('load', function(){"
|
| 37428 |
amit |
292 |
+ " try { var s=String(u);"
|
|
|
293 |
+ " if (s.indexOf('getDeviceInfo') !== -1) window.__oppoResp = this.responseText;"
|
| 37434 |
amit |
294 |
+ " else if (s.indexOf('/api/v1') !== -1) { window.__oppoVerifyCount++; window.__oppoVerify = (this.responseText||'').slice(0,160); window.__oppoCaptcha = s + ' -> ' + (this.responseText||'').slice(0,200); }"
|
| 37428 |
amit |
295 |
+ " else if (s.indexOf('captcha') !== -1) window.__oppoCaptcha = s + ' -> ' + (this.responseText||'').slice(0,200);"
|
|
|
296 |
+ " } catch(e){}"
|
| 37420 |
amit |
297 |
+ " });"
|
|
|
298 |
+ " return O.apply(this, arguments);"
|
|
|
299 |
+ " };"
|
| 37425 |
amit |
300 |
+ " var F = window.fetch;"
|
|
|
301 |
+ " if (F) { window.fetch = function(){"
|
|
|
302 |
+ " var u = arguments[0]; u = (u && u.url) ? u.url : String(u);"
|
|
|
303 |
+ " return F.apply(this, arguments).then(function(r){"
|
|
|
304 |
+ " try { if (u.indexOf('getDeviceInfo') !== -1) { r.clone().text().then(function(t){ window.__oppoResp = t; }); } } catch(e){}"
|
|
|
305 |
+ " return r;"
|
|
|
306 |
+ " });"
|
|
|
307 |
+ " }; }"
|
| 37431 |
amit |
308 |
// A window.fetch wrapper only catches clients that resolve fetch at call
|
|
|
309 |
// time. Anything that captured globalThis.fetch when its bundle loaded --
|
|
|
310 |
// Nuxt's $fetch/ofetch does exactly this, and it is what hid realme's
|
|
|
311 |
// lookup from us -- sails straight past it. Response.prototype is resolved
|
|
|
312 |
// per call, so it catches every client regardless.
|
|
|
313 |
// Read the clone with the ORIGINAL reader; the patched one recurses forever.
|
|
|
314 |
+ " ['json','text'].forEach(function(name){"
|
|
|
315 |
+ " var orig = Response.prototype[name];"
|
|
|
316 |
+ " if (!orig) return;"
|
|
|
317 |
+ " Response.prototype[name] = function(){"
|
|
|
318 |
+ " try { var u = this.url || '';"
|
|
|
319 |
+ " if (u.indexOf('getDeviceInfo') !== -1 && !this.__oppoSeenBody) {"
|
|
|
320 |
+ " var c = this.clone(); c.__oppoSeenBody = 1;"
|
|
|
321 |
+ " orig.call(c).then(function(t){ window.__oppoResp = (typeof t === 'string') ? t : JSON.stringify(t); });"
|
|
|
322 |
+ " } } catch(e){}"
|
|
|
323 |
+ " return orig.apply(this, arguments);"
|
|
|
324 |
+ " };"
|
|
|
325 |
+ " });"
|
| 37420 |
amit |
326 |
+ "}");
|
|
|
327 |
} catch (Exception e) {
|
|
|
328 |
LOGGER.warn("Could not install the response capture hook: " + e.getMessage());
|
|
|
329 |
}
|
|
|
330 |
}
|
|
|
331 |
|
| 37428 |
amit |
332 |
/** Last response from the captcha widget itself -- says WHY a drag was refused. */
|
|
|
333 |
private String captchaSignal(WebDriver driver) {
|
|
|
334 |
try {
|
| 37434 |
amit |
335 |
Object v = ((JavascriptExecutor) driver).executeScript(
|
|
|
336 |
"return 'verifies=' + (window.__oppoVerifyCount||0)"
|
|
|
337 |
+ " + ' lastVerify=' + (window.__oppoVerify || 'NONE')"
|
|
|
338 |
+ " + ' | ' + (window.__oppoCaptcha || 'none');");
|
| 37428 |
amit |
339 |
return v == null ? null : v.toString();
|
|
|
340 |
} catch (Exception e) {
|
|
|
341 |
return null;
|
|
|
342 |
}
|
|
|
343 |
}
|
|
|
344 |
|
| 37429 |
amit |
345 |
/** Poll for the response instead of reading once: the success signal can fire
|
|
|
346 |
* before the lookup request has completed, which loses the payload. */
|
|
|
347 |
private String awaitResponse(WebDriver driver, long timeoutMs) {
|
|
|
348 |
long deadline = System.currentTimeMillis() + timeoutMs;
|
|
|
349 |
while (System.currentTimeMillis() < deadline) {
|
|
|
350 |
String json = capturedResponse(driver);
|
|
|
351 |
if (json != null && !json.trim().isEmpty()) return json;
|
|
|
352 |
try {
|
|
|
353 |
Thread.sleep(300);
|
|
|
354 |
} catch (InterruptedException ie) {
|
|
|
355 |
Thread.currentThread().interrupt();
|
|
|
356 |
return null;
|
|
|
357 |
}
|
|
|
358 |
}
|
|
|
359 |
return null;
|
|
|
360 |
}
|
|
|
361 |
|
| 37420 |
amit |
362 |
private String capturedResponse(WebDriver driver) {
|
|
|
363 |
try {
|
|
|
364 |
Object v = ((JavascriptExecutor) driver).executeScript("return window.__oppoResp || null;");
|
|
|
365 |
return v == null ? null : v.toString();
|
|
|
366 |
} catch (Exception e) {
|
|
|
367 |
return null;
|
|
|
368 |
}
|
|
|
369 |
}
|
|
|
370 |
|
|
|
371 |
private void clearCapture(WebDriver driver) {
|
|
|
372 |
try {
|
|
|
373 |
((JavascriptExecutor) driver).executeScript("window.__oppoResp = null;");
|
|
|
374 |
} catch (Exception ignored) {
|
|
|
375 |
}
|
|
|
376 |
}
|
|
|
377 |
|
|
|
378 |
/** data.regDate is epoch millis; absent or blank means the device is not activated yet. */
|
|
|
379 |
private LocalDate regDateFrom(String json) {
|
|
|
380 |
if (json == null) return null;
|
|
|
381 |
try {
|
|
|
382 |
JSONObject data = new JSONObject(json).optJSONObject("data");
|
|
|
383 |
if (data == null) return null;
|
|
|
384 |
String reg = data.optString("regDate", "");
|
|
|
385 |
if (reg == null || reg.trim().isEmpty() || "null".equals(reg)) return null;
|
|
|
386 |
return Instant.ofEpochMilli(Long.parseLong(reg.trim()))
|
|
|
387 |
.atZone(ZoneId.of("Asia/Kolkata")).toLocalDate();
|
|
|
388 |
} catch (Exception e) {
|
|
|
389 |
LOGGER.warn("Could not read regDate from the Oppo response: " + e.getMessage());
|
|
|
390 |
return null;
|
|
|
391 |
}
|
|
|
392 |
}
|
|
|
393 |
|
| 37422 |
amit |
394 |
/**
|
| 37424 |
amit |
395 |
* Calibration nudge, in slider px, sized from the gap rather than fixed.
|
| 37422 |
amit |
396 |
*
|
| 37424 |
amit |
397 |
* A fixed 15px was far too small: it closed only ~25px, so the ratio came from a
|
|
|
398 |
* measurement ~20% noise and the aim landed ~30px out. A fixed 60px then proved too
|
|
|
399 |
* large in the other direction -- production data showed 85% of attempts with a gap
|
|
|
400 |
* under 60px ended up UNUSABLE (the piece shot past the hole and the measured gap
|
|
|
401 |
* grew), and 45% overall.
|
| 37422 |
amit |
402 |
*
|
| 37424 |
amit |
403 |
* Aim to close about half the gap: the piece travels roughly ASSUMED_RATIO px per
|
|
|
404 |
* slider px, so nudge ~= gap / (2 * ratio), clamped. The real ratio is still derived
|
|
|
405 |
* from the measurement; this only sizes the probe.
|
| 37422 |
amit |
406 |
*/
|
|
|
407 |
private static final double ALIGNED_PX = 2.0;
|
|
|
408 |
|
| 37437 |
amit |
409 |
/**
|
|
|
410 |
* margin-left for logging only. Reading it off a detached element throws, and this is
|
|
|
411 |
* a diagnostic -- it must never be the reason an attempt is abandoned.
|
|
|
412 |
*/
|
|
|
413 |
private String marginLeftOf(WebElement el) {
|
|
|
414 |
try {
|
|
|
415 |
return el.getCssValue("margin-left");
|
|
|
416 |
} catch (Exception e) {
|
|
|
417 |
return "?";
|
|
|
418 |
}
|
| 37424 |
amit |
419 |
}
|
|
|
420 |
|
| 37437 |
amit |
421 |
/** Seed probe, in slider px. Deliberately small: it only has to produce a first
|
|
|
422 |
* measurable movement, and it must be too small to cross the hole. */
|
|
|
423 |
private static final int SEED_NUDGE = 12;
|
|
|
424 |
private static final int MAX_AIM_STEPS = 5;
|
|
|
425 |
private static final int MAX_STEP = 140;
|
|
|
426 |
|
| 37438 |
amit |
427 |
/** Centre of the draggable ring, in page CSS px, or null if it is not there. */
|
|
|
428 |
private Double pieceCentreX(WebDriver driver) {
|
|
|
429 |
try {
|
|
|
430 |
WebElement piece = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_sub-slider_')]"));
|
|
|
431 |
return piece.getLocation().getX() + (piece.getSize().getWidth() / 2.0);
|
|
|
432 |
} catch (Exception e) {
|
|
|
433 |
return null;
|
|
|
434 |
}
|
|
|
435 |
}
|
|
|
436 |
|
| 37422 |
amit |
437 |
/**
|
| 37438 |
amit |
438 |
* Drag the ring onto the hole, deriving px-per-px as we go.
|
| 37437 |
amit |
439 |
*
|
| 37438 |
amit |
440 |
* Why this does not re-run circle detection: it cannot. Hough needs to resolve TWO
|
|
|
441 |
* circles of similar radius, and as the ring closes on the hole they overlap and stop
|
|
|
442 |
* being two -- so the measurement dies exactly at convergence. Measured in production
|
|
|
443 |
* after r37437: 25 of 36 attempts lost the circles on the very step after the main
|
|
|
444 |
* move, and NOT ONE ever reported aligned. The old refine() hit the same wall and
|
|
|
445 |
* silently released. Any loop built on "distance between two detected circles" is
|
|
|
446 |
* blind at the only moment that matters.
|
| 37437 |
amit |
447 |
*
|
| 37438 |
amit |
448 |
* So the target is fixed ONCE, from the detection already done while the two are far
|
|
|
449 |
* apart and resolvable, and from then on we track the RING'S OWN ELEMENT, which stays
|
|
|
450 |
* readable however close it gets. Verified locally against the live widget: the ring's
|
|
|
451 |
* rect tracks the drag cleanly the whole way in (+10 mouse -> +11 ring, repeatably).
|
| 37437 |
amit |
452 |
*
|
| 37438 |
amit |
453 |
* The circle x's are already CSS px relative to the bg element -- the crop in
|
|
|
454 |
* getMatCircles2 uses CSS coordinates and chrome runs with
|
|
|
455 |
* --force-device-scale-factor=1 -- so the only conversion needed is the bg offset.
|
|
|
456 |
*
|
|
|
457 |
* Every move is also a measurement: the ratio is re-derived from what that move
|
|
|
458 |
* actually achieved, and it is signed, so overshoot corrects itself instead of needing
|
|
|
459 |
* to be detected.
|
|
|
460 |
*
|
|
|
461 |
* @return total slider px moved, or 0 if the ring could not be located at all.
|
| 37422 |
amit |
462 |
*/
|
| 37438 |
amit |
463 |
private int aim(WebDriver driver, Actions actionProvider, double[] circleXs) throws Exception {
|
|
|
464 |
Double piece = pieceCentreX(driver);
|
|
|
465 |
if (piece == null) {
|
|
|
466 |
LOGGER.warn("Aim: no ring element to track");
|
|
|
467 |
return 0;
|
|
|
468 |
}
|
|
|
469 |
int bgX;
|
|
|
470 |
try {
|
|
|
471 |
bgX = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]")).getLocation().getX();
|
|
|
472 |
} catch (Exception e) {
|
|
|
473 |
LOGGER.warn("Aim: bg element gone - " + e.getMessage());
|
|
|
474 |
return 0;
|
|
|
475 |
}
|
|
|
476 |
|
|
|
477 |
// Of the two detected circles the ring is whichever sits at the ring element; the
|
|
|
478 |
// other one is the hole we are aiming at.
|
|
|
479 |
double a = bgX + circleXs[0], b = bgX + circleXs[1];
|
|
|
480 |
double target = (Math.abs(a - piece) <= Math.abs(b - piece)) ? b : a;
|
|
|
481 |
LOGGER.info("Aim: ring at {} target at {} ({}px to close)",
|
|
|
482 |
Math.round(piece), Math.round(target), Math.round(target - piece));
|
|
|
483 |
|
|
|
484 |
double ratio = 0; // ring px per mouse px, signed, derived from real moves
|
| 37437 |
amit |
485 |
int total = 0;
|
|
|
486 |
int step = SEED_NUDGE;
|
| 37422 |
amit |
487 |
|
| 37437 |
amit |
488 |
for (int i = 0; i < MAX_AIM_STEPS; i++) {
|
|
|
489 |
actionProvider.moveByOffset(step, 0).perform();
|
|
|
490 |
total += step;
|
| 37422 |
amit |
491 |
|
| 37438 |
amit |
492 |
Double now = pieceCentreX(driver);
|
|
|
493 |
if (now == null) {
|
|
|
494 |
LOGGER.warn("Aim step {}: lost the ring after {}px", i, total);
|
| 37437 |
amit |
495 |
return total;
|
|
|
496 |
}
|
| 37438 |
amit |
497 |
double moved = now - piece;
|
|
|
498 |
if (Math.abs(moved) > 0.5) {
|
|
|
499 |
double observed = moved / step;
|
|
|
500 |
ratio = (ratio == 0) ? observed : (ratio + observed) / 2;
|
| 37437 |
amit |
501 |
}
|
| 37438 |
amit |
502 |
double remaining = target - now;
|
|
|
503 |
LOGGER.info("Aim step {}: mouse {}px -> ring moved {}px, {}px left, ratio {}",
|
|
|
504 |
i, step, Math.round(moved), Math.round(remaining), String.format("%.2f", ratio));
|
| 37422 |
amit |
505 |
|
| 37438 |
amit |
506 |
if (Math.abs(remaining) <= ALIGNED_PX) {
|
|
|
507 |
LOGGER.info("Aim: aligned to {}px after {} step(s), {}px of slider",
|
|
|
508 |
Math.round(remaining), i + 1, total);
|
| 37437 |
amit |
509 |
return total;
|
|
|
510 |
}
|
| 37438 |
amit |
511 |
piece = now;
|
|
|
512 |
if (ratio == 0) { // nothing measurable yet, probe again
|
| 37437 |
amit |
513 |
step = SEED_NUDGE;
|
|
|
514 |
continue;
|
|
|
515 |
}
|
| 37438 |
amit |
516 |
int next = (int) Math.round(remaining / ratio);
|
|
|
517 |
if (next == 0) next = (remaining > 0 ? 1 : -1);
|
| 37437 |
amit |
518 |
if (next > MAX_STEP) next = MAX_STEP;
|
| 37438 |
amit |
519 |
if (next < -MAX_STEP) next = -MAX_STEP;
|
|
|
520 |
step = next;
|
| 37437 |
amit |
521 |
}
|
| 37438 |
amit |
522 |
LOGGER.info("Aim: {} steps used, {}px of slider, still short", MAX_AIM_STEPS, total);
|
| 37437 |
amit |
523 |
return total;
|
| 32146 |
amit.gupta |
524 |
}
|
| 30209 |
amit.gupta |
525 |
|
| 32146 |
amit.gupta |
526 |
private Mat getMatCircles(WebDriver driver, String fileName) throws Exception {
|
| 30209 |
amit.gupta |
527 |
|
| 32146 |
amit.gupta |
528 |
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
|
|
|
529 |
BufferedImage fullImg = ImageIO.read(screenshot);
|
| 30209 |
amit.gupta |
530 |
|
| 32146 |
amit.gupta |
531 |
// Get the location of element on the page
|
| 36583 |
amit |
532 |
WebElement imageElement = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]"));
|
| 32146 |
amit.gupta |
533 |
Point point = imageElement.getLocation();
|
| 30209 |
amit.gupta |
534 |
|
| 32146 |
amit.gupta |
535 |
// Get width and height of the element
|
|
|
536 |
int eleWidth = imageElement.getSize().getWidth();
|
|
|
537 |
int eleHeight = imageElement.getSize().getHeight();
|
| 30209 |
amit.gupta |
538 |
|
| 32146 |
amit.gupta |
539 |
// Crop the entire page screenshot to get only element screenshot
|
|
|
540 |
BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
|
|
|
541 |
eleWidth, eleHeight);
|
|
|
542 |
ImageIO.write(eleScreenshot, "png", screenshot);
|
| 30209 |
amit.gupta |
543 |
|
| 32146 |
amit.gupta |
544 |
// Copy the element screenshot to disk
|
|
|
545 |
File screenshotLocation = new File(fileName);
|
|
|
546 |
FileUtils.copyFile(screenshot, screenshotLocation);
|
| 30209 |
amit.gupta |
547 |
|
| 32146 |
amit.gupta |
548 |
Imgcodecs imageCodecs = new Imgcodecs();
|
|
|
549 |
Mat grayMatrix = imageCodecs.imread(fileName, Imgcodecs.IMREAD_COLOR);
|
|
|
550 |
Imgproc.cvtColor(grayMatrix, grayMatrix, Imgproc.COLOR_BGR2GRAY);
|
|
|
551 |
Mat medianBlur = new Mat();
|
|
|
552 |
Imgproc.medianBlur(grayMatrix, medianBlur, 5);
|
|
|
553 |
Mat circles = new Mat();
|
|
|
554 |
Imgproc.HoughCircles(medianBlur, circles, Imgproc.HOUGH_GRADIENT, 1, 15, 50, 20, 17, 25);
|
|
|
555 |
return circles;
|
|
|
556 |
}
|
| 30209 |
amit.gupta |
557 |
|
| 34413 |
amit.gupta |
558 |
private double[] getMatCircles2(WebDriver driver, String fileName) throws Exception {
|
|
|
559 |
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
|
|
|
560 |
BufferedImage fullImg = ImageIO.read(screenshot);
|
|
|
561 |
|
|
|
562 |
// Get the location of element on the page
|
| 36583 |
amit |
563 |
WebElement imageElement = driver.findElement(By.xpath("//*[starts-with(@id, 'dx_captcha_basic_bg_')]"));
|
| 34413 |
amit.gupta |
564 |
Point point = imageElement.getLocation();
|
|
|
565 |
|
|
|
566 |
// Get width and height of the element
|
|
|
567 |
int eleWidth = imageElement.getSize().getWidth();
|
|
|
568 |
int eleHeight = imageElement.getSize().getHeight();
|
|
|
569 |
|
|
|
570 |
// Crop the entire page screenshot to get only element screenshot
|
|
|
571 |
BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(),
|
|
|
572 |
eleWidth, eleHeight);
|
|
|
573 |
ImageIO.write(eleScreenshot, "png", screenshot);
|
|
|
574 |
|
|
|
575 |
// Copy the element screenshot to disk
|
|
|
576 |
File screenshotLocation = new File(fileName);
|
|
|
577 |
FileUtils.copyFile(screenshot, screenshotLocation);
|
|
|
578 |
|
|
|
579 |
Mat src = Imgcodecs.imread(fileName);
|
|
|
580 |
if (src.empty()) {
|
|
|
581 |
System.err.println("Cannot read image: " + fileName);
|
| 36253 |
amit |
582 |
new File(fileName).delete();
|
| 34413 |
amit.gupta |
583 |
return null;
|
|
|
584 |
}
|
|
|
585 |
|
|
|
586 |
Mat gray = new Mat();
|
|
|
587 |
Imgproc.cvtColor(src, gray, Imgproc.COLOR_BGR2GRAY);
|
|
|
588 |
Imgproc.GaussianBlur(gray, gray, new Size(9, 9), 2, 2);
|
|
|
589 |
|
|
|
590 |
Mat circles = new Mat();
|
|
|
591 |
Imgproc.HoughCircles(gray, circles, Imgproc.HOUGH_GRADIENT, 1.0,
|
|
|
592 |
20, // min distance between centers
|
|
|
593 |
100, 20, // param1 (Canny high threshold), param2 (accumulator threshold)
|
|
|
594 |
10, 50); // minRadius, maxRadius (adjust as needed)
|
|
|
595 |
|
| 36253 |
amit |
596 |
if (circles.cols() < 2) {
|
|
|
597 |
new File(fileName).delete();
|
|
|
598 |
return null;
|
|
|
599 |
}
|
| 34413 |
amit.gupta |
600 |
|
|
|
601 |
for (int i = 0; i < circles.cols(); i++) {
|
|
|
602 |
double[] c1 = circles.get(0, i);
|
|
|
603 |
for (int j = i + 1; j < circles.cols(); j++) {
|
|
|
604 |
double[] c2 = circles.get(0, j);
|
|
|
605 |
if (Math.abs(c1[2] - c2[2]) < 3) { // check similar radius
|
| 36253 |
amit |
606 |
new File(fileName).delete();
|
| 34413 |
amit.gupta |
607 |
return new double[] {
|
|
|
608 |
c1[0], c2[0] // x-coordinates
|
|
|
609 |
};
|
|
|
610 |
}
|
|
|
611 |
}
|
|
|
612 |
}
|
|
|
613 |
|
| 36253 |
amit |
614 |
new File(fileName).delete();
|
| 34413 |
amit.gupta |
615 |
return null;
|
|
|
616 |
}
|
|
|
617 |
|
|
|
618 |
|
| 30209 |
amit.gupta |
619 |
}
|