-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync-rss.ts
More file actions
407 lines (337 loc) · 11.9 KB
/
sync-rss.ts
File metadata and controls
407 lines (337 loc) · 11.9 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import Parser from 'rss-parser';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// ============================================================================
// Type Definitions
// ============================================================================
interface BlogPost {
title: string;
link: string;
date: string;
}
/**
* Desktop index.json structure from desktop.dl.hagicode.com/index.json
*/
interface DesktopIndex {
updatedAt: string;
versions: Array<{
version: string;
files: string[];
assets: Array<{
name: string;
path: string;
size: number;
lastModified: string;
}>;
}>;
channels: {
[channelName: string]: {
latest: string;
versions: string[];
};
};
}
/**
* Server index.json structure from server.dl.hagicode.com/index.json
*/
interface ServerIndex {
updatedAt: string;
versions: Array<{
version: string;
files: string[];
assets: Array<{
name: string;
path: string;
size: number;
lastModified: string;
}>;
}>;
channels: {
[channelName: string]: {
latest: string;
versions: string[];
};
};
}
/**
* Represents a version extracted from a specific channel
*/
interface ChannelVersion {
channel: string;
version: string;
product: 'desktop' | 'server';
}
/**
* Configuration for generating version badges
*/
interface BadgeConfig {
label: string;
color: string;
}
// ============================================================================
// Constants
// ============================================================================
const RSS_URL = 'https://docs.hagicode.com/blog/rss.xml';
const README_PATH = path.join(__dirname, 'profile', 'README.md');
const MAX_POSTS = 10;
const DESKTOP_INDEX_URL = 'https://index.hagicode.com/desktop/index.json';
const SERVER_INDEX_URL = 'https://index.hagicode.com/server/index.json';
/**
* Badge configurations for different product-channel combinations
* Stable versions use blue, beta versions use orange
*/
const BADGE_CONFIGS: Record<string, BadgeConfig> = {
'desktop-stable': { label: 'Desktop Stable', color: 'blue' },
'desktop-beta': { label: 'Desktop Beta', color: 'orange' },
'server-stable': { label: 'Server Stable', color: 'blue' },
'server-beta': { label: 'Server Beta', color: 'orange' }
};
// ============================================================================
// RSS Fetching Functions
// ============================================================================
/**
* Fetches and parses the RSS feed from the blog
*/
async function fetchRSS(): Promise<BlogPost[]> {
console.log(`Fetching RSS from ${RSS_URL}...`);
const parser = new Parser();
try {
const feed = await parser.parseURL(RSS_URL);
console.log(`Successfully fetched ${feed.items.length} items from RSS`);
const posts: BlogPost[] = feed.items.slice(0, MAX_POSTS).map(item => ({
title: item.title ?? 'Untitled',
link: item.link ?? '',
date: item.pubDate ? new Date(item.pubDate).toLocaleDateString('zh-CN') : ''
}));
return posts;
} catch (error) {
console.error('Failed to fetch RSS:', error);
throw new Error(`RSS fetch failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
function generateBlogTable(posts: BlogPost[]): string {
const header = '| 日期 | 标题 |\n|------|------|';
const rows = posts.map(post => {
const date = post.date || 'N/A';
const title = `[${post.title}](${post.link})`;
return `| ${date} | ${title} |`;
});
return `${header}\n${rows.join('\n')}`;
}
function updateReadme(blogTable: string): void {
console.log('Reading existing README...');
if (!fs.existsSync(README_PATH)) {
throw new Error(`README not found at ${README_PATH}`);
}
let content = fs.readFileSync(README_PATH, 'utf-8');
const startMarker = '<!-- blog-posts-start -->';
const endMarker = '<!-- blog-posts-end -->';
const startIndex = content.indexOf(startMarker);
const endIndex = content.indexOf(endMarker);
if (startIndex === -1 || endIndex === -1) {
throw new Error('Placeholder markers not found in README');
}
const before = content.substring(0, startIndex + startMarker.length);
const after = content.substring(endIndex);
content = `${before}\n${blogTable}\n${after}`;
fs.writeFileSync(README_PATH, content, 'utf-8');
console.log('README updated successfully');
}
// ============================================================================
// Version Fetching Functions
// ============================================================================
/**
* Fetches all channel versions from Desktop index.json
* @returns Array of ChannelVersion objects for Desktop
*/
async function fetchDesktopVersions(): Promise<ChannelVersion[]> {
console.log(`Fetching Desktop index from ${DESKTOP_INDEX_URL}...`);
try {
const response = await fetch(DESKTOP_INDEX_URL);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const index: DesktopIndex = await response.json();
// Validate JSON structure
if (!index.channels) {
throw new Error('channels not found in Desktop index');
}
const versions: ChannelVersion[] = [];
// Extract all channel versions
for (const [channelName, channelData] of Object.entries(index.channels)) {
if (channelData.latest) {
versions.push({
channel: channelName,
version: channelData.latest,
product: 'desktop'
});
}
}
console.log(`Found ${versions.length} Desktop channel(s): ${versions.map(v => `${v.channel}:${v.version}`).join(', ')}`);
return versions;
} catch (error) {
console.error('Failed to fetch Desktop versions:', error);
throw new Error(`Desktop version fetch failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
/**
* Fetches all channel versions from Server index.json
* @returns Array of ChannelVersion objects for Server
*/
async function fetchServerVersions(): Promise<ChannelVersion[]> {
console.log(`Fetching Server index from ${SERVER_INDEX_URL}...`);
try {
const response = await fetch(SERVER_INDEX_URL);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const index: ServerIndex = await response.json();
// Validate JSON structure
if (!index.channels) {
throw new Error('channels not found in Server index');
}
const versions: ChannelVersion[] = [];
// Extract all channel versions
for (const [channelName, channelData] of Object.entries(index.channels)) {
if (channelData.latest) {
versions.push({
channel: channelName,
version: channelData.latest,
product: 'server'
});
}
}
console.log(`Found ${versions.length} Server channel(s): ${versions.map(v => `${v.channel}:${v.version}`).join(', ')}`);
return versions;
} catch (error) {
console.error('Failed to fetch Server versions:', error);
throw new Error(`Server version fetch failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
// ============================================================================
// Badge Generation Functions
// ============================================================================
/**
* Generates Markdown badge URLs for channel versions
* @param versions Array of channel versions
* @returns Array of badge Markdown strings
*/
function generateChannelBadges(versions: ChannelVersion[]): string[] {
const badges: string[] = [];
for (const versionData of versions) {
const configKey = `${versionData.product}-${versionData.channel}`;
const config = BADGE_CONFIGS[configKey];
if (!config) {
console.warn(`No badge config found for ${configKey}, skipping`);
continue;
}
// Spaces in label should be URL-encoded
const escapedLabel = config.label.replace(/ /g, '%20');
// Version should be URL-encoded (hyphens don't need escaping in URL, but spaces do)
const encodedVersion = encodeURIComponent(versionData.version);
const badgeUrl = ``;
badges.push(badgeUrl);
}
return badges;
}
/**
* Updates version badges in README.md
* @param badges Array of badge Markdown strings to update
*/
function updateChannelBadges(badges: string[]): void {
console.log('Reading existing README...');
if (!fs.existsSync(README_PATH)) {
throw new Error(`README not found at ${README_PATH}`);
}
let content = fs.readFileSync(README_PATH, 'utf-8');
let updatedCount = 0;
// Update each badge separately using regex with channel label matching
for (const badge of badges) {
// Extract label and color from badge for pattern matching
const badgeMatch = badge.match(/!\[([^\]]+)\]\(https:\/\/img\.shields\.io\/badge\/([^\)]+)\)/);
if (!badgeMatch) {
console.warn(`Could not parse badge: ${badge}`);
continue;
}
const label = badgeMatch[1];
const badgeUrlPattern = badgeMatch[2];
// Create regex that matches badges with this label regardless of version/color
// Handle both space and %20 encoding for spaces in labels
const escapedLabel = escapeRegex(label);
const encodedLabel = label.replace(/ /g, '%20').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(`!\\[${escapedLabel}\\]\\(https://img\\.shields\\.io/badge/(?:${escapedLabel}|${encodedLabel})-[^\)]+\\)`, 'g');
const oldContent = content;
content = content.replace(regex, badge);
if (oldContent !== content) {
updatedCount++;
}
}
if (updatedCount > 0) {
fs.writeFileSync(README_PATH, content, 'utf-8');
console.log(`Updated ${updatedCount} version badge(s)`);
} else {
console.warn('No version badges found to update');
}
}
/**
* Escapes special regex characters
*/
function escapeRegex(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// ============================================================================
// Main Function
// ============================================================================
async function main(): Promise<void> {
console.log('=== Starting Sync Job ===');
try {
// Blog RSS Sync
console.log('\n--- Blog RSS Sync ---');
const posts = await fetchRSS();
if (posts.length > 0) {
const blogTable = generateBlogTable(posts);
updateReadme(blogTable);
console.log('=== Blog RSS Sync Completed ===\n');
} else {
console.log('No blog posts found, skipping RSS update\n');
}
// Version Sync with error isolation
console.log('--- Version Sync ---');
let hasVersionErrors = false;
// Sync Desktop versions
try {
const desktopVersions = await fetchDesktopVersions();
if (desktopVersions.length > 0) {
const desktopBadges = generateChannelBadges(desktopVersions);
updateChannelBadges(desktopBadges);
}
} catch (error) {
console.error('Desktop version sync failed:', error);
hasVersionErrors = true;
}
// Sync Server versions (independent of Desktop)
try {
const serverVersions = await fetchServerVersions();
if (serverVersions.length > 0) {
const serverBadges = generateChannelBadges(serverVersions);
updateChannelBadges(serverBadges);
}
} catch (error) {
console.error('Server version sync failed:', error);
hasVersionErrors = true;
}
if (hasVersionErrors) {
console.warn('=== Version Sync Completed with Errors ===\n');
} else {
console.log('=== Version Sync Completed ===\n');
}
console.log('=== All Sync Jobs Completed ===');
} catch (error) {
console.error('Fatal error during sync:', error);
process.exit(1);
}
}
main();