-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake.js
More file actions
262 lines (225 loc) · 10.7 KB
/
make.js
File metadata and controls
262 lines (225 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/* eslint-disable no-console */
const commander = require('commander');
const fs = require('fs-extra');
const path = require('path');
const AwsArchitect = require('aws-architect');
const aws = require('aws-sdk');
const { DateTime } = require('luxon');
const { Builder: XmlBuilder } = require('xml2js');
const { Route53Client, ListHostedZonesByNameCommand } = require('@aws-sdk/client-route-53');
const { STSClient, GetCallerIdentityCommand } = require('@aws-sdk/client-sts');
const stackTemplateProvider = require('./template/cloudFormationWebsiteTemplate.js').default;
const { getEpisodesFromDirectory, ensureS3Episode, getLocalRssData } = require('./release-generator/publisher/sync.js');
const { syncEpisodesToSpreaker, getSpreakerPublishedEpisode } = require('./release-generator/publisher/spreaker.js');
aws.config.update({ region: 'us-east-1' });
function getVersion() {
let release_version = '0.0';
const pull_request = '';
const branch = process.env.GITHUB_REF;
const build_number = `${process.env.GITHUB_RUN_NUMBER}`;
// Builds of pull requests
if (pull_request && !pull_request.match(/false/i)) {
release_version = `0.${pull_request}`;
} else if (!branch || !branch.match(/^(refs\/heads\/)?release[/-]/i)) {
// Builds of branches that aren't main or release
release_version = '0.0';
} else {
// Builds of release branches (or locally or on server)
release_version = branch.match(/^(?:refs\/heads\/)?release[/-](\d+(?:\.\d+){0,3})$/i)[1];
}
return `${release_version}.${(build_number || '0')}.0.0.0.0`.split('.').slice(0, 3).join('.');
}
const version = getVersion();
commander.version(version);
const packageMetadata = require('./package.json');
packageMetadata.version = version;
const parameters = {
hostedName: 'adventuresindevops.com',
serviceName: 'AdventuresInDevops',
serviceDescription: 'AdventuresInDevops Podcast website'
};
const contentOptions = {
bucket: parameters.hostedName,
contentDirectory: path.join(__dirname, 'build')
};
/**
* Build
*/
commander
.command('setup')
.description('Setup require build files for npm package.')
.action(async () => {
await fs.writeJson('./package.json', packageMetadata, { spaces: 2 });
console.log('Building package %s (%s)', packageMetadata.name, version);
console.log('');
});
commander
.command('rss')
.option('-o, --output-directory <path>', 'The output directory to write the RSS feed to.', 'build')
.description('Create the RSS File')
.action(async cmd => {
try {
// spam / rss@email-devops.com address
const email = Buffer.from('cnNzQGFkdmVudHVyZXNpbmRldm9wcy5jb20', 'base64url').toString();
const xmlObject = await getLocalRssData();
xmlObject.rss.channel.copyright = 'Rhosys AG';
xmlObject.rss.channel.lastBuildDate = DateTime.utc().toRFC2822();
xmlObject.rss.channel['itunes:owner']['itunes:email'] = email;
xmlObject.rss.channel['itunes:applepodcastsverify'] = 'ffe0a5a0-80d4-11f0-aa9e-b10ce375a2e5';
xmlObject.rss.channel['itunes:explicit'] = 'false';
xmlObject.rss.channel['podcast:locked'] = { $: { owner: email }, _: 'yes' };
// https://tools.rssblue.com/podcast-guid
xmlObject.rss.channel['podcast:guid'] = '917758d3-7b50-5ea4-906e-00f3fb05e50a';
const existingEpisodes = xmlObject.rss.channel.item;
const recentEpisodes = await getEpisodesFromDirectory();
const newItems = [];
for (const recentEpisode of recentEpisodes.sort((a, b) => a.date.diff(b.date))) {
if (existingEpisodes.some(e => e.link.includes(recentEpisode.slug))) {
continue;
}
// Dev - Skip episodes that will be released in the far future
// Prd - Skip attempting put future episodes in the RSS feed, wait until it is one day before release to put them there.
if (DateTime.utc().plus({ days: 1 }) < recentEpisode.date && process.env.CI
|| DateTime.utc().plus({ days: 100 }) < recentEpisode.date) {
continue;
}
let spreakerEpisodeData = null;
for (let iteration = 0; iteration < 20; iteration++) {
spreakerEpisodeData = await getSpreakerPublishedEpisode({ episodeSlug: recentEpisode.slug });
if (spreakerEpisodeData) {
break;
}
if (!process.env.CI) {
console.error(`Cannot find published episode for locally available episode, skipping invalid spreaker data from RSS feed: ${recentEpisode.title}`);
spreakerEpisodeData = {
audioDurationSeconds: 'Spearker-Data-Not-Found',
audioUrl: 'Spearker-Data-Not-Found',
audioFileSize: 'Spearker-Data-Not-Found'
};
break;
}
await new Promise(resolve => setTimeout(resolve, 2 ** iteration * 5 * 1000));
}
if (!spreakerEpisodeData && process.env.CI) {
throw Error(`Cannot find published episode for locally available episode, refusing to generating RSS feed: ${recentEpisode.title}`);
}
const audioDurationSeconds = spreakerEpisodeData.audioDurationSeconds;
const audioUrl = spreakerEpisodeData.audioUrl;
const audioFileSize = spreakerEpisodeData.audioFileSize;
newItems.push({
title: recentEpisode.title,
link: recentEpisode.episodeLink,
description: recentEpisode.sanitizedBody,
guid: { $: { isPermaLink: "false" }, _: recentEpisode.episodeLink },
pubDate: recentEpisode.date.toRFC2822(),
enclosure: { $: {
url: audioUrl, length: `${audioFileSize}`, type: "audio/mpeg"
} },
'podcast:transcript': [
{ $: {
url: `https://links.adventuresindevops.com/storage/episodes/${recentEpisode.episodeNumber}-${recentEpisode.slug}/transcript.srt`,
type: 'application/x-subrip', language: 'en' } },
{ $: {
url: `https://links.adventuresindevops.com/storage/episodes/${recentEpisode.episodeNumber}-${recentEpisode.slug}/transcript.txt`,
type: 'text/plain', language: 'en' } }
],
'itunes:author': 'Will Button, Warren Parad',
'itunes:title': recentEpisode.title,
'itunes:summary': recentEpisode.sanitizedBody,
'itunes:duration': audioDurationSeconds,
'itunes:keywords': `devops,platform,engineering,software,security,leadership,product,software,architecture,microservices,career`.split(',').slice(0, 12).join(','),
'itunes:explicit': 'false',
'itunes:image': { $: { href: "https://d3wo5wojvuv7l.cloudfront.net/t_rss_itunes_square_1400/images.spreaker.com/original/2f474744f84e93eba827bee58d58c1c9.jpg" } },
'itunes:episode': recentEpisode.episodeNumber,
'itunes:episodeType': 'full'
});
}
xmlObject.rss.channel.item = [].concat(newItems.map(i => i).sort((a, b) => Number(b['itunes:episode']) - Number(a['itunes:episode']))).concat(existingEpisodes);
const rssXml = new XmlBuilder({ cdata: true }).buildObject(xmlObject);
const rssOutputDirectory = path.resolve(path.join(__dirname, cmd.outputDirectory));
await fs.mkdirp(path.resolve(path.join(rssOutputDirectory, '/episodes')));
await fs.writeFile(path.resolve(path.join(rssOutputDirectory, '/episodes/rss.xml')), Buffer.from(rssXml));
await fs.writeFile(path.resolve(path.join(rssOutputDirectory, '/episodes/rss')), Buffer.from(rssXml));
await fs.writeFile(path.resolve(path.join(rssOutputDirectory, '/rss')), Buffer.from(rssXml));
await fs.writeFile(path.resolve(path.join(rssOutputDirectory, '/rss.xml')), Buffer.from(rssXml));
console.log('Finished RSS feed page');
console.log('');
console.log('');
} catch (error) {
console.log('Failed to build RSS feed file, error:', error, error.stack);
process.exit(1);
}
});
commander
.command('s3sync')
.description('[RUN LOCALLY] Sync the release to S3')
.action(async () => {
try {
console.log("Starting S3 synchronization...");
await ensureS3Episode();
console.log("S3 release synchronization completed successfully.");
} catch (error) {
console.error('');
console.error('');
console.error("Synchronization failed:", error.message, error.code || '', error.stack);
console.error('');
console.error('');
process.exit(1);
}
});
commander
.command('publish-episode')
.description('[RUN IN CICD]: Sync the release to other locations')
.action(async () => {
try {
console.log("Starting Spreaker synchronization...");
await syncEpisodesToSpreaker();
console.log("Spreaker synchronization completed successfully.");
} catch (error) {
console.error("Publishing failed:", error, error.message, error.code || '', error.stack);
process.exit(1);
}
});
commander
.command('deploy')
.description('Deploying website to AWS.')
.action(async () => {
const requestInterceptorLambdaFunction = await fs.readFile(path.join(__dirname, 'template/requestInterceptorLambdaFunction.js'));
const stackTemplate = stackTemplateProvider.getStack({
requestInterceptorLambdaFunctionString: requestInterceptorLambdaFunction.toString()
});
const stsClient = new STSClient({});
const callerIdentityResponse = await stsClient.send(new GetCallerIdentityCommand({}));
const apiOptions = {
deploymentBucket: `rhosys-deployments-artifacts-${callerIdentityResponse.Account}-${aws.config.region}`
};
const awsArchitect = new AwsArchitect(packageMetadata, apiOptions, contentOptions);
const isProductionBranch = process.env.GITHUB_REF === 'refs/heads/main';
try {
await awsArchitect.validateTemplate(stackTemplate);
if (isProductionBranch) {
const stackConfiguration = {
changeSetName: `${process.env.GITHUB_REPOSITORY.replace(/[^a-z0-9]/ig, '-')}-${process.env.GITHUB_RUN_NUMBER || '1'}`,
stackName: packageMetadata.name,
automaticallyProtectStack: true
};
const route53Client = new Route53Client({});
const command = new ListHostedZonesByNameCommand({ DNSName: parameters.hostedName });
const response = await route53Client.send(command);
const hostedZoneId = response.HostedZones[0].Id.replace('/hostedzone/', '');
parameters.hostedZoneId = hostedZoneId;
await awsArchitect.deployTemplate(stackTemplate, stackConfiguration, parameters);
}
console.log('Deployment Success!');
} catch (failure) {
console.log(`Failed to upload website ${failure} - ${JSON.stringify(failure, null, 2)}`);
process.exit(1);
}
});
commander.on('*', () => {
if (commander.args.join(' ') === 'tests/**/*.js') { return; }
console.log(`Unknown Command: ${commander.args.join(' ')}`);
commander.help();
process.exit(0);
});
commander.parse(process.argv[2] ? process.argv : process.argv.concat(['build']));