|
| 1 | +from fastapi import APIRouter, Depends |
| 2 | +from app.utils.db import get_db_connection_direct |
| 3 | +from app.utils.make_meta import make_meta |
| 4 | +from app.utils.api_key_auth import get_api_key |
| 5 | +import os |
| 6 | +import requests |
| 7 | +import json |
| 8 | +from dotenv import load_dotenv |
| 9 | + |
| 10 | +router = APIRouter() |
| 11 | + |
| 12 | +@router.post("/youtube/sync") |
| 13 | +def sync_youtube(api_key: str = Depends(get_api_key)) -> dict: |
| 14 | + """POST /youtube/sync: Fetches data from YouTube Data API and stores in DB.""" |
| 15 | + load_dotenv() |
| 16 | + youtube_key = os.getenv("YOUTUBE_API_KEY") |
| 17 | + if not youtube_key: |
| 18 | + return {"meta": make_meta("error", "Missing YouTube API key"), "data": {}} |
| 19 | + |
| 20 | + # Example: Fetch channel info and latest videos for a given channel ID |
| 21 | + channel_id = os.getenv("YOUTUBE_CHANNEL_ID") # Optionally add this to .env |
| 22 | + if not channel_id: |
| 23 | + return {"meta": make_meta("error", "Missing YOUTUBE_CHANNEL_ID in .env"), "data": {}} |
| 24 | + |
| 25 | + try: |
| 26 | + # Fetch channel details |
| 27 | + channel_url = "https://www.googleapis.com/youtube/v3/channels" |
| 28 | + channel_params = { |
| 29 | + "part": "snippet,contentDetails,statistics", |
| 30 | + "id": channel_id, |
| 31 | + "key": youtube_key |
| 32 | + } |
| 33 | + channel_resp = requests.get(channel_url, params=channel_params) |
| 34 | + channel_resp.raise_for_status() |
| 35 | + channel_data = channel_resp.json() |
| 36 | + channel_items = channel_data.get("items", []) |
| 37 | + if channel_items: |
| 38 | + channel = channel_items[0] |
| 39 | + else: |
| 40 | + return {"meta": make_meta("error", "Channel not found"), "data": {}} |
| 41 | + |
| 42 | + # Insert channel info |
| 43 | + conn = get_db_connection_direct() |
| 44 | + cur = conn.cursor() |
| 45 | + cur.execute( |
| 46 | + """ |
| 47 | + INSERT INTO youtube_channels (youtube_id, title, payload) |
| 48 | + VALUES (%s, %s, %s) |
| 49 | + ON CONFLICT (youtube_id) DO NOTHING; |
| 50 | + """, |
| 51 | + (channel.get("id"), channel["snippet"].get("title"), json.dumps(channel)) |
| 52 | + ) |
| 53 | + |
| 54 | + # Fetch latest videos from uploads playlist |
| 55 | + uploads_playlist_id = channel["contentDetails"]["relatedPlaylists"]["uploads"] |
| 56 | + playlist_url = "https://www.googleapis.com/youtube/v3/playlistItems" |
| 57 | + playlist_params = { |
| 58 | + "part": "snippet,contentDetails", |
| 59 | + "playlistId": uploads_playlist_id, |
| 60 | + "maxResults": 100, |
| 61 | + "key": youtube_key |
| 62 | + } |
| 63 | + playlist_resp = requests.get(playlist_url, params=playlist_params) |
| 64 | + playlist_resp.raise_for_status() |
| 65 | + playlist_data = playlist_resp.json() |
| 66 | + videos = playlist_data.get("items", []) |
| 67 | + for video in videos: |
| 68 | + video_id = video["contentDetails"]["videoId"] |
| 69 | + title = video["snippet"].get("title") |
| 70 | + cur.execute( |
| 71 | + """ |
| 72 | + INSERT INTO youtube_videos (youtube_id, title, payload) |
| 73 | + VALUES (%s, %s, %s) |
| 74 | + ON CONFLICT (youtube_id) DO NOTHING; |
| 75 | + """, |
| 76 | + (video_id, title, json.dumps(video)) |
| 77 | + ) |
| 78 | + conn.commit() |
| 79 | + cur.close() |
| 80 | + conn.close() |
| 81 | + return {"meta": make_meta("success", f"Synced {len(videos)} videos from YouTube"), "data": {"count": len(videos)}} |
| 82 | + except Exception as e: |
| 83 | + return {"meta": make_meta("error", f"Sync error: {str(e)}"), "data": {}} |
0 commit comments