@sockethub/platform-feeds 4.0.0-alpha.8 → 4.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.test.ts DELETED
@@ -1,139 +0,0 @@
1
- import { beforeEach, describe, expect, it } from "bun:test";
2
- import { RSSFeed} from "./index.test.data";
3
- import Feeds from "./index";
4
- import { ASCollection, PlatformSession } from "@sockethub/schemas";
5
- import debug from "debug";
6
-
7
- describe("platform-feeds", () => {
8
- let platform;
9
- beforeEach(() => {
10
- platform = new Feeds({
11
- debug: debug("sockethub:platform:feeds")
12
- } as unknown as PlatformSession);
13
-
14
- platform.makeRequest = (
15
- url: string,
16
- ): Promise<string> => {
17
- return Promise.resolve(RSSFeed);
18
- };
19
- });
20
-
21
- it("fetches expected feed", () => {
22
- platform.fetch({
23
- id: "an id",
24
- actor: {
25
- id: "some url"
26
- }
27
- }, (err, results: ASCollection) => {
28
- expect(results['totalItems']).toEqual(20);
29
- expect(results['items'][5]['object']).toEqual({
30
- type: "article",
31
- title: "Sockethub 3.x",
32
- id: "https://sockethub.org/news/2019-09-26-3x.html",
33
- brief: undefined,
34
- content: "<p>Sockethub 3.0 has been released and includes a lot of improvements focusing mainly on XMPP and IRC, additionally a ton of internal improvements. Ongoing releases tracked on the <a href=\"https://github.com/sockethub/sockethub/releases\">Github page</a>. </p>",
35
- contentType: "html",
36
- url: "https://sockethub.org/news/2019-09-26-3x.html",
37
- published: "2019-09-26T00:00:00.000Z",
38
- updated: undefined,
39
- datenum: 1569456000000,
40
- tags: undefined,
41
- media: undefined,
42
- source: undefined,
43
- })
44
- })
45
- })
46
-
47
- it("handles empty feed gracefully", () => {
48
- // Mock empty feed
49
- platform.makeRequest = (): Promise<string> => {
50
- return Promise.resolve('<rss><channel><title>Empty Feed</title></channel></rss>');
51
- };
52
-
53
- platform.fetch({
54
- id: "empty-feed-id",
55
- actor: {
56
- id: "http://example.com/empty.xml"
57
- }
58
- }, (err, results: ASCollection) => {
59
- expect(err).toBeNull();
60
- expect(results.type).toEqual("collection");
61
- expect(results.totalItems).toEqual(0);
62
- expect(results.items).toEqual([]);
63
- expect(results.summary).toEqual("Unknown Feed");
64
- })
65
- })
66
-
67
- it("handles feed with no actor name", () => {
68
- // Mock feed with no title/name but proper structure
69
- platform.makeRequest = (): Promise<string> => {
70
- return Promise.resolve(`
71
- <rss>
72
- <channel>
73
- <item>
74
- <title>Test Item</title>
75
- <description>Test content</description>
76
- <link>http://example.com/item</link>
77
- <pubDate>Thu, 01 Jan 2024 00:00:00 GMT</pubDate>
78
- </item>
79
- </channel>
80
- </rss>
81
- `);
82
- };
83
-
84
- platform.fetch({
85
- id: "no-name-feed-id",
86
- actor: {
87
- id: "http://example.com/noname.xml"
88
- }
89
- }, (err, results: ASCollection) => {
90
- expect(err).toBeNull();
91
- // When no title is provided, buildFeedChannel falls back to URL
92
- expect(results.summary).toEqual("http://example.com/noname.xml");
93
- })
94
- })
95
-
96
- it("handles network errors properly", () => {
97
- platform.makeRequest = (): Promise<string> => {
98
- return Promise.reject(new Error("Network timeout"));
99
- };
100
-
101
- platform.fetch({
102
- id: "error-test-id",
103
- actor: {
104
- id: "http://example.com/timeout.xml"
105
- }
106
- }, (err, results: ASCollection) => {
107
- expect(err).toBeInstanceOf(Error);
108
- expect(err.message).toEqual("Network timeout");
109
- expect(results).toBeUndefined();
110
- })
111
- })
112
-
113
- it("validates collection structure matches ASCollection interface", () => {
114
- platform.fetch({
115
- id: "validation-test-id",
116
- actor: {
117
- id: "some url"
118
- }
119
- }, (err, results: ASCollection) => {
120
- expect(err).toBeNull();
121
-
122
- // Validate required ASCollection properties
123
- expect(results).toHaveProperty("context");
124
- expect(results).toHaveProperty("type", "collection");
125
- expect(results).toHaveProperty("summary");
126
- expect(results).toHaveProperty("totalItems");
127
- expect(results).toHaveProperty("items");
128
-
129
- // Validate types
130
- expect(typeof results.context).toBe("string");
131
- expect(typeof results.summary).toBe("string");
132
- expect(typeof results.totalItems).toBe("number");
133
- expect(Array.isArray(results.items)).toBe(true);
134
-
135
- // Validate collection consistency
136
- expect(results.items.length).toEqual(results.totalItems);
137
- })
138
- })
139
- })
package/src/index.ts DELETED
@@ -1,281 +0,0 @@
1
- /**
2
- * This is a platform for Sockethub implementing Atom/RSS fetching functionality.
3
- *
4
- * Developed by Nick Jennings (https://github.com/silverbucket)
5
- *
6
- * Sockethub is licensed under the LGPLv3.
7
- * See the LICENSE file for details.
8
- *
9
- * The latest version of this module can be found here:
10
- * git://github.com/sockethub/sockethub.git
11
- *
12
- * For more information about Sockethub visit http://sockethub.org/.
13
- *
14
- * This program is distributed in the hope that it will be useful,
15
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
17
- */
18
-
19
- import htmlTags from "html-tags";
20
- import getPodcastFromFeed, { type Episode, type Meta } from "podparse";
21
-
22
- import type {
23
- ActivityStream,
24
- Logger,
25
- PlatformCallback,
26
- PlatformConfig,
27
- PlatformInterface,
28
- PlatformSchemaStruct,
29
- PlatformSession,
30
- } from "@sockethub/schemas";
31
-
32
- import PlatformSchema from "./schema.js";
33
- import {
34
- ASFeedType,
35
- ASObjectType,
36
- type PlatformFeedsActivityActor,
37
- type PlatformFeedsActivityObject,
38
- type PlatformFeedsActivityStream,
39
- } from "./types.js";
40
-
41
- const MAX_NOTE_LENGTH = 256;
42
-
43
- const basic = /\s?<!doctype html>|(<html\b[^>]*>|<body\b[^>]*>|<x-[^>]+>)+/i;
44
- const full = new RegExp(
45
- htmlTags.map((tag) => `<${tag}\\b[^>]*>`).join("|"),
46
- "i",
47
- );
48
-
49
- function isHtml(s: string): boolean {
50
- // limit it to a reasonable length to improve performance.
51
- const limitedString = s.trim().slice(0, 1000);
52
- return basic.test(limitedString) || full.test(s);
53
- }
54
-
55
- /**
56
- * Class: Feeds
57
- *
58
- * Handles all actions related to fetching feeds.
59
- *
60
- * Current supported feed types:
61
- *
62
- * - RSS (1 & 2)
63
- *
64
- * - Atom
65
- *
66
- * Uses the `podparse` module as a base tool fetching feeds.
67
- *
68
- * https://github.com/Tombarr/podcast-feed-parser
69
- *
70
- */
71
- export default class Feeds implements PlatformInterface {
72
- id: string;
73
- debug: Logger;
74
- config: PlatformConfig = {
75
- persist: false,
76
- connectTimeoutMs: 5000,
77
- };
78
-
79
- /**
80
- * @constructor
81
- * @param session - a unique session object for this platform instance
82
- */
83
- constructor(session: PlatformSession) {
84
- this.debug = session.debug;
85
- }
86
-
87
- get schema(): PlatformSchemaStruct {
88
- return PlatformSchema;
89
- }
90
-
91
- /**
92
- * Fetch feeds from specified source. Upon completion, it will send back a
93
- * response to the original request with a complete ActivityStreams Collection
94
- * containing all feed items and metadata.
95
- *
96
- * @param job - Activity streams object containing job data with actor.id as feed URL
97
- * @param done - Callback function that receives (error, ASCollection)
98
- *
99
- * @example
100
- * Request:
101
- * {
102
- * context: "feeds",
103
- * type: "fetch",
104
- * actor: {
105
- * id: 'http://blog.example.com/rss',
106
- * type: "feed"
107
- * }
108
- * }
109
- *
110
- *
111
- * // Without any parameters specified, the platform will return most
112
- * // recent 10 articles fetched from the feed.
113
- *
114
- * // Example of the resulting JSON AS Object:
115
- *
116
- * {
117
- * context: 'feeds',
118
- * type: 'collection',
119
- * summary: 'Best Feed Inc.'
120
- * totalItems: 10,
121
- * items: [
122
- * {
123
- * context: 'feeds',
124
- * type: 'post',
125
- * actor: {
126
- * type: 'feed',
127
- * name: 'Best Feed Inc.',
128
- * id: 'http://blog.example.com/rss',
129
- * description: 'Where the best feed comes to be the best',
130
- * image: {
131
- * width: '144',
132
- * height: '144',
133
- * url: 'http://blog.example.com/images/bestfeed.jpg',
134
- * }
135
- * favicon: 'http://blog.example.com/favicon.ico',
136
- * link: 'http://blog.example.com',
137
- * categories: ['best', 'feed', 'aminals'],
138
- * language: 'en',
139
- * author: 'John Doe'
140
- * },
141
- * object: {
142
- * id: "http://blog.example.com/articles/about-stuff"
143
- * type: 'article',
144
- * title: 'About stuff...',
145
- * url: "http://blog.example.com/articles/about-stuff"
146
- * date: "2013-05-28T12:00:00.000Z",
147
- * datenum: 1369742400000,
148
- * brief: "Brief synopsis of stuff...",
149
- * content: "Once upon a time...",
150
- * contentType: "text",
151
- * media: [
152
- * {
153
- * length: '13908973',
154
- * type: 'audio/mpeg',
155
- * url: 'http://blog.example.com/media/thing.mpg'
156
- * }
157
- * ]
158
- * tags: ['foo', 'bar']
159
- * }
160
- * },
161
- * ...
162
- * ]
163
- * }
164
- *
165
- */
166
- fetch(job: ActivityStream, done: PlatformCallback) {
167
- // ready to execute job
168
- this.fetchFeed(job.actor.id, job.id)
169
- .then((results) => {
170
- return done(null, {
171
- id: job.id || null,
172
- context: "feeds",
173
- type: "collection",
174
- summary:
175
- results.length > 0 && results[0]?.actor?.name
176
- ? results[0].actor.name
177
- : "Unknown Feed",
178
- totalItems: results.length,
179
- items: results,
180
- });
181
- })
182
- .catch(done);
183
- }
184
-
185
- /**
186
- * Cleanup method called when platform instance is being shut down.
187
- * Currently, no cleanup required for feeds platform.
188
- *
189
- * @param done - Callback function to signal completion
190
- */
191
- cleanup(done: PlatformCallback) {
192
- done();
193
- }
194
-
195
- private async makeRequest(url: string): Promise<string> {
196
- const opts = {
197
- signal: undefined,
198
- };
199
- if (this.config.connectTimeoutMs) {
200
- opts.signal = AbortSignal.timeout(this.config.connectTimeoutMs);
201
- }
202
- const res = await fetch(url, opts);
203
- return await res.text();
204
- }
205
-
206
- // fetches the articles from a feed, adding them to an array
207
- // for processing
208
- private async fetchFeed(
209
- url: string,
210
- id: string,
211
- ): Promise<Array<PlatformFeedsActivityStream>> {
212
- this.debug(`fetching ${url}`);
213
- const res = await this.makeRequest(url);
214
- const feed = getPodcastFromFeed(res);
215
- const actor = buildFeedChannel(url, feed.meta);
216
- const articles = [];
217
-
218
- for (const item of feed.episodes) {
219
- const article = buildFeedStruct(actor);
220
- article.id = id;
221
- article.object = buildFeedItem(item as FeedItem);
222
- articles.push(article);
223
- }
224
- this.debug(`fetched ${articles.length} articles`);
225
- return articles;
226
- }
227
- }
228
-
229
- interface FeedItem extends Episode {
230
- meta: Meta;
231
- date: string;
232
- categories: Array<string>;
233
- media: Array<unknown>;
234
- source: string;
235
- }
236
-
237
- function buildFeedItem(item: FeedItem): PlatformFeedsActivityObject {
238
- const dateNum = Date.parse(item.pubDate.toString()) || 0;
239
- return {
240
- type:
241
- item.description.length > MAX_NOTE_LENGTH
242
- ? ASObjectType.ARTICLE
243
- : ASObjectType.NOTE,
244
- title: item.title,
245
- id: item.link || `${item.meta.link}#${dateNum}`,
246
- brief: item.description === item.summary ? undefined : item.summary,
247
- content: item.description,
248
- contentType: isHtml(item.description || "") ? "html" : "text",
249
- url: item.link || item.meta.link,
250
- published: item.pubDate,
251
- updated: item.pubDate === item.date ? undefined : item.date,
252
- datenum: dateNum,
253
- tags: item.categories,
254
- media: item.media,
255
- source: item.source,
256
- };
257
- }
258
-
259
- function buildFeedStruct(
260
- actor: PlatformFeedsActivityActor,
261
- ): PlatformFeedsActivityStream {
262
- return {
263
- context: ASFeedType.FEEDS,
264
- actor: actor,
265
- type: "post",
266
- };
267
- }
268
-
269
- function buildFeedChannel(url: string, meta: Meta): PlatformFeedsActivityActor {
270
- return {
271
- id: url,
272
- type: ASFeedType.FEED_CHANNEL,
273
- name: meta.title ? meta.title : meta.link ? meta.link : url,
274
- link: meta.link || url,
275
- description: meta.description ? meta.description : undefined,
276
- image: meta.image ? meta.image : undefined,
277
- categories: meta.category ? meta.category : [],
278
- language: meta.language ? meta.language : undefined,
279
- author: meta.author ? meta.author : undefined,
280
- };
281
- }
package/src/schema.ts DELETED
@@ -1,22 +0,0 @@
1
- import packageJSON from "../package.json" with { type: "json" };
2
-
3
- export default {
4
- name: "feeds",
5
- version: packageJSON.version,
6
- messages: {
7
- required: ["type"],
8
- properties: {
9
- type: {
10
- type: "string",
11
- enum: ["fetch"],
12
- },
13
- object: {
14
- type: "object",
15
- oneOf: [
16
- { $ref: "#/definitions/objectTypes/feed-parameters-date" },
17
- { $ref: "#/definitions/objectTypes/feed-parameters-url" },
18
- ],
19
- },
20
- },
21
- },
22
- };