summaryrefslogtreecommitdiff
path: root/src/loaders/pleroma.ts
blob: a0b169f9e1a95eee0f5fdac4eaba99476c0c4d27 (plain)
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
import type { Loader } from "astro/loaders";
import { XMLParser } from "fast-xml-parser";
import TurndownService from "turndown";
import { marked } from "marked";

interface PleromaFeedConfig {
	instanceUrl: string;
	username: string;
	maxPosts?: number;
	feedType?: "rss" | "atom";
}

interface RssItem {
	guid: string;
	title: string;
	description: string;
	pubDate: string;
	link: string;
	category?: string | string[];
	"activity:object-type"?: string;
	"activity:verb"?: string;
	"thr:in-reply-to"?: {
		"@_ref": string;
	};
}

interface RssFeed {
	rss: {
		channel: {
			title: string;
			description: string;
			link: string;
			item?: RssItem | RssItem[];
		};
	};
}

interface AtomEntry {
	id: string;
	title: string;
	content: {
		"#text": string;
		"@_type": string;
	};
	published: string;
	updated: string;
	link: {
		"@_href": string;
		"@_rel": string;
		"@_type": string;
	}[];
	author: {
		name: string;
		uri: string;
	};
	category?: {
		"@_term": string;
	}[];
	"activity:object-type"?: string;
	"activity:verb"?: string;
	"thr:in-reply-to"?: {
		"@_ref": string;
	};
}

interface AtomFeed {
	feed: {
		title: string;
		id: string;
		updated: string;
		entry?: AtomEntry | AtomEntry[];
	};
}

function parseAtomFeed(xmlContent: string): AtomEntry[] {
	const parser = new XMLParser({
		ignoreAttributes: false,
		attributeNamePrefix: "@_",
		parseAttributeValue: true,
	});

	const result: AtomFeed = parser.parse(xmlContent);

	if (!result.feed?.entry) {
		return [];
	}

	// Handle both single entry and array of entries
	const entries = Array.isArray(result.feed.entry) ? result.feed.entry : [result.feed.entry];

	return entries;
}

function parseRssFeed(xmlContent: string): RssItem[] {
	const parser = new XMLParser({
		ignoreAttributes: false,
		attributeNamePrefix: "@_",
		parseAttributeValue: true,
	});

	try {
		const result: RssFeed = parser.parse(xmlContent);

		if (!result.rss?.channel?.item) {
			console.log("RSS structure:", JSON.stringify(result, null, 2));
			return [];
		}

		// Handle both single item and array of items
		const items = Array.isArray(result.rss.channel.item)
			? result.rss.channel.item
			: [result.rss.channel.item];

		return items;
	} catch (error) {
		console.error("Failed to parse RSS feed:", error);
		console.log("XML content length:", xmlContent.length);
		console.log("XML preview:", xmlContent.substring(0, 1000));
		return [];
	}
}

function isFilteredPostAtom(entry: AtomEntry): boolean {
	// Filter out boosts/reblogs
	if (entry["activity:verb"] === "http://activitystrea.ms/schema/1.0/share") {
		return true;
	}

	// Filter out replies
	if (entry["thr:in-reply-to"]) {
		return true;
	}

	// Filter out NSFW/sensitive content
	if (entry.category) {
		const categories = Array.isArray(entry.category) ? entry.category : [entry.category];
		const hasNsfwTag = categories.some(
			(cat) =>
				cat["@_term"]?.toLowerCase().includes("nsfw") ||
				cat["@_term"]?.toLowerCase().includes("sensitive"),
		);
		if (hasNsfwTag) {
			return true;
		}
	}

	return false;
}

function isFilteredPostRss(item: RssItem): boolean {
	// Filter out boosts/reblogs
	if (item["activity:verb"] === "http://activitystrea.ms/schema/1.0/share") {
		return true;
	}

	// Filter out replies
	if (item["thr:in-reply-to"]) {
		return true;
	}

	// Filter out NSFW/sensitive content
	if (item.category) {
		const categories = Array.isArray(item.category) ? item.category : [item.category];
		const hasNsfwTag = categories.some(
			(cat) => cat?.toLowerCase().includes("nsfw") || cat?.toLowerCase().includes("sensitive"),
		);
		if (hasNsfwTag) {
			return true;
		}
	}

	return false;
}

function cleanContent(htmlContent: string): string {
	const turndownService = new TurndownService({
		headingStyle: "atx",
		codeBlockStyle: "fenced",
	});

	// Remove or replace common Pleroma/Mastodon elements
	const cleanedContent = htmlContent
		.replace(/<span class="[^"]*mention[^"]*"[^>]*>/gi, "") // Remove mention spans but keep content
		.replace(/<\/span>/gi, "")
		.replace(/<span class="[^"]*hashtag[^"]*"[^>]*>/gi, "") // Remove hashtag spans but keep content
		.replace(/<span class="[^"]*ellipsis[^"]*"[^>]*>.*?<\/span>/gi, "") // Remove ellipsis
		.replace(/<span class="[^"]*invisible[^"]*"[^>]*>.*?<\/span>/gi, ""); // Remove invisible text

	// Convert to markdown
	const markdown = turndownService.turndown(cleanedContent);

	// Clean up extra whitespace
	return markdown.trim().replace(/\n\s*\n\s*\n/g, "\n\n");
}

function markdownToHtml(markdown: string): string {
	// Configure marked options for safe rendering
	marked.setOptions({
		breaks: true, // Convert line breaks to <br>
		gfm: true, // GitHub flavored markdown
	});
	
	// Convert markdown to HTML
	const html = marked.parse(markdown);
	
	// Return as string (marked.parse can return string or Promise<string>)
	return typeof html === 'string' ? html : '';
}

function extractTitle(content: string): string {
	// Extract first line or first sentence as title
	const firstLine = content.split("\n")[0];
	if (!firstLine) return "Micro post";

	const firstSentence = firstLine.split(/[.!?]/)[0];
	if (!firstSentence) return "Micro post";

	// Limit title length and clean it up
	const title = (firstSentence.length > 60 ? `${firstSentence.substring(0, 57)}...` : firstSentence)
		.replace(/[#*_`]/g, "") // Remove markdown formatting
		.trim();

	return title || "Micro post";
}

export function pleromaLoader(config: PleromaFeedConfig): Loader {
	return {
		name: "pleroma-loader",
		load: async ({ store, logger }) => {
			try {
				const { instanceUrl, username, maxPosts = 20 } = config;
				// Use RSS URL that redirects to Atom - this bypasses some access restrictions
				const feedUrl = `${instanceUrl}/users/${username}.rss`;

				logger.info(`Fetching Pleroma feed from: ${feedUrl}`);

				// Add retry logic for network issues
				let response: Response | undefined;
				let lastError: unknown;

				for (let attempt = 1; attempt <= 3; attempt++) {
					try {
						logger.info(`Attempt ${attempt} to fetch feed...`);

						// Create timeout controller
						const controller = new AbortController();
						const timeoutId = setTimeout(() => controller.abort(), 10000);

						response = await fetch(feedUrl, {
							headers: {
								"User-Agent": "Astro Blog (pleroma-loader)",
							},
							redirect: "follow", // Follow redirects
							signal: controller.signal,
						});

						clearTimeout(timeoutId);

						if (response.ok) {
							break; // Success, exit retry loop
						}
							throw new Error(`HTTP ${response.status}: ${response.statusText}`);
					} catch (error) {
						lastError = error;
						logger.warn(`Attempt ${attempt} failed: ${error}`);

						if (attempt < 3) {
							logger.info("Retrying in 2 seconds...");
							await new Promise((resolve) => setTimeout(resolve, 2000));
						}
					}
				}

				if (!response || !response.ok) {
					logger.warn(`Failed to fetch Pleroma feed after 3 attempts. Last error: ${lastError}`);
					logger.info("Continuing without Pleroma posts...");
					store.clear();
					return;
				}

				const xmlContent = await response.text();
				logger.info(`Received XML content length: ${xmlContent.length}`);

				// Auto-detect if it's Atom or RSS based on content
				const isAtomFeed =
					xmlContent.includes("<feed") ||
					xmlContent.includes('xmlns="http://www.w3.org/2005/Atom"');
				logger.info(`Detected feed type: ${isAtomFeed ? "Atom" : "RSS"}`);

				let validEntries: AtomEntry[] = [];

				if (isAtomFeed) {
					// Process as Atom feed
					const entries = parseAtomFeed(xmlContent);
					logger.info(`Parsed ${entries.length} entries from Atom feed`);

					validEntries = entries.filter((entry) => !isFilteredPostAtom(entry)).slice(0, maxPosts);

					logger.info(`After filtering: ${validEntries.length} valid posts`);

					// Clear existing entries
					store.clear();

					// Process each Atom entry
					for (const entry of validEntries) {
						try {
							const content = entry.content?.["#text"] || "";
							const cleanedContent = cleanContent(content);
							const title = extractTitle(cleanedContent);

							// Extract post ID from the entry ID
							const postId = entry.id.split("/").pop() || entry.id;

							// Extract source URL from the entry
							const sourceUrl = entry.link?.find(link => link["@_rel"] === "alternate")?.["@_href"] || entry.id;

							// Create note entry
							store.set({
								id: `pleroma-${postId}`,
								data: {
									title,
									description:
										cleanedContent.substring(0, 160) + (cleanedContent.length > 160 ? "..." : ""),
									publishDate: new Date(entry.published),
									sourceUrl,
								},
								body: cleanedContent,
								rendered: {
									html: markdownToHtml(cleanedContent),
								},
							});

							logger.info(`Processed post: ${title.substring(0, 50)}...`);
						} catch (error) {
							logger.warn(`Failed to process entry ${entry.id}: ${error}`);
						}
					}
				} else {
					// Process as RSS feed
					const items = parseRssFeed(xmlContent);
					logger.info(`Parsed ${items.length} items from RSS feed`);

					const validRssItems = items.filter((item) => !isFilteredPostRss(item)).slice(0, maxPosts);

					logger.info(`After filtering: ${validRssItems.length} valid posts`);

					// Clear existing entries
					store.clear();

					// Process each RSS item
					for (const item of validRssItems) {
						try {
							const content = item.description || "";
							const cleanedContent = cleanContent(content);
							const title = extractTitle(cleanedContent);

							// Extract post ID from the GUID or link
							const postId =
								item.guid?.split("/").pop() ||
								(typeof item.link === "string" ? item.link.split("/").pop() : null) ||
								Math.random().toString(36);

							// Use the link as source URL
							const sourceUrl = typeof item.link === "string" ? item.link : item.guid || "";

							// Create note entry
							store.set({
								id: `pleroma-${postId}`,
								data: {
									title,
									description:
										cleanedContent.substring(0, 160) + (cleanedContent.length > 160 ? "..." : ""),
									publishDate: new Date(item.pubDate),
									sourceUrl,
								},
								body: cleanedContent,
								rendered: {
									html: markdownToHtml(cleanedContent),
								},
							});

							logger.info(`Processed post: ${title.substring(0, 50)}...`);
						} catch (error) {
							logger.warn(`Failed to process RSS item ${item.guid}: ${error}`);
						}
					}
				}

				logger.info(`Successfully loaded ${validEntries.length} Pleroma posts`);
			} catch (error) {
				logger.warn(`Pleroma loader failed: ${error}`);
				logger.info("Continuing build without Pleroma posts...");
				// Don't throw error to prevent build failure
				store.clear();
			}
		},
	};
}