webmentions.js (1663B)
1 const fs = require("fs"); 2 const https = require("https"); 3 4 function fetchWebmentions() { 5 const token = process.env.WEBMENTIONS_TOKEN; 6 7 const since = new Date(); 8 since.setDate(since.getDate() - 3); 9 10 const url = 11 "https://webmention.io/api/mentions.jf2" + 12 "?domain=ybbond.id" + 13 `&token=${token}` + 14 `&since=${since.toISOString()}` + 15 "&per-page=999"; 16 17 return new Promise((resolve, reject) => { 18 https 19 .get(url, res => { 20 let body = ""; 21 22 res.on("data", chunk => { 23 body += chunk; 24 }); 25 26 res.on("end", () => { 27 try { 28 resolve(JSON.parse(body)); 29 } catch (error) { 30 reject(error); 31 } 32 }); 33 }) 34 .on("error", error => { 35 reject(error); 36 }); 37 }).then(response => { 38 if (!("children" in response)) { 39 throw new Error("Invalid webmention.io response."); 40 } 41 42 return response.children; 43 }); 44 } 45 46 fetchWebmentions().then(webmentions => { 47 webmentions.forEach(webmention => { 48 const slug = webmention["wm-target"] 49 .replace("https://ybbond.id/", "") 50 .replace(/\/$/, "") 51 .replace("/", "--"); 52 53 const filename = `${__dirname}/data/webmentions/${slug !== '' ? slug : 'home'}.json`; 54 55 if (!fs.existsSync(filename)) { 56 fs.writeFileSync(filename, JSON.stringify([webmention], null, 2)); 57 58 return; 59 } 60 61 const entries = JSON.parse(fs.readFileSync(filename)) 62 .filter(wm => wm["wm-id"] !== webmention["wm-id"]) 63 .concat([webmention]); 64 65 entries.sort((a, b) => a["wm-id"] - b["wm-id"]); 66 67 fs.writeFileSync(filename, JSON.stringify(entries, null, 2)); 68 }); 69 });