Compare commits

...

11 Commits

Author SHA1 Message Date
xream
e5c1ae9ed8 feat: 优化流量解析规则 2024-01-20 23:00:37 +08:00
xream
9b6d9d49f9 Merge pull request #275 from dnomd343/master
fix: 流量信息匹配错误
2024-01-20 22:40:13 +08:00
xream
a12adf5255 chore: 脚本操作时不使用空值合并运算符 2024-01-20 22:14:23 +08:00
Dnomd343
8682f14ee7 fix: scientific counting matching error 2024-01-20 13:16:11 +08:00
xream
b3de7a4bc5 feat: 优化调整 Gist 同步逻辑; 增加 GitLab Snippet 同步 2024-01-20 05:33:31 +08:00
xream
099ae5ad83 fix: 配置接口补齐错误处理 2024-01-20 00:50:35 +08:00
xream
c7d00ac512 feat: 域名解析支持类型和过滤 2024-01-19 21:43:54 +08:00
xream
ca0d800bbb release: backend version 2.14.184 2024-01-19 12:54:40 +08:00
xream
31b48d7a6c Merge pull request #274 from izhangxm/feat_add_proxy_convter_api
增加规则转换与协议转换API接口
2024-01-19 12:35:32 +08:00
makabaka
ab96ae9413 增加规则转换与协议转换API接口 2024-01-19 12:23:04 +08:00
xream
3fc507b576 feat: 解析并删除旧的 ws-path ws-headers 字段 2024-01-19 10:18:27 +08:00
13 changed files with 463 additions and 123 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "sub-store",
"version": "2.14.182",
"version": "2.14.189",
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and ShadowRocket.",
"main": "src/main.js",
"scripts": {

View File

@@ -224,6 +224,19 @@ function lastParse(proxy) {
.replace(/^\[/, '')
.replace(/\]$/, '');
}
if (proxy.network === 'ws') {
if (!proxy['ws-opts'] && (proxy['ws-path'] || proxy['ws-headers'])) {
proxy['ws-opts'] = {};
if (proxy['ws-path']) {
proxy['ws-opts'].path = proxy['ws-path'];
}
if (proxy['ws-headers']) {
proxy['ws-opts'].headers = proxy['ws-headers'];
}
}
delete proxy['ws-path'];
delete proxy['ws-headers'];
}
if (proxy.type === 'trojan') {
if (proxy.network === 'tcp') {
delete proxy.network;

View File

@@ -324,7 +324,7 @@ function ScriptOperator(script, targetPlatform, $arguments, source) {
const operator = createDynamicFunction(
'operator',
`async function operator(input = []) {
if (input?.$files || input?.$content) {
if (input && (input.$files || input.$content)) {
let { $content, $files } = input
${script}
return { $content, $files }
@@ -348,14 +348,14 @@ function ScriptOperator(script, targetPlatform, $arguments, source) {
}
const DOMAIN_RESOLVERS = {
Google: async function (domain) {
const id = hex_md5(`GOOGLE:${domain}`);
Google: async function (domain, type) {
const id = hex_md5(`GOOGLE:${domain}:${type}`);
const cached = resourceCache.get(id);
if (cached) return cached;
const resp = await $.http.get({
url: `https://8.8.4.4/resolve?name=${encodeURIComponent(
domain,
)}&type=A`,
)}&type=${type === 'IPv6' ? 'AAAA' : 'A'}`,
headers: {
accept: 'application/dns-json',
},
@@ -389,14 +389,14 @@ const DOMAIN_RESOLVERS = {
resourceCache.set(id, result);
return result;
},
Cloudflare: async function (domain) {
const id = hex_md5(`CLOUDFLARE:${domain}`);
Cloudflare: async function (domain, type) {
const id = hex_md5(`CLOUDFLARE:${domain}:${type}`);
const cached = resourceCache.get(id);
if (cached) return cached;
const resp = await $.http.get({
url: `https://1.0.0.1/dns-query?name=${encodeURIComponent(
domain,
)}&type=A`,
)}&type=${type === 'IPv6' ? 'AAAA' : 'A'}`,
headers: {
accept: 'application/dns-json',
},
@@ -413,14 +413,14 @@ const DOMAIN_RESOLVERS = {
resourceCache.set(id, result);
return result;
},
Ali: async function (domain) {
const id = hex_md5(`ALI:${domain}`);
Ali: async function (domain, type) {
const id = hex_md5(`ALI:${domain}:${type}`);
const cached = resourceCache.get(id);
if (cached) return cached;
const resp = await $.http.get({
url: `http://223.6.6.6/resolve?name=${encodeURIComponent(
domain,
)}&type=A&short=1`,
)}&type=${type === 'IPv6' ? 'AAAA' : 'A'}&short=1`,
headers: {
accept: 'application/dns-json',
},
@@ -433,14 +433,14 @@ const DOMAIN_RESOLVERS = {
resourceCache.set(id, result);
return result;
},
Tencent: async function (domain) {
const id = hex_md5(`ALI:${domain}`);
Tencent: async function (domain, type) {
const id = hex_md5(`ALI:${domain}:${type}`);
const cached = resourceCache.get(id);
if (cached) return cached;
const resp = await $.http.get({
url: `http://119.28.28.28/d?type=A&dn=${encodeURIComponent(
domain,
)}`,
url: `http://119.28.28.28/d?type=${
type === 'IPv6' ? 'AAAA' : 'A'
}&dn=${encodeURIComponent(domain)}`,
headers: {
accept: 'application/dns-json',
},
@@ -455,10 +455,13 @@ const DOMAIN_RESOLVERS = {
},
};
function ResolveDomainOperator({ provider }) {
function ResolveDomainOperator({ provider, type, filter }) {
if (type === 'IPv6' && ['IP-API'].includes(provider)) {
throw new Error(`域名解析服务提供方 ${provider} 不支持 IPv6`);
}
const resolver = DOMAIN_RESOLVERS[provider];
if (!resolver) {
throw new Error(`Cannot find resolver: ${provider}`);
throw new Error(`找不到域名解析服务提供方: ${provider}`);
}
return {
name: 'Resolve Domain Operator',
@@ -477,7 +480,7 @@ function ResolveDomainOperator({ provider }) {
const currentBatch = [];
for (let domain of totalDomain.splice(0, limit)) {
currentBatch.push(
resolver(domain)
resolver(domain, type)
.then((ip) => {
results[domain] = ip;
$.info(
@@ -504,7 +507,19 @@ function ResolveDomainOperator({ provider }) {
}
});
return proxies;
return proxies.filter((p) => {
if (filter === 'removeFailed') {
return p['no-resolve'] || p.resolved;
} else if (filter === 'IPOnly') {
return isIP(p.server);
} else if (filter === 'IPv4Only') {
return isIPv4(p.server);
} else if (filter === 'IPv6Only') {
return isIPv6(p.server);
} else {
return true;
}
});
},
};
}

View File

@@ -54,9 +54,18 @@ async function doSync() {
if (artifact.sync) {
artifact.updated = new Date().getTime();
// extract real url from gist
artifact.url = body.files[
encodeURIComponent(artifact.name)
]?.raw_url.replace(/\/raw\/[^/]*\/(.*)/, '/raw/$1');
let files = body.files;
let isGitLab;
if (Array.isArray(files)) {
isGitLab = true;
files = Object.fromEntries(
files.map((item) => [item.path, item]),
);
}
const url = files[encodeURIComponent(artifact.name)]?.raw_url;
artifact.url = isGitLab
? url
: url?.replace(/\/raw\/[^/]*\/(.*)/, '/raw/$1');
}
}

View File

@@ -35,13 +35,14 @@ export default function register($app) {
async function restoreArtifacts(_, res) {
$.info('开始恢复远程配置...');
try {
const { gistToken } = $.read(SETTINGS_KEY);
const { gistToken, syncPlatform } = $.read(SETTINGS_KEY);
if (!gistToken) {
return Promise.reject('未设置 GitHub Token');
}
const manager = new Gist({
token: gistToken,
key: ARTIFACT_REPOSITORY_KEY,
syncPlatform,
});
try {
@@ -243,13 +244,14 @@ function validateArtifactName(name) {
}
async function syncToGist(files) {
const { gistToken } = $.read(SETTINGS_KEY);
const { gistToken, syncPlatform } = $.read(SETTINGS_KEY);
if (!gistToken) {
return Promise.reject('未设置 GitHub Token');
}
const manager = new Gist({
token: gistToken,
key: ARTIFACT_REPOSITORY_KEY,
syncPlatform,
});
return manager.upload(files);
}

View File

@@ -16,6 +16,7 @@ import registerPreviewRoutes from './preview';
import registerSortingRoutes from './sort';
import registerMiscRoutes from './miscs';
import registerNodeInfoRoutes from './node-info';
import registerParserRoutes from './parser';
export default function serve() {
let port;
@@ -38,6 +39,7 @@ export default function serve() {
registerSyncRoutes($app);
registerNodeInfoRoutes($app);
registerMiscRoutes($app);
registerParserRoutes($app);
$app.start();

View File

@@ -1,7 +1,7 @@
import $ from '@/core/app';
import { ENV } from '@/vendor/open-api';
import { failed, success } from '@/restful/response';
import { updateArtifactStore, updateGitHubAvatar } from '@/restful/settings';
import { updateArtifactStore, updateAvatar } from '@/restful/settings';
import resourceCache from '@/utils/resource-cache';
import {
GIST_BACKUP_FILE_NAME,
@@ -68,7 +68,7 @@ function getEnv(req, res) {
async function refresh(_, res) {
// 1. get GitHub avatar and artifact store
await updateGitHubAvatar();
await updateAvatar();
await updateArtifactStore();
// 2. clear resource cache
@@ -79,7 +79,7 @@ async function refresh(_, res) {
async function gistBackup(req, res) {
const { action } = req.query;
// read token
const { gistToken } = $.read(SETTINGS_KEY);
const { gistToken, syncPlatform } = $.read(SETTINGS_KEY);
if (!gistToken) {
failed(
res,
@@ -92,6 +92,7 @@ async function gistBackup(req, res) {
const gist = new Gist({
token: gistToken,
key: GIST_BACKUP_KEY,
syncPlatform,
});
try {
let content;

View File

@@ -0,0 +1,54 @@
import { success, failed } from '@/restful/response';
import { ProxyUtils } from '@/core/proxy-utils';
import { RuleUtils } from '@/core/rule-utils';
export default function register($app) {
$app.route('/api/proxy/parse').post(proxy_parser);
$app.route('/api/rule/parse').post(rule_parser);
}
/***
* 感谢 izhangxm 的 PR!
* 目前没有节点操作, 没有支持完整参数, 以后再完善一下
*/
/***
* 代理服务器协议转换接口。
* 请求方法为POST数据为json。需要提供data和client字段。
* data: string, 协议数据每行一个或者是clash
* client: string, 目标平台名称见backend/src/core/proxy-utils/producers/index.js
*
*/
function proxy_parser(req, res) {
const { data, client, content, platform } = req.body;
var result = {};
try {
var proxies = ProxyUtils.parse(data ?? content);
var par_res = ProxyUtils.produce(proxies, client ?? platform);
result['par_res'] = par_res;
} catch (err) {
failed(res, err);
return;
}
success(res, result);
}
/**
* 规则转换接口。
* 请求方法为POST数据为json。需要提供data和client字段。
* data: string, 多行规则字符串
* client: string, 目标平台名称具体见backend/src/core/rule-utils/producers.js
*/
function rule_parser(req, res) {
const { data, client, content, platform } = req.body;
var result = {};
try {
const rules = RuleUtils.parse(data ?? content);
var par_res = RuleUtils.produce(rules, client ?? platform);
result['par_res'] = par_res;
} catch (err) {
failed(res, err);
return;
}
success(res, result);
}

View File

@@ -1,5 +1,6 @@
import { SETTINGS_KEY, ARTIFACT_REPOSITORY_KEY } from '@/constants';
import { success } from './response';
import { success, failed } from './response';
import { InternalServerError } from '@/restful/errors';
import $ from '@/core/app';
import Gist from '@/utils/gist';
@@ -10,53 +11,105 @@ export default function register($app) {
}
async function getSettings(req, res) {
let settings = $.read(SETTINGS_KEY);
if (!settings) {
settings = {};
$.write(settings, SETTINGS_KEY);
}
try {
let settings = $.read(SETTINGS_KEY);
if (!settings) {
settings = {};
$.write(settings, SETTINGS_KEY);
}
if (!settings.avatarUrl) await updateGitHubAvatar();
if (!settings.artifactStore) await updateArtifactStore();
success(res, settings);
// TODO: 缺错误处理 前端也缺
if (!settings.avatarUrl) await updateAvatar();
if (!settings.artifactStore) await updateArtifactStore();
success(res, settings);
} catch (e) {
$.error(`Failed to get settings: ${e.message ?? e}`);
failed(
res,
new InternalServerError(
`FAILED_TO_GET_SETTINGS`,
`Failed to get settings`,
`Reason: ${e.message ?? e}`,
),
);
}
}
async function updateSettings(req, res) {
const settings = $.read(SETTINGS_KEY);
const newSettings = {
...settings,
...req.body,
};
$.write(newSettings, SETTINGS_KEY);
await updateGitHubAvatar();
await updateArtifactStore();
success(res, newSettings);
// TODO: 缺错误处理 前端也缺
try {
const settings = $.read(SETTINGS_KEY);
const newSettings = {
...settings,
...req.body,
};
$.write(newSettings, SETTINGS_KEY);
await updateAvatar();
await updateArtifactStore();
success(res, newSettings);
} catch (e) {
$.error(`Failed to update settings: ${e.message ?? e}`);
failed(
res,
new InternalServerError(
`FAILED_TO_UPDATE_SETTINGS`,
`Failed to update settings`,
`Reason: ${e.message ?? e}`,
),
);
}
}
export async function updateGitHubAvatar() {
export async function updateAvatar() {
const settings = $.read(SETTINGS_KEY);
const username = settings.githubUser;
const { githubUser: username, syncPlatform } = settings;
if (username) {
try {
const data = await $.http
.get({
url: `https://api.github.com/users/${username}`,
headers: {
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36',
},
})
.then((resp) => JSON.parse(resp.body));
settings.avatarUrl = data['avatar_url'];
$.write(settings, SETTINGS_KEY);
} catch (err) {
$.error(
`Failed to fetch GitHub avatar for User: ${username}. Reason: ${
err.message ?? err
}`,
);
if (syncPlatform === 'gitlab') {
try {
const data = await $.http
.get({
url: `https://gitlab.com/api/v4/users?username=${encodeURIComponent(
username,
)}`,
headers: {
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36',
},
})
.then((resp) => JSON.parse(resp.body));
settings.avatarUrl = data[0]['avatar_url'].replace(
/(\?|&)s=\d+(&|$)/,
'$1s=160$2',
);
$.write(settings, SETTINGS_KEY);
} catch (err) {
$.error(
`Failed to fetch GitLab avatar for User: ${username}. Reason: ${
err.message ?? err
}`,
);
}
} else {
try {
const data = await $.http
.get({
url: `https://api.github.com/users/${encodeURIComponent(
username,
)}`,
headers: {
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36',
},
})
.then((resp) => JSON.parse(resp.body));
settings.avatarUrl = data['avatar_url'];
$.write(settings, SETTINGS_KEY);
} catch (err) {
$.error(
`Failed to fetch GitHub avatar for User: ${username}. Reason: ${
err.message ?? err
}`,
);
}
}
}
}
@@ -64,19 +117,21 @@ export async function updateGitHubAvatar() {
export async function updateArtifactStore() {
$.log('Updating artifact store');
const settings = $.read(SETTINGS_KEY);
const { gistToken } = settings;
const { gistToken, syncPlatform } = settings;
if (gistToken) {
const manager = new Gist({
token: gistToken,
key: ARTIFACT_REPOSITORY_KEY,
syncPlatform,
});
try {
const gist = await manager.locate();
if (gist?.html_url) {
$.log(`找到 Sub-Store Gist: ${gist.html_url}`);
const url = gist?.html_url ?? gist?.web_url;
if (url) {
$.log(`找到 Sub-Store Gist: ${url}`);
// 只需要保证 token 是对的, 现在 username 错误只会导致头像错误
settings.artifactStore = gist.html_url;
settings.artifactStore = url;
settings.artifactStoreStatus = 'VALID';
} else {
$.error(`找不到 Sub-Store Gist`);

View File

@@ -492,9 +492,18 @@ async function syncArtifacts() {
if (artifact.sync) {
artifact.updated = new Date().getTime();
// extract real url from gist
artifact.url = body.files[
encodeURIComponent(artifact.name)
]?.raw_url.replace(/\/raw\/[^/]*\/(.*)/, '/raw/$1');
let files = body.files;
let isGitLab;
if (Array.isArray(files)) {
isGitLab = true;
files = Object.fromEntries(
files.map((item) => [item.path, item]),
);
}
const url = files[encodeURIComponent(artifact.name)]?.raw_url;
artifact.url = isGitLab
? url
: url?.replace(/\/raw\/[^/]*\/(.*)/, '/raw/$1');
}
}
@@ -582,9 +591,16 @@ async function syncArtifact(req, res) {
});
artifact.updated = new Date().getTime();
const body = JSON.parse(resp.body);
artifact.url = body.files[
encodeURIComponent(artifact.name)
]?.raw_url.replace(/\/raw\/[^/]*\/(.*)/, '/raw/$1');
let files = body.files;
let isGitLab;
if (Array.isArray(files)) {
isGitLab = true;
files = Object.fromEntries(files.map((item) => [item.path, item]));
}
const url = files[encodeURIComponent(artifact.name)]?.raw_url;
artifact.url = isGitLab
? url
: url?.replace(/\/raw\/[^/]*\/(.*)/, '/raw/$1');
$.write(allArtifacts, ARTIFACTS_KEY);
success(res, artifact);
} catch (err) {

View File

@@ -88,17 +88,27 @@ export async function getFlowHeaders(rawUrl, ua, timeout) {
export function parseFlowHeaders(flowHeaders) {
if (!flowHeaders) return;
// unit is KB
const uploadMatch = flowHeaders.match(/upload=(-?)(\d+)/);
const uploadMatch = flowHeaders.match(
/upload=([-+]?)([0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)/,
);
const upload = Number(uploadMatch[1] + uploadMatch[2]);
const downloadMatch = flowHeaders.match(/download=(-?)(\d+)/);
const downloadMatch = flowHeaders.match(
/download=([-+]?)([0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)/,
);
const download = Number(downloadMatch[1] + downloadMatch[2]);
const total = Number(flowHeaders.match(/total=(\d+)/)[1]);
const totalMatch = flowHeaders.match(
/total=([-+]?)([0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)/,
);
const total = Number(totalMatch[1] + totalMatch[2]);
// optional expire timestamp
const match = flowHeaders.match(/expire=(\d+)/);
const expires = match ? Number(match[1]) : undefined;
const expireMatch = flowHeaders.match(
/expire=([-+]?)([0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)/,
);
const expires = expireMatch
? Number(expireMatch[1] + expireMatch[2])
: undefined;
return { expires, total, usage: { upload, download } };
}

View File

@@ -4,64 +4,216 @@ import { HTTP } from '@/vendor/open-api';
* Gist backup
*/
export default class Gist {
constructor({ token, key }) {
this.http = HTTP({
baseURL: 'https://api.github.com',
headers: {
constructor({ token, key, syncPlatform }) {
if (syncPlatform === 'gitlab') {
this.headers = {
'PRIVATE-TOKEN': `${token}`,
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36',
};
this.http = HTTP({
baseURL: 'https://gitlab.com/api/v4',
headers: { ...this.headers },
events: {
onResponse: (resp) => {
if (/^[45]/.test(String(resp.statusCode))) {
const body = JSON.parse(resp.body);
return Promise.reject(
`ERROR: ${body.message?.error ?? body.message}`,
);
} else {
return resp;
}
},
},
});
} else {
this.headers = {
Authorization: `token ${token}`,
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36',
},
events: {
onResponse: (resp) => {
if (/^[45]/.test(String(resp.statusCode))) {
return Promise.reject(
`ERROR: ${JSON.parse(resp.body).message}`,
);
} else {
return resp;
}
};
this.http = HTTP({
baseURL: 'https://api.github.com',
headers: { ...this.headers },
events: {
onResponse: (resp) => {
if (/^[45]/.test(String(resp.statusCode))) {
return Promise.reject(
`ERROR: ${JSON.parse(resp.body).message}`,
);
} else {
return resp;
}
},
},
},
});
});
}
this.key = key;
this.syncPlatform = syncPlatform;
}
async locate() {
return this.http.get('/gists').then((response) => {
const gists = JSON.parse(response.body);
for (let g of gists) {
if (g.description === this.key) {
return g;
if (this.syncPlatform === 'gitlab') {
return this.http.get('/snippets').then((response) => {
const gists = JSON.parse(response.body);
for (let g of gists) {
if (g.title === this.key) {
return g;
}
}
}
return;
});
return;
});
} else {
return this.http.get('/gists').then((response) => {
const gists = JSON.parse(response.body);
for (let g of gists) {
if (g.description === this.key) {
return g;
}
}
return;
});
}
}
async upload(files) {
if (Object.keys(files).length === 0) {
async upload(input) {
if (Object.keys(input).length === 0) {
return Promise.reject('未提供需上传的文件');
}
const gist = await this.locate();
let files = input;
if (gist?.id) {
// update an existing gist
return this.http.patch({
url: `/gists/${gist.id}`,
body: JSON.stringify({ files }),
if (this.syncPlatform === 'gitlab') {
gist.files = gist.files.reduce((acc, item) => {
acc[item.path] = item;
return acc;
}, {});
}
// console.log(`files`, files);
// console.log(`gist`, gist.files);
let actions = [];
const result = { ...gist.files };
Object.keys(files).map((key) => {
if (result[key]) {
if (
files[key].content == null ||
files[key].content === ''
) {
delete result[key];
actions.push({
action: 'delete',
file_path: key,
});
} else {
result[key] = files[key];
actions.push({
action: 'update',
file_path: key,
content: files[key].content,
});
}
} else {
if (
files[key].content == null ||
files[key].content === ''
) {
delete result[key];
delete files[key];
} else {
result[key] = files[key];
actions.push({
action: 'create',
file_path: key,
content: files[key].content,
});
}
}
});
console.log(`result`, result);
console.log(`files`, files);
console.log(`actions`, actions);
if (this.syncPlatform === 'gitlab') {
if (Object.keys(result).length === 0) {
return Promise.reject(
'本次操作将导致所有文件的内容都为空, 无法更新 snippet',
);
}
if (Object.keys(result).length > 10) {
return Promise.reject(
'本次操作将导致 snippet 的文件数超过 10, 无法更新 snippet',
);
}
files = actions;
return this.http.put({
headers: {
...this.headers,
'Content-Type': 'application/json',
},
url: `/snippets/${gist.id}`,
body: JSON.stringify({ files }),
});
} else {
if (Object.keys(result).length === 0) {
return Promise.reject(
'本次操作将导致所有文件的内容都为空, 无法更新 gist',
);
}
return this.http.patch({
url: `/gists/${gist.id}`,
body: JSON.stringify({ files }),
});
}
} else {
// create a new gist for backup
return this.http.post({
url: '/gists',
body: JSON.stringify({
description: this.key,
public: false,
files,
}),
});
files = Object.entries(files).reduce((acc, [key, file]) => {
if (file.content !== null && file.content !== '') {
acc[key] = file;
}
return acc;
}, {});
if (this.syncPlatform === 'gitlab') {
if (Object.keys(files).length === 0) {
return Promise.reject(
'所有文件的内容都为空, 无法创建 snippet',
);
}
files = Object.keys(files).map((key) => ({
file_path: key,
content: files[key].content,
}));
return this.http.post({
headers: {
...this.headers,
'Content-Type': 'application/json',
},
url: '/snippets',
body: JSON.stringify({
title: this.key,
visibility: 'private',
files,
}),
});
} else {
if (Object.keys(files).length === 0) {
return Promise.reject(
'所有文件的内容都为空, 无法创建 gist',
);
}
return this.http.post({
url: '/gists',
body: JSON.stringify({
description: this.key,
public: false,
files,
}),
});
}
}
}

View File

@@ -314,6 +314,17 @@ export function HTTP(defaultOptions = { baseURL: '' }) {
request[method.toLowerCase()](
options,
(err, response, body) => {
// if (err) {
// console.log(err);
// } else {
// console.log({
// statusCode:
// response.status || response.statusCode,
// headers: response.headers,
// body,
// });
// }
if (err) reject(err);
else
resolve({