api: refactor /api/json POST handler

This commit is contained in:
dumbmoron 2024-05-15 13:29:18 +00:00
parent 0a7cdfbbfe
commit c10012130b
No known key found for this signature in database
2 changed files with 36 additions and 30 deletions

View file

@ -95,37 +95,42 @@ export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
} }
}); });
const acceptRegex = /^application\/json(; charset=utf-8)?$/;
app.post('/api/json', async (req, res) => { app.post('/api/json', async (req, res) => {
try { const request = req.body;
let lang = languageCode(req); const lang = languageCode(req);
let j = apiJSON(0, { t: "bad request" }); const fail = (t) => {
try { const { status, body } = apiJSON(0, { t: loc(lang, t) });
let contentCon = String(req.header('Content-Type')) === "application/json"; res.status(status).json(body);
let request = req.body; }
if (contentCon && request.url) {
request.dubLang = request.dubLang ? lang : false;
let chck = checkJSONPost(request);
if (!chck) throw new Error();
const parsed = extract(chck.url); if (!acceptRegex.test(req.header('Content-Type'))) {
if (parsed === null) { return fail('ErrorInvalidContentType');
return apiJSON(0, { t: errorUnsupported(lang) }) }
}
if (!request.url) {
j = await match(parsed.host, parsed.patternMatch, lang, chck) return fail('ErrorNoLink');
.catch(() => apiJSON(0, { t: loc(lang, 'ErrorSomethingWentWrong') })) }
} else {
j = apiJSON(0, { request.dubLang = request.dubLang ? lang : false;
t: !contentCon ? "invalid content type header" : loc(lang, 'ErrorNoLink') const normalizedRequest = checkJSONPost(request);
}); if (!normalizedRequest) {
} return fail('ErrorCantProcess');
} catch (e) { }
j = apiJSON(0, { t: loc(lang, 'ErrorCantProcess') });
} const parsed = extract(normalizedRequest.url);
return res.status(j.status).json(j.body); if (parsed === null) {
} catch (e) { return fail('ErrorUnsupported');
return res.destroy(); }
try {
const result = await match(
parsed.host, parsed.patternMatch, lang, normalizedRequest
);
res.status(result.status).json(result.body);
} catch {
fail('ErrorSomethingWentWrong');
} }
}); });

View file

@ -155,6 +155,7 @@
"SettingsTikTokH265Description": "download 1080p videos from tiktok in h265/hevc format when available.", "SettingsTikTokH265Description": "download 1080p videos from tiktok in h265/hevc format when available.",
"SettingsYoutubeDub": "use browser language", "SettingsYoutubeDub": "use browser language",
"SettingsYoutubeDubDescription": "uses your browser's default language for youtube dubbed audio tracks. works even if cobalt ui isn't translated to your language.", "SettingsYoutubeDubDescription": "uses your browser's default language for youtube dubbed audio tracks. works even if cobalt ui isn't translated to your language.",
"UpdateIstream": "better service support and ux" "UpdateIstream": "better service support and ux",
"ErrorInvalidContentType": "invalid content type header"
} }
} }