FileConfig.java 5.65 KB
package com.bs.fileservice.config;

import com.ruiyun.jvppeteer.core.Puppeteer;
import com.ruiyun.jvppeteer.core.browser.Browser;
import com.ruiyun.jvppeteer.core.browser.BrowserFetcher;
import com.ruiyun.jvppeteer.options.LaunchOptions;
import com.ruiyun.jvppeteer.options.LaunchOptionsBuilder;
import jakarta.servlet.MultipartConfigElement;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import java.io.File;

import org.springframework.core.env.Environment;
import org.springframework.util.unit.DataSize;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

@Slf4j
@Configuration
public class FileConfig {

    @Value("${bs.file.maxFileSize}")
    private Integer maxFileSize;

    @Value("${bs.file.maxRequestSize}")
    private Integer maxRequestSize;

    @Value("${bs.file.browserDir.windows:}")
    private String win64BrowserDir;

    @Value("${bs.file.browserDir.linux:}")
    private String linuxBrowserDir;

    // 浏览器(Chromium)下载镜像地址配置,作为系统属性 PUPPETEER_DOWNLOAD_HOST 的默认值
    @Value("${bs.file.downloadHost:https://npmmirror.com}")
    private String downloadHost;

    // 指定本地已安装的 Chrome/Chromium 可执行文件路径;存在则优先使用本地浏览器,跳过下载
    @Value("${bs.file.executablePath:}")
    private String executablePath;

    // 浏览器无头模式开关;默认开启无头模式
    @Value("${bs.file.headless:true}")
    private Boolean headless;

    @Autowired
    private Environment ent;

    /**
     * Description: springboot对文件上传大小控制
     *
     * @return
     * @interfaceName
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 单个数据大小
        factory.setMaxFileSize(DataSize.ofMegabytes(maxFileSize)); // MB
        // 总上传数据大小
        factory.setMaxRequestSize(DataSize.ofMegabytes(maxRequestSize));
        return factory.createMultipartConfig();
    }

    @Lazy
    @Bean
    public Browser browser() throws IOException, ExecutionException, InterruptedException {
        //设置本地浏览器文件的路径
        String dir = null;
        if (SystemUtils.IS_OS_WINDOWS) {
            dir = win64BrowserDir;
        } else {
            dir = linuxBrowserDir;
        }
        if (StringUtils.isBlank(dir)){
            log.error("请配置无头浏览器地址");
            return null;
        }
        new File(dir).mkdirs();
        System.setProperty("user.dir", dir);
        // 同步设置下载镜像与下载目录到系统属性,供 jvppeteer 下载与缓存使用
        String host = StringUtils.isNotBlank(downloadHost) ? downloadHost : System.getProperty("PUPPETEER_DOWNLOAD_HOST");
        if (StringUtils.isBlank(host)) {
            host = "https://npmmirror.com";
        }
        System.setProperty("PUPPETEER_DOWNLOAD_HOST", host);
        System.setProperty("PUPPETEER_DOWNLOAD_PATH", dir);
        //判断linux系统支持
        if (SystemUtils.IS_OS_LINUX) {
            String command = "cat /etc/centos-release";
            String result = executeCommand(command);
            log.info("CentOS version:" + result);
            if (StringUtils.isNotEmpty(result)) {
                //centos 5.x,6.x不支持
                if (result.contains("release 5.") || result.contains("release 6.")) {
                    log.warn("Skipping browser initialization because the system({}) does not support puppeteer.", result);
                    return null;
                }
            }
        }
        // 若配置了有效的 executablePath,则直接使用本地浏览器;否则按镜像系统属性下载 Chromium
        boolean useLocalChrome = StringUtils.isNotBlank(executablePath) && new File(executablePath).exists();
        if (!useLocalChrome) {
            BrowserFetcher.downloadIfNotExist(null);
        }
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("--no-sandbox");
        arrayList.add("--disable-setuid-sandbox");
        arrayList.add("--disable-extensions");
        // 根据配置设定无头模式;当使用本地浏览器时,注入可执行路径以跳过下载
        LaunchOptionsBuilder builder = new LaunchOptionsBuilder().withProduct("chrome").withArgs(arrayList).withHeadless(Boolean.TRUE.equals(headless));
        if (useLocalChrome) {
            builder = builder.withExecutablePath(executablePath);
        }
        LaunchOptions options = builder.build();
        Browser browser = Puppeteer.launch(options);
        return browser;
    }

    private String executeCommand(String command) {
        StringBuffer output = new StringBuffer();
        Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return output.toString();
    }

}