Skip to content

Commit

Permalink
Initial
Browse files Browse the repository at this point in the history
  • Loading branch information
boronine committed Sep 11, 2022
0 parents commit 29b2404
Show file tree
Hide file tree
Showing 14 changed files with 5,276 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules

# CDK asset staging directory
.cdk.staging
cdk.out
3 changes: 3 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# CDK asset staging directory
.cdk.staging
cdk.out
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2022 Alexei Boronine

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
62 changes: 62 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# CDK Screenshot (powered by Puppeteer)

Made possible by the excellent [Puppeteer](https://pptr.dev/).

## Install

```bash
export AWS_PROFILE=myprofile
export AWS_DEFAULT_REGION=us-east-1

# If this is your first time using CDK on this AWS account
npx cdk bootstrap

# Review stack before deploying
npx cdk synth

# Deploy (make sure Docker is running on your development machine)
npx cdk deploy
```

## Usage

This function is invoked by passing parameters directly into Puppeteer.

```json
{
"url": "https://www.wikipedia.org/",
"viewport": {
"width": 1920,
"height": 1080
},
"waitforoptions": {
"timeout": 10000,
"waitUntil": "networkidle2"
},
"screenshotoptions": {
"fullPage": true
}
}
```

- `"viewport"` https://pptr.dev/api/puppeteer.viewport/
- `"waitforoptions"` https://pptr.dev/api/puppeteer.waitforoptions
- `"screenshotoptions"` https://pptr.dev/api/puppeteer.screenshotoptions

The resulting screenshot will be saved to an S3 bucket. Sample output:

```json
{
"response": {
"$metadata": {
"httpStatusCode": 200,
"extendedRequestId": "etAXPmAcRodh+o3llGpSR5pUvW5bUlnQJlXLJ8nFgawxGjfF8gJwoCJ7BnIgvTAkBA0u/Ocq8P0=",
"attempts": 1,
"totalRetryDelay": 0
},
"ETag": "be375e15fdd474ca1421e852f5b1bf52"
},
"key": "3d6a714a-4e37-4a08-be6b-a58b632cfff7.png",
"bucket": "puppeteerscreenshotstack-puppeteerscreenshotbucke-1nh0w9anigpwe"
}
```
7 changes: 7 additions & 0 deletions bin/puppeteer-screenshot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/usr/bin/env node

const cdk = require('aws-cdk-lib');
const { PuppeteerScreenshotStack } = require('../lib/puppeteer-screenshot-stack');

const app = new cdk.App();
new PuppeteerScreenshotStack(app, 'PuppeteerScreenshotStack', {});
37 changes: 37 additions & 0 deletions cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"app": "node bin/puppeteer-screenshot.js",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"package*.json",
"node_modules"
]
},
"context": {
"@aws-cdk/aws-apigateway:usagePlanKeyOrderInsensitiveId": true,
"@aws-cdk/core:stackRelativeExports": true,
"@aws-cdk/aws-rds:lowercaseDbIdentifier": true,
"@aws-cdk/aws-lambda:recognizeVersionProps": true,
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": true,
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
"@aws-cdk/core:checkSecretUsage": true,
"@aws-cdk/aws-iam:minimizePolicies": true,
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
"@aws-cdk/core:enablePartitionLiterals": true,
"@aws-cdk/core:target-partitions": [
"aws",
"aws-cn"
]
}
}
1 change: 1 addition & 0 deletions image/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
22 changes: 22 additions & 0 deletions image/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
FROM amazon/aws-lambda-nodejs:16

ARG AWS_ACCESS_KEY_ID
ARG AWS_SECRET_ACCESS_KEY
ARG AWS_REGION=us-east-1

# Install Chrome to get all of the dependencies installed
RUN yum install -y amazon-linux-extras
RUN amazon-linux-extras install epel -y
RUN yum install -y chromium

ENV AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID
ENV AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY
ENV AWS_REGION=$AWS_REGION

COPY package.json package-lock.json ${LAMBDA_TASK_ROOT}/

RUN npm install

COPY app.js ${LAMBDA_TASK_ROOT}/

CMD [ "app.handler" ]
54 changes: 54 additions & 0 deletions image/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const s3 = require('@aws-sdk/client-s3');
const puppeteer = require('puppeteer');

const handler = async (event, context) => {
if (typeof event['url'] !== 'string') {
throw new Error("Missing or invalid 'url' property");
}
if (typeof event['viewport'] !== 'object') {
throw new Error("Missing or invalid 'viewport' property");
}
if (typeof event['waitforoptions'] !== 'object') {
throw new Error("Missing or invalid 'waitforoptions' property");
}
if (typeof event['screenshotoptions'] !== 'object') {
throw new Error("Missing or invalid 'screenshotoptions' property");
}
const imageType = event['screenshotoptions']['type'] ?? 'png';
const bucket = process.env.SCREENSHOT_BUCKET;
const browser = await puppeteer.launch({
args: [
'--no-sandbox',
// https://github.com/adieuadieu/serverless-chrome/issues/316
'--no-zygote',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--single-process'
]
});
const browserVersion = await browser.version()
console.log(`Started ${browserVersion}`);

const page = await browser.newPage();
await page.setViewport(event['viewport']);
await page.goto(event['url'], event['waitforoptions']);
const screenshot = await page.screenshot({...event['screenshotoptions'], encoding: 'binary', type: imageType});
await page.close();
await browser.close();

const client = new s3.S3Client({});
const key = `${context['awsRequestId']}.${imageType}`;
const response = await client.send(new s3.PutObjectCommand({
Bucket: bucket,
Key: `${context['awsRequestId']}.${imageType}`,
Body: screenshot,
ContentType: `image/${imageType}`
}))

return {
statusCode: 200,
body: JSON.stringify({response, key, bucket})
}
}

module.exports = {handler};
Loading

0 comments on commit 29b2404

Please sign in to comment.