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;