-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebmentions.js
67 lines (54 loc) · 1.86 KB
/
webmentions.js
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
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname } from 'node:path'
import { get } from 'node:https'
const DIRECTORY = `content/webmentions`
const DOMAIN = 'imacrayon.com'
const FEED = 'https://webmention.io/api/mentions.jf2'
const TOKEN = process.env.WEBMENTIONS_TOKEN
fetchWebmentions().then(webmentions => {
webmentions.forEach(webmention => {
const filePath = webmention['wm-target'].replace(`https://${DOMAIN}/`, '').replace(/\/$/, '') || 'index'
const filename = `${DIRECTORY}/${filePath}.json`
if (!existsSync(filename)) {
mkdirSync(dirname(filename), { recursive: true })
writeFileSync(filename, JSON.stringify([webmention], null, 2))
return
}
const entries = JSON.parse(readFileSync(filename))
.filter(wm => wm['wm-id'] !== webmention['wm-id'])
.concat([webmention])
.sort(latestReceivedDate)
writeFileSync(filename, JSON.stringify(entries, null, 2))
})
})
function fetchWebmentions() {
const since = '2019-06-01T10:00:00-0700' // new Date()
// since.setDate(since.getDate() - 3)
const url = `${FEED}?domain=${DOMAIN}&token=${TOKEN}&since=${since}&per-page=100`
return new Promise((resolve, reject) => {
get(url, res => {
let body = ''
res.on('data', chunk => { body += chunk })
res.on('end', () => {
try {
resolve(JSON.parse(body))
} catch (error) {
reject(error)
}
})
}).on('error', error => {
reject(error)
})
}).then(response => {
if (!('children' in response)) {
throw new Error('Invalid webmention.io response.')
}
return response.children
})
}
function latestReceivedDate(a, b) {
let dateA = a.published || a['wm-received'];
let dateB = b.published || b['wm-received'];
// Newest first
return (dateA < dateB) ? -1 : ((dateA > dateB) ? 1 : 0)
}