forked from hplush/slowreader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatom.ts
More file actions
220 lines (202 loc) · 6.09 KB
/
atom.ts
File metadata and controls
220 lines (202 loc) · 6.09 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
import {
createDownloadTask,
type DownloadTask,
type TextResponse
} from '../lib/download.ts'
import { type OriginPost, type PostMedia, stringifyMedia } from '../post.ts'
import { createPostsList, type PostsListLoader } from '../posts-list.ts'
import {
buildFullURL,
findAnchorHrefs,
findDocumentLinks,
findHeaderLinks,
findMediaInText,
isHTML,
type Loader,
toTime
} from './common.ts'
export function findMRSS(element: Element): PostMedia[] {
let result: PostMedia[] = []
let mrss = element.getElementsByTagNameNS(
'http://search.yahoo.com/mrss/',
'content'
)
for (let content of mrss) {
let type = content.getAttribute('type') ?? content.getAttribute('medium')
let url = content.getAttribute('url')
if (!url) {
let thumbnail = content.querySelector('thumbnail')
if (thumbnail) url = thumbnail.getAttribute('url')
}
if (url && type) {
result.push({ type, url })
}
}
return result
}
function removeNS(node: Element | undefined): string {
let html = ''
if (!node) return html
node.childNodes.forEach(i => {
let child = i as Element
if (child.nodeType === 3 /* Node.TEXT_NODE */) {
html += child.textContent
} else if (child.nodeType === 1 /* Node.ELEMENT_NODE */) {
let tagName = child.localName
let attributes = Array.from(child.attributes)
.map(attr => ` ${attr.localName}="${attr.value}"`)
.join('')
html += `<${tagName}${attributes}>${removeNS(child)}</${tagName}>`
}
})
return html
}
function extractHtml(node: Element | null): string | undefined {
if (!node) return undefined
if (node.getAttribute('type') === 'xhtml') {
return removeNS(node.children[0])
} else {
return node.textContent
}
}
function parsePostSources(text: TextResponse): Element[] {
let document = text.parseXml()
if (!document) return []
return [...document.querySelectorAll('entry')].filter(
entry => entry.querySelector('id')?.textContent
)
}
function parsePosts(text: TextResponse): OriginPost[] {
return parsePostSources(text).map(entry => {
let content = entry.querySelector('content')
let textMedia = findMediaInText(content)
let postMedia: PostMedia[] = []
let enclosures = entry.querySelectorAll('link[rel=enclosure]')
for (let enclosure of enclosures) {
let url = enclosure.getAttribute('href')
let type = enclosure.getAttribute('type')
if (url && type) {
postMedia.push({ type, url })
}
}
postMedia = postMedia.concat(findMRSS(entry))
return {
full: extractHtml(content),
intro: extractHtml(entry.querySelector('summary')),
media: stringifyMedia([...postMedia, ...textMedia]),
originId: entry.querySelector('id')!.textContent,
publishedAt: toTime(
entry.querySelector('published')?.textContent ??
entry.querySelector('updated')?.textContent
),
title: entry.querySelector('title')?.textContent ?? undefined,
url:
entry
.querySelector('link[rel=alternate], link:not([rel])')
?.getAttribute('href') ?? undefined
}
})
}
/**
* Returns next or previous pagination url from feed XML, if present.
* See "paged feeds" https://www.rfc-editor.org/rfc/rfc5005#section-3
*/
function getPaginationUrl(
xmlResponse: TextResponse,
rel: 'first' | 'last' | 'next' | 'previous'
): string | undefined {
let document = xmlResponse.parseXml()
if (!document) return undefined
let nextPageLink = [...document.querySelectorAll('link')].find(
link => link.getAttribute('rel') === rel
)
return nextPageLink ? buildFullURL(nextPageLink, xmlResponse.url) : undefined
}
type PostsCursor =
| [OriginPost[], PostsListLoader | undefined]
| [undefined, PostsListLoader]
/**
* If XML response is ready, returns a tuple of posts and possibly
* the loader of the next portion of posts, if XML contains a link to them.
* If XML response is not yet ready, returns the recursive loader of posts.
*/
function getPostsCursor(
task: DownloadTask,
feedUrl: string,
feedResponse: TextResponse | undefined
): PostsCursor {
if (!feedResponse) {
return [
undefined,
async () => {
let response = await task.text(feedUrl)
let [posts, loader] = getPostsCursor(task, feedUrl, response)
return [posts || [], loader]
}
]
}
let nextPageUrl = getPaginationUrl(feedResponse, 'next')
let posts = parsePosts(feedResponse)
if (nextPageUrl) {
return [
posts,
async () => {
let nextPageResponse = await task.text(nextPageUrl)
let [nextPosts, loader] = getPostsCursor(
task,
nextPageUrl,
nextPageResponse
)
return [nextPosts || [], loader]
}
]
} else {
return [posts, undefined]
}
}
export const atom: Loader = {
getMineLinksFromText(text) {
let type = 'application/atom+xml'
let headerLinks = findHeaderLinks(text, type)
if (!isHTML(text)) return headerLinks
let links = [
...headerLinks,
...findDocumentLinks(text, type),
...findAnchorHrefs(text, /feeds\.|feed\.|\.atom|\/atom/i, /feed|atom/i)
]
if (links.length > 0) {
return links
} else {
return [...findAnchorHrefs(text, /\.xml/i)]
}
},
getPosts(task, url, text) {
let [posts, nextLoader] = getPostsCursor(task, url, text)
if (!posts && nextLoader) {
return createPostsList(undefined, nextLoader)
} else {
return createPostsList(posts || [], nextLoader)
}
},
async getPostSource(feed, originId) {
let xml = await createDownloadTask().text(feed.url)
return parsePostSources(xml).find(i => {
return i.querySelector('id')?.textContent === originId
})?.outerHTML
},
getSuggestedLinksFromText(text) {
let { origin } = new URL(text.url)
return [new URL('/feed', origin).href, new URL('/atom', origin).href]
},
isMineText(text) {
let document = text.parseXml()
if (document?.firstElementChild?.nodeName === 'feed') {
return document.querySelector(':root > title')?.textContent ?? ''
} else {
return false
}
},
isMineUrl() {
return undefined
}
}