Created
May 10, 2019 01:13
-
-
Save Petah/468bcb321651d47971916cad11531ad0 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
const chromium = require('chrome-aws-lambda'); | |
const puppeteer = require('puppeteer-core'); | |
const crypto = require('crypto'); | |
const AWS = require('aws-sdk'); | |
const hashResult = (data) => { | |
const hashDigest = crypto.createHash('md5'); | |
hashDigest.update(data); | |
return hashDigest.digest('hex'); | |
}; | |
const uploadResult = (data, hash) => { | |
return new Promise((resolve, reject) => { | |
new AWS.S3({ | |
accessKeyId: process.env.ACCESS_KEY_ID, | |
secretAccessKey: process.env.SECRET_ACCESS_KEY, | |
region: 'us-east-1', | |
}).putObject({ | |
Bucket: 'mybucket', | |
Key: hash, | |
Body: data, | |
}, (error) => { | |
if (error) { | |
reject(error); | |
return; | |
} | |
resolve('https://s3.amazonaws.com/mybucket/' + hash); | |
}); | |
}); | |
}; | |
exports.handler = async (event, context) => { | |
let result = null; | |
let browser = null; | |
try { | |
if (!event.width || !event.height) { | |
return context.fail('No width/height supplied'); | |
} | |
const puppeteerOptions = event.puppeteer || {}; | |
browser = await puppeteer.launch({ | |
args: chromium.args, | |
defaultViewport: { | |
deviceScaleFactor: 1, | |
hasTouch: false, | |
isLandscape: true, | |
isMobile: false, | |
width: parseInt(event.width), | |
height: parseInt(event.height), | |
}, | |
executablePath: puppeteerOptions.executablePath || await chromium.executablePath, | |
headless: true, | |
}); | |
let page = await browser.newPage(); | |
if (!event.url) { | |
return context.fail('No URL supplied'); | |
} | |
await page.goto(event.url, { | |
waitUntil: 'load', | |
timeout: 0, | |
}); | |
const data = await page.screenshot({ | |
format: 'png', | |
fullPage: false, | |
omitBackground: true, | |
}); | |
const hash = hashResult(data); | |
result = await uploadResult(data, hash); | |
} catch (error) { | |
return context.fail(error); | |
} finally { | |
if (browser !== null) { | |
await browser.close(); | |
} | |
} | |
return context.succeed(result); | |
}; |
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
<?php | |
$s3Url = $lambda->invoke([ | |
'FunctionName' => 'chromeScreenshot', | |
'InvocationType' => 'RequestResponse', | |
'LogType' => 'Tail', | |
'Payload' => json_encode([ | |
'url' => 'https://www.google.com/', | |
'width' => $width, | |
'height' => $height, | |
]), | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment