| 1 | import { Readability } from "@mozilla/readability"; |
| 2 | import { JSDOM } from "jsdom"; |
| 3 | import { NodeHtmlMarkdown } from "node-html-markdown"; |
| 4 | |
| 5 | import { BaseContextProvider } from "../"; |
| 6 | import { |
| 7 | ContextItem, |
| 8 | ContextProviderDescription, |
| 9 | ContextProviderExtras, |
| 10 | FetchFunction, |
| 11 | } from "../../index.js"; |
| 12 | import { fetchFavicon } from "../../util/fetchFavicon"; |
| 13 | |
| 14 | class URLContextProvider extends BaseContextProvider { |
| 15 | static description: ContextProviderDescription = { |
| 16 | title: "url", |
| 17 | displayTitle: "URL", |
| 18 | description: "Reference a webpage at a given URL", |
| 19 | type: "query", |
| 20 | }; |
| 21 | |
| 22 | async getContextItems( |
| 23 | query: string, |
| 24 | extras: ContextProviderExtras, |
| 25 | ): Promise<ContextItem[]> { |
| 26 | return await getUrlContextItems(query, extras.fetch); |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | export default URLContextProvider; |
| 31 | |
| 32 | export async function getUrlContextItems( |
| 33 | query: string, |
| 34 | fetchFn: FetchFunction, |
| 35 | ): Promise<ContextItem[]> { |
| 36 | try { |
| 37 | const url = new URL(query); |
| 38 | const icon = await fetchFavicon(url); |
| 39 | const resp = await fetchFn(url); |
| 40 | const html = await resp.text(); |
| 41 | |
| 42 | const dom = new JSDOM(html); |
| 43 | let reader = new Readability(dom.window.document); |
| 44 | let article = reader.parse(); |
| 45 | const content = article?.content || ""; |
| 46 | const markdown = NodeHtmlMarkdown.translate( |
| 47 | content, |
| 48 | {}, |
| 49 | undefined, |
| 50 | undefined, |
| 51 | ); |
| 52 | |
| 53 | const title = article?.title || url.pathname; |
| 54 | |
| 55 | return [ |
| 56 | { |
| 57 | icon, |
| 58 | description: url.toString(), |
| 59 | content: markdown, |
| 60 | name: title, |
| 61 | uri: { |
| 62 | type: "url", |
| 63 | value: url.toString(), |
| 64 | }, |
| 65 | }, |
| 66 | ]; |
| 67 | } catch (e) { |
| 68 | console.log(e); |
| 69 | return []; |
| 70 | } |
| 71 | } |