Skip to content

Instantly share code, notes, and snippets.

@ngs
Last active December 15, 2021 16:59
Show Gist options
  • Save ngs/aff2179ba5075007b92baeff6cc3293a to your computer and use it in GitHub Desktop.
Save ngs/aff2179ba5075007b92baeff6cc3293a to your computer and use it in GitHub Desktop.
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
exports.handler = async (event) => {
const filename = 'feed.xml';
const { bucket, object } = event.Records[0].s3;
const { eventTime, awsRegion } = event.Records[0];
const date = new Date(eventTime).toUTCString();
console.info(JSON.stringify(event, null, 2));
const res = await s3.getObject({ Bucket: bucket.name, Key: filename }).promise();
let xml = res.Body.toString('utf-8').replace(/\s*<\/channel>[\n\s]*<\/rss>/, '').split('<item>');
xml[0] = xml[0].replace(/<pubDate>[^<]+<\/pubDate>/, `<pubDate>${date}</pubDate>`);
xml[0] = xml[0].replace(/<lastBuildDate>[^<]+<\/lastBuildDate>/, `<lastBuildDate>${date}</lastBuildDate>`);
while(xml.length > 49) {
xml.pop();
}
const url = `https://${bucket.name}.s3.${awsRegion}.amazonaws.com/${object.key}`;
xml.splice(1, 0, `
<title>${object.key.replace(/\.m4a$/, '')}</title>
<link>${url}</link>
<pubDate>${date}</pubDate>
<description></description>
<enclosure url="${url}" length="${object.size}" type="audio/m4a" />
<guid>${url}</guid>
<itunes:explicit>no</itunes:explicit>
</item>`)
await s3.putObject({
ACL: 'public-read',
Body: xml.join('<item>').replace(/\s*\n+\s*/g, '') + '</channel></rss>',
Bucket: bucket.name,
ContentType: 'application/rss+xml',
Key: filename,
}).promise();
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment