Created
October 4, 2017 21:48
-
-
Save tspecht/45b64998d2dc14393607cb8163b2c266 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var http = require('http'); | |
module.exports.metaTagOriginRequestRewriter = (event, context, callback) => { | |
const request = event.Records[0].cf.request; | |
request.headers["x-dubsmash-uri"] = [{key: "X-Dubsmash-URI", value: request.uri}]; | |
request.uri = "/index.html"; | |
callback(null, request); | |
}; | |
const downloadContent = function(url, callback) { | |
http.get(url, function(res){ | |
var body = ''; | |
res.on('data', function(chunk){ | |
body += chunk.toString(); | |
}); | |
res.on('end', function(){ | |
callback(body, null); | |
}); | |
}).on('error', function(e){ | |
callback(null, e); | |
}); | |
}; | |
module.exports.metaTagOriginResponseRewriter = (event, context, callback) => { | |
const request = event.Records[0].cf.request; | |
const response = event.Records[0].cf.response; | |
var topicUriMatches = /\/topic\/([a-z0-9]{32})\/([a-z0-9]{32})/gi.exec(request.headers["x-dubsmash-uri"][0].value); | |
if (topicUriMatches && topicUriMatches.length >= 3) { | |
// We have a topic URI! | |
response.headers["x-dubsmash-is-topic"] = [{key: "X-Dubsmash-Is-Topic", value: "true"}]; | |
response.headers["x-dubsmash-topic-uuid"] = [{key: "X-Dubsmash-Topic-UUID", value: topicUriMatches[1]}]; | |
response.headers["x-dubsmash-submission-uuid"] = [{key: "X-Dubsmash-Submission-UUID", value: topicUriMatches[2]}]; | |
var url = 'http://messages.dubsmash.com/1/messages/topic_submission/' + topicUriMatches[2]; | |
const host = request.headers["host"][0].value; | |
downloadContent(url, (body, error) => { | |
if (error) { | |
callback(null, response); | |
} else { | |
var topicSubmission = JSON.parse(body); | |
var video = topicSubmission.video; | |
var metaTags = `<meta property="og:image" content="`+ video.thumbnail + `" /><meta property="og:video" content="` + video.video + `" />`; | |
// Download the index file | |
downloadContent("http://" + host + "/index.html", (indexBody, error) => { | |
console.log(indexBody, error); | |
if (error) { | |
callback(null, response); | |
} else { | |
var finishedBody = indexBody.replace(/(<head>)/gi, "<head>" + metaTags); | |
// Generate the final response and call the callback | |
const newResponse = { | |
status: '200', | |
statusDescription: 'OK', | |
headers: response.headers, | |
body: finishedBody, | |
}; | |
console.log(JSON.stringify(newResponse)); | |
callback(null, newResponse); | |
} | |
}); | |
} | |
}); | |
} else { | |
callback(null, response); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment