|
| 1 | +import { google } from "googleapis"; |
| 2 | + |
| 3 | +const oauth2Client = new google.auth.OAuth2( |
| 4 | + process.env.YOUTUBE_CLIENT_ID, |
| 5 | + process.env.YOUTUBE_CLIENT_SECRET, |
| 6 | +); |
| 7 | +oauth2Client.setCredentials({ |
| 8 | + refresh_token: process.env.YOUTUBE_REFRESH_TOKEN, |
| 9 | +}); |
| 10 | + |
| 11 | +const youtube = google.youtube({ version: "v3", auth: oauth2Client }); |
| 12 | + |
| 13 | +/** |
| 14 | + * Upload a video to YouTube (main channel video, 16:9). |
| 15 | + */ |
| 16 | +export async function uploadVideo(opts: { |
| 17 | + title: string; |
| 18 | + description: string; |
| 19 | + tags: string[]; |
| 20 | + videoUrl: string; |
| 21 | +}): Promise<{ videoId: string; url: string }> { |
| 22 | + // Fetch the video from GCS URL |
| 23 | + const response = await fetch(opts.videoUrl); |
| 24 | + if (!response.ok) throw new Error(`Failed to fetch video: ${response.statusText}`); |
| 25 | + |
| 26 | + const res = await youtube.videos.insert({ |
| 27 | + part: ["snippet", "status"], |
| 28 | + requestBody: { |
| 29 | + snippet: { |
| 30 | + title: opts.title, |
| 31 | + description: opts.description, |
| 32 | + tags: opts.tags, |
| 33 | + categoryId: "28", // Science & Technology |
| 34 | + }, |
| 35 | + status: { |
| 36 | + privacyStatus: "public", |
| 37 | + selfDeclaredMadeForKids: false, |
| 38 | + }, |
| 39 | + }, |
| 40 | + media: { |
| 41 | + body: response.body as unknown as NodeJS.ReadableStream, |
| 42 | + }, |
| 43 | + }); |
| 44 | + |
| 45 | + const videoId = res.data.id || ""; |
| 46 | + return { videoId, url: `https://youtube.com/watch?v=${videoId}` }; |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * Upload a Short to YouTube (9:16 vertical). |
| 51 | + */ |
| 52 | +export async function uploadShort(opts: { |
| 53 | + title: string; |
| 54 | + description: string; |
| 55 | + tags: string[]; |
| 56 | + videoUrl: string; |
| 57 | +}): Promise<{ videoId: string; url: string }> { |
| 58 | + // Shorts are just regular uploads with #Shorts in title/description |
| 59 | + return uploadVideo({ |
| 60 | + ...opts, |
| 61 | + title: `${opts.title} #Shorts`, |
| 62 | + description: `${opts.description}\n\n#Shorts`, |
| 63 | + }); |
| 64 | +} |
0 commit comments