-
Notifications
You must be signed in to change notification settings - Fork 6
/
process.js
238 lines (212 loc) · 6.93 KB
/
process.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
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
const core = require('@actions/core');
const github = require('@actions/github');
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const { parseStringPromise } = require('xml2js');
const sanitize = require('sanitize-filename');
const TurndownService = require('turndown');
const imageTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'];
function parseFeedUrls(feedUrl, feedUrlsFile) {
let feedUrls = [];
if (feedUrl) {
try {
const parsedFeedUrl = JSON.parse(feedUrl);
if (Array.isArray(parsedFeedUrl)) {
feedUrls = parsedFeedUrl;
} else {
feedUrls.push(feedUrl);
}
} catch (error) {
feedUrls.push(feedUrl);
}
} else if (feedUrlsFile) {
if (!fs.existsSync(feedUrlsFile)) {
throw new Error(`Feed URLs file '${feedUrlsFile}' does not exist.`);
}
const feedUrlsContent = fs.readFileSync(feedUrlsFile, 'utf8');
try {
feedUrls = JSON.parse(feedUrlsContent);
} catch (error) {
// If JSON parsing fails, treat it as a plain text file
feedUrls = feedUrlsContent
.split('\n')
.map((line) => line.trim())
.filter((line) => line && !line.startsWith('#'));
}
} else {
throw new Error('Either feed_url or feed_urls_file must be provided.');
}
return feedUrls;
}
async function processFeeds(feedUrls, template, outputDir) {
for (const url of feedUrls) {
try {
// Fetch and parse the RSS feed
const feedData = await fetchAndParseFeed(url);
const feedType = detectFeedType(feedData);
let entries;
if (feedType === 'atom') {
// Atom Feed
entries = feedData.feed.entry;
} else if (feedType === 'rss') {
// RSS Feed
entries = feedData?.rss?.channel?.[0]?.item || [];
} else {
throw new Error('Unknown feed type.');
}
// Process the feed entries and generate Markdown files
entries.forEach((entry) => {
try {
const { output, date, title } = generateFeedMarkdown(template, entry);
const filePath = saveMarkdown(outputDir, date, title, output);
console.log(`Markdown file '${filePath}' created.`);
} catch (error) {
console.error(`Error processing feed entry for ${url}`);
console.error(error.message);
}
});
} catch (error) {
console.error(`Error processing feed at ${url}`);
console.error(error.message);
}
}
}
// Fetch the RSS feed
async function fetchAndParseFeed(feedUrl) {
const response = await axios.get(feedUrl);
const feedData = response.data;
if (typeof feedData === 'object') {
// Assume it's a JSON feed
return feedData;
} else {
// Assume it's an XML feed (RSS or Atom)
return parseStringPromise(feedData);
}
}
// Helper function to detect feed type based on entry fields
function detectFeedType(feedData) {
if (feedData?.feed?.entry) {
return 'atom';
} else if (feedData?.rss?.channel) {
return 'rss';
} else {
return 'unknown';
}
}
// Main function for generating Markdown
const generateFeedMarkdown = (template, entry) => {
const id =
entry['yt:videoId']?.[0] ||
entry.id?.[0] ||
entry.guid?.[0]?.['_'] ||
entry.guid?.[0] ||
'';
const date = entry.published?.[0] || entry.pubDate?.[0] || entry.updated?.[0] || '';
const link = entry.link?.[0]?.$?.href || entry.link?.[0] || '';
const titleRaw = typeof entry.title?.[0] === 'string' ? entry.title[0] : entry.title?.[0]?._ || '';
const title = titleRaw.replace(/[^\w\s-]/g, '') || '';
// Extract and clean up content for Markdown conversion and description
const content =
entry.description?.[0] ||
entry['media:group']?.[0]?.['media:description']?.[0] ||
entry.content?.[0]?._ || '';
const markdown = new TurndownService({
codeBlockStyle: 'fenced',
fenced: '```',
bulletListMarker: '-',
}).turndown(content);
const description =
entry.summary?.[0]?._ ||
entry.summary?.[0] ||
(content
? content.replace(/(<([^>]+)>)/gi, '').split(' ').splice(0, 50).join(' ')
: '');
// Extract author, handling possible formats across feed types
const author =
entry.author?.[0]?.name?.[0] ||
entry['dc:creator']?.[0] ||
entry.author?.[0] ||
entry.author ||
'Unknown Author';
// Extract media information (video, images, etc.) with checks for feed type specifics
const video = entry['media:group']?.[0]?.['media:content']?.[0]?.$?.url || '';
const image =
entry['media:group']?.[0]?.['media:thumbnail']?.[0]?.$.url ||
entry['media:thumbnail']?.[0]?.$.url ||
'';
const images =
(entry['enclosure'] || entry['media:content'])
?.filter((e) => imageTypes.includes(e.$['type']))
?.map((e) => e.$.url) || [];
// Handle categories with flexibility for both RSS and Atom structures
const categories = (entry.category || []).map((cat) =>
typeof cat === 'string' ? cat : cat?.$?.term || cat
);
// Specific to YouTube (if present)
const views =
entry['media:group']?.[0]?.['media:community']?.[0]?.['media:statistics']?.[0]?.$.views || '';
const rating =
entry['media:group']?.[0]?.['media:community']?.[0]?.['media:starRating']?.[0]?.$.average || '';
// Final output preparation
return generateOutput(template, {
id,
date,
link: link.trim(),
title,
content,
markdown,
description,
author,
video,
image,
images,
categories,
views,
rating,
});
};
// Helper function to generate the output
const generateOutput = (template, data) => {
const output = template
.replaceAll('[ID]', data.id || '')
.replaceAll('[DATE]', data.date || '')
.replaceAll('[LINK]', data.link || '')
.replaceAll(
'[TITLE]',
(data.title.trim() || '').replace(/\s+/g, ' '),
)
.replaceAll(
'[DESCRIPTION]',
typeof data.description === 'string'
? data.description.replace(/\s+/g, ' ')
: '',
)
.replaceAll('[CONTENT]', data.content|| '')
.replaceAll('[MARKDOWN]', data.markdown || '')
.replaceAll('[AUTHOR]', data.author || '')
.replaceAll('[VIDEO]', data.video || '')
.replaceAll('[IMAGE]', data.image || '')
.replaceAll('[IMAGES]', (data.images || []).join(','))
.replaceAll('[CATEGORIES]', (data.categories || []).join(','))
.replaceAll('[VIEWS]', data.views || '')
.replaceAll('[RATING]', data.rating || '');
return { output, date: data.date || '', title: data.title || '' };
};
function saveMarkdown(outputDir, date, title, markdown) {
const formattedDate = date ? new Date(date).toISOString().split('T')[0] : '';
const slug = sanitize(
`${formattedDate}-${title.toLowerCase().replace(/\s+/g, '-')}`,
).substring(0, 50);
const fileName = `${slug}.md`;
const filePath = path.join(outputDir, fileName);
fs.writeFileSync(filePath, markdown);
return filePath;
}
module.exports = {
parseFeedUrls,
processFeeds,
fetchAndParseFeed,
generateFeedMarkdown,
saveMarkdown,
};