H5JsApiPermissionUtil.java 8.95 KB
/*
 * Copyright (c) Wondertek Technologies Co., Ltd. 2019-2022. All rights reserved.
 */

package com.wd.common.utils;

import android.text.TextUtils;

import com.wd.foundation.wdkit.file.MyFileUtils;
import com.wd.foundation.wdkitcore.tools.AppContext;
import com.wd.foundation.wdkitcore.tools.ArrayUtils;
import com.wd.foundation.wdkitcore.tools.JsonUtils;
import com.wd.foundation.wdkitcore.tools.StringUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 描述:设置白名单
 *
 * @author : lvjinhui
 * @since: 2022/5/26
 */
public class H5JsApiPermissionUtil {
    /**
     * 典型实现 HashSet()是一个无序,不可重复的集合
     * */
    private static final Set<String> WHITE_URL_LIST_FOR_JS = new HashSet<>();
    private static final Set<String> WHITE_URL_LIST_FOR_OPEN = new HashSet<>();
    private final String H5_WHITE_HOST_FILE_NAME =  "h5_white_host.txt";
    public static H5JsApiPermissionUtil instance;
    /**
     * false--不校验白名单;ture校验;
     * 默认不用校验
     */
    public static boolean enabled;

    public static H5JsApiPermissionUtil getInstance() {
        if (instance == null) {
            synchronized (H5JsApiPermissionUtil.class) {
                if (instance == null) {
                    instance = new H5JsApiPermissionUtil();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化添加默认白名单
     */
    public void init(){
        addDefaultWhiteList();
        addDefaultWhiteListForOpen();
    }

    /**
     * 默认白名单,1.js交互的
     */
    private static void addDefaultWhiteList() {
        if (WHITE_URL_LIST_FOR_JS != null) {
            WHITE_URL_LIST_FOR_JS.add("cdnpeoplefrontdev.aikan.pdnews.cn");
            WHITE_URL_LIST_FOR_JS.add("cdnpeoplefrontsit.aikan.pdnews.cn");
            WHITE_URL_LIST_FOR_JS.add("cdnpeoplefrontuat.aikan.pdnews.cn");
            WHITE_URL_LIST_FOR_JS.add("cdnpeoplefront.aikan.pdnews.cn");
            WHITE_URL_LIST_FOR_JS.add("pd-people-uat.pdnews.cn");
            WHITE_URL_LIST_FOR_JS.add("pd-people-sit.pdnews.cn");
            WHITE_URL_LIST_FOR_JS.add("pd-people-dev.pdnews.cn");
            WHITE_URL_LIST_FOR_JS.add("www.peopleapp.com");
            WHITE_URL_LIST_FOR_JS.add("h5.peopleapp.com");
        }
    }

    /**
     * 默认白名单=.可以打开
     */
    private static void addDefaultWhiteListForOpen() {
        if (WHITE_URL_LIST_FOR_OPEN != null) {
            WHITE_URL_LIST_FOR_OPEN.add("cdnpeoplefrontdev.aikan.pdnews.cn");
            WHITE_URL_LIST_FOR_OPEN.add("cdnpeoplefrontsit.aikan.pdnews.cn");
            WHITE_URL_LIST_FOR_OPEN.add("cdnpeoplefrontuat.aikan.pdnews.cn");
            WHITE_URL_LIST_FOR_OPEN.add("cdnpeoplefront.aikan.pdnews.cn");
            WHITE_URL_LIST_FOR_OPEN.add("pd-people-uat.pdnews.cn");
            WHITE_URL_LIST_FOR_OPEN.add("pd-people-sit.pdnews.cn");
            WHITE_URL_LIST_FOR_OPEN.add("pd-people-dev.pdnews.cn");
            WHITE_URL_LIST_FOR_OPEN.add("www.peopleapp.com");
            WHITE_URL_LIST_FOR_OPEN.add("h5.peopleapp.com");
        }
    }

    /**
     * 检测是否在白名单内
     * @param inputUrl
     * @return true不拦截
     */
    public boolean isAppWhiteHostForJs(String inputUrl) {
        if (!enabled){
            //不校验
            return true;
        }
        if (TextUtils.isEmpty(inputUrl)) {
            return false;
        }
        if (ArrayUtils.isEmpty(WHITE_URL_LIST_FOR_JS)) {
            return true;
        }
        for (String whiteUrl:WHITE_URL_LIST_FOR_JS) {
            if (inputUrl.contains(whiteUrl)){
                return true;
            }
        }
        return false;
    }

    /**
     * 添加新的白名单
     *
     * @param url
     */
    public void addWhiteListUrlForJs(List<String> url) {
        if (WHITE_URL_LIST_FOR_JS != null) {
            WHITE_URL_LIST_FOR_JS.addAll(url);
        }
    }


    /**
     * 添加新的白名单
     *
     * @param url
     */
    public void addWhiteListUrlForOpen(List<String> url) {
        if (WHITE_URL_LIST_FOR_OPEN != null) {
            WHITE_URL_LIST_FOR_OPEN.addAll(url);
        }
    }

    /**
     * 检测是否在白名单内,是否运行打开
     *
     * @param inputUrl
     * @return true不拦截
     */
    public boolean isAppWhiteHostForOpen(String inputUrl) {
        if (!enabled){
            //不校验
            return true;
        }
        if (TextUtils.isEmpty(inputUrl)) {
            return false;
        }
        if (ArrayUtils.isEmpty(WHITE_URL_LIST_FOR_OPEN)) {
            return true;
        }
        for (String whiteUrl:WHITE_URL_LIST_FOR_OPEN) {
            if (inputUrl.contains(whiteUrl)){
                return true;
            }
        }
        return false;
    }

    /**
     * 保存H5白名单文件,enqueue异步,execute同步
     * @param h5FileStr
     */
    public void saveH5WhiteHostFile(String h5FileStr){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(h5FileStr).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    String fileName = getH5WhiteHostCachePath(H5_WHITE_HOST_FILE_NAME);
                    String tempFileName = "";
                    if(fileName.contains(".")){
                        tempFileName = fileName.substring(0,fileName.lastIndexOf("."))+".temp";
                    }
                    File file = new File(TextUtils.isEmpty(tempFileName) ? fileName : tempFileName);
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                    if(!TextUtils.isEmpty(tempFileName)){
                        file.renameTo(new File(fileName));
                    }
                    //然后读取文件内容添加到白名单
                    addH5WhiteHostList();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    /**
     * 文件是否不存在
     * @return true 不存在, false存在
     */
    public boolean isH5WhiteHostFileNoExists(){
        try {
            File tempFile = getH5WhiteHostFile();
            return !tempFile.exists();
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

    private File getH5WhiteHostFile(){
        String appCachePath = AppContext.getContext().getCacheDir().getAbsolutePath();
        File tempFile = new File(appCachePath, H5_WHITE_HOST_FILE_NAME);
        return tempFile;
    }

    public static String getH5WhiteHostCachePath(String fileName) {
        return new File(AppContext.getContext().getCacheDir(), fileName).getAbsolutePath();
    }

    /**
     * 读取白名单文件
     * @return
     */
     public void addH5WhiteHostList(){
         List<String> hostList = new ArrayList<>();
         File h5WhiteHostFile = getH5WhiteHostFile();
         if (h5WhiteHostFile != null && h5WhiteHostFile.exists()){
             String readJsonData = MyFileUtils.readJsonFile(h5WhiteHostFile);
             if (StringUtils.isNotBlank(readJsonData)){
                 try {
                     JSONObject jsonObject = new JSONObject(readJsonData);
                     if (jsonObject != null) {
                         JSONArray jsonArray = jsonObject.optJSONArray("whiteurls");
                         hostList = JsonUtils.convertJsonArrayToObjList(jsonArray.toString(), String.class);
                         addWhiteListUrlForOpen(hostList);
                         addWhiteListUrlForJs(hostList);
                     }
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
             }
         }
     }



}