forked from kaoskeya/bs-email-pipeline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (72 loc) · 2.47 KB
/
index.js
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
const path = require('path');
const fs = require('fs');
const cheerio = require('cheerio')
const axios = require('axios');
const formurlencoded = require('form-urlencoded').default;
const minify = require('html-minifier').minify;
const htmlToText = require('html-to-text');
const queryString = require('query-string');
const _ = require('lodash');
const ENDPOINT = "https://bootstrap-email.herokuapp.com/";
function decodeData(value) {
return queryString.stringify(
queryString.parse(
value
),
{ encode: false }
)
}
async function convertBsEmail() {
// set up filename, base dir, extract markup.
const file = process.argv[2];
const env = process.argv[3];
const filename = path.basename(file).split(".")[0];
const markup = fs.readFileSync(file, 'utf8');
const renderedFile = path.resolve(path.dirname(file), `../rendered/${filename}.html`);
const outputJsonFile = path.resolve(path.dirname(file), `../json/${env ? `${env}/` : ''}${filename}.json`);
// fetch page and set up cookies and token
const initialPage = await axios.get(ENDPOINT);
const tempCookie = initialPage.headers['set-cookie'][0];
const cookie = tempCookie.substring(tempCookie.indexOf("=") + 1, tempCookie.indexOf(";"));
const $ = cheerio.load(initialPage.data);
const body = {
"utf": "✓",
"authenticity_token": $('[name=authenticity_token]').val(),
markup,
"checkbox1": "on",
}
let renderedPage;
try {
renderedPage = await axios.request({
url: ENDPOINT,
method: "post",
headers: {
"Cookie": `_bootstrap_email_rails_example_session=${cookie};`,
"Content-Type": "application/x-www-form-urlencoded"
},
data: formurlencoded(body),
})
} catch (e) {
console.log(e)
return;
}
const $2 = cheerio.load(renderedPage.data);
const outputHtml = minify(decodeData($2('#responseCodeMirror').val()), {
collapseWhitespace: true,
removeComments: true,
quoteCharacter: "'",
}).replace(/\s{2,}/g, ' ')
.replace('"', "'");
const $3 = cheerio.load(outputHtml);
const outputSubject = $3('#subject').text();
fs.writeFileSync(renderedFile, outputHtml, 'utf8');
fs.writeFileSync(outputJsonFile, JSON.stringify({
"Template": {
"TemplateName": `${env ? `${env}-` : ''}${filename}`,
"SubjectPart": outputSubject.replace(/ +(?= )/g,''),
"TextPart": "Please view the HTML version", // htmlToText.fromString(outputHtml),
"HtmlPart": outputHtml,
}
}), 'utf8');
}
convertBsEmail();