api/reddit: add support for short links

This commit is contained in:
Felix Vuong 🍂 2025-03-29 13:29:22 +07:00
parent 2d38d63003
commit 987b0559fb
4 changed files with 32 additions and 4 deletions

View File

@ -90,7 +90,9 @@ export const services = {
"r/u_:user/comments/:id/:title",
"r/u_:user/comments/:id/comment/:commentId",
"r/:sub/s/:shareId"
"r/:sub/s/:shareId",
"video/:shortId",
],
subdomains: "*",
},

View File

@ -23,7 +23,8 @@ export const testers = {
pattern.id?.length <= 16 && !pattern.sub && !pattern.user
|| (pattern.sub?.length <= 22 && pattern.id?.length <= 16)
|| (pattern.user?.length <= 22 && pattern.id?.length <= 16)
|| (pattern.sub?.length <= 22 && pattern.shareId?.length <= 16),
|| (pattern.sub?.length <= 22 && pattern.shareId?.length <= 16)
|| (pattern.shortId?.length <= 16),
"rutube": pattern =>
(pattern.id?.length === 32 && pattern.key?.length <= 32) ||

View File

@ -1,4 +1,4 @@
import { resolveRedirectingURL } from "../url.js";
import { extract, resolveRedirectingURL, normalizeURL } from "../url.js";
import { genericUserAgent, env } from "../../config.js";
import { getCookie, updateCookieValues } from "../cookie/manager.js";
@ -50,6 +50,24 @@ async function getAccessToken() {
export default async function(obj) {
let params = obj;
const accessToken = await getAccessToken();
if (params.shortId) {
let r = await fetch(`https://www.reddit.com/video/${params.shortId}`, {
headers: {
'User-Agent': genericUserAgent,
'Authorization': `Bearer ${accessToken}`
}
}).then(r => r.url).catch(() => {});
if (!r) return { error: "fetch.fail" };
try {
params = extract(normalizeURL(r)).patternMatch;
} catch (error) {
return { error: "fetch.fail" };
}
}
if (!params.id && params.shareId) {
params = await resolveRedirectingURL(
@ -63,7 +81,6 @@ export default async function(obj) {
const url = new URL(`https://www.reddit.com/comments/${params.id}.json`);
const accessToken = await getAccessToken();
if (accessToken) url.hostname = 'oauth.reddit.com';
let data = await fetch(

View File

@ -106,6 +106,14 @@ function aliasURL(url) {
url.pathname = `/share/${idPart.slice(-32)}`;
}
break;
case "redd":
/* reddit short video links can be treated by changing https://v.redd.it/<id>
to https://reddit.com/video/<id>.*/
if (url.hostname === "v.redd.it" && parts.length === 2) {
url = new URL(`https://www.reddit.com/video/${parts[1]}`);
}
break;
}
return url;