Skip to content

Instantly share code, notes, and snippets.

@VFUC
Last active September 3, 2015 17:07
Show Gist options
  • Save VFUC/ec298beb28ee613ab2cd to your computer and use it in GitHub Desktop.
Save VFUC/ec298beb28ee613ab2cd to your computer and use it in GitHub Desktop.
mylatest.video dynamic redirecting
var express = require('express');
var request = require('request');
var winston = require('winston');
var app = express();
var logger = new (winston.Logger)({
transports: [
new (winston.transports.File)({ filename: 'errors.log' })
]
});
var tracker = new (winston.Logger)({
transports: [
new (winston.transports.File)({ filename: 'stats.log' })
]
});
app.use(express.static('static'));
app.get('/', function (req, res) {
// res.send('Hello World!');
res.redirect("/index.html");
});
app.get('/:username', function (req, res) {
var username = req.params.username
var apiKey = ""
var channelRequestURL = "https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername="+username+"&key="+apiKey
request(channelRequestURL, function (channelError, channelResponse, channelBody) {
if (channelResponse.statusCode != 200 || channelError) {
logger.log('info', 'Error during channelRequest (statusCode: %d), requested username: %s', channelResponse.statusCode, username);
res.redirect("/error.html");
}else{
// console.log(channelBody)
var channelDataJSON = JSON.parse(channelBody)
if (channelDataJSON['pageInfo']['totalResults'] == 0) {
logger.log('info', 'Error during channelRequest (totalResults = 0), requested username: %s', username);
res.redirect("/error.html");
}else{
var channelId = channelDataJSON['items'][0]['id']
var maxResults = 1
var videoRequestURL = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=" + channelId + "&maxResults=" + maxResults + "&order=date&type=video&key=" + apiKey
request(videoRequestURL, function (videoError, videoResponse, videoBody){
if (videoResponse.statusCode != 200 || videoError) {
logger.log('info', 'Error during videoRequest (statusCode: %d), requested username: %s', videoResponse.statusCode, username);
res.redirect("/error.html");
}else{
var videoDataJSON = JSON.parse(videoBody);
// console.log(videoBody);
if (videoDataJSON['pageInfo']['totalResults'] == 0) {
res.redirect('https://www.youtube.com/user/'+username+'/videos');
}else{
var videos = videoDataJSON["items"];
var videoID = videos[0]["id"]["videoId"]
tracker.log('info', 'Success, requested username: %s', username);
res.redirect('https://youtu.be/'+videoID);
}//else
}//else
})//request
}//else
}//else
})//request
});//app.get
var server = app.listen(80, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Latest vid forwarder running at http://%s:%s', host, port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment