Skip to content

Commit

Permalink
debug resolve url endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
ArthurHeitmann committed Jan 6, 2024
1 parent 04f5848 commit 13f4040
Showing 1 changed file with 54 additions and 2 deletions.
56 changes: 54 additions & 2 deletions src/serverScripts/photonApi.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import express from "express";
import RateLimit from "express-rate-limit";
import fetch from "node-fetch";
import fetch, { Response } from "node-fetch";
import youtube_dl from "youtube-dl-exec";
import {
basicRateLimitConfig,
Expand Down Expand Up @@ -177,7 +177,7 @@ photonApiRouter.get("/resolveRedditUrl", RateLimit(tokenRequestRateLimitConfig),
if (url.startsWith("/"))
url = "https://www.reddit.com" + url;

let response;
let response: Response;
let isRedirect = false;
const supportedRedditUrl = /^https:\/\/(\w+\.)?reddit.com\/(r|u|user)\/[^/#?]+\//;
do {
Expand Down Expand Up @@ -208,3 +208,55 @@ photonApiRouter.get("/resolveRedditUrl", RateLimit(tokenRequestRateLimitConfig),

res.json({ url, path: urlObj.pathname });
}));


photonApiRouter.get("/resolveRedditUrlDebug", RateLimit(tokenRequestRateLimitConfig), safeExcAsync(async (req, res) => {
let url = req.query["url"].toString();
if (!url) {
res.status(400).json({ error: "¯\\_(ツ)_/¯" });
return;
}
if (url.startsWith("https://reddit.com/"))
url = url.replace("https://reddit.com/", "https://www.reddit.com/");
if (url.startsWith("/"))
url = "https://www.reddit.com" + url;

let response: Response;
let isRedirect = false;
const supportedRedditUrl = /^https:\/\/(\w+\.)?reddit.com\/(r|u|user)\/[^/#?]+\//;
do {
response = await fetch(url, {
redirect: "manual",
headers: {
"User-Agent": `web_backend:photon-reddit.com:v${photonVersion} (by /u/RaiderBDev)`
}
});
let newUrl = response.headers.get("location");
if (!newUrl)
break;
if (!newUrl.startsWith("http"))
newUrl = new URL(newUrl, response.url).href;
url = newUrl;
isRedirect = response.status >= 300 && response.status < 400;
}
while (isRedirect && !supportedRedditUrl.test(url));

if (!supportedRedditUrl.test(url)) {
res.status(400).json({ error: "Failed to resolve url" });
return;
}
const urlObj = new URL(url);
urlObj.search = "";
urlObj.hash = "";
url = urlObj.toString();

res.json({
url,
path: urlObj.pathname,
response: {
status: response.status,
headers: response.headers.raw(),
text: await response.text()
}
});
}));

0 comments on commit 13f4040

Please sign in to comment.