package com.cm.common.utils.content;

import org.springframework.util.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName: ContentUtil
 * @Description: 内容管理
 * @Author: wenc
 * @Date: 2018/9/17 下午3:02
 * @Version: 1.0
 **/
public class ContentUtil {

    public static Pattern REGEX_SRC = Pattern.compile("(src=\"[^\"]*\")|(href=\"[^\"]*\")");
    public static Pattern REGEX_HTTP = Pattern.compile("(http://)|(https://)");

    /**
     * 将内容中的URL信息不全
     *
     * @param content 内容
     * @param baseUrl 基础链接
     * @return
     */
    public static String buildContentUrlFull(String content, String baseUrl) {
        if (null == baseUrl) {
            baseUrl = "";
        }
        if(StringUtils.isEmpty(content)) {
            return content;
        }
        Matcher matcher = REGEX_SRC.matcher(content);
        while (matcher.find()) {
            String srcContent = matcher.group();
            if(REGEX_HTTP.matcher(srcContent).find()) {
                continue;
            }
            content = content.replace(srcContent, srcContent.replace("=\"", "=\"" + baseUrl));
        }
        return content;
    }

    public static void main(String[] args) {
        System.out.println(ContentUtil.buildContentUrlFull("<img src=\"http://123123123\"/><img src=\"https://123123123\"/><img src=\"sdfff\"/>", "http://127.0.0.1"));
    }

}
