Subversion Repositories SmartDukaan

Rev

Rev 37472 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
29451 manish 1
package com.smartdukaan.cron.scheduled;
2
 
36420 amit 3
import com.spice.profitmandi.common.web.client.HttpClientFactory;
30209 amit.gupta 4
import com.spice.profitmandi.dao.model.ImeiActivationTimestampModel;
5
import com.spice.profitmandi.dao.repository.fofo.ActivatedImeiRepository;
6
import com.spice.profitmandi.service.inventory.InventoryService;
36420 amit 7
import org.apache.http.NameValuePair;
8
import org.apache.http.client.entity.UrlEncodedFormEntity;
9
import org.apache.http.client.methods.CloseableHttpResponse;
10
import org.apache.http.client.methods.HttpGet;
11
import org.apache.http.client.methods.HttpPost;
12
import org.apache.http.impl.client.BasicCookieStore;
13
import org.apache.http.impl.client.CloseableHttpClient;
14
import org.apache.http.message.BasicNameValuePair;
15
import org.apache.http.util.EntityUtils;
29451 manish 16
import org.apache.logging.log4j.LogManager;
17
import org.apache.logging.log4j.Logger;
18
import org.json.JSONObject;
19
import org.springframework.beans.factory.annotation.Autowired;
20
import org.springframework.stereotype.Component;
36260 amit 21
import org.springframework.transaction.annotation.Propagation;
22
import org.springframework.transaction.annotation.Transactional;
29451 manish 23
 
36420 amit 24
import java.io.IOException;
25
import java.nio.charset.StandardCharsets;
30209 amit.gupta 26
import java.time.LocalDate;
27
import java.time.format.DateTimeFormatter;
30335 amit.gupta 28
import java.util.ArrayList;
37472 amit 29
import java.util.HashSet;
30335 amit.gupta 30
import java.util.List;
37472 amit 31
import java.util.Set;
32
import java.util.function.Predicate;
33
import java.util.stream.Collectors;
29451 manish 34
 
35
@Component
36
class VivoImeiActivationService {
37
 
33453 amit.gupta 38
    @Autowired
39
    InventoryService inventoryService;
29451 manish 40
 
33453 amit.gupta 41
    @Autowired
42
    CaptchaService captchaService;
29466 amit.gupta 43
 
33453 amit.gupta 44
    @Autowired
45
    ActivatedImeiRepository activatedImeiRepository;
29451 manish 46
 
33453 amit.gupta 47
    private static final Logger LOGGER = LogManager.getLogger(VivoImeiActivationService.class);
29451 manish 48
 
37472 amit 49
    /** Days an imei rests after an ANSWER. 0 = due again in the next day's pass. */
50
    private static final int DAYS = 0;
51
 
52
    /** Safety stop so a mis-set DAYS cannot pull an unbounded list into memory. */
53
    private static final int POOL_CAP = 20000;
54
 
55
    /**
37565 amit 56
     * Imeis per tick. Ten times the browser lane's because this is direct HTTP, not a
57
     * ChromeDriver: vivo measured 9,723 imeis in 39 minutes on 09-Sep, 0.24s each against
58
     * oppo's 10.2s. At 250 a tick that is ~60s of work per turn and ~52 minutes for the
59
     * whole pool -- a chunk small enough that a restart costs little, large enough that
60
     * the 20s gap between ticks stays a rounding error rather than a third of the budget.
61
     */
62
    private static final int CHUNK = 250;
63
 
64
    /**
65
     * The day this lane is working through; null until the first tick ever.
37472 amit 66
     *
37565 amit 67
     * volatile because consecutive ticks of a fixedDelay job are serialised but NOT
68
     * pinned to one thread -- they land on whichever scheduled-task-pool thread is free.
69
     * The executor does establish happens-before between them, so this is belt and
70
     * braces; without it a stale read would re-log the day boundary and re-fetch the
71
     * whole pool on every tick.
72
     */
73
    private volatile LocalDate day;
74
 
75
    /** Whether today's pool has already come back empty, so the cleared line is logged once. */
76
    private volatile boolean cleared;
77
 
78
    /**
79
     * ONE CHUNK PER TICK until the day's pool is empty, then nothing until tomorrow.
37472 amit 80
     *
37565 amit 81
     * Called every 20 seconds on its OWN lane. Vivo must not share the browser lane: it
82
     * is direct HTTP plus the captcha solver at 0.24s an imei, against oppo's 10.2s and
83
     * realme's 14.2s through a ChromeDriver. Behind them in one rotation its ~9,700 imeis
84
     * would need 389 turns at roughly eleven minutes a cycle -- about 70 hours, for work
85
     * that takes it 39 minutes alone. Separate lanes also mean it never contends for the
86
     * resource the browser lane is rationing, since it opens no driver at all.
37472 amit 87
     *
37565 amit 88
     * Before the daily pass this was two @Scheduled jobs every 5 minutes capped at 50 and
89
     * 10 imeis, which never finished a pass over a 9,510-row pool and retried a failed
90
     * lookup five minutes later instead of the next day. Returning to a tick does NOT
91
     * reopen that. The runaway was caused by failures writing no row, and every outcome
92
     * vivo actually ANSWERS is stamped: status 2, an empty dueTime and a real date all
93
     * reach saveActivation, so those imeis leave today's pool. The pool query is the only
94
     * cursor; there is no snapshot to lose to a restart.
95
     *
96
     * Three paths still stamp nothing, and none of them can run away:
97
     *   - a REJECTED CAPTCHA returns without a row, so the imei comes back on a later
98
     *     tick. That converges rather than loops -- the solver is right about 89% of the
99
     *     time, so an imei needs ~1.1 attempts -- and it is strictly better than the daily
100
     *     pass, where one wrong captcha cost that imei a full day.
101
     *   - a line item with NO SERIAL is skipped, and the pool query excludes it anyway.
102
     *   - a DEAD SOLVER abandons the tick, not the day. It spends one request per 20s
103
     *     instead of a chunk's worth, and recovers by itself.
104
     *
37472 amit 105
     * The 1st-of-month skip is kept -- vivo's own portal is unreliable on that day.
106
     */
36260 amit 107
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
33453 amit.gupta 108
    public void checkImeiActivation() throws Exception {
109
        if (LocalDate.now().getDayOfMonth() == 1) return;
36253 amit 110
 
37565 amit 111
        boolean dayStart = !LocalDate.now().equals(day);
112
        List<ImeiActivationTimestampModel> due = pending(dayStart ? POOL_CAP : CHUNK);
36253 amit 113
 
37565 amit 114
        if (dayStart) {
115
            day = LocalDate.now();
116
            cleared = false;
117
            LOGGER.info("Vivo day begin: {} imeis due", due.size());
118
        }
37472 amit 119
 
37565 amit 120
        if (due.isEmpty()) {
121
            // Cleared for today. One line, then silence until midnight -- at a 20-second
122
            // tick, logging every idle turn is 4,320 lines a day.
123
            if (!cleared) {
124
                cleared = true;
125
                LOGGER.info("Vivo day cleared");
126
            }
127
            return;
128
        }
37472 amit 129
 
37565 amit 130
        processImeis(due.size() <= CHUNK ? due : due.subList(0, CHUNK));
36253 amit 131
    }
132
 
37565 amit 133
    /**
134
     * Vivo's own pool, as one de-duplicated list capped at maxResults.
135
     *
136
     * Unlike the browser lane this concatenates rather than interleaves, and can: vivo
137
     * clears its whole pool in well under an hour, so the tail is always reached and
138
     * ordering cannot starve the tertiary queue.
139
     */
140
    private List<ImeiActivationTimestampModel> pending(int maxResults) {
141
        List<ImeiActivationTimestampModel> pool = new ArrayList<>();
142
        pool.addAll(activatedImeiRepository.selectImeiActivationPendingByBrand("Vivo", DAYS, maxResults));
143
        pool.addAll(activatedImeiRepository.selectImeiActivationPendingByBrandTertiary("Vivo", DAYS, maxResults));
144
        return pool.stream()
145
                .filter(distinctBySerial())
146
                .limit(maxResults)
147
                .collect(Collectors.toList());
148
    }
149
 
37472 amit 150
    private static Predicate<ImeiActivationTimestampModel> distinctBySerial() {
151
        Set<String> seen = new HashSet<>();
152
        return m -> seen.add(m.getSerialNumber());
36253 amit 153
    }
154
 
155
    private void processImeis(List<ImeiActivationTimestampModel> imeisActivationList) throws Exception {
156
        if (imeisActivationList.isEmpty()) return;
157
 
36420 amit 158
        BasicCookieStore cookieStore = new BasicCookieStore();
159
        try (CloseableHttpClient httpClient = HttpClientFactory.apacheHttpWithCookies(cookieStore)) {
160
            // Seed the session cookies
161
            HttpGet seed = new HttpGet("https://www.vivo.com/in/support/IMEI");
162
            try (CloseableHttpResponse seedResponse = httpClient.execute(seed)) {
163
                EntityUtils.consumeQuietly(seedResponse.getEntity());
33453 amit.gupta 164
            }
29466 amit.gupta 165
 
36420 amit 166
            for (ImeiActivationTimestampModel imeiActivationTimestampModel : imeisActivationList) {
37408 amit 167
                // Never spend a captcha on a line item with no IMEI. Vivo answers
168
                // those with {"msg":"参数为空"} ("parameter is empty") and status 0,
169
                // which this code used to record as a captcha failure -- so a correct
170
                // code looked wrong, the row was never saved, and it came back every
171
                // 5 minutes forever. That was 76% of all rejections.
172
                String serial = imeiActivationTimestampModel.getSerialNumber();
173
                if (serial == null || serial.trim().isEmpty()) {
174
                    LOGGER.warn("Skipping activation lookup: line item has no serial number");
175
                    continue;
176
                }
177
 
37402 amit 178
                Captcha captcha = this.getNewCaptcha(httpClient, cookieStore);
179
                if (captcha == null) {
37393 amit 180
                    // Solver returned something that is not a captcha code (it was down
181
                    // for 46 days returning an nginx 502 page, which used to be submitted
37565 amit 182
                    // to Vivo verbatim).
183
                    //
184
                    // BREAK, not continue: the solver is a shared dependency, so one null
185
                    // means the next 249 are almost certainly null too. Continuing spends
186
                    // a whole chunk of HTTP calls on a box with 957MB of RAM to learn the
187
                    // same thing 250 times. Abandoning the tick costs nothing -- no row is
188
                    // stamped, so every imei here is still due -- and the next tick probes
189
                    // again in 20 seconds with a single call. Deliberately NOT stamped:
190
                    // a solver outage is not a verdict on the imei, and resting the pool
191
                    // over it would forfeit the day's ~9,700 lookups over a transient blip.
192
                    LOGGER.warn("Vivo captcha solver returned no code; abandoning this tick");
193
                    break;
37393 amit 194
                }
37407 amit 195
                this.getImeiActivation(captcha, httpClient, cookieStore, imeiActivationTimestampModel);
33453 amit.gupta 196
            }
36253 amit 197
        }
33453 amit.gupta 198
    }
29451 manish 199
 
37402 amit 200
    /** A solved captcha: the code, plus the image it came from so the verdict can be reported. */
201
    static final class Captcha {
202
        final String code;
203
        final byte[] image;
37407 amit 204
        final long fetchedAt;
29451 manish 205
 
37402 amit 206
        Captcha(String code, byte[] image) {
207
            this.code = code;
208
            this.image = image;
37407 amit 209
            this.fetchedAt = System.currentTimeMillis();
37402 amit 210
        }
211
    }
212
 
213
    public Captcha getNewCaptcha(CloseableHttpClient httpClient, BasicCookieStore cookieStore) throws Exception {
214
        HttpGet request = new HttpGet("https://www.vivo.com/in/support/generatingCodes");
215
 
216
        // Kept in memory rather than written to a shared /tmp/captcha.jpg: the two
217
        // Vivo jobs run concurrently and used to overwrite each other's image. The
218
        // bytes are needed for the verdict report anyway.
219
        byte[] bytes;
36420 amit 220
        try (CloseableHttpResponse response = httpClient.execute(request)) {
37402 amit 221
            bytes = EntityUtils.toByteArray(response.getEntity());
36253 amit 222
        }
29451 manish 223
 
37402 amit 224
        String code = captchaService.getCaptchaCode(bytes);
225
        return code == null ? null : new Captcha(code, bytes);
33453 amit.gupta 226
    }
29451 manish 227
 
37402 amit 228
    public void getImeiActivation(Captcha captcha, CloseableHttpClient httpClient,
37407 amit 229
                                  BasicCookieStore cookieStore,
33453 amit.gupta 230
                                  ImeiActivationTimestampModel vivoImeiAndActivationTimeStampModel) throws Exception {
29451 manish 231
 
33453 amit.gupta 232
        String imei = vivoImeiAndActivationTimeStampModel.getSerialNumber();
29466 amit.gupta 233
 
36420 amit 234
        List<NameValuePair> form = new ArrayList<>();
235
        form.add(new BasicNameValuePair("imei", imei));
37402 amit 236
        form.add(new BasicNameValuePair("code", captcha.code));
36420 amit 237
        HttpPost post = new HttpPost("https://www.vivo.com/in/support/checkCode");
238
        post.setEntity(new UrlEncodedFormEntity(form, StandardCharsets.UTF_8));
29466 amit.gupta 239
 
36253 amit 240
        JSONObject imeiActivationJson;
36420 amit 241
        try (CloseableHttpResponse response2 = httpClient.execute(post)) {
242
            imeiActivationJson = new JSONObject(EntityUtils.toString(response2.getEntity()));
36253 amit 243
        }
244
 
33453 amit.gupta 245
        JSONObject data = imeiActivationJson.getJSONObject("data");
246
        int status = data.getInt("status");
37402 amit 247
 
248
        // Vivo is the only judge of whether our guess was right; status 0 means the
249
        // captcha was wrong. Hand that back so the sample becomes training data.
250
        captchaService.reportVerdict(captcha.image, captcha.code, status != 0);
251
 
33453 amit.gupta 252
        if (status == 0) {
37407 amit 253
            // Vivo refuses ~56% of submissions in production, but reading the stored
254
            // images by hand showed 9 of 10 carried the CORRECT code, and no external
255
            // replication reproduces it (IMEI, user-agent, session reuse, concurrency,
256
            // source IP and submit delay were all measured and ruled out). The old log
257
            // line recorded five words and discarded the evidence, so capture it:
258
            // the code submitted, the imei, how long fetch->submit actually took inside
259
            // this process, the session cookies held at submit time, and Vivo's reply.
260
            LOGGER.info("Vivo rejected captcha code={} imei={} elapsedMs={} cookies={} response={}",
261
                    captcha.code, imei, System.currentTimeMillis() - captcha.fetchedAt,
262
                    cookieStore.getCookies(), imeiActivationJson);
33453 amit.gupta 263
            return;
264
        } else if (status == 2) {
265
            LOGGER.info("Received status 2 for {}, data {}", imei, data);
36253 amit 266
            activatedImeiRepository.saveActivation(imei, null);
33453 amit.gupta 267
            return;
268
        }
29451 manish 269
 
33453 amit.gupta 270
        JSONObject imeiQueryDto = data.getJSONObject("imeiQueryDto");
271
        LOGGER.info("imeiQueryDto - {}", imeiQueryDto);
272
        String dueTimeString = imeiQueryDto.getString("dueTime");
29466 amit.gupta 273
 
36253 amit 274
        if (dueTimeString.equals("")) {
275
            activatedImeiRepository.saveActivation(imei, null);
276
            return;
33453 amit.gupta 277
        }
29469 amit.gupta 278
 
33453 amit.gupta 279
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
280
        dueTimeString = dueTimeString.split(" ")[0];
281
        LocalDate dueDate = LocalDate.parse(dueTimeString, formatter);
30343 amit.gupta 282
 
36253 amit 283
        activatedImeiRepository.saveActivation(imei, dueDate.atStartOfDay().minusYears(1));
284
        LOGGER.info("activatedImei saved for {} with dueDate {}", imei, dueDate.atStartOfDay());
33453 amit.gupta 285
    }
36253 amit 286
}