ScreenshotRemoteImpl.java 9.09 KB
package com.bs.fileservice.service.impl;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.bs.common.core.domain.model.ScreenshotRequest;
import com.bs.fileservice.service.IFileService;
import com.bs.fileservice.service.ScreenshotRemote;
import com.ruiyun.jvppeteer.core.browser.Browser;
import com.ruiyun.jvppeteer.core.page.ElementHandle;
import com.ruiyun.jvppeteer.core.page.Page;
import com.ruiyun.jvppeteer.exception.NavigateException;
import com.ruiyun.jvppeteer.options.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Slf4j
@Service
public class ScreenshotRemoteImpl implements ScreenshotRemote {

    @Autowired(required = false)
    private Browser browser;

    @Autowired
    private IFileService fileService;

    @Retryable(value = {RuntimeException.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2))
    @Override
    public String screenshot(ScreenshotRequest request) throws InterruptedException, IOException, NavigateException {
        StopWatch stopWatch = new StopWatch(request.getUrl());
        stopWatch.start("task1");
        //设置默认参数
        String filename = StringUtils.isNotEmpty(request.getFilename()) ? request.getFilename() : String.valueOf(UUID.randomUUID().toString());
        Integer timeout = request.getTimeout() != null ? request.getTimeout() : 1000 * 10;
        Integer quality = request.getQuality() != null ? request.getQuality() : 80;
        log.info("screenshot image params: {} at {}", request, DateUtil.formatDateTime(new Date()));

        //处理系统不支持Puppeteer情况
        if (browser == null) {
            return "";
        }
        //地址为空
        if (StringUtils.isEmpty(request.getUrl())) {
            return "";
        }

        PageNavigateOptions navigateOptions = new PageNavigateOptions();
        List<String> waitUntil = Lists.newArrayList("networkidle0", "load");
        navigateOptions.setWaitUntil(waitUntil);
        navigateOptions.setTimeout(timeout);

        Page page = browser.newPage();
        try {
            page.setDefaultTimeout(timeout);
//            page.tracing().start("tracing.json");
            page.goTo(request.getUrl(), navigateOptions, true);
//            page.tracing().stop();
//            page.once("load", event -> log.info(event.toString()));
            stopWatch.stop();

            stopWatch.start("task2");
            //根据dom判断是否加载完
            if (StringUtils.isNotEmpty(request.getSelector())) {
                WaitForSelectorOptions waitForSelectorOptions = new WaitForSelectorOptions();
                waitForSelectorOptions.setTimeout(timeout);
                waitForSelectorOptions.setVisible(Boolean.TRUE);
                ElementHandle elementHandle = page.waitForSelector(request.getSelector(), waitForSelectorOptions);
            }

            ScreenshotOptions screenshotOptions = new ScreenshotOptions();
            screenshotOptions.setType(MediaType.IMAGE_JPEG.getSubtype());
            screenshotOptions.setQuality(quality);

            //设置截图范围
            if (request.getClip() == null) {
                screenshotOptions.setFullPage(Boolean.TRUE);
            } else {
                screenshotOptions.setFullPage(Boolean.FALSE);
                screenshotOptions.setClip(new Clip(request.getClip().getX(), request.getClip().getY(), request.getClip().getWidth(), request.getClip().getHeight()));
            }

            //保存到本地
            //screenshotOptions.setPath(filename + ".jpg");

            //执行截图

            String base64Str = page.screenshot(screenshotOptions);
            stopWatch.stop();

            stopWatch.start("task3");
            byte[] buffer = Base64.getDecoder().decode(base64Str);
            stopWatch.stop();
            int imgBufferSize = buffer.length;
            log.info("page screenshot image size:{}", imgBufferSize);
            if (Objects.equals(request.getRetry(), true) && imgBufferSize < 5140) {
                stopWatch.start("task4");
                log.warn("page content:{}", page.content());
                page.reload(navigateOptions);

                base64Str = page.screenshot(screenshotOptions);
                buffer = Base64.getDecoder().decode(base64Str);
                imgBufferSize = buffer.length;
                log.info("reload page screenshot image size:{}", imgBufferSize);
                stopWatch.stop();
            }
            stopWatch.start("task5");
            // 上传文件服务器
            // 转化文件流buffer为MultipartFile
            try {
                MultipartFile file = new MockMultipartFile(
                        filename + ".jpg",
                        filename + ".jpg",
                        MediaType.IMAGE_JPEG_VALUE,
                        buffer
                );
                String url = fileService.uploadFile(file);
                log.info("page screenshot image url:{}", url);
                stopWatch.stop();

                log.info(stopWatch.shortSummary());
                return url;
            } catch (Exception e) {
                log.error("upload screenshot file error", e);
                throw new RuntimeException(e);
            }
        } finally {
            page.close();
        }
    }

    @Retryable(value = {RuntimeException.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2))
    @Override
    public String pdf(ScreenshotRequest request) throws InterruptedException, IOException, NavigateException {
        StopWatch stopWatch = new StopWatch(request.getUrl());
        stopWatch.start("task1");
        //设置默认参数
        String filename = StringUtils.isNotEmpty(request.getFilename()) ? request.getFilename() : String.valueOf(UUID.randomUUID().toString());
        Integer timeout = request.getTimeout() != null ? request.getTimeout() : 1000 * 10;
        log.info("screenshot pdf params: {} at {}", request, DateUtil.formatDateTime(new Date()));

        //处理系统不支持Puppeteer情况
        if (browser == null) {
            return "";
        }
        //地址为空
        if (StringUtils.isEmpty(request.getUrl())) {
            return "";
        }

        PageNavigateOptions navigateOptions = new PageNavigateOptions();
        List<String> waitUntil = Lists.newArrayList("networkidle0", "load");
        navigateOptions.setWaitUntil(waitUntil);
        navigateOptions.setTimeout(timeout);

        Page page = browser.newPage();
        try {
            page.setDefaultTimeout(timeout);
            page.goTo(request.getUrl(), navigateOptions, true);
            stopWatch.stop();

            stopWatch.start("task2");
            //根据dom判断是否加载完
            if (StringUtils.isNotEmpty(request.getSelector())) {
                WaitForSelectorOptions waitForSelectorOptions = new WaitForSelectorOptions();
                waitForSelectorOptions.setTimeout(timeout);
                waitForSelectorOptions.setVisible(Boolean.TRUE);
                ElementHandle elementHandle = page.waitForSelector(request.getSelector(), waitForSelectorOptions);
            }

            PDFOptions pdfOptions = new PDFOptions();
            //执行截图
            byte[] buffer = page.pdf(pdfOptions);
            stopWatch.stop();

            stopWatch.start("task3");
            int imgBufferSize = buffer.length;
            log.info("page screenshot pdf size:{}", imgBufferSize);
            if (Objects.equals(request.getRetry(), true) && imgBufferSize < 5140) {
                stopWatch.start("task4");
                log.warn("page content:{}", page.content());
                page.reload(navigateOptions);

                buffer = page.pdf(pdfOptions);
                imgBufferSize = buffer.length;
                log.info("reload page screenshot pdf size:{}", imgBufferSize);
                stopWatch.stop();
            }

            //上传文件服务器
            try {
                MultipartFile file = new MockMultipartFile(
                        filename + ".pdf",
                        filename + ".pdf",
                        MediaType.APPLICATION_PDF_VALUE,
                        buffer
                );
                String url = fileService.uploadFile(file);
                log.info("page screenshot image url:{}", url);
                stopWatch.stop();

                log.info(stopWatch.shortSummary());
                return url;
            } catch (Exception e) {
                log.error("upload screenshot file error", e);
                throw new RuntimeException(e);
            }
        } finally {
            page.close();
        }
    }
}