-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
74 lines (61 loc) · 1.99 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
#!/usr/bin/env node
const fetch = require('node-fetch');
const Parser = require('rss-parser');
const TurndownService = require('turndown');
const dotenv = require('dotenv');
dotenv.config();
var turndownService = new TurndownService();
const parser = new Parser();
const now = new Date();
const rssURL = process.env.RSS_URL;
const buttondownApiKey = process.env.BUTTONDOWN_API_KEY;
const maxRecentPostAge = Number(process.env.MAX_RECENT_POST_AGE) * 1000;
async function sendDrafts() {
const feed = await getFeed(rssURL);
// Remove posts older that minLastPostDiff
const recentItems = feed.items.filter(
(item) => now.getTime() - new Date(item.pubDate).getTime() < maxRecentPostAge,
);
console.log(`Found ${recentItems.length} new post(s)`);
if (recentItems.length === 0) {
return;
}
const subject =
(recentItems.length > 1 ? 'Recent posts: ' : '') +
recentItems.map((item) => item.title).join(', ');
const body = recentItems
// Convert HTML back to Markdown, Buttondown doesn't play well with raw HTML
.map((item) => ({ item, content: turndownService.turndown(item.content) }))
// Add title block for each post
.map(({ item, content }) => `## [${item.title}](${item.link})\n\n${content}`)
// Add HR separator between posts
.join('\n\n---\n\n');
// writeFileSync('output.md', body);
return sendDraft(subject, body).then((response) => {
if (response.status !== 201) {
return response.text().then((text) =>
Promise.reject({
status: response.status,
body: text,
}),
);
}
});
}
function getFeed(url) {
return parser.parseURL(url);
}
function sendDraft(subject, body) {
return fetch('https://api.buttondown.email/v1/drafts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Token ${buttondownApiKey}`,
},
body: JSON.stringify({ subject: subject, body: body }),
});
}
sendDrafts().catch((error) => {
console.error(error);
process.exit(1);
});