index.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { serve } from "https://deno.land/std@0.177.0/http/server.ts"
  2. const corsHeaders = {
  3. 'Access-Control-Allow-Origin': '*',
  4. 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
  5. }
  6. serve(async (req) => {
  7. if (req.method === 'OPTIONS') {
  8. return new Response('ok', { headers: corsHeaders })
  9. }
  10. try {
  11. const { url } = await req.json()
  12. if (!url || !url.includes('youtube.com')) {
  13. return new Response(
  14. JSON.stringify({ error: 'Invalid YouTube URL' }),
  15. {
  16. headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  17. status: 400
  18. }
  19. )
  20. }
  21. console.log('Fetching YouTube page:', url)
  22. // Fetch the YouTube page
  23. const response = await fetch(url, {
  24. headers: {
  25. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
  26. }
  27. })
  28. if (!response.ok) {
  29. throw new Error(`Failed to fetch page: ${response.status}`)
  30. }
  31. const html = await response.text()
  32. // Look for the RSS feed link in the HTML
  33. const rssLinkMatch = html.match(/<link[^>]+rel="alternate"[^>]+type="application\/rss\+xml"[^>]+href="([^"]+)"/i)
  34. if (!rssLinkMatch) {
  35. return new Response(
  36. JSON.stringify({ error: 'RSS feed not found on this YouTube page' }),
  37. {
  38. headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  39. status: 404
  40. }
  41. )
  42. }
  43. const rssUrl = rssLinkMatch[1]
  44. // Also try to extract the channel name from the page title
  45. const titleMatch = html.match(/<title>([^<]+)<\/title>/i)
  46. let channelName = null
  47. if (titleMatch) {
  48. // Remove " - YouTube" from the end if present
  49. channelName = titleMatch[1].replace(/ - YouTube$/, '')
  50. }
  51. console.log('Found RSS URL:', rssUrl)
  52. console.log('Found channel name:', channelName)
  53. return new Response(
  54. JSON.stringify({
  55. rssUrl,
  56. channelName
  57. }),
  58. {
  59. headers: { ...corsHeaders, 'Content-Type': 'application/json' }
  60. }
  61. )
  62. } catch (error: any) {
  63. console.error('Error:', error)
  64. return new Response(
  65. JSON.stringify({ error: error?.message || 'Unknown error' }),
  66. {
  67. headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  68. status: 500
  69. }
  70. )
  71. }
  72. })