001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package io.jboot.web.render.cdn;
017
018import com.jfinal.core.JFinal;
019import io.jboot.Jboot;
020import io.jboot.utils.StrUtil;
021import org.jsoup.Jsoup;
022import org.jsoup.nodes.Document;
023import org.jsoup.nodes.Element;
024import org.jsoup.select.Elements;
025
026import java.io.IOException;
027import java.io.InputStream;
028import java.util.Iterator;
029
030/**
031 * @author Michael Yang 杨福海 (fuhai999@gmail.com)
032 * @version V1.0
033 */
034public class CdnUtil {
035
036    private static String charSet = JFinal.me().getConstants().getEncoding();
037    private static JbootWebCdnConfig cdnConfig = Jboot.config(JbootWebCdnConfig.class);
038
039    public static String appendCdnDomain(String path) {
040        if (StrUtil.isBlank(path)) {
041            return path;
042        }
043
044        if (cdnConfig.isEnable() && StrUtil.isNotBlank(cdnConfig.getDomain())) {
045            if (!path.startsWith("/")) {
046                path = "/" + path;
047            }
048            return cdnConfig.getDomain() + path;
049        }
050
051        return path;
052    }
053
054
055    public static String toHtml(InputStream content, String domain) throws IOException {
056        Document doc = Jsoup.parse(content, charSet, "");
057
058        Elements jsElements = doc.select("script[src]");
059        replace(jsElements, "src", domain);
060
061        Elements imgElements = doc.select("img[src]");
062        replace(imgElements, "src", domain);
063
064        Elements linkElements = doc.select("link");
065        replace(linkElements, "href", domain);
066
067        return doc.toString();
068
069    }
070
071    private static void replace(Elements elements, String attrName, String domain) {
072        Iterator<Element> iterator = elements.iterator();
073        while (iterator.hasNext()) {
074
075            Element element = iterator.next();
076
077            if (element.hasAttr("cdn-exclude")) {
078                continue;
079            }
080
081            String url = element.attr(attrName);
082            if (StrUtil.isBlank(url) || !url.startsWith("/") || url.startsWith("//")) {
083                continue;
084            }
085
086            url = domain + url;
087
088            element.attr(attrName, url);
089        }
090    }
091}