组合订阅现在允许添加所有节点操作

This commit is contained in:
Peng-YM committed 2020-11-24 21:21:43 +08:00
1 parent f886bc11e9
commit ff4790f12e
7 files changed
+202 -97

No files matched your search

+38 -11
View File
@@ -25,7 +25,7 @@ function startService() {
___/ // /_/ // /_/ //_____/___/ // /_ / /_/ // / / __/
/____/ \__,_//_.___/ /____/ \__/ \____//_/ \___/
*/
});
});
console.log(welcome);
const $app = express();
// Constants
@@ -90,22 +90,36 @@ function startService() {
$app.get("/api/utils/env", getEnv); // get runtime environment
$app.get("/api/utils/backup", gistBackup); // gist backup actions
// Redirect sub.store to vercel webpage
$app.get("/", async (req, res) => {
// 302 redirect
res.set("location", "https://sub-store.vercel.app/").status(302).end();
});
// handle preflight request for QX
if (ENV().isQX) {
$app.options("/", async (req, res) => {
res.status(200).end();
});
}
$app.start();
// subscriptions API
async function downloadSubscription(req, res) {
const {name} = req.params;
const {cache} = req.query || false;
const {cache} = req.query;
const platform = req.query.target || getPlatformFromHeaders(req.headers);
const allSubs = $.read(SUBS_KEY);
const sub = allSubs[name];
if (sub) {
try {
const raw = await getResource(sub.url, cache);
const useCache = typeof cache === 'undefined' ? (platform === 'JSON' || platform === 'URI') : cache;
const raw = await getResource(sub.url, useCache);
// parse proxies
let proxies = ProxyUtils.parse(raw);
// apply processors
proxies = await ProxyUtils.process(proxies, sub.process);
proxies = await ProxyUtils.process(proxies, sub.process || []);
// produce
const output = ProxyUtils.produce(proxies, platform);
if (platform === 'JSON') {
@@ -138,6 +152,7 @@ function startService() {
function createSubscription(req, res) {
const sub = req.body;
const allSubs = $.read(SUBS_KEY);
$.info(`正在创建订阅: ${sub.name}`);
if (allSubs[sub.name]) {
res.status(500).json({
status: "failed",
@@ -185,6 +200,7 @@ function startService() {
...allSubs[name],
...sub,
};
$.info(`正在更新订阅: ${name}`);
// allow users to update the subscription name
if (name !== sub.name) {
// we need to find out all collections refer to this name
@@ -216,6 +232,7 @@ function startService() {
function deleteSubscription(req, res) {
const {name} = req.params;
$.info(`删除订阅:${name}...`);
// delete from subscriptions
let allSubs = $.read(SUBS_KEY);
delete allSubs[name];
@@ -260,9 +277,12 @@ function startService() {
const sub = allSubs[subs[i]];
$.info(`正在处理子订阅:${sub.name},进度--${100 * (i + 1 / subs.length).toFixed(1)}% `);
try {
const raw = await getResource(sub.url, cache);
const useCache = typeof cache === 'undefined' ? (platform === 'JSON' || platform === 'URI') : cache;
const raw = await getResource(sub.url, useCache);
// parse proxies
proxies = proxies.concat(ProxyUtils.parse(raw));
// apply processors
proxies = await ProxyUtils.process(proxies, sub.process || []);
} catch (err) {
$.error(`处理组合订阅中的子订阅: ${sub.name}时出现错误:${err}! 该订阅已被跳过。`);
}
@@ -312,6 +332,7 @@ function startService() {
function createCollection(req, res) {
const collection = req.body;
$.info(`正在创建组合订阅:${collection.name}`);
const allCol = $.read(COLLECTIONS_KEY);
if (allCol[collection.name]) {
res.status(500).json({
@@ -360,6 +381,7 @@ function startService() {
...allCol[name],
...collection,
};
$.info(`正在更新组合订阅:${name}...`);
// allow users to update collection name
delete allCol[name];
allCol[collection.name || name] = newCol;
@@ -378,6 +400,7 @@ function startService() {
function deleteCollection(req, res) {
const {name} = req.params;
$.info(`正在删除组合订阅:${name}`);
let allCol = $.read(COLLECTIONS_KEY);
delete allCol[name];
$.write(allCol, COLLECTIONS_KEY);
@@ -423,6 +446,7 @@ function startService() {
async function refreshCache(req, res) {
const {url} = req.body;
$.info(`Refreshing cache for URL: ${url}`);
try {
const raw = await getResource(url, false);
$.write(raw, `#${Base64.safeEncode(url)}`);
@@ -531,6 +555,9 @@ function startService() {
return resource;
}
const {body} = await $http.get(url);
if (body.replace(/\s/g, "").length === 0) {
throw new Error("订阅内容为空!");
}
$.write(body, key);
$.write(new Date().getTime(), timeKey);
return body;
@@ -666,7 +693,7 @@ var ProxyUtils = (function () {
return producer.produce(proxy);
} catch (err) {
$.error(
`ERROR: cannot produce proxy: ${JSON.stringify(
`Cannot produce proxy: ${JSON.stringify(
proxy, null, 2
)}\nReason: ${err}`
);
@@ -1385,7 +1412,7 @@ var PROXY_PARSERS = (function () {
if (params.length > 4) {
const [key, val] = params[4].split(":");
if (key === "tls-name") proxy.sni = val;
else throw new Error(`ERROR: unknown option ${key} for line: \n${line}`);
else throw new Error(`Unknown option ${key} for line: \n${line}`);
}
return proxy;
};
@@ -2122,7 +2149,7 @@ var PROXY_PROCESSORS = (function () {
if (output_) output = output_;
} catch (err) {
// print log and skip this operator
console.log(`ERROR: cannot apply operator ${op.name}! Reason: ${err}`);
console.log(`Cannot apply operator ${op.name}! Reason: ${err}`);
}
return output;
}
@@ -2413,9 +2440,8 @@ var PROXY_PRODUCERS = (function () {
}
function URI_Producer() {
const targetPlatform = "URI";
const Base64 = new Base64Code();
const output = (proxy) => {
const type = "SINGLE";
const produce = (proxy) => {
let result = "";
switch (proxy.type) {
case "ss":
@@ -2489,6 +2515,7 @@ var PROXY_PRODUCERS = (function () {
}
return result;
}
return {type, produce};
}
function JSON_Producer() {
+2 -2
View File
@@ -1,2 +1,2 @@
// UPDATED AT: 2020年11月24日 星期二 17时24分20秒 CST
const $=API("sub-store"),Base64=new Base64Code;function startService(){const e=heredoc(function(){});console.log(e);const t=express(),s="settings",r="subs",n="collections";function o(e){const t=Object.keys(e);let s="";for(let r of t)if(/USER-AGENT/i.test(r)){s=e[r];break}return-1!==s.indexOf("Quantumult%20X")?"QX":-1!==s.indexOf("Surge")?"Surge":-1!==s.indexOf("Decar")||-1!==s.indexOf("Loon")?"Loon":"JSON"}async function a(e,t=!0){const s=HTTP({headers:{"User-Agent":"Quantumult%20X"}}),r="#"+Base64.safeEncode(e),n=$.read(r),o=`#TIME-${Base64.safeEncode(e)}`,a=(new Date).getTime()-$.read(o)>864e5;if(t&&n&&!a)return $.log(`Use cached for url: ${e}`),n;const{body:i}=await s.get(e);return $.write(i,r),$.write((new Date).getTime(),o),i}$.read(r)||$.write({},r),$.read(n)||$.write({},n),$.read(s)||$.write({},s),t.get("/download/:name",async function(e,t){const{name:s}=e.params,{cache:n}=e.query||!1,i=e.query.target||o(e.headers),p=$.read(r)[s];if(p)try{const e=await a(p.url,n);let r=ProxyUtils.parse(e);r=await ProxyUtils.process(r,p.process);const o=ProxyUtils.produce(r,i);"JSON"===i?t.set("Content-Type","application/json").send(o):t.send(o)}catch(e){$.notify("🌍 [Sub-Store] 下载订阅失败",`❌ 无法下载订阅:${s}!`,`🤔 原因:${e}`),t.status(500).json({status:"failed",message:e})}else $.notify("🌍 [Sub-Store] 下载订阅失败",`❌ 未找到订阅:${s}!`),t.status(404).json({status:"failed"})}),t.get("/download/collection/:name",async function(e,t){const{name:s}=e.params,{cache:i}=e.query||"false",p=e.query.target||o(e.headers),l=$.read(n),u=$.read(r),c=l[s];if($.info(`正在下载组合订阅:${s}`),c){const e=c.subscriptions;let r=[];for(let t=0;t<e.length;t++){const s=u[e[t]];$.info(`正在处理子订阅:${s.name},进度--${100*(t+1/e.length).toFixed(1)}% `);try{const e=await a(s.url,i);r=r.concat(ProxyUtils.parse(e))}catch(e){$.error(`处理组合订阅中的子订阅: ${s.name}时出现错误:${e}! 该订阅已被跳过。`)}}0===(r=await ProxyUtils.process(r,c.process||[])).length&&($.notify("🌍 [Sub-Store] 下载组合订阅失败",`❌ 未找到组合订阅:${s}!`),t.status(500).json({status:"failed",message:`❌ 组合订阅${s}中不含有${p}可用的节点!`}));try{const e=ProxyUtils.produce(r,p);"JSON"===p?t.set("Content-Type","application/json").send(e):t.send(e)}catch(e){$.notify("🌍 [Sub-Store] 下载组合订阅失败",`❌ 无法下载组合订阅:${s}!`,`🤔 原因:${e}`),t.status(500).json({status:"failed",message:e})}}else $.notify("🌍 [Sub-Store] 下载组合订阅失败",`❌ 未找到组合订阅:${s}!`),t.status(404).json({status:"failed"})}),t.route("/api/sub/:name").get(function(e,t){const{name:s}=e.params,n=$.read(r)[s];n?t.json({status:"success",data:n}):t.status(404).json({status:"failed",message:`未找到订阅:${s}!`})}).patch(function(e,t){const{name:s}=e.params;let o=e.body;const a=$.read(r);if(a[s]){const e={...a[s],...o};if(s!==o.name){const t=$.read(n);for(const e of Object.keys(t)){const r=t[e].subscriptions.indexOf(s);-1!==r&&(t[e].subscriptions[r]=o.name)}delete a[s],a[o.name]=e}else a[s]=e;$.write(a,r),t.json({status:"success",data:e})}else t.status(500).json({status:"failed",message:`订阅${s}不存在,无法更新!`})}).delete(function(e,t){const{name:s}=e.params;let o=$.read(r);delete o[s],$.write(o,r);let a=$.read(n);for(const e of Object.keys(a))a[e].subscriptions=a[e].subscriptions.filter(e=>e!==s);$.write(a,n),t.json({status:"success"})}),t.route("/api/subs").get(function(e,t){const s=$.read(r);t.json({status:"success",data:s})}).post(function(e,t){const s=e.body,n=$.read(r);n[s.name]&&t.status(500).json({status:"failed",message:`订阅${s.name}已存在!`});/^[\w-_]*$/.test(s.name)?(n[s.name]=s,$.write(n,r),t.status(201).json({status:"success",data:s})):t.status(500).json({status:"failed",message:`订阅名称 ${s.name} 中含有非法字符!名称中只能包含英文字母、数字、下划线、横杠。`})}),t.route("/api/collection/:name").get(function(e,t){const{name:s}=e.params,r=$.read(n)[s];r?t.json({status:"success",data:r}):t.status(404).json({status:"failed",message:`未找到订阅集:${s}!`})}).patch(function(e,t){const{name:s}=e.params;let r=e.body;const o=$.read(n);if(o[s]){const e={...o[s],...r};delete o[s],o[r.name||s]=e,$.write(o,n),t.json({status:"success",data:e})}else t.status(500).json({status:"failed",message:`订阅集${s}不存在,无法更新!`})}).delete(function(e,t){const{name:s}=e.params;let r=$.read(n);delete r[s],$.write(r,n),t.json({status:"success"})}),t.route("/api/collections").get(function(e,t){const s=$.read(n);t.json({status:"success",data:s})}).post(function(e,t){const s=e.body,r=$.read(n);r[s.name]&&t.status(500).json({status:"failed",message:`订阅集${s.name}已存在!`});/^[\w-_]*$/.test(s.name)?(r[s.name]=s,$.write(r,n),t.status(201).json({status:"success",data:s})):t.status(500).json({status:"failed",message:`订阅集名称 ${s.name} 中 Line truncated
// UPDATED AT: 2020年11月24日 星期二 21时20分42秒 CST
const $=API("sub-store"),Base64=new Base64Code;function startService(){const e=heredoc(function(){});console.log(e);const t=express(),s="settings",r="subs",n="collections";function o(e){const t=Object.keys(e);let s="";for(let r of t)if(/USER-AGENT/i.test(r)){s=e[r];break}return-1!==s.indexOf("Quantumult%20X")?"QX":-1!==s.indexOf("Surge")?"Surge":-1!==s.indexOf("Decar")||-1!==s.indexOf("Loon")?"Loon":"JSON"}async function a(e,t=!0){const s=HTTP({headers:{"User-Agent":"Quantumult%20X"}}),r="#"+Base64.safeEncode(e),n=$.read(r),o=`#TIME-${Base64.safeEncode(e)}`,a=(new Date).getTime()-$.read(o)>864e5;if(t&&n&&!a)return $.log(`Use cached for url: ${e}`),n;const{body:i}=await s.get(e);if(0===i.replace(/\s/g,"").length)throw new Error("订阅内容为空!");return $.write(i,r),$.write((new Date).getTime(),o),i}$.read(r)||$.write({},r),$.read(n)||$.write({},n),$.read(s)||$.write({},s),t.get("/download/:name",async function(e,t){const{name:s}=e.params,{cache:n}=e.query,i=e.query.target||o(e.headers),p=$.read(r)[s];if(p)try{const e=void 0===n?"JSON"===i||"URI"===i:n,r=await a(p.url,e);let o=ProxyUtils.parse(r);o=await ProxyUtils.process(o,p.process||[]);const l=ProxyUtils.produce(o,i);"JSON"===i?t.set("Content-Type","application/json").send(l):t.send(l)}catch(e){$.notify("🌍 [Sub-Store] 下载订阅失败",`❌ 无法下载订阅:${s}!`,`🤔 原因:${e}`),t.status(500).json({status:"failed",message:e})}else $.notify("🌍 [Sub-Store] 下载订阅失败",`❌ 未找到订阅:${s}!`),t.status(404).json({status:"failed"})}),t.get("/download/collection/:name",async function(e,t){const{name:s}=e.params,{cache:i}=e.query||"false",p=e.query.target||o(e.headers),l=$.read(n),c=$.read(r),u=l[s];if($.info(`正在下载组合订阅:${s}`),u){const e=u.subscriptions;let r=[];for(let t=0;t<e.length;t++){const s=c[e[t]];$.info(`正在处理子订阅:${s.name},进度--${100*(t+1/e.length).toFixed(1)}% `);try{const e=void 0===i?"JSON"===p||"URI"===p:i,t=await a(s.url,e);r=r.concat(ProxyUtils.parse(t)),r=await ProxyUtils.process(r,s.process||[])}catch(e){$.error(`处理组合订阅中的子订阅: ${s.name}时出现错误:${e}! 该订阅已被跳过。`)}}0===(r=await ProxyUtils.process(r,u.process||[])).length&&($.notify("🌍 [Sub-Store] 下载组合订阅失败",`❌ 未找到组合订阅:${s}!`),t.status(500).json({status:"failed",message:`❌ 组合订阅${s}中不含有${p}可用的节点!`}));try{const e=ProxyUtils.produce(r,p);"JSON"===p?t.set("Content-Type","application/json").send(e):t.send(e)}catch(e){$.notify("🌍 [Sub-Store] 下载组合订阅失败",`❌ 无法下载组合订阅:${s}!`,`🤔 原因:${e}`),t.status(500).json({status:"failed",message:e})}}else $.notify("🌍 [Sub-Store] 下载组合订阅失败",`❌ 未找到组合订阅:${s}!`),t.status(404).json({status:"failed"})}),t.route("/api/sub/:name").get(function(e,t){const{name:s}=e.params,n=$.read(r)[s];n?t.json({status:"success",data:n}):t.status(404).json({status:"failed",message:`未找到订阅:${s}!`})}).patch(function(e,t){const{name:s}=e.params;let o=e.body;const a=$.read(r);if(a[s]){const e={...a[s],...o};if($.info(`正在更新订阅: ${s}`),s!==o.name){const t=$.read(n);for(const e of Object.keys(t)){const r=t[e].subscriptions.indexOf(s);-1!==r&&(t[e].subscriptions[r]=o.name)}delete a[s],a[o.name]=e}else a[s]=e;$.write(a,r),t.json({status:"success",data:e})}else t.status(500).json({status:"failed",message:`订阅${s}不存在,无法更新!`})}).delete(function(e,t){const{name:s}=e.params;$.info(`删除订阅:${s}...`);let o=$.read(r);delete o[s],$.write(o,r);let a=$.read(n);for(const e of Object.keys(a))a[e].subscriptions=a[e].subscriptions.filter(e=>e!==s);$.write(a,n),t.json({status:"success"})}),t.route("/api/subs").get(function(e,t){const s=$.read(r);t.json({status:"success",data:s})}).post(function(e,t){const s=e.body,n=$.read(r);$.info(`正在创建订阅: ${s.name}`),n[s.name]&&t.status(500).json({status:"failed",message:`订阅${s.name}已存在!`});/^[\w-_]*$/.test(s.name)?(n[s.name]=s,$.write(n,r),t.status(201).json({status:"success",data:s})):t.status(500).json({status:"failed",message:`订阅名称 ${s.name} 中含有非法字符!名称中只能包含英文字母、数字、下划线、横杠。`})}),t.route("/api/collection/:name").get(function(e,t){const{name:s}=e.params,r=$.read(n)[s];r?t.json({status:"success",data:r}):t.status(404).json({status:"failed",message:`未找到订阅集:${s}!`})}).patch(function(e,t){const{name:s}=e.params;let r=e.body;const o=$.read(n);if(o[s]){const e={...o[s],...r};$.info(`正在更新组合订阅:${s}...`),delete o[s],o[r.name||s]=e,$.write(o,n),t.json({status:"success",data:e})}else t.status(500).json({status:"failed",message:`订阅集${s}不存在,无法更新!`})}).delete(function(e,t){const{name:s}=e.params;$.info(`正在删除组合订阅:${s}`);let r=$.read(n);delete r[s],$.write(r,n),t.json({status:"success"})}),t.route("/api/colLine truncated
+8 -10
View File
@@ -16,7 +16,7 @@
<v-icon left x-small>mdi-flash</v-icon>
TFO
</v-chip>
<v-chip x-small v-if="proxy.scert" color="error" outlined>
<v-chip x-small v-if="proxy['skip-cert-verify']" color="error" outlined>
<v-icon left x-small>error</v-icon>
SCERT
</v-chip>
@@ -78,7 +78,7 @@
</v-btn>
</v-card-title>
<v-card-text
align="center"
align="center"
>
<vue-q-r-code-component
:text="qr"
@@ -117,20 +117,18 @@ export default {
},
methods: {
refresh() {
axios.post(`/refresh`, {url: this.sub}).then(() => {
axios.post(`/utils/refresh`, {url: this.sub}).then(() => {
this.fetch();
}).catch(err => {
this.$store.commit("SET_ERROR_MESSAGE", err.response.data.message);
})
},
async fetch() {
await axios.get(this.url).then(resp => {
let {data} = resp;
if ((typeof data === 'string' || data instanceof String) && data.indexOf("\n") !== -1){
this.proxies = data.split("\n").map(p => JSON.parse(p));
}
else {
this.proxies = [data];
}
// eslint-disable-next-line no-debugger
this.proxies = data;
}).catch(err => {
this.$store.commit("SET_ERROR_MESSAGE", err);
});
@@ -150,7 +148,7 @@ export default {
async showInfo(idx) {
const {server, name} = this.proxies[idx];
const res = await axios.get(`/IP_API/${encodeURIComponent(server)}`).then(resp => resp.data);
const res = await axios.get(`/utils/IP_API/${encodeURIComponent(server)}`).then(resp => resp.data);
this.info.name = name;
this.info.isp = `ISP:${res.isp}`;
this.info.region = `地区:${flags.get(res.countryCode)} ${res.regionName} ${res.city}`;
+2 -2
View File
@@ -6,7 +6,6 @@ import Subscription from "@/views/Subscription";
import Dashboard from "@/views/Dashboard";
import User from "@/views/User";
import SubEditor from "@/views/SubEditor";
import CollectionEditor from "@/views/CollectionEditor";
Vue.use(Router);
@@ -40,7 +39,8 @@ const router = new Router({
{
path: "/collection-edit/:name",
name: "collection-edit",
component: CollectionEditor,
component: SubEditor,
props: {isCollection: true},
meta: {title: "订阅编辑"}
}
]
+5 -5
View File
@@ -45,21 +45,21 @@ const store = new Vuex.Store({
actions: {
// fetch subscriptions
async FETCH_SUBSCRIPTIONS({state}) {
return axios.get("/sub").then(resp => {
return axios.get("/subs").then(resp => {
const {data} = resp.data;
state.subscriptions = data;
});
},
// fetch collections
async FETCH_COLLECTIONS({state}) {
return axios.get("/collection").then(resp => {
return axios.get("/collections").then(resp => {
const {data} = resp.data;
state.collections = data;
});
},
// fetch env
async FETCH_ENV({state}) {
return axios.get("/env").then(resp => {
return axios.get("/utils/env").then(resp => {
state.env = resp.data;
})
},
@@ -72,7 +72,7 @@ const store = new Vuex.Store({
},
// new subscription
async NEW_SUBSCRIPTION({dispatch}, sub) {
return axios.post(`/sub`, sub).then(() => {
return axios.post(`/subs`, sub).then(() => {
dispatch("FETCH_SUBSCRIPTIONS");
});
},
@@ -91,7 +91,7 @@ const store = new Vuex.Store({
},
// new collection
async NEW_COLLECTION({dispatch}, collection) {
return axios.post(`/collection`, collection).then(() => {
return axios.post(`/collections`, collection).then(() => {
dispatch("FETCH_COLLECTIONS");
})
},
+146 -66
View File
@@ -1,7 +1,7 @@
<template>
<v-container>
<v-card class="mb-4">
<v-subheader>基本信息</v-subheader>
<v-subheader>订阅配置</v-subheader>
<v-form class="pl-4 pr-4 pb-0" v-model="formState.basicValid">
<v-text-field
v-model="options.name"
@@ -13,7 +13,9 @@
clearable
clear-icon="clear"
/>
<!--For Subscription-->
<v-textarea
v-if="!isCollection"
v-model="options.url"
class="mt-2"
rows="2"
@@ -24,6 +26,27 @@
clearable
clear-icon="clear"
/>
<!--For Collection-->
<v-list
v-if="isCollection"
dense
>
<v-subheader class="pl-0">包含的订阅</v-subheader>
<v-list-item v-for="sub in availableSubs" :key="sub.name">
<v-list-item-avatar dark>
<v-icon>mdi-cloud</v-icon>
</v-list-item-avatar>
<v-list-item-content>
{{ sub.name }}
</v-list-item-content>
<v-spacer></v-spacer>
<v-checkbox
:value="sub.name"
v-model="selected"
class="pr-1"
/>
</v-list-item>
</v-list>
</v-form>
<v-card-actions>
<v-spacer></v-spacer>
@@ -46,7 +69,7 @@
</v-btn>
</v-card-title>
<v-textarea
v-model="importedSub"
v-model="imported"
solo
label="粘贴配置以导入"
rows="5"
@@ -56,7 +79,7 @@
/>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn text color="primary" @click="importSub">确认</v-btn>
<v-btn text color="primary" @click="importConf">确认</v-btn>
<v-btn text @click="showShareDialog = false">取消</v-btn>
</v-card-actions>
</v-card>
@@ -105,7 +128,7 @@
</v-radio-group>
<v-radio-group
v-model="options.scert"
v-model="options['skip-cert-verify']"
dense
class="mt-0 mb-0"
>
@@ -258,6 +281,14 @@ const AVAILABLE_PROCESSORS = {
}
export default {
props: {
isCollection: {
type: Boolean,
default() {
return false;
}
}
},
components: {
FlagOperator,
KeywordFilter,
@@ -277,7 +308,7 @@ export default {
return {
selectedProcess: null,
showShareDialog: false,
importedSub: "",
imported: "",
dialog: false,
validations: {
nameRules: [
@@ -300,21 +331,37 @@ export default {
url: "",
useless: "KEEP",
udp: "DEFAULT",
scert: "DEFAULT",
"skip-cert-verify": "DEFAULT",
tfo: "DEFAULT",
},
process: [],
selected: []
}
},
created() {
const name = this.$route.params.name;
const sub = (typeof name === 'undefined' || name === 'UNTITLED') ? {} : this.$store.state.subscriptions[name];
this.$store.commit("SET_NAV_TITLE", sub.name ? `订阅编辑 -- ${sub.name}` : "新建订阅");
const {options, process} = loadSubscription(this.options, sub);
let source;
if (this.isCollection) {
source = (typeof name === 'undefined' || name === 'UNTITLED') ? {} : this.$store.state.collections[name];
this.$store.commit("SET_NAV_TITLE", source.name ? `组合订阅编辑 -- ${source.name}` : "新建组合订阅");
this.selected = source.subscriptions || [];
} else {
source = (typeof name === 'undefined' || name === 'UNTITLED') ? {} : this.$store.state.subscriptions[name];
this.$store.commit("SET_NAV_TITLE", source.name ? `订阅编辑 -- ${source.name}` : "新建订阅");
}
this.name = source.name;
const {options, process} = loadProcess(this.options, source);
this.options = options;
this.process = process;
},
computed: {
availableSubs() {
return this.$store.state.subscriptions;
},
availableProcessors() {
return AVAILABLE_PROCESSORS;
},
@@ -327,45 +374,101 @@ export default {
id: p.id
}
});
},
config() {
const output = {
name: this.options.name,
process: []
};
if (this.isCollection) {
output.subscriptions = this.selected;
} else {
output.url = this.options.url;
}
// useless filter
if (this.options.useless === 'REMOVE') {
output.process.push({
type: "Useless Filter"
});
}
// udp, tfo, scert
for (const opt of ['udp', 'tfo', 'skip-cert-verify']) {
if (this.options[opt] !== 'DEFAULT') {
output.process.push({
type: "Set Property Operator",
args: {key: opt, value: this.options[opt] === 'FORCE_OPEN'}
});
}
}
for (const p of this.process) {
output.process.push(p);
}
return output;
}
},
methods: {
save() {
if (this.options.name && this.options.url) {
const sub = buildSubscription(this.options, this.process);
if (this.$route.params.name !== "UNTITLED") {
this.$store.dispatch("UPDATE_SUBSCRIPTION", {
name: this.$route.params.name,
sub
}).then(() => {
showInfo(`成功保存订阅:${this.options.name}!`);
}).catch(() => {
showError(`发生错误,无法保存订阅!`);
});
} else {
this.$store.dispatch("NEW_SUBSCRIPTION", sub).then(() => {
showInfo(`成功创建订阅:${this.options.name}!`);
}).catch(() => {
showError(`发生错误,无法创建订阅!`);
});
if (this.isCollection) {
if (this.options.name && this.selected) {
if (this.$route.params.name === 'UNTITLED') {
this.$store.dispatch("NEW_COLLECTION", this.config).then(() => {
showInfo(`成功创建组合订阅:${this.name}!`)
}).catch(() => {
showError(`发生错误,无法创建组合订阅!`)
});
} else {
this.$store.dispatch("UPDATE_COLLECTION", {
name: this.$route.params.name,
collection: this.config
}).then(() => {
showInfo(`成功保存组合订阅:${this.name}!`)
}).catch(() => {
showError(`发生错误,无法保存组合订阅!`)
});
}
}
} else {
console.log("Saving subscription...");
if (this.options.name && this.options.url) {
if (this.$route.params.name !== "UNTITLED") {
this.$store.dispatch("UPDATE_SUBSCRIPTION", {
name: this.$route.params.name,
sub: this.config
}).then(() => {
showInfo(`成功保存订阅:${this.options.name}!`);
}).catch(() => {
showError(`发生错误,无法保存订阅!`);
});
} else {
this.$store.dispatch("NEW_SUBSCRIPTION", this.config).then(() => {
showInfo(`成功创建订阅:${this.options.name}!`);
}).catch(() => {
showError(`发生错误,无法创建订阅!`);
});
}
}
}
},
share() {
let sub = buildSubscription(this.options, this.process);
sub.name = "「订阅名称」";
sub.url = "「订阅链接」";
sub = JSON.stringify(sub);
this.$clipboard(sub);
let config = this.config;
config.name = "「订阅名称」";
if (this.isCollection) {
config.subscriptions = [];
} else {
config.url = "「订阅链接」";
}
config = JSON.stringify(config);
this.$clipboard(config);
this.$store.commit("SET_SUCCESS_MESSAGE", "导出成功,订阅已复制到剪贴板!");
this.showShareDialog = false;
},
importSub() {
if (this.importedSub) {
const sub = JSON.parse(this.importedSub);
const {options, process} = loadSubscription(this.options, sub);
importConf() {
if (this.imported) {
const sub = JSON.parse(this.imported);
const {options, process} = loadProcess(this.options, sub);
delete options.name;
delete options.url;
@@ -433,16 +536,20 @@ export default {
}
}
function loadSubscription(options, sub) {
function loadProcess(options, source, isCollection = false) {
options = {
...options,
name: sub.name,
url: sub.url,
name: source.name,
};
if (isCollection) {
options.subscriptions = source.subscriptions;
} else {
options.url = source.url;
}
let process = []
// flag
for (const p of (sub.process || [])) {
for (const p of (source.process || [])) {
switch (p.type) {
case 'Useless Filter':
options.useless = "REMOVE";
@@ -458,33 +565,6 @@ function loadSubscription(options, sub) {
return {options, process};
}
function buildSubscription(options, process) {
const sub = {
name: options.name,
url: options.url,
process: []
};
// useless filter
if (options.useless === 'REMOVE') {
sub.process.push({
type: "Useless Filter"
});
}
// udp, tfo, scert
for (const opt of ['udp', 'tfo', 'scert']) {
if (options[opt] !== 'DEFAULT') {
sub.process.push({
type: "Set Property Operator",
args: {key: opt, value: options[opt] === 'FORCE_OPEN'}
});
}
}
for (const p of process) {
sub.process.push(p);
}
return sub;
}
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
+1 -1
View File
@@ -52,7 +52,7 @@ export default {
return;
}
this.save();
axios.get(`/backup?action=${action}`).then(resp => {
axios.get(`/utils/backup?action=${action}`).then(resp => {
if (resp.data.status === 'success') {
this.$store.commit("SET_SUCCESS_MESSAGE", `${action === 'upload' ? "备份" : "还原"}成功!`);
this.updateStore(this.$store);