Skip to content

Instantly share code, notes, and snippets.

@aligumustosun
Created March 17, 2023 00:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aligumustosun/40801eb6549ed7af9cf9ceba18af1f93 to your computer and use it in GitHub Desktop.
Save aligumustosun/40801eb6549ed7af9cf9ceba18af1f93 to your computer and use it in GitHub Desktop.
const http = require('http')
const url = require('url')
const { google } = require('googleapis')
const fs = require('fs')
const { web: credentials } = require('./client_secret.json')
const oauth2Client = new google.auth.OAuth2(
credentials.client_id,
credentials.client_secret,
'http://localhost:3000' // this is our redirect url for the authorization.
)
const scopes = ['https://www.googleapis.com/auth/youtube.upload']
const authorizationUrl = oauth2Client.generateAuthUrl({
access_type: 'online',
scope: scopes,
include_granted_scopes: true
})
http.createServer(async function (req, res) {
if (req.url == '/') {
res.writeHead(301, { Location: authorizationUrl })
res.end()
}
if (req.url.includes('code')) {
let q = url.parse(req.url, true).query
if (q.error) {
console.log('Error:' + q.error)
} else {
let { tokens } = await oauth2Client.getToken(q.code)
oauth2Client.setCredentials(tokens)
userCredential = tokens
const service = google.youtube({
version: 'v3'
})
service.videos.insert(
{
auth: oauth2Client,
part: 'snippet,status',
requestBody: {
snippet: {
title: 'My video title',
description: 'My video description',
tags: 'tag1,tag2,tag3',
categoryId: 1, // you can check from https://gist.github.com/dgp/1b24bf2961521bd75d6c
defaultLanguage: 'en',
defaultAudioLanguage: 'en'
},
status: {
privacyStatus: 'private'
}
},
media: {
body: fs.createReadStream('video.mp4')
}
},
function (err, response) {
if (err) {
console.log('The API returned an error: ' + err)
return
}
// Video is uploaded here
}
)
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment