import * as vscode from "vscode"; import axios from "axios"; import { submitQuestion } from "../service"; import { login, checkIsLogin } from "./login"; import { getDayId } from '../utils/getDayID'; export async function postAnswer( document: vscode.TextDocument, content: string, context: vscode.ExtensionContext ) { try { const { name, token } = await checkIsLogin(); const answer = pickUserAnswer(content); if (!answer) { vscode.window.showErrorMessage("答案不能为空"); return; } const question_id = Number(getDayId(document.fileName)); const data = { question_id, name, answer, }; try { const response = await submitQuestion(data, token); vscode.window.showInformationMessage("提交成功"); } catch (error) { vscode.window.showErrorMessage("提交失败"); console.log(error); } } catch (error) { vscode.window .showWarningMessage("请先点击此处登录", "登录") .then((result) => { if (result === "登录") { login(context); } }); } } function pickUserAnswer(content: string): string { const regex = /\*\[攀峰\]: start(.*?)\*\[攀峰\]: end/s; const regexJs = /\/\/ @攀峰 start(.*?)\/\/ @攀峰 end/s; if (regex.exec(content)) { const [, answer = ""] = regex.exec(content) || []; return answer.trim(); } else if (regexJs.exec(content)) { const [, answer = ""] = regexJs.exec(content) || []; // TODO: XSS规则会把部分符号转译 // return "```javascript \n" + answer.trim() + "\n```"; return answer.trim(); } return ""; }