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