-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
132 lines (106 loc) · 4.23 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
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
import showdown from 'showdown';
import moment from 'moment-timezone';
import * as core from '@actions/core';
import GhostAdminAPI from '@tryghost/admin-api';
const ghostUrl = core.getInput('url');
const period = core.getInput('period');
const debug = core.getBooleanInput('debug');
const tags = core.getInput('tags') || 'Digest';
const timezone = core.getInput('timezone') || 'America/Chicago';
const title = core.getInput('title') || `${period.charAt(0).toUpperCase() + period.slice(1)} Digest`;
function isPeriod(period) {
return period.toLowerCase() === 'daily' || period.toLowerCase() === 'weekly';
}
async function fetchPosts(api) {
try {
if (debug) core.debug('Fetching posts from Ghost API...');
let posts = await api.posts.browse();
if (debug) core.debug(`Fetched ${posts.length} posts from Ghost API.`);
return posts;
} catch (error) {
core.setFailed(`Failed to fetch posts from Ghost API: ${error.message}`);
}
}
function generateMarkdownDigest(posts, period) {
if (debug) core.debug(`Generating ${period} digest for ${posts.length} posts.`);
let markdown = '';
posts.forEach(post => {
if (debug) core.debug(`Processing post: ${post.title}`);
markdown += `## ${post.title}\n`;
markdown += `**Date:** ${moment(post.published_at).format('YYYY-MM-DD')}\n\n`;
let imageUrl = post.feature_image ? post.feature_image : null;
if (imageUrl) markdown += `![Image](${imageUrl})\n\n`;
markdown += `${post.excerpt}...\n\n`;
markdown += `[Read more](${post.url})\n\n`;
});
return markdown;
}
async function generateDigests(startDate, period, api) {
if (debug) core.debug(`Generating ${period} digest starting from ${startDate}.`);
// Determine the end date based on the period
let start, end;
if (period.toLowerCase() === 'weekly') {
start = moment.tz(startDate, 'YYYY-MM-DD', timezone).startOf('day');
start = moment(startDate).subtract(1, 'week').add(1, 'day');
end = moment(start).add(1, 'week');
} else {
start = moment.tz(startDate, 'YYYY-MM-DD', timezone).startOf('day');
end = moment(start).add(1, 'day');
}
end.set({ hour: 0, minute: 0, second: 0, millisecond: 0 });
if (debug) core.debug(`Date range: ${start.toISOString()} to ${end.toISOString()}`);
let posts = await fetchPosts(api);
let filteredPosts = posts.filter(post => {
let pubDate = moment(post.published_at).tz(timezone).startOf('day');
return pubDate.isSameOrAfter(start) && pubDate.isBefore(end);
});
if (debug) core.debug(`Filtered ${filteredPosts.length} posts for the ${period} digest.`);
let formattedDate;
if (period.toLowerCase() === 'weekly') {
formattedDate = `${start.format('M/D')} - ${moment(start).add(6, 'days').format('M/D')}`; // Weekly date range
} else {
formattedDate = `${start.format('M/D')}`; // Daily date
}
let markdownDigest = generateMarkdownDigest(filteredPosts, period);
let converter = new showdown.Converter();
let htmlDigest = converter.makeHtml(markdownDigest);
try {
if (debug) core.debug('Creating newsletter post...', period, formattedDate);
let response = await api.posts.add({
title: `${title} (${formattedDate})`,
html: htmlDigest,
tags: tags.split(',').map(tag => tag.trim()), // Convert comma-separated tags to array
status: 'draft'
}, {
source: 'html'
});
core.setOutput('result', `Newsletter post created: ${response.slug}`);
} catch (error) {
core.setFailed(`Failed to create newsletter post: ${error.message}`);
}
}
export async function run() {
// Initialize Ghost Admin API
const api = new GhostAdminAPI({
url: ghostUrl,
key: process.env.GHOST_API_KEY,
version: 'v5.0'
});
try {
let startDate;
if (isPeriod(period)) {
startDate = moment().tz(timezone).format('YYYY-MM-DD');
} else {
startDate = period; // Use provided date
}
if (!isPeriod(period) && !startDate) {
core.setFailed('Please provide a period (Daily or Weekly) or a start date.');
return;
}
if (debug) core.debug(`Starting digest generation with startDate: ${startDate} and period: ${period}`);
await generateDigests(startDate, period, api);
} catch (error) {
core.setFailed(`Action failed with error: ${error.message}`);
}
}
// await run();