-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkblog.js
334 lines (282 loc) · 7.47 KB
/
linkblog.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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
require("dotenv").config();
const sqlite = require("sqlite");
const sqlite3 = require("sqlite3");
const fetchModule = import("node-fetch");
const FeedParser = require("feedparser");
const {
createMessage,
notifyFollowers,
} = require("./activitystreams/outbox.js");
const {
DIST,
RSS_SIZE,
POSTS_DB,
ACTIVITYSTREAMS_DB,
LINKLIST_SOURCE_FEED,
loadIcu,
embedCallback,
getLinkId,
getBlogObject,
} = require("./common.js");
const { render } = require("./render.js");
const EmbedsLoader = require("./embeds-loader.js");
const RETRY_TIMEOUT = 1000 * 60 * 30; // 30 minutes
async function loadFreshFeed(db, asdb, stdout, _stderr) {
const feedparser = new FeedParser({ normalize: true });
const { default: fetch } = await fetchModule;
const res = await fetch(LINKLIST_SOURCE_FEED);
if (res.status !== 200) {
throw new Error("Bad status code");
} else {
res.body.pipe(feedparser);
}
const feed = await new Promise((resolve, reject) => {
let meta;
const items = [];
feedparser.on("error", function (error) {
reject(error);
});
feedparser.on("readable", function () {
const stream = this;
meta = stream.meta;
let item;
while ((item = stream.read())) {
// eslint-disable-line no-cond-assign
items.push(item);
}
});
feedparser.on("end", function () {
resolve({ meta, items });
});
});
let hasNewItems = false;
const blog = await getBlogObject();
for (const item of feed.items) {
const exists = await db.get(
`SELECT id FROM linklist WHERE source_id = $1 LIMIT 1`,
{ 1: item.guid }
);
if (!exists) {
hasNewItems = true;
stdout.write(`new link item: ${item.link}\n`);
const id = getLinkId();
const created = new Date();
await db.run(
`
INSERT INTO linklist
(id, source_id, original_url, created)
VALUES ($1, $2, $3, $4)
`,
{
1: id,
2: item.guid,
3: item.link,
4: created.toISOString().replace(/\.\d{3}Z$/, "Z"),
}
);
const object = generateLinkblogActivityStreamNote(
id,
item.link,
created,
blog
);
const messageId = await createMessage(asdb, {
type: "Create",
from: blog.linkblog.activitystream.id,
object,
});
await notifyFollowers(asdb, messageId, blog.linkblog.activitystream.id);
}
}
return hasNewItems;
}
function generateLinkblogActivityStreamNote(id, link, created, blog) {
const content = `<p><a href="${link}" target="_blank" rel="nofollow noopener noreferrer"><span class="invisible">${link.replace(
/^(https?:\/\/).+$/,
"$1"
)}</span><span>${link.replace(/^https?:\/\//, "")}</span></a></p>`;
const asId = new URL(`actor/linkblog/notes/${id}`, blog.url);
return {
id: asId,
type: "Note",
published: created,
attributedTo: new URL(`actor/linkblog`, blog.url),
to: ["https://www.w3.org/ns/activitystreams#Public"],
cc: [
// "https://mastodon.devua.club/users/zemlanin/followers"
],
url: blog.linkblog.url + "#" + id,
content: content,
contentMap: {
[blog.lang]: content,
},
updated: null,
attachement: [],
};
}
async function prepareLink(link, embedsLoader, options) {
const created = new Date(parseInt(link.created));
return {
...link,
url: link.original_url,
created: created.toISOString().replace(/\.\d{3}Z$/, "Z"),
createdDate: created.toISOString().split("T")[0],
createdUTC: created.toUTCString(),
html: await embedsLoader.load(
`<p>${embedCallback(link.original_url)}</p>`,
{
externalFrames: options && options.externalFrames,
maxWidth: options && options.maxWidth,
}
),
title: (await embedsLoader.query([link.original_url]))[0].title,
};
}
async function generateLinkblogPage(db, blog) {
const rawLinks = await db.all(
`
SELECT id, strftime('%s000', created) created, original_url
FROM linklist
WHERE private = 0
ORDER BY created DESC
LIMIT ?1;
`,
{
1: RSS_SIZE,
}
);
const embedsLoader = new EmbedsLoader(db);
const links = [];
for (const l of rawLinks) {
links.push(await prepareLink(l, embedsLoader));
}
return await render("linkblog.mustache", {
blog,
linkblog: true,
url: "./linkblog.html",
links,
});
}
async function generateLinkblogRSSPage(db, blog) {
const rawLinks = await db.all(`
SELECT id, strftime('%s000', created) created, original_url
FROM linklist
WHERE private = 0
ORDER BY created DESC
LIMIT 20;
`);
const embedsLoader = new EmbedsLoader(db);
const links = [];
for (const l of rawLinks) {
const entry = await prepareLink(l, embedsLoader, {
externalFrames: true,
maxWidth: 720,
});
entry.html += `<p><a href="${blog.linkblog.url}">via</a></p>`;
links.push(entry);
}
return await render("rss-linkblog.mustache", {
blog,
links,
pubDate: new Date().toUTCString(),
});
}
async function generateLinkblogSection(db, blog) {
const rawLinks = await db.all(`
SELECT id, strftime('%s000', created) created, original_url
FROM linklist
WHERE private = 0
ORDER BY created DESC
LIMIT 20;
`);
const embedsLoader = new EmbedsLoader(db);
const embeds = await embedsLoader.query(rawLinks.map((l) => l.original_url));
const blogHostname = new URL(blog.url).hostname;
return embeds
.map((card, i) => ({ ...card, id: rawLinks[i].id }))
.filter((card) => card.title && card.img)
.filter((card) => new URL(card.url).hostname !== blogHostname)
.map((card) => ({
id: card.id,
url: card.url,
title: card.title,
site_name:
card.site_name && !card.title.endsWith(card.site_name)
? card.site_name
: "",
img: card.img,
}))
.slice(0, 4);
}
async function checkAndUpdate(stdout, stderr) {
if (!LINKLIST_SOURCE_FEED) {
return;
}
const db = await sqlite
.open({ filename: POSTS_DB, driver: sqlite3.Database })
.then(loadIcu);
const asdb = await sqlite.open({
filename: ACTIVITYSTREAMS_DB,
driver: sqlite3.Database,
});
const hasNewItems = await loadFreshFeed(
db,
asdb,
stdout || process.stdout,
stderr || process.stderr
);
if (hasNewItems) {
await require("./generate.js").generate(
db,
asdb,
DIST,
stdout || process.stdout,
stderr || process.stderr,
{ only: new Set(["linkblog"]) }
);
await notifyWebSub();
}
}
async function notifyWebSub() {
const { default: fetch } = await fetchModule;
const { linkblog } = await getBlogObject();
const { feed } = linkblog;
if (!feed.websub) {
return;
}
try {
await fetch(feed.websub, {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
"hub.mode": "publish",
"hub.url": feed.url,
}).toString(),
});
} catch (e) {
console.error(e);
}
}
function watch() {
if (!LINKLIST_SOURCE_FEED) {
return;
}
checkAndUpdate()
.then(() => setTimeout(watch, RETRY_TIMEOUT))
.catch(() => setTimeout(watch, RETRY_TIMEOUT * (Math.random() + 1)));
}
module.exports = {
watch,
checkAndUpdate,
generateLinkblogPage,
generateLinkblogRSSPage,
generateLinkblogSection,
generateLinkblogActivityStreamNote,
getLinkId,
notifyWebSub,
};
if (require.main === module) {
checkAndUpdate();
}