-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
231 lines (203 loc) · 9.34 KB
/
Copy pathindex.js
File metadata and controls
231 lines (203 loc) · 9.34 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
require('dotenv').config();
const GhostContentAPI = require('@tryghost/content-api');
const GhostAdminAPI = require('@tryghost/admin-api');
const puppeteer = require('puppeteer');
const ejs = require('ejs');
const Epub = require('epub-gen');
const fs = require('fs');
const path = require('path');
const { startOfMonth, endOfMonth, startOfQuarter, endOfQuarter, startOfYear, endOfYear, subMonths, format } = require('date-fns');
// Ghost API client configuration
// The Content API normally strips the `html` of member-only posts for public users.
// However, if we pass `formats=html` and don't rely purely on default behavior,
// or if we need to we can switch to @tryghost/admin-api.
// For the Content API, typically we fetch everything available to the provided key.
const api = new GhostContentAPI({
url: process.env.GHOST_API_URL || 'https://demo.ghost.io',
key: process.env.GHOST_CONTENT_API_KEY || '22444f78447824223cefc48062',
version: "v5.0"
});
let adminApi = null;
if (process.env.GHOST_ADMIN_API_KEY) {
adminApi = new GhostAdminAPI({
url: process.env.GHOST_API_URL,
key: process.env.GHOST_ADMIN_API_KEY,
version: "v5.0"
});
}
async function main() {
// Determine target month - default to previous month
let targetDate = subMonths(new Date(), 1);
let startDate = startOfMonth(targetDate);
let endDate = endOfMonth(targetDate);
let periodName = `Tháng ${format(startDate, 'MM/yyyy')}`;
let fileNamePrefix = `thang-${format(startDate, 'M')}-${format(startDate, 'yyyy')}`;
// Allow overriding from CLI args e.g. "node index.js 2026-02", "2026-Q1", "2026"
const cliArg = process.argv[2];
if (cliArg) {
if (/^\d{4}-\d{2}$/.test(cliArg)) {
// Tháng
targetDate = new Date(`${cliArg}-01T00:00:00Z`);
startDate = startOfMonth(targetDate);
endDate = endOfMonth(targetDate);
periodName = `Tháng ${format(startDate, 'MM/yyyy')}`;
fileNamePrefix = `thang-${format(startDate, 'M')}-${format(startDate, 'yyyy')}`;
} else if (/^\d{4}-Q[1-4]$/i.test(cliArg)) {
// Quý
const match = cliArg.match(/^(\d{4})-Q([1-4])$/i);
const year = parseInt(match[1]);
const quarter = parseInt(match[2]);
// Convert quarter to month (Q1 -> Jan, Q2 -> Apr, etc)
const monthIndex = (quarter - 1) * 3;
targetDate = new Date(Date.UTC(year, monthIndex, 1));
startDate = startOfQuarter(targetDate);
endDate = endOfQuarter(targetDate);
periodName = `Quý ${quarter}/${year}`;
fileNamePrefix = `quy-${quarter}-${year}`;
} else if (/^\d{4}$/.test(cliArg)) {
// Năm
targetDate = new Date(`${cliArg}-01-01T00:00:00Z`);
startDate = startOfYear(targetDate);
endDate = endOfYear(targetDate);
periodName = `Năm ${cliArg}`;
fileNamePrefix = `nam-${cliArg}`;
} else {
console.error("Please provide a valid date format:");
console.error(" - Month: YYYY-MM (e.g., 2026-02)");
console.error(" - Quarter: YYYY-QX (e.g., 2026-Q1)");
console.error(" - Year: YYYY (e.g., 2026)");
process.exit(1);
}
}
console.log(`Fetching posts for period: ${periodName}...`);
// Fetch posts
// Filter syntax for Ghost Content API: published_at:>='2026-02-01T00:00:00.000Z'+published_at:<='2026-02-28T23:59:59.999Z'
const filterStr = `published_at:>='${startDate.toISOString()}'+published_at:<='${endDate.toISOString()}'`;
let posts = [];
try {
if (adminApi) {
console.log("Using Admin API to fetch full content (including member-gated posts)...");
posts = await adminApi.posts.browse({
limit: 'all',
filter: filterStr,
formats: 'html',
include: 'authors,tags,email'
});
} else {
console.log("Using Content API. Note: Member-gated posts may have restricted HTML content.");
posts = await api.posts.browse({
limit: 'all',
filter: filterStr,
include: 'authors,tags',
formats: ['html']
});
}
console.log(`Found ${posts.length} posts for the specified period.`);
// --- TEST OVERRIDE ---
// If it's the demo API and there's no data for this month, fallback to grabbing 5 recent posts
// just to guarantee we generate a beautiful report preview.
if (posts.length === 0 && (!process.env.GHOST_API_URL || process.env.GHOST_API_URL.includes('demo.ghost.io'))) {
console.log("No posts found for this month on demo server. Fetching recent 3 posts for demonstration.");
posts = await api.posts.browse({ limit: 3, include: 'authors,tags' });
}
} catch (err) {
console.error("Error fetching posts from Ghost API:", err.message);
console.log("Please check your .env file inside c:\\Code\\ghost-paper\\ for valid GHOST_API_URL and GHOST_CONTENT_API_KEY");
}
// Determine the cover image based on the post with the highest opened_count
let bestCoverImage = null;
if (posts.length > 0) {
let bestPost = posts[0];
let maxOpens = -1;
for (const post of posts) {
const opens = post.email ? (post.email.opened_count || 0) : -1;
if (opens > maxOpens) {
maxOpens = opens;
bestPost = post;
}
}
bestCoverImage = bestPost.featureImage || bestPost.feature_image;
if (maxOpens > -1) {
console.log(`Selected cover from post: "${bestPost.title}" (${maxOpens} opens)`);
} else {
console.log(`Selected cover from latest post: "${bestPost.title}" (No email engagement data)`);
}
}
// Prepare template data
const templateData = {
periodName: periodName,
coverImage: bestCoverImage,
posts: posts.map(post => {
// Force eager loading for images and remove srcset so Puppeteer fetches the main src immediately
let processedHtml = post.html || '';
processedHtml = processedHtml.replace(/loading="lazy"/g, 'loading="eager"');
processedHtml = processedHtml.replace(/srcset="[^"]*"/g, '');
return {
title: post.title,
excerpt: post.excerpt,
html: processedHtml,
featureImage: post.featureImage || post.feature_image,
publishedAt: format(new Date(post.published_at), 'dd/MM/yyyy'),
author: post.primary_author ? post.primary_author.name : 'Unknown'
};
})
};
// Render HTML using EJS
const templatePath = path.join(__dirname, 'template.ejs');
if (!fs.existsSync(templatePath)) {
console.error("Template file not found:", templatePath);
process.exit(1);
}
console.log("Rendering HTML template...");
const htmlContent = await ejs.renderFile(templatePath, templateData);
// Save temporary HTML for debugging in browser
const outHtmlPath = path.join(__dirname, 'preview.html');
fs.writeFileSync(outHtmlPath, htmlContent);
console.log(`Saved HTML preview to ${outHtmlPath}`);
// Generate PDF using Puppeteer
console.log("Starting Puppeteer to generate high-quality PDF...");
const browser = await puppeteer.launch({
headless: "new"
});
const page = await browser.newPage();
// Load HTML directly into puppeteer
await page.setContent(htmlContent, { waitUntil: 'networkidle0' });
// Adjust layout for A3 Landscape (Double-spread standard A4)
const outPdfPath = path.join(__dirname, `tong-hop-bai-viet-${fileNamePrefix}.pdf`);
await page.pdf({
path: outPdfPath,
format: 'A3',
landscape: true,
printBackground: true,
margin: { top: '0', right: '0', bottom: '0', left: '0' } // Full bleed for aesthetic cover images
});
await browser.close();
// Generate EPUB
const outEpubPath = path.join(__dirname, `tong-hop-bai-viet-${fileNamePrefix}.epub`);
console.log("Starting EPUB Generation...");
const epubOptions = {
title: `Tổng hợp bài viết ${periodName}`,
author: posts.length > 0 && posts[0].primary_author ? posts[0].primary_author.name : "Ghost Paper",
publisher: "Ghost Paper",
cover: bestCoverImage || undefined,
content: templateData.posts.map(post => ({
title: post.title,
author: post.author,
// Include title at the top of the chapter data just in case the ereader requires it
data: `<h2>${post.title}</h2>${post.html}`
}))
};
try {
await new Epub(epubOptions, outEpubPath).promise;
console.log(`SUCCESS! Generated EPUB: ${outEpubPath}`);
} catch (epubErr) {
console.error("Error generating EPUB:", epubErr);
}
console.log(`\n======================================================`);
console.log(`SUCCESS! Generated PDF: ${outPdfPath}`);
console.log(`SUCCESS! Generated EPUB: ${outEpubPath}`);
console.log(`======================================================\n`);
}
main().catch(err => {
console.error("Unexpected error:", err);
});