Skip to content

Instantly share code, notes, and snippets.

@malteos
Created July 24, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malteos/02c91068888ab94466f1 to your computer and use it in GitHub Desktop.
Save malteos/02c91068888ab94466f1 to your computer and use it in GitHub Desktop.
YoutubeUploadJS - Node JS program for uploading videos to YouTube via DataAPI v3 & CmdLine
/******************************
* YoutubeUploadJS
* *****************************
* Node JS program for uploading videos to YouTube via DataAPI v3 & CmdLine
* (inspired by https://github.com/rajeshujade/nodejs-upload-youtube-video-using-google-api )
*
* Run with: nodejs ytvideoupload.js <video-file> <video-title> <video-description> [<config-json>]
*
* Requires config.json in home directory or defined as argument. Example:
* {
* "CLIENT_ID": "___ include your api id here _____ .apps.googleusercontent.com",
* "CLIENT_SECRET": "____ include your api secret here ____",
* "REDIRECT_URL": "http://localhost",
* "scope": ["https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.upload"],
* "token_filename": "token.json"
* }
**/
var google = require('googleapis');
var youtube = google.youtube('v3');
var OAuth2 = google.auth.OAuth2;
var readlineSync = require('readline-sync');
if(process.argv.length <= 4) {
console.error("Error: Arguments missing. USAGE: <video-file> <video-title> <video-description> [<config-json>]");
process.exit(1);
}
var videoPath = process.argv[2];
var videoTitle = process.argv[3];
var videoDescription = process.argv[4];
var configPath = (process.argv.length > 5 ? process.argv[5] : './config.json');
var config = require(configPath);
var fs = require('fs');
var googleyoutube = function() {
this.token = {};
this.oauth2Client = new OAuth2(config.CLIENT_ID, config.CLIENT_SECRET, config.REDIRECT_URL);
};
googleyoutube.prototype.getAuthUrl = function(){
var options = {
'scope': config.scope,
'access_type': 'offline',
'approval_prompt': 'force',
'response_type':'code'
};
return this.oauth2Client.generateAuthUrl(options);
};
googleyoutube.prototype.storeToken = function(token) {
fs.writeFileSync(config.token_filename, JSON.stringify(token || this.token));
};
googleyoutube.prototype.getToken = function(callback) {
if(Object.keys(this.token || {}).length > 0 && this.isTokenValid()) {
// if valid?
callback(this.token);
} else if(fs.existsSync(config.token_filename)) {
// Fetch token from file
var token = JSON.parse(fs.readFileSync(config.token_filename, "utf8"));
// if valid?
this.token = token;
if(this.isTokenValid()) {
callback(this.token);
} else {
this.requestToken(callback);
}
} else {
this.requestToken(callback);
}
};
googleyoutube.prototype.requestToken = function (callback) {
console.log('Visit the url: ', this.getAuthUrl());
var code = readlineSync.question('Enter the code here:');
var that = this;
this.oauth2Client.getToken(code, function(err, token) {
if(!err) {
that.token = token;
that.oauth2Client.setCredentials(token);
that.storeToken();
callback(token);
} else {
console.log("Cannot request fresh token.", err);
}
});
};
googleyoutube.prototype.isTokenValid = function(){
var expiryDate = this.token.expiry_date;
var isTokenExpired = expiryDate ? expiryDate <= (new Date()).getTime() : false;
return !isTokenExpired;
};
googleyoutube.prototype.refreshToken = function(token, callback){
this.oauth2Client.refreshAccessToken(function(err, token) {
if(!err){
// foo
this.storeToken(token);
callback(token);
} else {
console.log('Error while trying to get refresh token', err);
}
});
};
googleyoutube.prototype.searchVideos = function(query) {
var that = this;
this.getToken(function(token) {
that.oauth2Client.setCredentials(token);
var params = {
part: 'snippet',
maxResults: 10,
order: 'viewCount',
q: query,
chart: 'mostPopular',
auth: that.oauth2Client
};
youtube.videos.list(params, function(err, res) {
if(!err) {
console.log(res);
} else {
console.log("Cannot receive video list", err);
}
});
});
};
googleyoutube.prototype.uploadVideo = function(options, callback){
var that = this;
this.getToken(function(token) {
that.oauth2Client.setCredentials(token);
youtube.videos.insert({
auth: that.oauth2Client,
part: 'status,snippet',
resource: {
snippet: {
title: options.title,
description: options.description
},
status: {
privacyStatus: 'public' //if you want the video to be private/public
}
},
media: { body: fs.createReadStream(options.videofile) }
}, function(err, resp) {
if(err){
callback(err, null)
} else {
callback(err, resp);
}
});
});
};
var yt = new googleyoutube();
//yt.searchVideos("foo bar");
if(fs.existsSync(videoPath)) {
yt.uploadVideo({"title": videoTitle, "description": videoDescription, "videofile": videoPath}, function(err, res) {
if(err){
console.log('Error while uploading video',err);
}else{
console.log('\n Video has been successfully uploaded \n',res);
console.log('\n Check your uploaded video using:\n https://www.youtube.com/watch?v='+res.id);
}
});
} else {
console.error("Video file does not exist: " + videoPath);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment