Subversion Repositories SmartDukaan

Rev

Rev 30938 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
29337 amit.gupta 1
package com.smartdukaan.cron.scheduled;
2
 
30935 amit.gupta 3
import com.spice.profitmandi.common.web.client.RestClient;
30335 amit.gupta 4
import org.apache.commons.io.FileUtils;
5
import org.apache.logging.log4j.LogManager;
6
import org.apache.logging.log4j.Logger;
30935 amit.gupta 7
import org.springframework.beans.factory.annotation.Autowired;
30335 amit.gupta 8
import org.springframework.stereotype.Service;
29337 amit.gupta 9
 
30335 amit.gupta 10
import java.io.File;
11
import java.util.Base64;
30935 amit.gupta 12
import java.util.HashMap;
37393 amit 13
import java.util.regex.Pattern;
30335 amit.gupta 14
 
29337 amit.gupta 15
@Service
16
public class CaptchaService {
17
 
30935 amit.gupta 18
	@Autowired
19
	RestClient restClient;
30335 amit.gupta 20
	private static final Logger LOGGER = LogManager.getLogger(CaptchaService.class);
29337 amit.gupta 21
 
37393 amit 22
	/** The 31 classes the solver model can emit: 123456789ABCDEFGHKMNPQRSTUVWXYZ */
23
	private static final Pattern CAPTCHA_CODE = Pattern.compile("^[1-9A-HK-NP-Z]{4}$");
24
 
25
	/**
26
	 * @return the 4-character captcha code, or null if the solver did not return
27
	 *         a usable one. Callers must skip the IMEI when this is null rather
28
	 *         than submitting the value to Vivo.
29
	 */
29337 amit.gupta 30
	public String getCaptchaCode(String filePath) throws Exception {
30935 amit.gupta 31
		byte[] fileContent = FileUtils.readFileToByteArray(new File(filePath));
32
		String encodedString = Base64.getEncoder().encodeToString(fileContent);
33
		Base64Image base64Image = new Base64Image();
34
		base64Image.setImage(encodedString);
37393 amit 35
 
36
		String response = restClient.postJson("http://45.79.121.178/uploader", base64Image, new HashMap<>());
37
 
38
		// RestClient returns the body for ANY status, so an nginx 502 page or a
39
		// solver error payload arrives here looking like a normal result. Anything
40
		// that is not a real code is rejected instead of being sent to Vivo.
41
		if (response == null || !CAPTCHA_CODE.matcher(response.trim()).matches()) {
42
			LOGGER.error("Captcha solver returned an unusable response: {}",
43
					response == null ? "null" : response.substring(0, Math.min(response.length(), 200)));
44
			return null;
45
		}
46
		return response.trim();
29337 amit.gupta 47
	}
48
 
30935 amit.gupta 49
	class Base64Image {
50
		private String image;
29337 amit.gupta 51
 
30935 amit.gupta 52
		public String getImage() {
53
			return image;
54
		}
29337 amit.gupta 55
 
30935 amit.gupta 56
		public void setImage(String image) {
57
			this.image = image;
58
		}
59
	}
29337 amit.gupta 60
 
61
}