Subversion Repositories SmartDukaan

Rev

Rev 36260 | 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.HttpClientFactory;
import com.spice.profitmandi.dao.model.ImeiActivationTimestampModel;
import com.spice.profitmandi.dao.repository.fofo.ActivatedImeiRepository;
import com.spice.profitmandi.service.inventory.InventoryService;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Component
class VivoImeiActivationService {

    @Autowired
    InventoryService inventoryService;

    @Autowired
    CaptchaService captchaService;

    @Autowired
    ActivatedImeiRepository activatedImeiRepository;

    private static final Logger LOGGER = LogManager.getLogger(VivoImeiActivationService.class);

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void checkImeiActivation() throws Exception {
        if (LocalDate.now().getDayOfMonth() == 1) return;

        List<ImeiActivationTimestampModel> imeisActivationList = activatedImeiRepository
                .selectImeiActivationPendingByBrand("Vivo", 2);
        LOGGER.info("Secondary imeisActivationList = {}, size = {}", imeisActivationList, imeisActivationList.size());

        processImeis(imeisActivationList);
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void checkImeiActivationTertiary() throws Exception {
        if (LocalDate.now().getDayOfMonth() == 1) return;

        List<ImeiActivationTimestampModel> imeisActivationList = activatedImeiRepository
                .selectImeiActivationPendingByBrandTertiary("Vivo", 2);
        LOGGER.info("Tertiary imeisActivationList = {}, size = {}", imeisActivationList, imeisActivationList.size());

        processImeis(imeisActivationList);
    }

    private void processImeis(List<ImeiActivationTimestampModel> imeisActivationList) throws Exception {
        if (imeisActivationList.isEmpty()) return;

        BasicCookieStore cookieStore = new BasicCookieStore();
        try (CloseableHttpClient httpClient = HttpClientFactory.apacheHttpWithCookies(cookieStore)) {
            // Seed the session cookies
            HttpGet seed = new HttpGet("https://www.vivo.com/in/support/IMEI");
            try (CloseableHttpResponse seedResponse = httpClient.execute(seed)) {
                EntityUtils.consumeQuietly(seedResponse.getEntity());
            }

            for (ImeiActivationTimestampModel imeiActivationTimestampModel : imeisActivationList) {
                String captchaBreak = this.getNewCaptcha(httpClient, cookieStore);
                this.getImeiActivation(captchaBreak, httpClient, imeiActivationTimestampModel);
            }
        }
    }

    public String getNewCaptcha(CloseableHttpClient httpClient, BasicCookieStore cookieStore) throws Exception {
        String vivoSupportUrl = "https://www.vivo.com/in/support/generatingCodes";
        HttpGet request = new HttpGet(vivoSupportUrl);

        String filePath = "/tmp/captcha.jpg";
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            LOGGER.info("cookie {}", cookieStore.getCookies());
            LOGGER.info("vivoSupportUrl" + vivoSupportUrl);
            byte[] bytes = EntityUtils.toByteArray(response.getEntity());
            Files.write(Paths.get(filePath), bytes);
        }

        String captchaBreak = captchaService.getCaptchaCode(filePath);
        System.out.println("Captcha is " + captchaBreak);
        return captchaBreak;
    }

    public void getImeiActivation(String captchaBreak, CloseableHttpClient httpClient,
                                  ImeiActivationTimestampModel vivoImeiAndActivationTimeStampModel) throws Exception {

        String imei = vivoImeiAndActivationTimeStampModel.getSerialNumber();

        List<NameValuePair> form = new ArrayList<>();
        form.add(new BasicNameValuePair("imei", imei));
        form.add(new BasicNameValuePair("code", captchaBreak));
        HttpPost post = new HttpPost("https://www.vivo.com/in/support/checkCode");
        post.setEntity(new UrlEncodedFormEntity(form, StandardCharsets.UTF_8));

        JSONObject imeiActivationJson;
        try (CloseableHttpResponse response2 = httpClient.execute(post)) {
            imeiActivationJson = new JSONObject(EntityUtils.toString(response2.getEntity()));
        }

        JSONObject data = imeiActivationJson.getJSONObject("data");
        int status = data.getInt("status");
        if (status == 0) {
            LOGGER.info("Found invalid captcha");
            return;
        } else if (status == 2) {
            LOGGER.info("Received status 2 for {}, data {}", imei, data);
            activatedImeiRepository.saveActivation(imei, null);
            return;
        }

        JSONObject imeiQueryDto = data.getJSONObject("imeiQueryDto");
        LOGGER.info("imeiQueryDto - {}", imeiQueryDto);
        String dueTimeString = imeiQueryDto.getString("dueTime");

        if (dueTimeString.equals("")) {
            activatedImeiRepository.saveActivation(imei, null);
            return;
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        dueTimeString = dueTimeString.split(" ")[0];
        LocalDate dueDate = LocalDate.parse(dueTimeString, formatter);

        activatedImeiRepository.saveActivation(imei, dueDate.atStartOfDay().minusYears(1));
        LOGGER.info("activatedImei saved for {} with dueDate {}", imei, dueDate.atStartOfDay());
    }
}