This repository has been archived by the owner on Sep 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.js
73 lines (65 loc) · 2.1 KB
/
lib.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
68
69
70
71
72
73
const { getLinkPreview } = require('link-preview-js')
const fetch = require('cross-fetch');
const fs = require('fs');
async function loadHN(type = "news", page = 1) {
let options = {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
credentials: 'omit',
redirect: 'follow',
referrerPolicy: 'no-referrer',
}
let baseUrl = 'https://hackerfeed.dev/' + type + '?page=' + page
let res = await fetch(baseUrl)
let json = await res.json();
return json;
}
function getHN(savePath) {
let rawdata = fs.readFileSync(savePath);
let posts = JSON.parse(rawdata);
return posts;
}
async function saveHN(posts, savePath) {
let data = JSON.stringify(posts);
fs.writeFileSync(savePath, data);
}
async function updateHN(savePath) {
hnPosts_raw = await loadHN();
hnPosts_wData = await createOutput(hnPosts_raw);
await saveHN(hnPosts_wData, savePath)
}
async function createOutput(hnPosts) {
for (const post of hnPosts) {
if (post.url != undefined || post.url != '') {
try {
let data = await getLinkPreview(post.url, {
imagesPropertyType: "og",
headers: {
"user-agent": "Twitterbot",
},
timeout: 100000
})
if (post.image_url != undefined) {
continue
} else if (data.hasOwnProperty("images")) {
post.image_url = data.images[0]
} else {
post.image_url = "https://www.google.com/s2/favicons?domain="+post.domain
}
if (data.hasOwnProperty("description")) {
post.description = data.description
} else {
post.description = post.domain
}
} catch (error) {
console.log(`get Link outer catch ${error}`)
}
}
}
return hnPosts
}
module.exports = {
updateHN,
getHN
}