Input:
import com.tokensTool.pandoraNext.pojo.Result;
import com.tokensTool.pandoraNext.pojo.poolToken;
import com.tokensTool.pandoraNext.pojo.systemSetting;
import com.tokensTool.pandoraNext.pojo.token;
import com.tokensTool.pandoraNext.service.impl.apiServiceImpl;
import com.tokensTool.pandoraNext.service.impl.poolServiceImpl;
import com.tokensTool.pandoraNext.service.impl.systemServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;

Context:
rearServer/src/main/java/com/tokensTool/pandoraNext/controller/tokenController.java
package com.tokensTool.pandoraNext.controller;

/**
 * @author Yangyang
 * @create 2023-11-29 10:22
 */
@RestController
public class tokenController {

    @Value("${server.servlet.context-path}")
    private String profix;

    @Autowired
    private systemServiceImpl systemService;

    @Autowired
    private apiServiceImpl apiService;

    @Autowired
    private poolServiceImpl poolService;

    /**
     * 获取全部share_tokens
     * 返回share_tokens或Not_Login
     */
    @GetMapping("/shared_token")
    public Result getSharedToken(@RequestParam("password") String password) {
        List<String> res = new ArrayList<>();
        systemSetting systemSetting = systemService.selectSetting();
        if (!systemSetting.getIsGetToken()) {
            return Result.error("Not_Open");
        }
        if (password.equals(systemSetting.getGetTokenPassword())) {
            for (token token : apiService.selectToken("")) {
                res.add(token.getShare_token());
            }
            return Result.success(res);
        } else {
            return Result.error("Not_Login");
        }
    }

    /**
     * 获取指定share_token
     * 返回share_token或Not_Login
     */
    @GetMapping("/token/shared_token")
    public Result getSimplySharedToken(@RequestParam("password") String password,
                                       @RequestParam("tokenName") String tokenName) {
        systemSetting systemSetting = systemService.selectSetting();
        if (!systemSetting.getIsGetToken()) {
            return Result.error("Not_Open");
        }
        if (password.equals(systemSetting.getGetTokenPassword())) {
            for (token token : apiService.selectToken("")) {
                if (token.getName().equals(tokenName)) {
                    if (token.getShare_token() != null) {
                        return Result.success(token.getShare_token());
                    }
                    return Result.error("该tokenName没有存放Shared_Token");
                }
            }
            return Result.error("未找到该tokenName！");
        } else {
            return Result.error("Not_Login");
        }

    }

    /**
     * 获取全部access_token
     * 返回access_token或Not_Login
     */
    @GetMapping("/access_token")
    public Result getAccessToken(@RequestParam("password") String password) {
        List<String> res = new ArrayList<>();
        systemSetting systemSetting = systemService.selectSetting();
        if (!systemSetting.getIsGetToken()) {
            return Result.error("Not_Open");
        }
        if (password.equals(systemSetting.getGetTokenPassword())) {
            for (token token : apiService.selectToken("")) {
                res.add(token.getAccess_token());
            }
            return Result.success(res);
        } else {
            return Result.error("Not_Login");
        }
    }

    /**
     * 获取指定access_token
     * 返回access_token或Not_Login
     */
    @GetMapping("/token/access_token")
    public Result getSimplyAccessToken(@RequestParam("password") String password,
                                       @RequestParam("tokenName") String tokenName) {
        systemSetting systemSetting = systemService.selectSetting();
        if (!systemSetting.getIsGetToken()) {
            return Result.error("Not_Open");
        }
        if (password.equals(systemSetting.getGetTokenPassword())) {
            for (token token : apiService.selectToken("")) {
                if (token.getName().equals(tokenName)) {
                    if (token.getAccess_token() != null) {
                        return Result.success(token.getAccess_token());
                    }
                    return Result.error("该tokenName没有存放Access_Token");
                }
            }
            return Result.error("未找到该tokenName！");
        } else {
            return Result.error("Not_Login");
        }
    }

    /**
     * 获取单个pool_token
     * 返回pool_token或Not_Login
     */
    @GetMapping("/token/pool_token")
    public Result getSimplePoolToken(@RequestParam("password") String password,
                                     @RequestParam("tokenName") String tokenName) {

rearServer/src/main/java/com/tokensTool/pandoraNext/service/impl/apiServiceImpl.java
@Slf4j
@Service
public class apiServiceImpl implements apiService {
    /**
     * 登录接口获取session_token或者access_token
     */
    private final String sessionToken = "/api/auth/login";
    /**
     * 登录接口获取refresh_token
     */
    private final String refreshToken = "/api/auth/login2";

    /**
     * 把refresh_token转化成access_token
     */
    private final String reAccessToken = "/api/auth/refresh";

    /**
     * 把session_token转化成access_token
     */
    private final String accessToken = "/api/auth/session";

    /**
     * 把access_token转化为share_token
     */
    private final String shareToken = "/api/token/register";

    /**
     * 把share_token转化成pool_token
     */
    private final String poolToken = "/api/pool/update";
    /**
     * 部署路径为默认的话，自动识别jar包路径下的文件
     */
    private final String deploy = "default";
    @Value("${deployPosition}")
    private String deployPosition;
    @Autowired
    private systemServiceImpl systemService;

    public String initializeTokenJson() {
        try {
            String parent = selectFile();
            ObjectMapper objectMapper = new ObjectMapper();
            // 读取JSON文件并获取根节点
            JsonNode rootNode = objectMapper.readTree(new File(parent));
            // 遍历根节点的所有子节点
            if (rootNode.isObject()) {
                ObjectNode rootObjectNode = (ObjectNode) rootNode;
                // 遍历所有子节点
                Iterator<Map.Entry<String, JsonNode>> fields = rootObjectNode.fields();
                while (fields.hasNext()) {
                    Map.Entry<String, JsonNode> entry = fields.next();
                    // 获取子节点的名称
                    String nodeName = entry.getKey();
                    // 获取子节点
                    JsonNode nodeToModify = entry.getValue();
                    if (nodeToModify != null && nodeToModify.isObject()) {
                        // 创建新的 ObjectNode，并复制原始节点内容
                        ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();
                        newObjectNode.setAll(rootObjectNode);
                        // 获取要修改的节点
                        ObjectNode nodeToModifyInNew = newObjectNode.with(nodeName);
                        // 初始化checkSession的值为true
                        if (!nodeToModifyInNew.has("useRefreshToken")) {
                            nodeToModifyInNew.put("useRefreshToken", false);
                            log.info("为节点 " + nodeName + " 添加 useRefreshToken 变量成功！");
                        }
                        // 将修改后的 newObjectNode 写回文件
                        objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);
                    }
                }
                return "为所有子节点添加 useRefreshToken 变量成功！";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "为所有子节点添加 useRefreshToken 变量失败！";
    }

    /**
     * 通过判断是否需要自定义查询tokens.json文件位置
     *
     * @return tokens.json文件位置
     * @throws IOException
     */
    public String selectFile() throws IOException {
        String projectRoot;
        if (deploy.equals(deployPosition)) {
            projectRoot = System.getProperty("user.dir");
        } else {
            projectRoot = deployPosition;
        }
        String parent = projectRoot + File.separator + "tokens.json";
        File jsonFile = new File(parent);
        Path jsonFilePath = Paths.get(parent);
        // 如果 JSON 文件不存在或为空，创建一个新的 JSON 对象
        if (!jsonFile.exists() || jsonFile.length() == 0) {
            // 创建文件
            Files.createFile(jsonFilePath);
            System.out.println("tokens.json创建完成: " + jsonFilePath);
            // 往 tokens.json 文件中添加一个空数组，防止重启报错
            Files.writeString(jsonFilePath, "{}");
            System.out.println("空数组添加完成");
        }
        return parent;
    }

    /**
     * 打印token全部
     *
     * @return res（List<token> ）
     */
    @Override
    public List<token> selectToken(String name) {
        List<token> res = new ArrayList<>();
        try {
            String parent = selectFile();
            log.info("请求路径查询token：" + parent);
            File jsonFile = new File(parent);
            ObjectMapper objectMapper = new ObjectMapper();
            // 如果 JSON 文件不存在或为空，则创建一个新的 JSON 对象并写入空数组
            if (!jsonFile.exists() || jsonFile.length() == 0) {
                Files.writeString(Paths.get(parent), "{}");
                log.info("未找到tokens.json,新建tokens.json并初始化tokens.json成功！");
                return res;
            }
            // 读取JSON文件并获取根节点
            JsonNode rootNode = objectMapper.readTree(new File(parent));
            // 遍历所有字段
            Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields();
            while (fields.hasNext()) {
                Map.Entry<String, JsonNode> entry = fields.next();
                String nodeName = entry.getKey();
                if (nodeName.contains(name)) {
                    token temRes = new token();
                    temRes.setName(nodeName);
                    // 获取对应的节点
                    JsonNode temNode = rootNode.get(nodeName);
                    temRes.setUsername(temNode.has("username") ? temNode.get("username").asText() : "");
                    temRes.setToken(temNode.has("token") ? temNode.get("token").asText() : "");
                    temRes.setAccess_token(temNode.has("access_token") ? temNode.get("access_token").asText() : "未开启pool_token无法生成");
                    temRes.setShare_token(temNode.has("share_token") ? temNode.get("share_token").asText() : "未开启pool_token无法生成");
                    temRes.setUserPassword(temNode.has("userPassword") ? temNode.get("userPassword").asText() : "");
                    temRes.setShared(temNode.has("shared") && temNode.get("shared").asBoolean());
                    temRes.setShow_user_info(temNode.has("show_user_info") && temNode.get("show_user_info").asBoolean());
                    temRes.setPlus(temNode.has("plus") && temNode.get("plus").asBoolean());
                    temRes.setSetPoolToken(temNode.has("setPoolToken") && temNode.get("setPoolToken").asBoolean());
                    temRes.setPassword(temNode.has("password") ? temNode.get("password").asText() : "");
                    temRes.setUpdateTime(temNode.has("updateTime") ? temNode.get("updateTime").asText() : "");
                    temRes.setUseRefreshToken(temNode.has("useRefreshToken") && temNode.get("useRefreshToken").asBoolean());
                    //是否session有效
                    temRes.setCheckSession(!temNode.has("checkSession") || temNode.get("checkSession").asBoolean());
                    res.add(temRes);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return res;
    }

    /**
     * 添加checkSession变量,初始化为true
     * 启动的时候自动全部添加
     */
    public String initializeCheckSession() {
        try {
            String parent = selectFile();
            ObjectMapper objectMapper = new ObjectMapper();

            // 读取JSON文件并获取根节点
            JsonNode rootNode = objectMapper.readTree(new File(parent));

            // 遍历根节点的所有子节点
            if (rootNode.isObject()) {
                ObjectNode rootObjectNode = (ObjectNode) rootNode;

                // 遍历所有子节点
                Iterator<Map.Entry<String, JsonNode>> fields = rootObjectNode.fields();
                while (fields.hasNext()) {
                    Map.Entry<String, JsonNode> entry = fields.next();

                    // 获取子节点的名称
                    String nodeName = entry.getKey();

                    // 获取子节点
                    JsonNode nodeToModify = entry.getValue();

                    if (nodeToModify != null && nodeToModify.isObject()) {
                        // 创建新的 ObjectNode，并复制原始节点内容
                        ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();
                        newObjectNode.setAll(rootObjectNode);

                        // 获取要修改的节点
                        ObjectNode nodeToModifyInNew = newObjectNode.with(nodeName);

                        // 初始化checkSession的值为true
                        if (!nodeToModifyInNew.has("checkSession")) {
                            nodeToModifyInNew.put("checkSession", true);
                            log.info("为节点 " + nodeName + " 添加 checkSession 变量成功！");
                        }

                        // 将修改后的 newObjectNode 写回文件
                        objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);
                    }
                }
                return "为所有子节点添加 checkSession 变量成功！";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "为所有子节点添加 checkSession 变量失败！";
    }

    /**
     * 添加token
     * 并添加对应keys
     *
     * @return "添加成功！"or"添加失败,检查你的token是否正确或登录是否过期！"
     */
    @Override
    public String addToken(token token) {
        String res = "";
        //不填token,填账号密码
        if (token.getToken() == null || token.getToken().length() == 0) {
            if (token.isUseRefreshToken()) {
                res = updateRefreshToken(token);
            } else {
                res = updateSessionToken(token);
            }
            if (res != null) {
                token.setToken(res);
            } else {
                return "添加失败,检查你的账号密码是否正确或刷新token网址有误！";
            }
        }
        try {
            String parent = selectFile();
            File jsonFile = new File(parent);
            Path jsonFilePath = Paths.get(parent);
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode rootNode;
            // 如果 JSON 文件不存在，创建一个新的 JSON 对象
            if (!jsonFile.exists()) {
                // 创建文件
                Files.createFile(jsonFilePath);
                log.info("tokens.json创建完成: " + jsonFilePath);
                rootNode = objectMapper.createObjectNode();
            } else {
                if (Files.exists(jsonFilePath) && Files.size(jsonFilePath) > 0) {
                    rootNode = objectMapper.readTree(jsonFile).deepCopy();
                } else {
                    rootNode = objectMapper.createObjectNode();
                }
            }
            // 创建要添加的新数据
            ObjectNode newData = objectMapper.createObjectNode();

            newData.put("token", token.getToken());

            String access_token = null;
            if (token.isSetPoolToken()) {
                access_token = getAccessToken(token);
                if (access_token != null) {
                    newData.put("access_token", access_token);
                    token.setAccess_token(access_token);
                    String share_token = getShareToken(token);
                    if (share_token != null && share_token.length() > 0) {
                        token.setShare_token(share_token);
                        newData.put("share_token", share_token);
                    }
                } else {
                    if (token.isUseRefreshToken()) {
                        return "添加失败！请确保自己填写的token为正确的refresh_token";
                    } else {
                        return "添加失败！请确保自己填写的token为正确的session_token";
                    }
                }
            }

            newData.put("username", token.getUsername());
            newData.put("userPassword", token.getUserPassword());
            newData.put("shared", token.isShared());
            newData.put("show_user_info", token.isShow_user_info());
            newData.put("plus", token.isPlus());
            newData.put("setPoolToken", token.isSetPoolToken());
            //是否使用refresh_token来进行
            newData.put("useRefreshToken", token.isUseRefreshToken());
            newData.put("checkSession", true);

            // 检查是否需要 TokenPassword
            if (token.getPassword() != null && token.getPassword().length() > 0) {
                newData.put("password", token.getPassword());
            } else {
                newData.put("password", "");
            }
            LocalDateTime now = LocalDateTime.now();
            newData.put("updateTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            // 将新数据添加到 JSON 树中
            rootNode.put(token.getName(), newData);
            // 将修改后的数据写回到文件
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile, rootNode);
            return "添加成功！";
        } catch (IOException e) {
            e.printStackTrace();
            return "添加失败！";
        }
    }

    /**
     * 修改token值或者其他
     *
     * @return "修改成功！"or"修改失败"or修改失败,检查你的token是否正确！
     */
    @Override
    public String requiredToken(token tem) {
        try {
            String parent = selectFile();
            ObjectMapper objectMapper = new ObjectMapper();
            // 读取JSON文件并获取根节点
            JsonNode rootNode = objectMapper.readTree(new File(parent));
            // 要修改的节点名称
            String nodeNameToModify = tem.getName();
            // 获取要修改的节点
            JsonNode nodeToModify = rootNode.get(nodeNameToModify);
            if (nodeToModify != null && nodeToModify.isObject()) {
                // 创建新的 ObjectNode，并复制原始节点内容
                ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();
                newObjectNode.setAll((ObjectNode) rootNode);
                // 获取要修改的节点
                ObjectNode nodeToModifyInNew = newObjectNode.with(nodeNameToModify);
                // 获取之前的节点值
                String previousToken = nodeToModifyInNew.has("token") ? nodeToModifyInNew.get("token").asText() : null;
                boolean previousSetPoolToken = nodeToModifyInNew.has("setPoolToken") && nodeToModifyInNew.get("setPoolToken").asBoolean();
                // 获取之前的节点值
                boolean previousUseRefreshToken = nodeToModifyInNew.has("useRefreshToken") && nodeToModifyInNew.get("useRefreshToken").asBoolean();
                // 初始修改相应的值
                require_beginToken(tem, nodeToModifyInNew);

                //web条件 api转web web转api 消耗余额
                if (previousSetPoolToken != tem.isSetPoolToken()) {
                    if (!tem.isSetPoolToken()) {
                        nodeToModifyInNew.put("token", tem.getUsername() + "," + tem.getUserPassword());
                        nodeToModifyInNew.put("share_token", "未开启API开关无法生成");
                        nodeToModifyInNew.put("access_token", "未开启API开关无法生成");
                        LocalDateTime now = LocalDateTime.now();
                        nodeToModifyInNew.put("updateTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        // 将修改后的 newObjectNode 写回文件
                        objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);
                        return "修改成功！";
                    }
                    // token相同的情况下 web 转 session_token
                    else if (!tem.isUseRefreshToken() && previousToken.equals(tem.getToken())) {
                        String reSessionToken = updateSessionToken(tem);
                        if (reSessionToken != null) {
                            reupdate(reSessionToken, tem, nodeToModifyInNew);
                        } else {
                            return "修改失败，请确保你的账号密码是否正确且proxy的url配置是否正确，或者余额不足";
                        }
                    }
                    // token相同的情况下 web 转 refresh_token
                    else if (tem.isUseRefreshToken() && previousToken.equals(tem.getToken())) {
                        String refreshToken = updateRefreshToken(tem);
                        if (refreshToken != null) {
                            reupdate(refreshToken, tem, nodeToModifyInNew);
                        } else {
                            return "修改失败，请确保你的账号密码是否正确且proxy的url配置是否正确，或者余额不足";
                        }
                    }
                }

                // token不相同，直接看token是否对应
                // web转api 填写相应的token
                // session和refresh之间的互转 填写相应的token

                if (!previousToken.equals(tem.getToken())) {
                    String access_token = getAccessToken(tem);
                    if (access_token != null) {
                        tem.setAccess_token(access_token);
                        String share_token = getShareToken(tem);
                        nodeToModifyInNew.put("access_token", access_token);
                        if (share_token != null) {
                            nodeToModifyInNew.put("checkSession", true);
                            nodeToModifyInNew.put("share_token", share_token);
                        } else {
                            return "access_token转share_token失败！";
                        }
                        // 将修改后的 newObjectNode 写回文件
                        LocalDateTime now = LocalDateTime.now();
                        nodeToModifyInNew.put("updateTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);
                        return "修改成功！";
                    } else {
                        return tem.isUseRefreshToken() ? "添加失败！请填写正确的refresh_token或关闭使用refresh_token后重新尝试" : "修改失败！请填写正确的session_token或开启使用refresh_token后重新尝试";
                    }
                }

                // 在不改变token的值的API模式下，session和refresh之间的互相转换
                if (previousUseRefreshToken != tem.isUseRefreshToken()) {
                    if (tem.isUseRefreshToken()) {
                        String refreshToken = updateRefreshToken(tem);
                        if (refreshToken != null) {
                            reupdate(refreshToken, tem, nodeToModifyInNew);
                        } else {
                            return "修改失败，请确保你的账号密码是否正确且proxy的url配置是否正确，或者余额不足";
                        }
                    } else {
                        String reSessionToken = updateSessionToken(tem);
                        if (reSessionToken != null) {
                            reupdate(reSessionToken, tem, nodeToModifyInNew);
                        } else {
                            return "修改失败，请确保你的账号密码是否正确且proxy的url配置是否正确，或者余额不足";
                        }
                    }
                }
                // 将修改后的 newObjectNode 写回文件
                objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);
                return "修改成功！";
            } else {
                log.info("节点未找到或不是对象,请检查tokens.json！ " + nodeNameToModify);
                return "节点未找到或不是对象！";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "修改失败！";
    }

    public void reupdate(String token, token tem, ObjectNode nodeToModifyInNew) {
        tem.setToken(token);
        nodeToModifyInNew.put("token", token);
        require_UpdateToken(tem, nodeToModifyInNew);
        LocalDateTime now = LocalDateTime.now();
        nodeToModifyInNew.put("updateTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }

    public void require_beginToken(token tem, ObjectNode nodeToModifyInNew) {
        // 修改节点的值
        nodeToModifyInNew.put("token", tem.getToken());
        nodeToModifyInNew.put("username", tem.getUsername());
        nodeToModifyInNew.put("userPassword", tem.getUserPassword());
        nodeToModifyInNew.put("shared", tem.isShared());
        nodeToModifyInNew.put("show_user_info", tem.isShow_user_info());
        nodeToModifyInNew.put("plus", tem.isPlus());
        nodeToModifyInNew.put("setPoolToken", tem.isSetPoolToken());
        nodeToModifyInNew.put("access_token", tem.getAccess_token());
        nodeToModifyInNew.put("share_token", tem.getShare_token());
        nodeToModifyInNew.put("checkSession", tem.isCheckSession());
        nodeToModifyInNew.put("useRefreshToken", tem.isUseRefreshToken());
        if (tem.getPassword() != null && tem.getPassword().length() > 0) {
            nodeToModifyInNew.put("password", tem.getPassword());
        } else {
            nodeToModifyInNew.put("password", "");
        }
    }

    /**
     * 专门给生成函数写的修改token的值
     *
     * @param tem
     * @return
     */
    public String product_requireToken(token tem) {
        try {
            String parent = selectFile();
            ObjectMapper objectMapper = new ObjectMapper();
            // 读取JSON文件并获取根节点
            JsonNode rootNode = objectMapper.readTree(new File(parent));
            // 要修改的节点名称
            String nodeNameToModify = tem.getName();
            // 获取要修改的节点
            JsonNode nodeToModify = rootNode.get(nodeNameToModify);
            if (nodeToModify != null && nodeToModify.isObject()) {
                // 创建新的 ObjectNode，并复制原始节点内容
                ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();
                newObjectNode.setAll((ObjectNode) rootNode);
                // 获取要修改的节点
                ObjectNode nodeToModifyInNew = newObjectNode.with(nodeNameToModify);
                // 获取之前的节点值
                String previousToken = nodeToModifyInNew.has("token") ? nodeToModifyInNew.get("token").asText() : null;
                // 初始修改相应的值
                require_beginToken(tem, nodeToModifyInNew);
                if (!previousToken.equals(tem.getToken())
                        && tem.isSetPoolToken()) {
                    // 将修改后的 newObjectNode 写回文件
                    LocalDateTime now = LocalDateTime.now();
                    nodeToModifyInNew.put("updateTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);
                    return "修改成功！";
                }
                // 将修改后的 newObjectNode 写回文件
                objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);
                return "修改成功！";
            } else {
                log.info("节点未找到或不是对象,请检查tokens.json！ " + nodeNameToModify);
                return "节点未找到或不是对象！";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "修改失败！";
    }

    public void require_UpdateToken(token tem, ObjectNode nodeToModifyInNew) {
        try {
            String access_token = getAccessToken(tem);
            if (access_token != null) {
                tem.setAccess_token(access_token);
                String share_token = getShareToken(tem);
                nodeToModifyInNew.put("access_token", access_token);
                nodeToModifyInNew.put("checkSession", true);
                if (share_token != null) {
                    nodeToModifyInNew.put("share_token", share_token);
                } else {
                    nodeToModifyInNew.put("share_token", "检查session或refresh是否过期，请重新刷新获取");
                }
            } else {
                nodeToModifyInNew.put("access_token", "检查session或refresh是否过期，请重新刷新获取");
                nodeToModifyInNew.put("checkSession", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除token
     * 并删除对应keys
     *
     * @return "删除成功！"or"删除失败"
     */
    @Override
    public String deleteToken(token token) {
        try {
            String name = token.getName();
            String parent = selectFile();
            ObjectMapper objectMapper = new ObjectMapper();
            // 读取JSON文件并获取根节点
            JsonNode rootNode = objectMapper.readTree(new File(parent));

            // 检查要删除的节点是否存在
            JsonNode nodeToRemove = rootNode.get(name);
            if (nodeToRemove != null) {
                // 创建新的 ObjectNode，并复制原始节点内容
                ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();
                newObjectNode.setAll((ObjectNode) rootNode);
                // 删除节点
                newObjectNode.remove(name);
                // 将修改后的 newObjectNode 写回文件
                objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);
                if (token.getAccess_token().startsWith("eyJhb") && deleteShareToken(token)) {
                    return "删除并销毁share_token成功！";
                }
                return "删除成功！";
            } else {
                log.info("token未找到: " + name);
                return "token未找到！";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "删除失败";
    }

    /**
     * 自动更新Token方法
     * 通过api/auth/login拿到session_token
     * 更换tokens.json里存储的Token
     * 账号为token.getUserName()
     * 密码为token.getUserPassword()
     */
    public String updateSessionToken(token token) {
        String url;
        systemSetting systemSetting = systemService.selectSetting();
        if (systemSetting.getAutoToken_url().equals("default")) {
            String bingUrl = systemSetting.getBing();
            String[] parts = bingUrl.split(":");
            url = "http://127.0.0.1" + ":" + parts[1] + "/" + systemSetting.getProxy_api_prefix() + sessionToken;
        } else {
            url = systemSetting.getAutoToken_url() + sessionToken;
        }
        log.info("将通过这个网址请求登录信息：" + url);
        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("username", token.getUsername())
                    .addFormDataPart("password", token.getUserPassword())
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    log.info("Request failed: " + response.body().string().trim());
                    return null;
                }
                String responseContent = response.body().string();
                String resToken = null;
                try {
                    JSONObject jsonResponse = new JSONObject(responseContent);
                    resToken = jsonResponse.getString("session_token");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (response.code() == 200 && resToken != null && resToken.startsWith("eyJhb")) {
                    return resToken;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 自动Token方法
     * 通过api/auth/login2拿到refresh_token
     * 更换tokens.json里存储的Token
     * 账号为token.getUserName()
     * 密码为token.getUserPassword()
     */
    public String updateRefreshToken(token token) {
        String url;
        systemSetting systemSetting = systemService.selectSetting();
        if (systemSetting.getAutoToken_url().equals("default")) {
            String bingUrl = systemSetting.getBing();
            String[] parts = bingUrl.split(":");
            url = "http://127.0.0.1" + ":" + parts[1] + "/" + systemSetting.getProxy_api_prefix() + refreshToken;
        } else {
            url = systemSetting.getAutoToken_url() + refreshToken;
        }
        log.info("将通过这个网址请求登录信息：" + url);
        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("username", token.getUsername())
                    .addFormDataPart("password", token.getUserPassword())
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    log.info("Request failed: " + response.body().string().trim());
                    return null;
                }
                String responseContent = response.body().string();
                String resToken = null;
                try {
                    JSONObject jsonResponse = new JSONObject(responseContent);
                    log.info(jsonResponse.toString());
                    resToken = jsonResponse.getString("refresh_token");
                    log.info(resToken);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (response.code() == 200) {
                    return resToken;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getAccessToken(token token) {
        String url;
        systemSetting systemSetting = systemService.selectSettingUrl();
        String tokenKind;
        String tokenName;
        if (token.isUseRefreshToken()) {
            tokenKind = reAccessToken;
            tokenName = "refresh_token";
        } else {
            tokenKind = accessToken;
            tokenName = "session_token";
        }
        if (systemSetting.getAutoToken_url().equals("default")) {
            String bingUrl = systemSetting.getBing();
            String[] parts = bingUrl.split(":");
            url = "http://127.0.0.1" + ":" + parts[1] + "/" + systemSetting.getProxy_api_prefix() + tokenKind;
        } else {
            url = systemSetting.getAutoToken_url() + tokenKind;
        }
        log.info("将通过这个网址请求登录信息：" + url);
        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart(tokenName, token.getToken())
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    log.info("Request failed: " + response.body().string().trim());
                    return null;
                }
                String responseContent = response.body().string();
                String resToken = null;
                try {
                    JSONObject jsonResponse = new JSONObject(responseContent);
                    resToken = jsonResponse.getString("access_token");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (response.code() == 200 && resToken != null && resToken.length() > 400) {
                    return resToken;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getShareToken(token token) {
        systemSetting systemSetting = systemService.selectSettingUrl();
        String url = systemSetting.getAutoToken_url().equals("default")
                ? "http://127.0.0.1:" + systemSetting.getBing().split(":")[1] + "/" + systemSetting.getProxy_api_prefix() + shareToken
                : systemSetting.getAutoToken_url() + shareToken;
        log.info("将通过这个网址请求登录信息：" + url);
        String data = "unique_name=" + token.getName() + "&access_token=" + token.getAccess_token() +
                "&expires_in=0&show_conversations=false&show_userinfo=" + token.isShow_user_info();
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(data, MediaType.parse("application/x-www-form-urlencoded"));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.info("share token failed: " + response.body().string().trim());
                return null;
            }
            String tokenKey = new JSONObject(response.body().string()).getString("token_key");
            if (tokenKey.matches("^(fk-|pk-).*")) {
                return tokenKey;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean deleteShareToken(token token) {
        systemSetting systemSetting = systemService.selectSettingUrl();
        String url = systemSetting.getAutoToken_url().equals("default")
                ? "http://127.0.0.1:" + systemSetting.getBing().split(":")[1] + "/" + systemSetting.getProxy_api_prefix() + shareToken
                : systemSetting.getAutoToken_url() + shareToken;
        log.info("将通过这个网址请求登录信息：" + url);
        String data = "unique_name=" + token.getName() + "&access_token=" + token.getAccess_token() +
                "&expires_in=-1&show_conversations=false&show_userinfo=" + token.isShow_user_info();
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(data, MediaType.parse("application/x-www-form-urlencoded"));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.info("share token failed: " + response.body().string().trim());
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public String getPoolToken(String pool_token, String shareTokens) {
        systemSetting systemSetting = systemService.selectSettingUrl();
        String url = systemSetting.getAutoToken_url().equals("default")
                ? "http://127.0.0.1:" + systemSetting.getBing().split(":")[1] + "/" + systemSetting.getProxy_api_prefix() + poolToken
                : systemSetting.getAutoToken_url() + poolToken;
        log.info("将通过这个网址请求登录信息：" + url);
        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody;
            if (shareTokens == "") {
                List<token> tokens = selectToken("");
                StringBuffer resToken = new StringBuffer();
                for (token token : tokens) {
                    if (token.getShare_token() != null && token.isSetPoolToken()) {
                        resToken.append(token.getShare_token() + "\n");
                    }
                }
                requestBody = new FormBody.Builder()
                        .add("share_tokens", resToken.toString())
                        .add("pool_token", pool_token)
                        .build();
            } else {
                requestBody = new FormBody.Builder()
                        .add("share_tokens", shareTokens)
                        .add("pool_token", pool_token)
                        .build();
            }
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    log.info("Request failed: " + response.body().string().trim());
                    return null;
                }
                String responseContent = response.body().string();
                JSONObject jsonResponse = new JSONObject(responseContent);
                String resPoolToken = jsonResponse.getString("pool_token");
                log.info("一共运行了" + jsonResponse.getString("count") + "条share_token");
                if (resPoolToken.contains("pk")) {
                    log.info("pool_token更新为：" + resPoolToken);
                    return resPoolToken;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成shareToken和accessToken
     *
     * @return "生成成功" or "生成失败"
     */
    @Override
    public token autoUpdateSimpleToken(token token) {
        if (token == null || !token.isSetPoolToken()) {
            log.info("未查询到相关数据");
            return null;
        }
        String access_token = getAccessToken(token);
        if (access_token != null) {
            token.setAccess_token(access_token);
            //执行获取share_token操作
            String share_token = getShareToken(token);
            token.setShare_token(share_token);
            if (share_token != null) {
                token.setCheckSession(true);
                String res = product_requireToken(token);
                if (res.contains("成功")) {
                    log.info(res + "，修改share_token为：" + share_token);
                    return token;
                }
            }
        } else {
            token.setCheckSession(false);
            token.setShared(false);
            String res = product_requireToken(token);
            if (res.contains("成功")) {
                log.info("已为您禁用该session_token!");
            }
        }
        return null;
    }

    /**
     * 自动更新Token
     * 更换tokensTool里存储的Token的access_token和share_token
     * 并自动检查session是否过期
     *
     * @return "更新成功" or "更新失败"
     */
    public String autoUpdateToken(String name) {
        List<token> resTokens = selectToken(name);
        int newToken = 0;
        int allToken = 0;
        try {
            for (token token : resTokens) {
                if (!token.isSetPoolToken()) {
                    continue;
                }
                token res = autoUpdateSimpleToken(token);
                if (res != null) {
                    newToken++;
                }
                allToken++;
                Thread.sleep(1000);
            }
            if (newToken == 0) {
                log.info("自动生成Token失败！");
                return "自动生成Token失败！";
            } else {
                log.info("自动生成Token成功：" + newToken + "session或refresh过期：" + (allToken - newToken));
                return "自动生成Token成功：" + newToken + "<br>session或refresh过期：" + (allToken - newToken);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 自动更新session_token时间80天
     *
     * @param token
     * @return
     */
    @Override
    public String autoUpdateSessionToken(token token) {
        if (token == null) {
            log.info("未查询到相关数据");
            return null;
        }
        try {
            if (token.isUseRefreshToken()) {
                String refreshToken = updateRefreshToken(token);
                if (refreshToken != null) {
                    return refreshToken;
                }
            } else {
                String sessionToken = updateSessionToken(token);
                if (sessionToken != null) {
                    return sessionToken;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String deletePoolToken(String pool_token) {
        String url;
        systemSetting systemSetting = systemService.selectSettingUrl();
        if (systemSetting.getAutoToken_url().equals("default")) {
            String bingUrl = systemSetting.getBing();
            String[] parts = bingUrl.split(":");
            url = "http://127.0.0.1" + ":" + parts[1] + "/" +
                    systemSetting.getProxy_api_prefix() + poolToken;
        } else {
            url = systemSetting.getAutoToken_url() + poolToken;
        }
        log.info("将通过这个网址请求登录信息：" + url);
        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = new FormBody.Builder()
                    .add("share_tokens", "")
                    .add("pool_token", pool_token)
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                String responseContent = response.body().string();
                JSONObject jsonResponse = new JSONObject(responseContent);
                if (!response.isSuccessful() && !jsonResponse.has("detail")) {
                    log.info("Request failed: " + response.body().string().trim());
                    return null;
                }
                String resPoolToken = jsonResponse.getString("detail");
                if (response.code() == 200 && resPoolToken.length() > 0) {
                    log.info("注销pool_token成功!");
                    return resPoolToken;
                } else if (response.code() == 400) {
                    return "不存在该pool_token";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public PandoraLimit getPandoraLimit() {
        systemSetting systemSetting = systemService.selectSettingLicense();
        String url = "https://dash.pandoranext.com/api/" + systemSetting.getLicense_id() + "/usage";
        log.info("将通过这个网址请求PandoraNext余额信息：" + url);
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    log.info("Request failed: " + response.body().string().trim());
                    return null;
                }
                String responseContent = response.body().string();
                PandoraLimit pandoraLimit = new PandoraLimit();
                JSONObject jsonResponse = new JSONObject(responseContent);
                //用量
                pandoraLimit.setCurrent(jsonResponse.getInt("current"));
                //ip
                pandoraLimit.setIp(jsonResponse.getString("ip"));
                //总额
                pandoraLimit.setTotal(jsonResponse.getInt("total"));
                //重载时间
                pandoraLimit.setTtl(jsonResponse.getInt("ttl"));
                if (response.code() == 200 && pandoraLimit.toString().length() > 0) {
                    return pandoraLimit;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void updateSession() {
        try {
            List<token> tokens = selectToken("");
            token resToken = null;
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime minDateTime = LocalDateTime.MAX;
            for (token token : tokens) {
                //保证refresh_token不被刷新
                if (token.isSetPoolToken() && !token.isUseRefreshToken()) {
                    LocalDateTime currentDateTime = LocalDateTime.parse(token.getUpdateTime(), formatter);
                    if (currentDateTime.isBefore(minDateTime)) {
                        minDateTime = currentDateTime;
                        resToken = token;
                    }
                }
            }
            token s = updateSession(resToken);
            if (s != null) {
                log.info("更新session_token,access_token和share_token成功！");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 刷新session，更新access_token和share_token
     *
     * @param token
     * @return
     */
    @Override
    public token updateSession(token token) {
        String res = autoUpdateSessionToken(token);
        if (res != null) {
            token.setToken(res);
            token.setSetPoolToken(true);
            token.setCheckSession(true);
            try {
                token resToken = autoUpdateSimpleToken(token);
                if (resToken != null) {
                    return resToken;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/Result.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {

    /**
     * 响应码，1 代表成功; 0 代表失败
     */

    private Integer code;
    /**
     * 响应信息 描述字符串
     */

    private String msg;
    /**
     * 返回的数据
     */
    private Object data;

    /**
     * 增删改 成功响应
     */
    public static Result success() {
        return new Result(1, "success", null);
    }

    /**
     * 查询 成功响应
     */
    public static Result success(Object data) {
        return new Result(1, "success", data);
    }

    /**
     * 失败响应
     */
    public static Result error(String msg) {
        return new Result(0, msg, null);
    }
}

rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/systemSetting.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class systemSetting {
    /**
     * 绑定IP和端口
     */
    private String bing;
    /**
     * 请求的超时时间
     */
    private Integer timeout;
    /**
     * 部署服务流量走代理
     */
    private String proxy_url;
    /**
     * GPT中创建的对话分享
     */
    private Boolean public_share;
    /**
     * 访问网站密码
     */
    private String site_password;
    /**
     * 重载服务密码
     */
    private String setup_password;
    /**
     * 白名单（null则不限制，为空数组[]则限制所有账号）
     */
    private String whitelist;

    /**
     * pandoraNext验证license_id
     */
    private String license_id;

    /**
     * tokensTool登录Username
     */
    private String loginUsername;

    /**
     * tokensTool密码Password
     */
    private String loginPassword;

    /**
     * tokensTool 验证信息
     */
    private validation validation;

    /**
     * tokensTool 更新token网址
     * 为"default"则调用本机的，不为“default"则自定义
     */
    private String autoToken_url;

    /**
     * 是否开启拿tokensTool的后台token
     */
    private Boolean isGetToken;
    /**
     * tokensTool 拿到getTokenPassword
     * 为"getTokenPassword" 默认：123456
     * 默认拿getTokenPassword
     */
    private String getTokenPassword;

    /**
     * tokensTool 更新containerName(容器名)
     * 通过容器名实现开启，关闭，重新启动容器
     */
    private String containerName;

    /**
     * PandoraNext tls证书
     */
    private tls tls;

    /**
     * PandoraNext config.json位置
     */
    private String configPosition;

    /**
     * PandoraNext 接口地址添加前缀
     */
    private String isolated_conv_title;

    /**
     * PandoraNext 会话标题
     */
    private String proxy_api_prefix;

    /**
     * 禁用注册账号功能，true或false
     */
    private Boolean disable_signup;

    /**
     * 在proxy模式使用gpt-4模型调用/backend-api/conversation接口是否自动打码，使用消耗为4+10。
     */
    private Boolean auto_conv_arkose;

    /**
     * 在proxy模式是否使用PandoraNext的文件代理服务，避免官方文件服务的墙。
     */
    private Boolean proxy_file_service;

    /**
     * 配置自定义的DoH主机名，建议使用IP形式。默认在+8区使用223.6.6.6，其余地区使用1.1.1.1。
     */
    private String custom_doh_host;

    /**
     * 自动刷新session的开关
     */
    private Boolean auto_updateSession;

    /**
     * 自动刷新session的时间 (天为单位)
     */
    private Integer auto_updateTime;

    /**
     * 自动刷新session的个数 （个）
     */
    private Integer auto_updateNumber;

    /**
     * PadoraNext的公网访问地址
     */
    private String pandoraNext_outUrl;

    /**
     * oneAPi的公网访问地址
     */
    private String oneAPi_outUrl;

    /**
     * oneApi访问令牌
     */
    private String oneAPi_intoToken;
}

rearServer/src/main/java/com/tokensTool/pandoraNext/service/impl/systemServiceImpl.java
@Slf4j
@Service
public class systemServiceImpl implements systemService {
    @Value("${deployPosition}")
    private String deployPosition;
    private String deploy = "default";

    public String selectFile() {
        String projectRoot;
        if (deploy.equals(deployPosition)) {
            projectRoot = System.getProperty("user.dir");
        } else {
            projectRoot = deployPosition;
        }
        String parent = projectRoot + File.separator + "config.json";
        File jsonFile = new File(parent);
        Path jsonFilePath = Paths.get(parent);
        // 如果 JSON 文件不存在，创建一个新的 JSON 对象
        if (!jsonFile.exists()) {
            try {
                // 创建文件config.json
                Files.createFile(jsonFilePath);
                // 往 config.json 文件中添加一个空数组，防止重启报错
                Files.writeString(jsonFilePath, "{}");
                log.info("空数组添加完成");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            log.info("config.json创建完成: " + jsonFilePath);
        }
        return parent;
    }

    /**
     * 初始化config.json文件
     */
    public void initializeConfigJson() {
        String parent = selectFile();
        try {
            String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));
            JSONObject jsonObject = new JSONObject(jsonContent);

            // 定义一个 Map，其中键是 JSON 属性的名称，值是默认值
            Map<String, Object> keysAndDefaults = new HashMap<>();
            keysAndDefaults.put("loginUsername", "root");
            keysAndDefaults.put("loginPassword", "123456");
            keysAndDefaults.put("license_id", "");
            keysAndDefaults.put("autoToken_url", "default");
            keysAndDefaults.put("isGetToken", "false");
            keysAndDefaults.put("getTokenPassword", "");
            keysAndDefaults.put("containerName", "PandoraNext");
            keysAndDefaults.put("isolated_conv_title", "*");
            keysAndDefaults.put("proxy_api_prefix", "");
            keysAndDefaults.put("disable_signup", false);
            keysAndDefaults.put("auto_conv_arkose", false);
            keysAndDefaults.put("proxy_file_service", false);
            keysAndDefaults.put("custom_doh_host", "");

            // 0.4.9.3
            keysAndDefaults.put("auto_updateSession", false);
            keysAndDefaults.put("auto_updateTime", 5);
            keysAndDefaults.put("auto_updateNumber", 1);
            keysAndDefaults.put("pandoraNext_outUrl", "");

            // 0.5.0

            keysAndDefaults.put("oneAPi_outUrl", "");
            keysAndDefaults.put("oneAPi_intoToken", "");

            boolean exist = checkAndSetDefaults(jsonObject, keysAndDefaults);

            JSONObject captchaJson = Optional.ofNullable(jsonObject.optJSONObject("captcha")).orElse(new JSONObject());
            validation captchaSetting = new validation(
                    captchaJson.optString("provider", ""),
                    captchaJson.optString("site_key", ""),
                    captchaJson.optString("site_secret", ""),
                    captchaJson.optBoolean("site_login", false),
                    captchaJson.optBoolean("setup_login", false),
                    captchaJson.optBoolean("oai_username", false),
                    captchaJson.optBoolean("oai_password", false)
            );

            JSONObject tlsJson = Optional.ofNullable(jsonObject.optJSONObject("tls")).orElse(new JSONObject());
            tls tlsSetting = new tls(
                    tlsJson.optBoolean("enabled", false),
                    tlsJson.optString("cert_file", ""),
                    tlsJson.optString("key_file", "")
            );

            if (tlsJson.length() == 0) {
                jsonObject.put("tls", tlsSetting.toJSONObject());
                exist = false;
            }
            if (captchaJson.length() == 0) {
                jsonObject.put("captcha", captchaSetting.toJSONObject());
                exist = false;
            }
            if (!exist) {
                String updatedJson = jsonObject.toString(2);
                Files.write(Paths.get(parent), updatedJson.getBytes());
            }
            log.info("初始化config.json成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 通用方法，检查和设置默认值
    private boolean checkAndSetDefaults(JSONObject jsonObject, Map<String, Object> keysAndDefaults) throws JSONException {
        boolean exist = true;
        for (Map.Entry<String, Object> entry : keysAndDefaults.entrySet()) {
            try {
                jsonObject.get(entry.getKey());
            } catch (JSONException e) {
                jsonObject.put(entry.getKey(), entry.getValue());
                log.info("config.json没有新增" + entry.getKey() + "参数,现已增加！");
                exist = false;
            }
        }
        return exist;
    }

    /**
     * 修改config.json里的系统值
     *
     * @return "修改成功！"or"修改失败"
     */
    @Override
    public String requiredSetting(systemSetting tem) {
        String parent = selectFile();
        try {
            // 读取 JSON 文件内容
            String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));
            JSONObject jsonObject = new JSONObject(jsonContent);
            updateJsonValue(jsonObject, "bind", tem.getBing());
            updateJsonValue(jsonObject, "timeout", tem.getTimeout());
            updateJsonValue(jsonObject, "proxy_url", tem.getProxy_url());
            updateJsonValue(jsonObject, "public_share", tem.getPublic_share());
            updateJsonValue(jsonObject, "site_password", tem.getSite_password());
            updateJsonValue(jsonObject, "setup_password", tem.getSetup_password());
            JSONArray jsonArray = null;
            if (tem.getWhitelist() != null && tem.getWhitelist().length() > 0 && tem.getWhitelist() != "null") {
                String numbersString = tem.getWhitelist().replaceAll("[\\[\\]]", "");
                String[] numbersArray = numbersString.split(",");
                // 将数组转换为 List<String>
                List<String> numbersList = new ArrayList<>(Arrays.asList(numbersArray));
                jsonArray = new JSONArray(numbersList);
                jsonObject.put("whitelist", jsonArray);
            } else {
                jsonObject.put("whitelist", JSONObject.NULL);
            }

            //4.7.2
            if (!tem.getLoginPassword().equals(jsonObject.optString("loginPassword"))
                    || !tem.getLoginUsername().equals(jsonObject.optString("loginUsername"))) {
                Instant instant = Instant.now();
                //时间戳
                String key = String.valueOf(instant.toEpochMilli());
                JwtUtils.setSignKey(key);
            }

            updateJsonValue(jsonObject, "loginUsername", tem.getLoginUsername());
            updateJsonValue(jsonObject, "loginPassword", tem.getLoginPassword());

            updateJsonValue(jsonObject, "license_id", tem.getLicense_id());
            updateJsonValue(jsonObject, "autoToken_url", tem.getAutoToken_url());
            updateJsonValue(jsonObject, "isGetToken", tem.getIsGetToken());
            updateJsonValue(jsonObject, "getTokenPassword", tem.getGetTokenPassword());
            updateJsonValue(jsonObject, "containerName", tem.getContainerName());

            updateJsonValue(jsonObject, "isolated_conv_title", tem.getIsolated_conv_title());
            updateJsonValue(jsonObject, "proxy_api_prefix", tem.getProxy_api_prefix());

            // 4,9
            updateJsonValue(jsonObject, "disable_signup", tem.getDisable_signup());
            updateJsonValue(jsonObject, "auto_conv_arkose", tem.getAuto_conv_arkose());
            updateJsonValue(jsonObject, "proxy_file_service", tem.getProxy_file_service());
            updateJsonValue(jsonObject, "custom_doh_host", tem.getCustom_doh_host());

            // validation
            validation validation = tem.getValidation();
            JSONObject captchaJson = jsonObject.getJSONObject("captcha");
            updateJsonValue(captchaJson, "provider", validation.getProvider());
            updateJsonValue(captchaJson, "site_key", validation.getSite_key());
            updateJsonValue(captchaJson, "site_secret", validation.getSite_secret());
            updateJsonValue(captchaJson, "site_login", validation.isSite_login());
            updateJsonValue(captchaJson, "setup_login", validation.isSetup_login());
            updateJsonValue(captchaJson, "oai_username", validation.isOai_username());
            updateJsonValue(captchaJson, "oai_password", validation.isOai_password());

            // tls
            tls tls = tem.getTls();
            JSONObject tlsJson = jsonObject.getJSONObject("tls");
            updateJsonValue(tlsJson, "enabled", tls.isEnabled());
            updateJsonValue(tlsJson, "cert_file", tls.getCert_file());
            updateJsonValue(tlsJson, "key_file", tls.getKey_file());

            // 将修改后的 JSONObject 转换为格式化的 JSON 字符串
            String updatedJson = jsonObject.toString(2);
            Files.write(Paths.get(parent), updatedJson.getBytes());
            return "修改config.json成功，快去重启PandoraNext吧!";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "修改config.json失败";
    }

    private void updateJsonValue(JSONObject jsonObject, String key, Object value) {
        if (value == null) {
            return;
        }
        try {
            if (value != null && value.toString().length() > 0) {
                jsonObject.put(key, value);
            } else if (value.toString().length() == 0) {
                jsonObject.put(key, "");
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询config.json里的系统值
     *
     * @return systemSettings类
     */
    public systemSetting selectSetting() {
        String parent = selectFile();
        try {
            // 读取 JSON 文件内容
            String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));
            // 将 JSON 字符串解析为 JSONObject
            JSONObject jsonObject = new JSONObject(jsonContent);

            // 将 JSONObject 转换为 Config 类的实例
            systemSetting config = new systemSetting();
            config.setSite_password(jsonObject.optString("site_password"));
            config.setSetup_password(jsonObject.optString("setup_password"));
            config.setBing(jsonObject.optString("bind"));
            config.setPublic_share(jsonObject.optBoolean("public_share"));
            config.setProxy_url(jsonObject.optString("proxy_url"));
            config.setWhitelist(jsonObject.isNull("whitelist") ? null : jsonObject.optString("whitelist"));
            config.setTimeout(jsonObject.optInt("timeout"));

            config.setLoginUsername(jsonObject.optString("loginUsername"));
            config.setLoginPassword(jsonObject.optString("loginPassword"));

            config.setLicense_id(jsonObject.optString("license_id"));
            config.setAutoToken_url(jsonObject.optString("autoToken_url"));
            config.setIsGetToken(jsonObject.optBoolean("isGetToken"));
            config.setGetTokenPassword(jsonObject.optString("getTokenPassword"));
            config.setContainerName(jsonObject.optString("containerName"));

            // 4.0
            config.setIsolated_conv_title(jsonObject.optString("isolated_conv_title"));
            config.setProxy_api_prefix(jsonObject.optString("proxy_api_prefix"));

            // 4.9
            config.setDisable_signup(jsonObject.optBoolean("disable_signup"));
            config.setAuto_conv_arkose(jsonObject.optBoolean("auto_conv_arkose"));
            config.setProxy_file_service(jsonObject.optBoolean("proxy_file_service"));
            config.setCustom_doh_host(jsonObject.optString("custom_doh_host"));

            // 0.4.9.3
            config.setAuto_updateSession(jsonObject.optBoolean("auto_updateSession"));
            config.setAuto_updateTime(jsonObject.optInt("auto_updateTime"));
            config.setAuto_updateNumber(jsonObject.optInt("auto_updateNumber"));
            config.setPandoraNext_outUrl(jsonObject.optString("pandoraNext_outUrl"));

            // 0.5.0
            config.setOneAPi_outUrl(jsonObject.optString("oneAPi_outUrl"));
            config.setOneAPi_intoToken(jsonObject.optString("oneAPi_intoToken"));

            // 获取 captcha 相关属性
            JSONObject captchaJson = Optional.ofNullable(jsonObject.optJSONObject("captcha")).orElse(new JSONObject());
            validation captchaSetting = new validation(
                    captchaJson.optString("provider", ""),
                    captchaJson.optString("site_key", ""),
                    captchaJson.optString("site_secret", ""),
                    captchaJson.optBoolean("site_login", false),
                    captchaJson.optBoolean("setup_login", false),
                    captchaJson.optBoolean("oai_username", false),
                    captchaJson.optBoolean("oai_password", false)
            );
            config.setValidation(captchaSetting);

            // 获取 tls 相关属性
            JSONObject tlsJson = Optional.ofNullable(jsonObject.optJSONObject("tls")).orElse(new JSONObject());
            tls tlsSetting = new tls(
                    tlsJson.optBoolean("enabled", false),
                    tlsJson.optString("cert_file", ""),
                    tlsJson.optString("key_file", "")
            );
            config.setTls(tlsSetting);
            return config;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public systemSetting selectSettingUrl() {
        String parent = selectFile();
        try {
            // 读取 JSON 文件内容
            String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));
            // 将 JSON 字符串解析为 JSONObject
            JSONObject jsonObject = new JSONObject(jsonContent);

            // 将 JSONObject 转换为 Config 类的实例
            systemSetting config = new systemSetting();
            config.setBing(jsonObject.optString("bind"));
            config.setAutoToken_url(jsonObject.optString("autoToken_url"));
            config.setProxy_api_prefix(jsonObject.optString("proxy_api_prefix"));
            return config;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public systemSetting selectSettingLicense() {
        String parent = selectFile();
        try {
            // 读取 JSON 文件内容
            String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));
            // 将 JSON 字符串解析为 JSONObject
            JSONObject jsonObject = new JSONObject(jsonContent);
            // 将 JSONObject 转换为 Config 类的实例
            systemSetting config = new systemSetting();
            config.setLicense_id(jsonObject.optString("license_id"));
            return config;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String requireTimeTask(systemSetting tem) {
        String parent = selectFile();
        try {
            // 读取 JSON 文件内容
            String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));

            JSONObject jsonObject = new JSONObject(jsonContent);
            // 0.4.9.3
            updateJsonValue(jsonObject, "auto_updateSession", tem.getAuto_updateSession());
            updateJsonValue(jsonObject, "auto_updateTime", tem.getAuto_updateTime());
            updateJsonValue(jsonObject, "auto_updateNumber", tem.getAuto_updateNumber());
            updateJsonValue(jsonObject, "pandoraNext_outUrl", tem.getPandoraNext_outUrl());
            // 0.5.0
            updateJsonValue(jsonObject, "oneAPi_outUrl", tem.getOneAPi_outUrl());
            updateJsonValue(jsonObject, "oneAPi_intoToken", tem.getOneAPi_intoToken());

            // 将修改后的 JSONObject 转换为格式化的 JSON 字符串
            String updatedJson = jsonObject.toString(2);
            Files.write(Paths.get(parent), updatedJson.getBytes());
            return "修改定时任务和url成功！";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "修改定时任务和url失败！";
    }

    public String[] selectOneAPi() {
        String parent = selectFile();
        try {
            // 读取 JSON 文件内容
            String jsonContent = new String(Files.readAllBytes(Paths.get(parent)));
            // 将 JSON 字符串解析为 JSONObject
            JSONObject jsonObject = new JSONObject(jsonContent);
            String[] oneApi = new String[2];
            oneApi[0] = jsonObject.optString("oneAPi_outUrl");
            oneApi[1] = jsonObject.optString("oneAPi_intoToken");
            return oneApi;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

rearServer/src/main/java/com/tokensTool/pandoraNext/service/impl/poolServiceImpl.java
@Service
@Slf4j
public class poolServiceImpl implements poolService {
    private static final String gpt3Models = "gpt-3.5-turbo";

    private static final String gpt4Models = "gpt-3.5-turbo,gpt-4";

    private static final String openAiChat = "/v1/chat/completions";
    private static final String oneApiSelect = "api/channel/?p=0";
    private static final String oneAPiChannel = "api/channel/";
    private final String deploy = "default";
    @Value("${deployPosition}")
    private String deployPosition;
    @Autowired
    private apiServiceImpl apiService;
    @Autowired
    private systemServiceImpl systemService;

    /**
     * 遍历文件
     *
     * @return
     */
    public String selectFile() {
        String projectRoot;
        if (deploy.equals(deployPosition)) {
            projectRoot = System.getProperty("user.dir");
        } else {
            projectRoot = deployPosition;
        }
        String parent = projectRoot + File.separator + "pool.json";
        File jsonFile = new File(parent);
        Path jsonFilePath = Paths.get(parent);
        // 如果 JSON 文件不存在，创建一个新的 JSON 对象
        if (!jsonFile.exists()) {
            try {
                // 创建文件pool.json
                Files.createFile(jsonFilePath);
                // 往 pool.json 文件中添加一个空数组，防止重启报错
                Files.writeString(jsonFilePath, "{}");
                log.info("新建pool.json，并初始化pool.json成功！");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return parent;
    }

    /**
     * 初始化pool.json
     * 添加checkPool变量,初始化为true
     * 启动的时候自动全部添加
     */
    public String initializeCheckPool() {
        try {
            String parent = selectFile();
            ObjectMapper objectMapper = new ObjectMapper();
            // 读取JSON文件并获取根节点
            JsonNode rootNode = objectMapper.readTree(new File(parent));
            // 遍历根节点的所有子节点
            if (rootNode.isObject()) {
                ObjectNode rootObjectNode = (ObjectNode) rootNode;
                // 遍历所有子节点
                Iterator<Map.Entry<String, JsonNode>> fields = rootObjectNode.fields();
                while (fields.hasNext()) {
                    Map.Entry<String, JsonNode> entry = fields.next();
                    // 获取子节点的名称
                    String nodeName = entry.getKey();
                    // 获取子节点
                    JsonNode nodeToModify = entry.getValue();
                    if (nodeToModify != null && nodeToModify.isObject()) {
                        // 创建新的 ObjectNode，并复制原始节点内容
                        ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();
                        newObjectNode.setAll(rootObjectNode);
                        // 获取要修改的节点
                        ObjectNode nodeToModifyInNew = newObjectNode.with(nodeName);
                        // 初始化checkSession的值为true
                        if (!nodeToModifyInNew.has("checkPool")) {
                            nodeToModifyInNew.put("checkPool", true);
                            log.info("为节点 " + nodeName + " 添加 checkPool 变量成功！");
                        }
                        // 初始化intoOneApi的值为false
                        if (!nodeToModifyInNew.has("intoOneApi")) {
                            nodeToModifyInNew.put("intoOneApi", false);
                            log.info("为节点 " + nodeName + " 添加 intoOneApi 变量成功！");
                        }
                        // 初始化pandoraNextGpt4的值为false
                        if (!nodeToModifyInNew.has("pandoraNextGpt4")) {
                            nodeToModifyInNew.put("pandoraNextGpt4", false);
                            log.info("为节点 " + nodeName + " 添加 pandoraNextGpt4 变量成功！");
                        }
                        // 初始化oneApi_pandoraUrl的值为""
                        if (!nodeToModifyInNew.has("oneApi_pandoraUrl")) {
                            nodeToModifyInNew.put("oneApi_pandoraUrl", "");
                            log.info("为节点 " + nodeName + " 添加 oneApi_pandoraUrl 变量成功！");
                        }
                        // 将修改后的 newObjectNode 写回文件
                        objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);
                    }
                }
                return "为所有子节点添加 checkPool 变量成功！";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "为所有子节点添加 checkPool 变量失败！";
    }

    /**
     * 通过name遍历poolToken
     *
     * @param name
     * @return
     */
    public List<poolToken> selectPoolToken(String name) {
        List<poolToken> res = new ArrayList<>();
        try {
            String parent = selectFile();
            ObjectMapper objectMapper = new ObjectMapper();
            // 读取JSON文件并获取根节点
            JsonNode rootNode = objectMapper.readTree(new File(parent));
            // 遍历所有字段
            Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields();
            while (fields.hasNext()) {
                Map.Entry<String, JsonNode> entry = fields.next();
                String nodeName = entry.getKey();
                if (nodeName.contains(name)) {
                    poolToken temRes = new poolToken();
                    temRes.setPoolName(nodeName);
                    // 获取对应的节点
                    JsonNode temNode = rootNode.get(nodeName);
                    temRes.setPoolToken(temNode.has("poolToken") ? temNode.get("poolToken").asText() : "");
                    temRes.setPoolTime(temNode.has("poolTime") ? temNode.get("poolTime").asText() : "");
                    // 将 JsonNode 转换为 List<String>
                    List<String> sharedTokens = new ArrayList<>();
                    if (temNode.has("shareTokens") && temNode.get("shareTokens").isArray()) {
                        for (JsonNode tokenNode : temNode.get("shareTokens")) {
                            sharedTokens.add(tokenNode.asText());
                        }
                    }
                    temRes.setShareTokens(sharedTokens);
                    temRes.setCheckPool(!temNode.has("checkPool") || temNode.get("checkPool").asBoolean());
                    //0.5.0
                    temRes.setIntoOneApi(temNode.has("intoOneApi") && temNode.get("intoOneApi").asBoolean());
                    temRes.setPandoraNextGpt4(temNode.has("pandoraNextGpt4") && temNode.get("pandoraNextGpt4").asBoolean());
                    temRes.setOneApi_pandoraUrl(temNode.has("oneApi_pandoraUrl") ? temNode.get("oneApi_pandoraUrl").asText() : "");
                    temRes.setPriority(temNode.has("priority") ? temNode.get("priority").asInt() : 0);
                    res.add(temRes);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return res;
    }

    /**
     * 仅支持修改poolToken的时间和值
     * 修改poolToken的时间
     * 修改poolToken的值
     *
     * @param poolToken
     * @return 修改成功！or 节点未找到或不是对象！
     * @throws Exception
     */
    public String requirePoolToken(poolToken poolToken) {
        try {
            String parent = selectFile();
            ObjectMapper objectMapper = new ObjectMapper();
            // 读取JSON文件并获取根节点
            JsonNode rootNode = objectMapper.readTree(new File(parent));

            // 要修改的节点名称
            String nodeNameToModify = poolToken.getPoolName();

            // 获取要修改的节点
            JsonNode nodeToModify = rootNode.get(nodeNameToModify);

            if (nodeToModify != null && nodeToModify.isObject()) {
                // 创建新的 ObjectNode，并复制原始节点内容
                ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();
                newObjectNode.setAll((ObjectNode) rootNode);

                // 获取要修改的节点
                ObjectNode nodeToModifyInNew = newObjectNode.with(nodeNameToModify);

                //仅支持修改poolToken的时间和值
                LocalDateTime now = LocalDateTime.now();
                nodeToModifyInNew.put("checkPool", poolToken.isCheckPool());
                nodeToModifyInNew.put("poolToken", poolToken.getPoolToken());
                nodeToModifyInNew.put("poolTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

                // 将修改后的 newObjectNode 写回文件
                objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);
                log.info("修改成功!");
                return "修改成功！";
            } else {
                log.info("节点未找到或不是对象,请检查pool.json！ " + nodeNameToModify);
                return "节点未找到或不是对象！";
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String requireCheckPoolToken(poolToken poolToken) {
        try {
            String parent = selectFile();
            ObjectMapper objectMapper = new ObjectMapper();
            // 读取JSON文件并获取根节点
            JsonNode rootNode = objectMapper.readTree(new File(parent));
            // 要修改的节点名称
            String nodeNameToModify = poolToken.getPoolName();
            // 获取要修改的节点
            JsonNode nodeToModify = rootNode.get(nodeNameToModify);
            if (nodeToModify != null && nodeToModify.isObject()) {
                // 创建新的 ObjectNode，并复制原始节点内容
                ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();
                newObjectNode.setAll((ObjectNode) rootNode);
                // 获取要修改的节点
                ObjectNode nodeToModifyInNew = newObjectNode.with(nodeNameToModify);
                //仅支持修改poolToken的时间和值
                LocalDateTime now = LocalDateTime.now();
                nodeToModifyInNew.put("checkPool", poolToken.isCheckPool());
                // 将修改后的 newObjectNode 写回文件
                objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);
                return "修改成功！";
            } else {
                log.info("节点未找到或不是对象,请检查pool.json！ " + nodeNameToModify);
                return "节点未找到或不是对象！";
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 通过poolToken添加PoolToken
     *
     * @param poolToken
     * @return
     */
    public String addPoolToken(poolToken poolToken) {
        String resPoolToken;
        try {
            String shareTokens = getShareTokens(poolToken.getShareTokens());
            String temPoolToken = poolToken.getPoolToken();
            if (temPoolToken != null && temPoolToken.contains("pk")) {
                resPoolToken = apiService.getPoolToken(temPoolToken, shareTokens);
            } else {
                resPoolToken = apiService.getPoolToken("", shareTokens);
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        try {
            if (resPoolToken == null) {
                return "pool_token数据添加失败，请先按全部选择并生成，并确保url配对正确！";
            }
            poolToken.setPoolToken(resPoolToken);
            if (poolToken.isIntoOneApi()) {
                String[] strings = systemService.selectOneAPi();
                boolean b = addKey(poolToken, strings);
                if (b && poolToken.getPriority() != 0) {
                    boolean b1 = getPriority(poolToken, strings);
                    if (b1) {
                        log.info("修改优先级成功！");
                    }
                }
                if (b) {
                    log.info("pool_token进one-Api成功！");
                } else {
                    return "pool_token添加进one-api失败！";
                }
            }
            String parent = selectFile();
            File jsonFile = new File(parent);
            Path jsonFilePath = Paths.get(parent);
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode rootNode;
            // 如果 JSON 文件不存在，创建一个新的 JSON 对象
            if (!jsonFile.exists()) {
                // 创建文件
                Files.createFile(jsonFilePath);
                System.out.println("pool.json创建完成: " + jsonFilePath);
                rootNode = objectMapper.createObjectNode();
            } else {
                if (Files.exists(jsonFilePath) && Files.size(jsonFilePath) > 0) {
                    rootNode = objectMapper.readTree(jsonFile).deepCopy();
                } else {
                    rootNode = objectMapper.createObjectNode();
                }
            }
            // 创建要添加的新数据
            ObjectNode newData = objectMapper.createObjectNode();
            newData.put("poolToken", resPoolToken);
            List<String> shareTokensList = poolToken.getShareTokens();
            ArrayNode arrayNode = objectMapper.createArrayNode();
            for (String value : shareTokensList) {
                arrayNode.add(value);
            }
            newData.set("shareTokens", arrayNode);
            //0.5.0
            newData.put("checkPool", true);
            newData.put("intoOneApi", poolToken.isIntoOneApi());
            newData.put("pandoraNextGpt4", poolToken.isPandoraNextGpt4());
            newData.put("oneApi_pandoraUrl", poolToken.getOneApi_pandoraUrl());

            LocalDateTime now = LocalDateTime.now();
            newData.put("poolTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            // 将新数据添加到 JSON 树中
            rootNode.put(poolToken.getPoolName(), newData);
            // 将修改后的数据写回到文件
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile, rootNode);
            log.info("数据成功添加到 JSON 文件中。");
            return "pool_token数据添加成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "添加失败！";
        }
    }

    /**
     * 删除通过poolToken里的poolName删除poolToken
     *
     * @param poolToken
     * @return
     */
    public String deletePoolToken(poolToken poolToken) {
        try {
            String name = poolToken.getPoolName();
            String parent = selectFile();
            String deletePoolToken = poolToken.getPoolToken();
            //确保注销成功！
            if (deletePoolToken != null && deletePoolToken.contains("pk")) {
                String s = apiService.deletePoolToken(deletePoolToken);
                if (s == null) {
                    log.info("删除失败，看看自己的poolToken是否合法");
                }
            }
            if (poolToken.isIntoOneApi()) {
                String[] strings = systemService.selectOneAPi();
                boolean b = deleteKeyId(poolToken, strings);
                if (!b) {
                    return "删除oneApi中的poolToken失败！";
                }
            }
            ObjectMapper objectMapper = new ObjectMapper();
            // 读取JSON文件并获取根节点
            JsonNode rootNode = objectMapper.readTree(new File(parent));
            // 检查要删除的节点是否存在
            JsonNode nodeToRemove = rootNode.get(name);
            if (nodeToRemove != null) {
                // 创建新的 ObjectNode，并复制原始节点内容
                ObjectNode newObjectNode = JsonNodeFactory.instance.objectNode();
                newObjectNode.setAll((ObjectNode) rootNode);
                // 删除节点
                newObjectNode.remove(name);
                // 将修改后的 newObjectNode 写回文件
                objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(parent), newObjectNode);
                log.info("删除成功");
                return "删除成功！";
            } else {
                System.out.println("Node not found: " + name);
                return "节点未找到！";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "删除失败";
    }

    /**
     * 从poolToken里拿到share_tokens的集合，传参给share_token
     *
     * @param shareName
     * @return
     */
    public String getShareTokens(List<String> shareName) {
        try {
            StringBuffer resToken = new StringBuffer();
            List<token> tokens = apiService.selectToken("");
            HashMap<String, String> tokensHashMap = new HashMap<>();
            for (token tem : tokens) {
                if (tem.isSetPoolToken() && tem.isCheckSession()) {
                    tokensHashMap.put(tem.getName(), tem.getShare_token());
                }
            }
            for (String temShareName : shareName) {
                try {
                    String temShareToken = tokensHashMap.get(temShareName);
                    String regex = "fk-[0-9a-zA-Z_\\-]{43}";
                    if (temShareToken != null && Pattern.matches(regex, temShareToken)) {
                        resToken.append(temShareToken + "\n");
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            return resToken.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 重新更新poolToken
     *
     * @return
     */
    public String refreshAllTokens() {
        log.info("开始自动更新PoolToken..........................");
        List<poolToken> poolTokens = selectPoolToken("");
        int count = 0;
        for (poolToken token : poolTokens) {
            String poolToken = token.getPoolToken();
            String shareToken = getShareTokens(token.getShareTokens());
            String resPoolToken = apiService.getPoolToken(poolToken, shareToken);
            if (resPoolToken != null && resPoolToken.equals(poolToken)) {
                token.setPoolToken(resPoolToken);
                if (requirePoolToken(token).contains("成功")) {
                    count++;
                }
            }
        }
        log.info("pool_token刷新成功:" + count + "，失败:" + (poolTokens.size() - count));
        return ("<br>pool_token刷新成功:" + count + "，失败:" + (poolTokens.size() - count));
    }

    /**
     * 手动单个更新poolToken
     *
     * @param poolToken
     * @return
     */
    public String refreshSimplyToken(poolToken poolToken) {
        try {
            List<poolToken> poolTokens = selectPoolToken("");
            for (poolToken token : poolTokens) {
                if (token.getPoolName().equals(poolToken.getPoolName())) {
                    String poolTokenValue = token.getPoolToken();
                    String shareToken = getShareTokens(token.getShareTokens());
                    log.info(shareToken);
                    String resPoolToken = apiService.getPoolToken(poolTokenValue, shareToken);
                    if (resPoolToken != null && resPoolToken.equals(poolTokenValue)) {
                        poolToken.setCheckPool(true);
                        if (requirePoolToken(poolToken).contains("成功")) {
                            return "刷新pool_token成功";
                        }
                    }
                }
            }
            return "没有找到该pool_token,刷新失败！";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "刷新失败！";
    }

    /**
     * 手动单个更改poolToken
     *
     * @param poolToken
     * @return
     */
    public String changePoolToken(poolToken poolToken) {
        try {
            String deletePoolToken = poolToken.getPoolToken();
            if (deletePoolToken != null && deletePoolToken.contains("pk")) {
                String s = null;
                try {
                    s = apiService.deletePoolToken(poolToken.getPoolToken());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                if (s == null) {
                    return "注销poolToken失败";
                }
            }
            String res = null;
            try {
                String resPoolToken = apiService.getPoolToken("", getShareTokens(poolToken.getShareTokens()));
                if (poolToken.isIntoOneApi()) {
                    String[] strings = systemService.selectOneAPi();
                    boolean temkeyId = deleteKeyId(poolToken, strings);
                    if (!temkeyId) {
                        return "删除oneAPi里的poolToken失败！";
                    } else {
                        try {
                            poolToken.setPoolToken(resPoolToken);
                            poolToken.setCheckPool(true);
                            res = requirePoolToken(poolToken);
                            boolean b = addKey(poolToken, strings);
                            if (b && res.contains("成功")) {
                                return res;
                            }
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
                poolToken.setPoolToken(resPoolToken);
                // 恢复正常
                poolToken.setCheckPool(true);
                res = requirePoolToken(poolToken);
                return res;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 检查全部pool_token
     * 是否过期或者出现问题
     */
    public String verifyAllPoolToken() {
        try {
            String openAiUrl = getOpenaiUrl() + openAiChat;
            List<poolToken> poolTokens = selectPoolToken("");
            int count = 0;
            for (poolToken poolToken : poolTokens) {
                String res = verifyPoolToken(poolToken, openAiUrl);
                if (res.contains("请确保")) {
                    return res;
                } else if (res != null && res.contains("正常")) {
                    count++;
                }
            }
            return "poolToken验证成功：" + count + "，失败：" + (poolTokens.size() - count);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String toRequirePoolToken(poolToken poolToken) {
        String[] strings = systemService.selectOneAPi();
        deleteKeyId(poolToken, strings);
        String resPoolToken;
        try {
            String shareTokens = getShareTokens(poolToken.getShareTokens());
            String temPoolToken = poolToken.getPoolToken();
            if (temPoolToken != null && temPoolToken.contains("pk")) {
                resPoolToken = apiService.getPoolToken(temPoolToken, shareTokens);
            } else {
                resPoolToken = apiService.getPoolToken("", shareTokens);
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        try {
            if (resPoolToken == null) {
                return "pool_token数据添加失败，请先按全部选择并生成，并确保url配对正确！";
            }
            poolToken.setPoolToken(resPoolToken);
            if (poolToken.isIntoOneApi()) {
                boolean b = addKey(poolToken, strings);
                if (poolToken.getPriority() != 0) {
                    boolean b1 = getPriority(poolToken, strings);
                    if (b1) {
                        log.info("修改优先级成功！");
                    }
                }
                if (b) {
                    log.info("pool_token进one-Api成功！");
                } else {
                    return "pool_token添加进one-api失败！";
                }
            }
            String parent = selectFile();
            File jsonFile = new File(parent);
            Path jsonFilePath = Paths.get(parent);
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode rootNode;
            // 如果 JSON 文件不存在，创建一个新的 JSON 对象
            if (!jsonFile.exists()) {
                // 创建文件
                Files.createFile(jsonFilePath);
                System.out.println("pool.json创建完成: " + jsonFilePath);
                rootNode = objectMapper.createObjectNode();
            } else {
                if (Files.exists(jsonFilePath) && Files.size(jsonFilePath) > 0) {
                    rootNode = objectMapper.readTree(jsonFile).deepCopy();
                } else {
                    rootNode = objectMapper.createObjectNode();
                }
            }
            // 创建要添加的新数据
            ObjectNode newData = objectMapper.createObjectNode();
            newData.put("poolToken", resPoolToken);
            List<String> shareTokensList = poolToken.getShareTokens();
            ArrayNode arrayNode = objectMapper.createArrayNode();
            for (String value : shareTokensList) {
                arrayNode.add(value);
            }
            newData.set("shareTokens", arrayNode);
            //0.5.0
            newData.put("checkPool", true);
            newData.put("intoOneApi", poolToken.isIntoOneApi());
            newData.put("pandoraNextGpt4", poolToken.isPandoraNextGpt4());
            newData.put("oneApi_pandoraUrl", poolToken.getOneApi_pandoraUrl());

            LocalDateTime now = LocalDateTime.now();
            newData.put("poolTime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            // 将新数据添加到 JSON 树中
            rootNode.put(poolToken.getPoolName(), newData);
            // 将修改后的数据写回到文件
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(jsonFile, rootNode);
            log.info("数据成功添加到 JSON 文件中。");
            return "pool_token数据修改成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "修改失败！";
        }
    }

    /**
     * 检查单个pool_token
     * 是否过期或者出现问题
     */
    @Override
    public String verifySimplyPoolToken(poolToken poolToken) {
        try {
            String openAiUrl = getOpenaiUrl();
            String res = verifyPoolToken(poolToken, openAiUrl + openAiChat);
            if (res != null) {
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 检查pool_token
     * 是否过期或者出现问题
     */
    public String verifyPoolToken(poolToken poolToken, String url) {
        OkHttpClient client = new OkHttpClient();

        // 构造请求体，JSON格式，包含一个字符串参数prompt和一个整数参数max_tokens，如果有其他参数，延续即可。
        String json = "{" +
                "    \"model\": \"gpt-3.5-turbo\"," +
                "    \"messages\": [{\"role\": \"user\", \"content\": \"Say this is a test!\"}]," +
                "    \"temperature\": 0.7" +
                "}";

        RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Authorization", "Bearer " + poolToken.getPoolToken())
                .build();

        try (Response response = client.newCall(request).execute()) {
            if(!response.isSuccessful() && response.code() == 404) {
                return "请检查PandoraNext公网地址是否填写正确！";
            }
            String result = response.body().string();
            JSONObject jsonResponse = new JSONObject(result);
            if (!jsonResponse.has("choices")) {
                poolToken.setCheckPool(false);
                String s = requireCheckPoolToken(poolToken);
                if (s.contains("成功")) {
                    return "pool_token过期，请重新刷新，" + s;
                } else {
                    log.info("已为你自动标记过期poolToken!");
                    return "pool_token过期，请重新刷新！";
                }
            }
            // 提取返回的数据
            JSONArray choicesArray = jsonResponse.getJSONArray("choices");
            JSONObject firstChoiceObject = choicesArray.getJSONObject(0);
            JSONObject messageObject = firstChoiceObject.getJSONObject("message");
            String content = messageObject.getString("content");
            poolToken.setCheckPool(true);
            String s = requireCheckPoolToken(poolToken);
            return "pool_token正常，请放心使用！";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getOpenaiUrl() {
        try {
            systemSetting systemSetting = systemService.selectSetting();
            String pandoraNextOutUrl = systemSetting.getPandoraNext_outUrl();
            String proxyApiPrefix = systemSetting.getProxy_api_prefix();
            if (pandoraNextOutUrl.charAt(pandoraNextOutUrl.length() - 1) != '/') {
                pandoraNextOutUrl += "/";
            }
            return pandoraNextOutUrl + proxyApiPrefix;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 添加Key值
     * 会通过Post方法访问One-Api接口/api/channel/,添加新keys
     *
     * @return "true"or"false"
     */
    public boolean addKey(poolToken addKeyPojo, String[] systemSetting) {
        if (!addKeyPojo.isIntoOneApi()) {
            return false;
        }
        String url = systemSetting[0].endsWith("/") ? systemSetting[0] + oneAPiChannel
                : systemSetting[0] + "/" + oneAPiChannel;
        log.info(url);
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", 8);
            jsonObject.put("key", addKeyPojo.getPoolToken());
            jsonObject.put("name", addKeyPojo.getPoolName());
            jsonObject.put("base_url", getOpenaiUrl());
            jsonObject.put("other", "");
            if (addKeyPojo.isPandoraNextGpt4()) {
                jsonObject.put("models", gpt4Models);
            } else {
                jsonObject.put("models", gpt3Models);
            }
            String group = addKeyPojo.getGroupChecked();
            jsonObject.put("group", group);
            jsonObject.put("model_mapping", "");
            jsonObject.put("groups", new JSONArray().put(group));
            // 将JSON对象转换为字符串
            String json = jsonObject.toString();

            OkHttpClient client = new OkHttpClient();
            RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Authorization", "Bearer " + systemSetting[1])
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    log.info("请求one-api失败，失败码: " + response.code());
                    return false;
                }
                String responseContent = response.body().string();
                JSONObject jsonResponse = new JSONObject(responseContent);
                boolean success = jsonResponse.getBoolean("success");
                if (response.code() == 200 && success) {
                    return true;
                } else {
                    log.info("请求one-api失败，失败码: " + response.code());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean deleteKeyId(poolToken poolToken, String[] systemSetting) {
        String url = systemSetting[0].endsWith("/") ? systemSetting[0] + oneApiSelect
                : systemSetting[0] + "/" + oneApiSelect;
        log.info(url);
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Authorization", "Bearer " + systemSetting[1])
                    .build();
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    log.info("浏览器状态为： " + response.code());
                    return false;
                }
                String responseContent = response.body().string();
                JSONObject jsonObject = new JSONObject(responseContent);
                JSONArray dataArray = jsonObject.getJSONArray("data");
                int id = -1;
                for (int i = 0; i < dataArray.length(); i++) {
                    JSONObject dataObject = dataArray.getJSONObject(i);
                    String name = dataObject.getString("name");
                    if (name.equals(poolToken.getPoolName())) {
                        id = dataObject.getInt("id");
                        break;
                    }
                }
                if (response.code() == 200) {
                    if (id > 0) {
                        boolean res = deleteKey(systemSetting, id);
                        return res;
                    }
                    log.info("没有找到相应的key名!");
                    return true;
                } else {
                    log.info("浏览器状态为： " + response.code());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean getPriority(poolToken poolToken, String[] systemSetting) {
        String url = systemSetting[0].endsWith("/") ? systemSetting[0] + oneApiSelect
                : systemSetting[0] + "/" + oneApiSelect;
        log.info(url);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + systemSetting[1])
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.info("没有找到相应的key名，浏览器状态为： " + response.code());
                return false;
            }
            String responseContent = response.body().string();
            JSONObject jsonObject = new JSONObject(responseContent);
            JSONArray dataArray = jsonObject.getJSONArray("data");
            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject dataObject = dataArray.getJSONObject(i);
                String name = dataObject.getString("name");
                if (name.equals(poolToken.getPoolName())) {
                    int id = dataObject.getInt("id");
                    return priorityKey(systemSetting, id, poolToken.getPriority());
                }
            }
            log.info("没有找到相应的key名");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean deleteKey(String[] systemSetting, int keyId) {
        String url = systemSetting[0].endsWith("/") ? systemSetting[0] + oneAPiChannel + keyId
                : systemSetting[0] + "/" + oneAPiChannel + keyId;
        log.info("请求one-api的网址为：" + url);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + systemSetting[1])
                .delete()
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.info("未找到当前的key，浏览器状态为: " + response.code());
                return false;
            }
            String responseContent = response.body().string();
            JSONObject jsonResponse = new JSONObject(responseContent);
            boolean success = jsonResponse.getBoolean("success");
            if (success) {
                log.info("key删除成功！");
                return true;
            }
            log.info(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean priorityKey(String[] systemSetting, int keyId, Integer priority) {
        String url = systemSetting[0].endsWith("/") ? systemSetting[0] + oneAPiChannel
                : systemSetting[0] + "/" + oneAPiChannel;
        log.info("请求one-api的网址为：" + url);
        OkHttpClient client = new OkHttpClient();
        RequestBody body = null;
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", keyId);
            jsonObject.put("priority", priority);
            String json = jsonObject.toString();
            body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + systemSetting[1])
                .put(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String responseContent = Objects.requireNonNull(response.body()).string();
            JSONObject jsonResponse = new JSONObject(responseContent);
            if (response.isSuccessful() && jsonResponse.getBoolean("success")) {
                return true;
            } else {
                log.info("更改优先级失败，失败码: " + response.code());
            }
            log.info(jsonResponse.toString());
        } catch (Exception e) {
            log.error("请求处理异常", e);
        }
        return false;
    }

}

Answer: systemSetting systemSetting = systemService.selectSetting();

<think>
The tokenController method getSimplePoolToken starts with its signature and an opening brace. Following the pattern of earlier methods (e.g., getSharedToken, getAccessToken), the first operation inside the method is to retrieve the system settings via systemService. Therefore the next line should be the declaration and assignment of a systemSetting variable.
</think>
systemSetting systemSetting = systemService.selectSetting();