feat (backend): Add backend API to get flow info for subscriptions

This commit is contained in:
Peng-YM
2022-06-29 00:12:28 +08:00
parent f8671dc8a9
commit 002428d8ff
6 changed files with 66 additions and 10 deletions

View File

@@ -66,6 +66,7 @@ function getEnv(req, res) {
if (isLoon) backend = 'Loon';
if (isSurge) backend = 'Surge';
res.json({
status: 200,
backend,
});
}

View File

@@ -7,6 +7,8 @@ export default function register($app) {
$app.get('/download/:name', downloadSubscription);
$app.get('/api/sub/flow/:name', getFlowInfo);
$app.route('/api/sub/:name')
.get(getSubscription)
.patch(updateSubscription)
@@ -72,6 +74,59 @@ async function downloadSubscription(req, res) {
}
}
async function getFlowInfo(req, res) {
let { name } = req.params;
name = decodeURIComponent(name);
const sub = $.read(SUBS_KEY)[name];
if (!sub) {
res.status(404).json({
status: 'failed',
code: 'NOT_FOUND',
});
}
if (sub.source === 'local') {
res.status(500).json({
status: 'failed',
code: 'IS_LOCAL_SUB',
});
}
try {
const flowHeaders = await getFlowHeaders(sub.url);
if (!flowHeaders) {
res.status(500).json({
status: 'failed',
code: 'NO_FLOW_INFO',
});
}
// unit is KB
const upload = Number(flowHeaders.match(/upload=(\d+)/)[1]);
const download = Number(flowHeaders.match(/download=(\d+)/)[1]);
const total = Number(flowHeaders.match(/total=(\d+)/)[1]);
// optional expire timestamp
const expires = flowHeaders.match(/expire=(\d+)/);
res.status(200).json({
status: 'success',
data: {
expires: expires ? Number(expires[1]) : undefined,
total,
usage: {
upload,
download,
},
},
});
} catch (err) {
res.status(500).json({
status: 'failed',
code: 'NOT_AVAILABLE',
});
}
}
function createSubscription(req, res) {
const sub = req.body;
const allSubs = $.read(SUBS_KEY);