fix: channel id irregular

This commit is contained in:
obvTiger 2025-06-13 23:20:44 +02:00
parent 77b597e5d8
commit c1a4025cbd
5 changed files with 1152 additions and 2026 deletions

41
routes/channel.js Normal file
View file

@ -0,0 +1,41 @@
const axios = require("axios");
const cheerio = require("cheerio");
function channelRouteHandler(app) {
app.get("/api/channel/:username", async (req, res) => {
try {
const username = req.params.username;
if (!username) {
return res.status(400).json({ error: "Username is required" });
}
const response = await axios.get(`https://www.youtube.com/${username}`);
const $ = cheerio.load(response.data);
const canonicalLink = $('link[rel="canonical"]').attr("href");
if (!canonicalLink) {
return res.status(404).json({ error: "Channel not found" });
}
const channelIdMatch = canonicalLink.match(/\/channel\/([\w-]+)/);
const channelId = channelIdMatch ? channelIdMatch[1] : null;
if (!channelId) {
return res.status(404).json({ error: "Could not extract channel ID" });
}
return res.json({
channelId: channelId,
username: username,
});
} catch (error) {
console.error("Error fetching channel ID:", error.message);
return res.status(500).json({
error: "Failed to fetch channel ID",
message: error.message,
});
}
});
}
module.exports = channelRouteHandler;