Subversion Repositories SmartDukaan

Rev

Rev 37393 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.smartdukaan.cron.scheduled;

import com.spice.profitmandi.common.web.client.RestClient;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.regex.Pattern;

@Service
public class CaptchaService {

        @Autowired
        RestClient restClient;
        private static final Logger LOGGER = LogManager.getLogger(CaptchaService.class);

        /** The 31 classes the solver model can emit: 123456789ABCDEFGHKMNPQRSTUVWXYZ */
        private static final Pattern CAPTCHA_CODE = Pattern.compile("^[1-9A-HK-NP-Z]{4}$");

        private static final String VERDICT_URL = "http://45.79.121.178/verdict";

        /** Falls back to a property when CAPTCHA_VERDICT_TOKEN is not in the environment. */
        @Value("${captcha.verdict.token:}")
        private String verdictTokenProperty;

        /**
         * @return the 4-character captcha code, or null if the solver did not return
         *         a usable one. Callers must skip the IMEI when this is null rather
         *         than submitting the value to Vivo.
         */
        public String getCaptchaCode(String filePath) throws Exception {
                return getCaptchaCode(FileUtils.readFileToByteArray(new File(filePath)));
        }

        public String getCaptchaCode(byte[] fileContent) throws Exception {
                String encodedString = Base64.getEncoder().encodeToString(fileContent);
                Base64Image base64Image = new Base64Image();
                base64Image.setImage(encodedString);

                String response = restClient.postJson("http://45.79.121.178/uploader", base64Image, new HashMap<>());

                // RestClient returns the body for ANY status, so an nginx 502 page or a
                // solver error payload arrives here looking like a normal result. Anything
                // that is not a real code is rejected instead of being sent to Vivo.
                if (response == null || !CAPTCHA_CODE.matcher(response.trim()).matches()) {
                        LOGGER.error("Captcha solver returned an unusable response: {}",
                                        response == null ? "null" : response.substring(0, Math.min(response.length(), 200)));
                        return null;
                }
                return response.trim();
        }

        /**
         * Tell the solver whether Vivo accepted this code, so samples can be split
         * into training data: accepted means the prediction was right (a free label),
         * rejected means it was wrong (and needs a human to label it).
         *
         * Strictly best-effort. This is data collection - it must never slow down or
         * break IMEI activation, so it has hard timeouts and swallows everything.
         */
        public void reportVerdict(byte[] image, String code, boolean accepted) {
                String token = verdictToken();
                if (token == null || token.isEmpty()) {
                        return;
                }
                HttpURLConnection conn = null;
                try {
                        String body = "{\"image\":\"" + Base64.getEncoder().encodeToString(image)
                                        + "\",\"code\":\"" + code + "\",\"accepted\":" + accepted + "}";
                        conn = (HttpURLConnection) new URL(VERDICT_URL).openConnection();
                        conn.setRequestMethod("POST");
                        conn.setConnectTimeout(2000);
                        conn.setReadTimeout(3000);
                        conn.setDoOutput(true);
                        conn.setRequestProperty("Content-Type", "application/json");
                        conn.setRequestProperty("X-Verdict-Token", token);
                        try (OutputStream os = conn.getOutputStream()) {
                                os.write(body.getBytes(StandardCharsets.UTF_8));
                        }
                        int rc = conn.getResponseCode();
                        if (rc != 200) {
                                LOGGER.warn("verdict report returned HTTP {}", rc);
                        }
                } catch (Exception e) {
                        LOGGER.debug("verdict report failed (non-fatal)", e);
                } finally {
                        if (conn != null) {
                                conn.disconnect();
                        }
                }
        }

        /** Environment wins, so the secret need not be committed to the properties file. */
        private String verdictToken() {
                String env = System.getenv("CAPTCHA_VERDICT_TOKEN");
                return (env != null && !env.isEmpty()) ? env : verdictTokenProperty;
        }

        class Base64Image {
                private String image;

                public String getImage() {
                        return image;
                }

                public void setImage(String image) {
                        this.image = image;
                }
        }

}