Subversion Repositories SmartDukaan

Rev

Rev 30938 | Go to most recent revision | 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 java.io.File;
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}$");

        /**
         * @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 {
                byte[] fileContent = FileUtils.readFileToByteArray(new File(filePath));
                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();
        }

        class Base64Image {
                private String image;

                public String getImage() {
                        return image;
                }

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

}