feat: 订阅失败处理新增兜底通知和兜底静默

This commit is contained in:
xream committed 2026-04-19 20:10:21 +08:00
1 parent 8ffb62f2d7
commit 9b0627142a
5 files changed
+672 -395

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "sub-store",
"version": "2.22.2",
"version": "2.22.3",
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
"main": "src/main.js",
"scripts": {
+44 -18
View File
@@ -12,6 +12,18 @@ import { isIPv4, isIPv6 } from '@/utils';
import { getISO } from '@/utils/geo';
import env from '@/utils/env';
function buildEmptyNezhaPayload() {
return JSON.stringify(
{
code: 0,
message: 'success',
result: [],
},
null,
2,
);
}
export default function register($app) {
$app.get('/share/col/:name/:target', async (req, res) => {
const { target } = req.params;
@@ -89,7 +101,10 @@ async function downloadSubscription(req, res) {
const useMihomoExternal = req.query.target === 'SurgeMac';
const platform =
req.query.target || getPlatformFromHeaders(req.headers) || 'JSON';
req.query.platform ||
req.query.target ||
getPlatformFromHeaders(req.headers) ||
'JSON';
const reqUA = req.headers['user-agent'] || req.headers['User-Agent'];
$.info(
`正在下载订阅:${name}\n请求 User-Agent: ${reqUA}\n请求 target: ${req.query.target}\n实际输出: ${platform}`,
@@ -340,14 +355,18 @@ async function downloadSubscription(req, res) {
if (resultFormat === 'nezha') {
output = nezhaTransform(output);
} else if (resultFormat === 'nezha-monitor') {
nezhaIndex = /^\d+$/.test(nezhaIndex)
? parseInt(nezhaIndex, 10)
: output.findIndex((i) => i.name === nezhaIndex);
output = await nezhaMonitor(
output[nezhaIndex],
nezhaIndex,
req.query,
);
if (!Array.isArray(output) || output.length === 0) {
output = buildEmptyNezhaPayload();
} else {
nezhaIndex = /^\d+$/.test(nezhaIndex)
? parseInt(nezhaIndex, 10)
: output.findIndex((i) => i.name === nezhaIndex);
output = await nezhaMonitor(
output[nezhaIndex],
nezhaIndex,
req.query,
);
}
}
res.set('Content-Type', 'application/json;charset=utf-8');
} else {
@@ -403,7 +422,10 @@ async function downloadCollection(req, res) {
const useMihomoExternal = req.query.target === 'SurgeMac';
const platform =
req.query.target || getPlatformFromHeaders(req.headers) || 'JSON';
req.query.platform ||
req.query.target ||
getPlatformFromHeaders(req.headers) ||
'JSON';
const allCols = $.read(COLLECTIONS_KEY);
const collection = findByName(allCols, name);
@@ -627,14 +649,18 @@ async function downloadCollection(req, res) {
if (resultFormat === 'nezha') {
output = nezhaTransform(output);
} else if (resultFormat === 'nezha-monitor') {
nezhaIndex = /^\d+$/.test(nezhaIndex)
? parseInt(nezhaIndex, 10)
: output.findIndex((i) => i.name === nezhaIndex);
output = await nezhaMonitor(
output[nezhaIndex],
nezhaIndex,
req.query,
);
if (!Array.isArray(output) || output.length === 0) {
output = buildEmptyNezhaPayload();
} else {
nezhaIndex = /^\d+$/.test(nezhaIndex)
? parseInt(nezhaIndex, 10)
: output.findIndex((i) => i.name === nezhaIndex);
output = await nezhaMonitor(
output[nezhaIndex],
nezhaIndex,
req.query,
);
}
}
res.set('Content-Type', 'application/json;charset=utf-8');
} else {
@@ -0,0 +1,80 @@
import { ProxyUtils } from '@/core/proxy-utils';
const IGNORE_FAILED_REMOTE_SUB_NOTIFY_MODES = new Set([
'enabled',
'fallbackNotify',
]);
const IGNORE_FAILED_REMOTE_SUB_FALLBACK_MODES = new Set([
'fallbackNotify',
'fallbackQuiet',
]);
function normalizeIgnoreFailedRemoteSub(mode) {
if (mode === true) return 'quiet';
if (mode === false || mode == null || mode === '') return 'disabled';
return mode;
}
function resolveIgnoreFailedRemoteSubMode(...values) {
for (const value of values) {
if (value != null && value !== '') {
return normalizeIgnoreFailedRemoteSub(value);
}
}
return 'disabled';
}
function shouldNotifyIgnoreFailedRemoteSub(mode) {
return IGNORE_FAILED_REMOTE_SUB_NOTIFY_MODES.has(
normalizeIgnoreFailedRemoteSub(mode),
);
}
function shouldFallbackIgnoreFailedRemoteSub(mode) {
return IGNORE_FAILED_REMOTE_SUB_FALLBACK_MODES.has(
normalizeIgnoreFailedRemoteSub(mode),
);
}
function handleIgnoreFailedRemoteSubError({ mode, message, notify }) {
const resolvedMode = normalizeIgnoreFailedRemoteSub(mode);
if (
resolvedMode === 'disabled' ||
shouldFallbackIgnoreFailedRemoteSub(resolvedMode)
) {
throw new Error(message);
}
if (shouldNotifyIgnoreFailedRemoteSub(resolvedMode)) {
notify?.(message);
}
}
function notifyIgnoreFailedRemoteSubFallback({ mode, notify, error }) {
if (!shouldNotifyIgnoreFailedRemoteSub(mode)) return;
notify?.(error);
}
function buildEmptySubscriptionOutput({
platform = 'JSON',
produceType,
produceOpts = {},
}) {
if (produceType === 'raw') {
return JSON.stringify([]);
}
return ProxyUtils.produce([], platform, produceType, produceOpts);
}
export {
buildEmptySubscriptionOutput,
handleIgnoreFailedRemoteSubError,
normalizeIgnoreFailedRemoteSub,
notifyIgnoreFailedRemoteSubFallback,
resolveIgnoreFailedRemoteSubMode,
shouldFallbackIgnoreFailedRemoteSub,
shouldNotifyIgnoreFailedRemoteSub,
};
+122 -49
View File
@@ -5,6 +5,12 @@ import { success, failed } from './response';
import download from '@/utils/download';
import { SUBS_KEY } from '@/constants';
import $ from '@/core/app';
import {
handleIgnoreFailedRemoteSubError,
notifyIgnoreFailedRemoteSubFallback,
resolveIgnoreFailedRemoteSubMode,
shouldFallbackIgnoreFailedRemoteSub,
} from '@/restful/ignore-failed-remote-sub';
import { normalizeClashYaml } from '@/core/proxy-utils/preprocessors';
export default function register($app) {
@@ -106,8 +112,10 @@ async function previewFile(req, res) {
}
async function compareSub(req, res) {
const sub = req.body;
const mode = resolveIgnoreFailedRemoteSubMode(sub.ignoreFailedRemoteSub);
try {
const sub = req.body;
const target = req.query.target || 'JSON';
let content;
if (
@@ -145,21 +153,20 @@ async function compareSub(req, res) {
);
if (Object.keys(errors).length > 0) {
if (!sub.ignoreFailedRemoteSub) {
throw new Error(
`订阅 ${sub.name} 的远程订阅 ${Object.keys(errors).join(
', ',
)} 发生错误, 请查看日志`,
);
} else if (sub.ignoreFailedRemoteSub === 'enabled') {
$.notify(
`🌍 Sub-Store 预览订阅失败`,
`❌ ${sub.name}`,
`远程订阅 ${Object.keys(errors).join(
', ',
)} 发生错误, 请查看日志`,
);
}
const message = `订阅 ${sub.name} 的远程订阅 ${Object.keys(
errors,
).join(', ')} 发生错误, 请查看日志`;
handleIgnoreFailedRemoteSubError({
mode,
message,
notify: () => {
$.notify(
`🌍 Sub-Store 预览订阅失败`,
`❌ ${sub.name}`,
message,
);
},
});
}
if (sub.mergeSources === 'localFirst') {
content.unshift(sub.content);
@@ -190,6 +197,27 @@ async function compareSub(req, res) {
// produce
success(res, { original, processed });
} catch (err) {
if (shouldFallbackIgnoreFailedRemoteSub(mode)) {
notifyIgnoreFailedRemoteSubFallback({
mode,
error: err,
notify: (error) => {
$.notify(
`🌍 Sub-Store 预览订阅失败`,
`❌ ${sub.name}`,
`🤔 原因:${error.message ?? error}`,
);
},
});
$.error(
`订阅 ${sub.name} 预览启用兜底后返回空结果: ${
err.message ?? err
}`,
);
success(res, { original: [], processed: [] });
return;
}
$.error(err.message ?? err);
failed(
res,
@@ -203,9 +231,13 @@ async function compareSub(req, res) {
}
async function compareCollection(req, res) {
const collection = req.body;
const collectionMode = resolveIgnoreFailedRemoteSubMode(
collection.ignoreFailedRemoteSub,
);
try {
const allSubs = $.read(SUBS_KEY);
const collection = req.body;
const subnames = [...collection.subscriptions];
let subscriptionTags = collection.subscriptionTags;
if (Array.isArray(subscriptionTags) && subscriptionTags.length > 0) {
@@ -225,6 +257,9 @@ async function compareCollection(req, res) {
await Promise.all(
subnames.map(async (name) => {
const sub = findByName(allSubs, name);
const subMode = resolveIgnoreFailedRemoteSubMode(
sub.ignoreFailedRemoteSub,
);
try {
let raw;
if (
@@ -264,23 +299,20 @@ async function compareCollection(req, res) {
);
if (Object.keys(errors).length > 0) {
if (!sub.ignoreFailedRemoteSub) {
throw new Error(
`订阅 ${sub.name} 的远程订阅 ${Object.keys(
errors,
).join(', ')} 发生错误, 请查看日志`,
);
} else if (
sub.ignoreFailedRemoteSub === 'enabled'
) {
$.notify(
`🌍 Sub-Store 预览订阅失败`,
`❌ ${sub.name}`,
`远程订阅 ${Object.keys(errors).join(
', ',
)} 发生错误, 请查看日志`,
);
}
const message = `订阅 ${sub.name} 的远程订阅 ${Object.keys(
errors,
).join(', ')} 发生错误, 请查看日志`;
handleIgnoreFailedRemoteSubError({
mode: subMode,
message,
notify: () => {
$.notify(
`🌍 Sub-Store 预览订阅失败`,
`❌ ${sub.name}`,
message,
);
},
});
}
if (sub.mergeSources === 'localFirst') {
raw.unshift(sub.content);
@@ -309,6 +341,27 @@ async function compareCollection(req, res) {
);
results[name] = currentProxies;
} catch (err) {
if (shouldFallbackIgnoreFailedRemoteSub(subMode)) {
notifyIgnoreFailedRemoteSubFallback({
mode: subMode,
error: err,
notify: (error) => {
$.notify(
`🌍 Sub-Store 预览订阅失败`,
`❌ ${sub.name}`,
`🤔 原因:${error.message ?? error}`,
);
},
});
$.error(
`订阅 ${sub.name} 在组合订阅预览中启用兜底后返回空结果: ${
err.message ?? err
}`,
);
results[name] = [];
return;
}
errors[name] = err;
$.error(
@@ -319,21 +372,20 @@ async function compareCollection(req, res) {
);
if (Object.keys(errors).length > 0) {
if (!collection.ignoreFailedRemoteSub) {
throw new Error(
`组合订阅 ${collection.name} 的子订阅 ${Object.keys(
errors,
).join(', ')} 发生错误, 请查看日志`,
);
} else if (collection.ignoreFailedRemoteSub === 'enabled') {
$.notify(
`🌍 Sub-Store 预览组合订阅失败`,
`❌ ${collection.name}`,
`子订阅 ${Object.keys(errors).join(
', ',
)} 发生错误, 请查看日志`,
);
}
const message = `组合订阅 ${collection.name} 的子订阅 ${Object.keys(
errors,
).join(', ')} 发生错误, 请查看日志`;
handleIgnoreFailedRemoteSubError({
mode: collectionMode,
message,
notify: () => {
$.notify(
`🌍 Sub-Store 预览组合订阅失败`,
`❌ ${collection.name}`,
message,
);
},
});
}
// merge proxies with the original order
const original = Array.prototype.concat.apply(
@@ -356,6 +408,27 @@ async function compareCollection(req, res) {
success(res, { original, processed });
} catch (err) {
if (shouldFallbackIgnoreFailedRemoteSub(collectionMode)) {
notifyIgnoreFailedRemoteSubFallback({
mode: collectionMode,
error: err,
notify: (error) => {
$.notify(
`🌍 Sub-Store 预览组合订阅失败`,
`❌ ${collection.name}`,
`🤔 原因:${error.message ?? error}`,
);
},
});
$.error(
`组合订阅 ${collection.name} 预览启用兜底后返回空结果: ${
err.message ?? err
}`,
);
success(res, { original: [], processed: [] });
return;
}
$.error(err.message ?? err);
failed(
res,
+425 -327
View File
@@ -13,6 +13,13 @@ import download from '@/utils/download';
import { ProxyUtils } from '@/core/proxy-utils';
import { RuleUtils } from '@/core/rule-utils';
import { syncToGist } from '@/restful/artifacts';
import {
buildEmptySubscriptionOutput,
handleIgnoreFailedRemoteSubError,
notifyIgnoreFailedRemoteSubFallback,
resolveIgnoreFailedRemoteSubMode,
shouldFallbackIgnoreFailedRemoteSub,
} from '@/restful/ignore-failed-remote-sub';
import { normalizeClashYaml } from '@/core/proxy-utils/preprocessors';
export default function register($app) {
@@ -56,167 +63,197 @@ async function produceArtifact({
} else {
throw new Error('未提供订阅名称或订阅数据');
}
let raw;
if (content && !['localFirst', 'remoteFirst'].includes(mergeSources)) {
raw = content;
} else if (url) {
const errors = {};
raw = await Promise.all(
url
.split(/[\r\n]+/)
.map((i) => i.trim())
.filter((i) => i.length)
.map(async (url) => {
try {
return await download(
url,
ua || sub.ua,
undefined,
proxy || sub.proxy,
undefined,
awaitCustomCache,
noCache || sub.noCache,
true,
);
} catch (err) {
errors[url] = err;
$.error(
`订阅 ${sub.name} 的远程订阅 ${url} 发生错误: ${err}`,
);
return '';
}
}),
);
let subIgnoreFailedRemoteSub = sub.ignoreFailedRemoteSub;
if (ignoreFailedRemoteSub != null && ignoreFailedRemoteSub !== '') {
subIgnoreFailedRemoteSub = ignoreFailedRemoteSub;
}
if (Object.keys(errors).length > 0) {
if (!subIgnoreFailedRemoteSub) {
throw new Error(
`订阅 ${sub.name} 的远程订阅 ${Object.keys(errors).join(
', ',
)} 发生错误, 请查看日志`,
);
} else if (subIgnoreFailedRemoteSub === 'enabled') {
$.notify(
`🌍 Sub-Store 处理订阅失败`,
`❌ ${sub.name}`,
`远程订阅 ${Object.keys(errors).join(
', ',
)} 发生错误, 请查看日志`,
);
}
}
if (mergeSources === 'localFirst') {
raw.unshift(content);
} else if (mergeSources === 'remoteFirst') {
raw.push(content);
}
} else if (
sub.source === 'local' &&
!['localFirst', 'remoteFirst'].includes(sub.mergeSources)
) {
raw = sub.content;
} else {
const errors = {};
raw = await Promise.all(
sub.url
.split(/[\r\n]+/)
.map((i) => i.trim())
.filter((i) => i.length)
.map(async (url) => {
try {
return await download(
url,
ua || sub.ua,
undefined,
proxy || sub.proxy,
undefined,
awaitCustomCache,
noCache || sub.noCache,
true,
);
} catch (err) {
errors[url] = err;
$.error(
`订阅 ${sub.name} 的远程订阅 ${url} 发生错误: ${err}`,
);
return '';
}
}),
);
let subIgnoreFailedRemoteSub = sub.ignoreFailedRemoteSub;
if (ignoreFailedRemoteSub != null && ignoreFailedRemoteSub !== '') {
subIgnoreFailedRemoteSub = ignoreFailedRemoteSub;
}
if (Object.keys(errors).length > 0) {
if (!subIgnoreFailedRemoteSub) {
throw new Error(
`订阅 ${sub.name} 的远程订阅 ${Object.keys(errors).join(
', ',
)} 发生错误, 请查看日志`,
);
} else if (subIgnoreFailedRemoteSub === 'enabled') {
$.notify(
`🌍 Sub-Store 处理订阅失败`,
`❌ ${sub.name}`,
`远程订阅 ${Object.keys(errors).join(
', ',
)} 发生错误, 请查看日志`,
);
}
}
if (sub.mergeSources === 'localFirst') {
raw.unshift(sub.content);
} else if (sub.mergeSources === 'remoteFirst') {
raw.push(sub.content);
}
}
if (produceType === 'raw') {
return JSON.stringify((Array.isArray(raw) ? raw : [raw]).flat());
}
// parse proxies
let proxies = (Array.isArray(raw) ? raw : [raw])
.map((i) => ProxyUtils.parse(i))
.flat();
proxies.forEach((proxy) => {
proxy._subName = sub.name;
proxy._subDisplayName = sub.displayName;
});
// apply processors
proxies = await ProxyUtils.process(
proxies,
sub.process || [],
platform,
{ [sub.name]: sub },
$options,
const subIgnoreFailedRemoteSub = resolveIgnoreFailedRemoteSubMode(
ignoreFailedRemoteSub,
sub.ignoreFailedRemoteSub,
);
if (proxies.length === 0) {
throw new Error(`订阅 ${name} 中不含有效节点`);
}
// check duplicate
const exist = {};
for (const proxy of proxies) {
if (exist[proxy.name]) {
$.notify(
'🌍 Sub-Store',
`⚠️ 订阅 ${name} 包含重复节点 ${proxy.name}!`,
'请仔细检测配置!',
{
'media-url':
'https://cdn3.iconfinder.com/data/icons/seo-outline-1/512/25_code_program_programming_develop_bug_search_developer-512.png',
},
try {
let raw;
if (
content &&
!['localFirst', 'remoteFirst'].includes(mergeSources)
) {
raw = content;
} else if (url) {
const errors = {};
raw = await Promise.all(
url
.split(/[\r\n]+/)
.map((i) => i.trim())
.filter((i) => i.length)
.map(async (url) => {
try {
return await download(
url,
ua || sub.ua,
undefined,
proxy || sub.proxy,
undefined,
awaitCustomCache,
noCache || sub.noCache,
true,
);
} catch (err) {
errors[url] = err;
$.error(
`订阅 ${sub.name} 的远程订阅 ${url} 发生错误: ${err}`,
);
return '';
}
}),
);
break;
if (Object.keys(errors).length > 0) {
const message = `订阅 ${sub.name} 的远程订阅 ${Object.keys(
errors,
).join(', ')} 发生错误, 请查看日志`;
handleIgnoreFailedRemoteSubError({
mode: subIgnoreFailedRemoteSub,
message,
notify: () => {
$.notify(
`🌍 Sub-Store 处理订阅失败`,
`❌ ${sub.name}`,
message,
);
},
});
}
if (mergeSources === 'localFirst') {
raw.unshift(content);
} else if (mergeSources === 'remoteFirst') {
raw.push(content);
}
} else if (
sub.source === 'local' &&
!['localFirst', 'remoteFirst'].includes(sub.mergeSources)
) {
raw = sub.content;
} else {
const errors = {};
raw = await Promise.all(
sub.url
.split(/[\r\n]+/)
.map((i) => i.trim())
.filter((i) => i.length)
.map(async (url) => {
try {
return await download(
url,
ua || sub.ua,
undefined,
proxy || sub.proxy,
undefined,
awaitCustomCache,
noCache || sub.noCache,
true,
);
} catch (err) {
errors[url] = err;
$.error(
`订阅 ${sub.name} 的远程订阅 ${url} 发生错误: ${err}`,
);
return '';
}
}),
);
if (Object.keys(errors).length > 0) {
const message = `订阅 ${sub.name} 的远程订阅 ${Object.keys(
errors,
).join(', ')} 发生错误, 请查看日志`;
handleIgnoreFailedRemoteSubError({
mode: subIgnoreFailedRemoteSub,
message,
notify: () => {
$.notify(
`🌍 Sub-Store 处理订阅失败`,
`❌ ${sub.name}`,
message,
);
},
});
}
if (sub.mergeSources === 'localFirst') {
raw.unshift(sub.content);
} else if (sub.mergeSources === 'remoteFirst') {
raw.push(sub.content);
}
}
exist[proxy.name] = true;
if (produceType === 'raw') {
return JSON.stringify((Array.isArray(raw) ? raw : [raw]).flat());
}
// parse proxies
let proxies = (Array.isArray(raw) ? raw : [raw])
.map((i) => ProxyUtils.parse(i))
.flat();
proxies.forEach((proxy) => {
proxy._subName = sub.name;
proxy._subDisplayName = sub.displayName;
});
// apply processors
proxies = await ProxyUtils.process(
proxies,
sub.process || [],
platform,
{ [sub.name]: sub },
$options,
);
if (proxies.length === 0) {
throw new Error(`订阅 ${name} 中不含有效节点`);
}
// check duplicate
const exist = {};
for (const proxy of proxies) {
if (exist[proxy.name]) {
$.notify(
'🌍 Sub-Store',
`⚠️ 订阅 ${name} 包含重复节点 ${proxy.name}!`,
'请仔细检测配置!',
{
'media-url':
'https://cdn3.iconfinder.com/data/icons/seo-outline-1/512/25_code_program_programming_develop_bug_search_developer-512.png',
},
);
break;
}
exist[proxy.name] = true;
}
// produce
return ProxyUtils.produce(
proxies,
platform,
produceType,
produceOpts,
);
} catch (err) {
if (!shouldFallbackIgnoreFailedRemoteSub(subIgnoreFailedRemoteSub)) {
throw err;
}
notifyIgnoreFailedRemoteSubFallback({
mode: subIgnoreFailedRemoteSub,
error: err,
notify: (error) => {
$.notify(
`🌍 Sub-Store 处理订阅失败`,
`❌ ${sub.name}`,
`🤔 原因:${error.message ?? error}`,
);
},
});
$.error(
`订阅 ${sub.name} 启用兜底后返回空结果: ${err.message ?? err}`,
);
return buildEmptySubscriptionOutput({
platform,
produceType,
produceOpts,
});
}
// produce
return ProxyUtils.produce(proxies, platform, produceType, produceOpts);
} else if (['collection', 'col'].includes(type)) {
const allSubs = $.read(SUBS_KEY);
const allCols = $.read(COLLECTIONS_KEY);
@@ -236,193 +273,254 @@ async function produceArtifact({
}
});
}
const results = {};
const errors = {};
let processed = 0;
const collectionIgnoreFailedRemoteSub = resolveIgnoreFailedRemoteSubMode(
ignoreFailedRemoteSub,
collection.ignoreFailedRemoteSub,
);
await Promise.all(
subnames.map(async (name) => {
const sub = findByName(allSubs, name);
const passThroughUA = sub.passThroughUA;
let reqUA = sub.ua;
if (passThroughUA) {
$.info(
`订阅开启了透传 User-Agent, 使用请求的 User-Agent: ${ua}`,
try {
const results = {};
const errors = {};
let processed = 0;
await Promise.all(
subnames.map(async (name) => {
const sub = findByName(allSubs, name);
const subMode = resolveIgnoreFailedRemoteSubMode(
sub.ignoreFailedRemoteSub,
);
reqUA = ua;
}
try {
$.info(`正在处理子订阅:${sub.name}...`);
let raw;
if (
sub.source === 'local' &&
!['localFirst', 'remoteFirst'].includes(
sub.mergeSources,
)
) {
raw = sub.content;
} else {
const errors = {};
raw = await await Promise.all(
sub.url
.split(/[\r\n]+/)
.map((i) => i.trim())
.filter((i) => i.length)
.map(async (url) => {
try {
return await download(
url,
reqUA,
undefined,
proxy ||
sub.proxy ||
collection.proxy,
undefined,
undefined,
noCache || sub.noCache,
true,
);
} catch (err) {
errors[url] = err;
$.error(
`订阅 ${sub.name} 的远程订阅 ${url} 发生错误: ${err}`,
);
return '';
}
}),
const passThroughUA = sub.passThroughUA;
let reqUA = sub.ua;
if (passThroughUA) {
$.info(
`订阅开启了透传 User-Agent, 使用请求的 User-Agent: ${ua}`,
);
reqUA = ua;
}
try {
$.info(`正在处理子订阅:${sub.name}...`);
let raw;
if (
sub.source === 'local' &&
!['localFirst', 'remoteFirst'].includes(
sub.mergeSources,
)
) {
raw = sub.content;
} else {
const errors = {};
raw = await Promise.all(
sub.url
.split(/[\r\n]+/)
.map((i) => i.trim())
.filter((i) => i.length)
.map(async (url) => {
try {
return await download(
url,
reqUA,
undefined,
proxy ||
sub.proxy ||
collection.proxy,
undefined,
undefined,
noCache || sub.noCache,
true,
);
} catch (err) {
errors[url] = err;
$.error(
`订阅 ${sub.name} 的远程订阅 ${url} 发生错误: ${err}`,
);
return '';
}
}),
);
if (Object.keys(errors).length > 0) {
if (!sub.ignoreFailedRemoteSub) {
throw new Error(
`订阅 ${sub.name} 的远程订阅 ${Object.keys(
errors,
).join(', ')} 发生错误, 请查看日志`,
);
} else if (
sub.ignoreFailedRemoteSub === 'enabled'
) {
$.notify(
`🌍 Sub-Store 处理订阅失败`,
`❌ ${sub.name}`,
`远程订阅 ${Object.keys(errors).join(
', ',
)} 发生错误, 请查看日志`,
);
if (Object.keys(errors).length > 0) {
const message = `订阅 ${sub.name} 的远程订阅 ${Object.keys(
errors,
).join(', ')} 发生错误, 请查看日志`;
handleIgnoreFailedRemoteSubError({
mode: subMode,
message,
notify: () => {
$.notify(
`🌍 Sub-Store 处理订阅失败`,
`❌ ${sub.name}`,
message,
);
},
});
}
if (sub.mergeSources === 'localFirst') {
raw.unshift(sub.content);
} else if (sub.mergeSources === 'remoteFirst') {
raw.push(sub.content);
}
}
if (sub.mergeSources === 'localFirst') {
raw.unshift(sub.content);
} else if (sub.mergeSources === 'remoteFirst') {
raw.push(sub.content);
// parse proxies
let currentProxies = (Array.isArray(raw) ? raw : [raw])
.map((i) => ProxyUtils.parse(i))
.flat();
currentProxies.forEach((proxy) => {
proxy._subName = sub.name;
proxy._subDisplayName = sub.displayName;
proxy._collectionName = collection.name;
proxy._collectionDisplayName =
collection.displayName;
});
// apply processors
currentProxies = await ProxyUtils.process(
currentProxies,
sub.process || [],
platform,
{
[sub.name]: sub,
_collection: collection,
$options,
},
);
results[name] = currentProxies;
processed++;
$.info(
`✅ 子订阅:${sub.name}加载成功,进度--${
100 * (processed / subnames.length).toFixed(1)
}% `,
);
} catch (err) {
processed++;
if (shouldFallbackIgnoreFailedRemoteSub(subMode)) {
notifyIgnoreFailedRemoteSubFallback({
mode: subMode,
error: err,
notify: (error) => {
$.notify(
`🌍 Sub-Store 处理订阅失败`,
`❌ ${sub.name}`,
`🤔 原因:${error.message ?? error}`,
);
},
});
$.error(
`订阅 ${sub.name} 在组合订阅处理中启用兜底后返回空结果: ${
err.message ?? err
}`,
);
results[name] = [];
return;
}
errors[name] = err;
$.error(
`❌ 处理组合订阅中的子订阅: ${
sub.name
}时出现错误:${err}!进度--${
100 * (processed / subnames.length).toFixed(1)
}%`,
);
}
// parse proxies
let currentProxies = (Array.isArray(raw) ? raw : [raw])
.map((i) => ProxyUtils.parse(i))
.flat();
}),
);
currentProxies.forEach((proxy) => {
proxy._subName = sub.name;
proxy._subDisplayName = sub.displayName;
proxy._collectionName = collection.name;
proxy._collectionDisplayName = collection.displayName;
});
if (Object.keys(errors).length > 0) {
const message = `组合订阅 ${collection.name} 的子订阅 ${Object.keys(
errors,
).join(', ')} 发生错误, 请查看日志`;
handleIgnoreFailedRemoteSubError({
mode: collectionIgnoreFailedRemoteSub,
message,
notify: () => {
$.notify(
`🌍 Sub-Store 处理组合订阅失败`,
`❌ ${collection.name}`,
message,
);
},
});
}
// apply processors
currentProxies = await ProxyUtils.process(
currentProxies,
sub.process || [],
platform,
// merge proxies with the original order
let proxies = Array.prototype.concat.apply(
[],
subnames.map((name) => results[name] || []),
);
proxies.forEach((proxy) => {
proxy._collectionName = collection.name;
proxy._collectionDisplayName = collection.displayName;
});
// apply own processors
proxies = await ProxyUtils.process(
proxies,
collection.process || [],
platform,
{ _collection: collection },
$options,
);
if (proxies.length === 0) {
throw new Error(`组合订阅 ${name} 中不含有效节点`);
}
// check duplicate
const exist = {};
for (const proxy of proxies) {
if (exist[proxy.name]) {
$.notify(
'🌍 Sub-Store',
`⚠️ 组合订阅 ${name} 包含重复节点 ${proxy.name}!`,
'请仔细检测配置!',
{
[sub.name]: sub,
_collection: collection,
$options,
'media-url':
'https://cdn3.iconfinder.com/data/icons/seo-outline-1/512/25_code_program_programming_develop_bug_search_developer-512.png',
},
);
results[name] = currentProxies;
processed++;
$.info(
`✅ 子订阅:${sub.name}加载成功,进度--${
100 * (processed / subnames.length).toFixed(1)
}% `,
);
} catch (err) {
processed++;
errors[name] = err;
$.error(
`❌ 处理组合订阅中的子订阅: ${
sub.name
}时出现错误:${err}!进度--${
100 * (processed / subnames.length).toFixed(1)
}%`,
);
break;
}
}),
);
let collectionIgnoreFailedRemoteSub = collection.ignoreFailedRemoteSub;
if (ignoreFailedRemoteSub != null && ignoreFailedRemoteSub !== '') {
collectionIgnoreFailedRemoteSub = ignoreFailedRemoteSub;
}
if (Object.keys(errors).length > 0) {
if (!collectionIgnoreFailedRemoteSub) {
throw new Error(
`组合订阅 ${collection.name} 的子订阅 ${Object.keys(
errors,
).join(', ')} 发生错误, 请查看日志`,
);
} else if (collectionIgnoreFailedRemoteSub === 'enabled') {
$.notify(
`🌍 Sub-Store 处理组合订阅失败`,
`❌ ${collection.name}`,
`子订阅 ${Object.keys(errors).join(
', ',
)} 发生错误, 请查看日志`,
);
exist[proxy.name] = true;
}
}
// merge proxies with the original order
let proxies = Array.prototype.concat.apply(
[],
subnames.map((name) => results[name] || []),
);
proxies.forEach((proxy) => {
proxy._collectionName = collection.name;
proxy._collectionDisplayName = collection.displayName;
});
// apply own processors
proxies = await ProxyUtils.process(
proxies,
collection.process || [],
platform,
{ _collection: collection },
$options,
);
if (proxies.length === 0) {
throw new Error(`组合订阅 ${name} 中不含有效节点`);
}
// check duplicate
const exist = {};
for (const proxy of proxies) {
if (exist[proxy.name]) {
$.notify(
'🌍 Sub-Store',
`⚠️ 组合订阅 ${name} 包含重复节点 ${proxy.name}!`,
'请仔细检测配置!',
{
'media-url':
'https://cdn3.iconfinder.com/data/icons/seo-outline-1/512/25_code_program_programming_develop_bug_search_developer-512.png',
},
);
break;
return ProxyUtils.produce(
proxies,
platform,
produceType,
produceOpts,
);
} catch (err) {
if (
!shouldFallbackIgnoreFailedRemoteSub(
collectionIgnoreFailedRemoteSub,
)
) {
throw err;
}
exist[proxy.name] = true;
notifyIgnoreFailedRemoteSubFallback({
mode: collectionIgnoreFailedRemoteSub,
error: err,
notify: (error) => {
$.notify(
`🌍 Sub-Store 处理组合订阅失败`,
`❌ ${collection.name}`,
`🤔 原因:${error.message ?? error}`,
);
},
});
$.error(
`组合订阅 ${collection.name} 启用兜底后返回空结果: ${
err.message ?? err
}`,
);
return buildEmptySubscriptionOutput({
platform,
produceType,
produceOpts,
});
}
return ProxyUtils.produce(proxies, platform, produceType, produceOpts);
} else if (type === 'rule') {
const allRules = $.read(RULES_KEY);
const rule = findByName(allRules, name);