// ==UserScript== // @name CPH API库 // @namespace http://tampermonkey.net/ // @version 0.1.0 // @author Andy_hpy // @icon https://divyanshuagrawal.gallerycdn.azure.cn/extensions/divyanshuagrawal/competitive-programming-helper/2025.12.1766739309/1766739324237/Microsoft.VisualStudio.Services.Icons.Default // @description 封装CPH的API // @grant GM_xmlhttpRequest // @grant unsafeWindow // @connect localhost // @connect 127.0.0.1 // ==/UserScript== function sendToCPH(data, port) { return new Promise((resolve) => { GM_xmlhttpRequest({ method: 'POST', url: `http://localhost:${port}/`, headers: { 'Content-Type': 'application/json' }, data: JSON.stringify(data), onload: function (response) { if (response.status !== 200) { resolve({ message: `错误:CPH 返回状态码 ${response.status}`, success: false, status: response.status }); } else { resolve({ message: `发送成功`, success: true, status: 200 }); } }, onerror: function () { resolve({ message: `连接失败\n请确认 CPH 插件已启动,且端口为 ${port}`, success: false, status: 502 }); }, ontimeout: function () { resolve({ message: `连接超时,请检查插件状态`, success: false, status: 504 }); } }); }); } function getSubmit(port) { return new Promise((resolve) => { GM_xmlhttpRequest({ method: 'GET', url: `http://localhost:${port}/getSubmit`, onload: function(res) { if (res.status === 200) { try { const data = JSON.parse(res.responseText); if (!data.empty) { const task = { problemName: data.problemName, languageId: data.languageId, sourceCode: data.sourceCode, url: data.url }; resolve({ data: task, success: true, status: 200 }); } else { resolve({ data: `服务器返回 empty,无任务`, success: false, status: 204 }); } } catch (e) { resolve({ data: `解析 JSON 失败: ${e.message}`, success: false, status: 500 }); } } else { resolve({ data: `HTTP 错误: ${res.status}`, success: false, status: res.status }); } }, onerror: function(err) { resolve({ data: `请求失败: ${err.statusText}`, success: false, status: err.status }); } }); }); } class CPH { constructor(port) { this.port = port; } async send(data) { return await sendToCPH(data, this.port); } async getSubmit() { return await getSubmit(this.port); } editPort(port) { this.port = port; } } CPH.version = '0.1.0'; CPH.url = 'https://scriptcat.org/zh-CN/script-show-page/5444'; (window.unsafeWindow || window).CPH = CPH;