Skip to content

Instantly share code, notes, and snippets.

@coleww
Last active October 23, 2015 16:01
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 coleww/94759e966d5750548c09 to your computer and use it in GitHub Desktop.
Save coleww/94759e966d5750548c09 to your computer and use it in GitHub Desktop.
automagic birthday greeter server thing
var http = require("http")
var url = require("url")
var MemJS = require("memjs").Client
memjs = MemJS.create();
var server = http.createServer(function (req, res) {
var name = url.parse(req.url).pathname.substr(1)
if(!!name) {
doThatThang(name, function (html) {
res.writeHead(200, {"Content-Type": 'text/html', 'Content-Length': html.length});
res.end(html);
})
} else {
res.writeHead(200, {"Content-Type": 'text/html'});
res.end("<h1>HEYYYYYYYYYYYYYSSSSSSSUP? WHAT U DOING HERE?</h1>");
}
})
server.listen(process.env.PORT || 8000)
console.log('listening on: ', process.env.PORT || 8000)
function doThatThang(name, cb) {
memjs.get(name, function(err, value) {
if (!value) {
hitTheYoutube(name, function (data) {
var html = "<title>HAPPY BIRTHDAY " + name.toUpperCase() + "!!!</title><center>" +
data.map(function (id) {
return "<iframe width=\"30%\" height=\"30%\" src=\"http://www.youtube.com/embed/" +
id + "?autoplay=1&loop=1&playlist=" + id +
" frameborder=\"0\" allowfullscreen></iframe>​"
}).join('') + "</center>"
memjs.set(name, html)
cb(html)
})
} else {
console.log(value)
cb(value.toString())
}
})
}
var $ = require('cheerio')
var request = require('request')
function hitTheYoutube(name, cb) {
request("https://www.youtube.com/results?search_query=happy+birthday+" + name, function (err, resp, html) {
if (err) return console.error(err)
var parsedHTML = $.load(html)
// get all img tags and loop over them
var vidURLs = []
parsedHTML('a').each(function(i, link) {
var href = $(link).attr('href')
console.log(href)
if (!href.match('watch') || href.match('list')) return
vidURLs.push(href.replace('/watch?v=', ''))
})
cb(vidURLs.filter(function(v, i, a){
return a.indexOf(v) == i
}))
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment