-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
show-similar-submissions.js
executable file
·112 lines (92 loc) · 2.63 KB
/
show-similar-submissions.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
import compareUrls from "compare-urls";
import { monthNames } from "../libs/utils";
function getSimilarSubmissions(storyLink, metadata) {
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve) => {
const API_URL =
"https://hn.algolia.com/api/v1/search_by_date?tags=story&restrictSearchableAttributes=url&query=";
const safeStoryLink = encodeURI(storyLink);
const results = [];
const rawResults = await fetch(API_URL + safeStoryLink)
.then((res) => res.json())
.then((obj) => obj.hits);
if (!rawResults) {
return resolve(results);
}
for (const result of rawResults) {
// eslint-disable-next-line eqeqeq
if (result.objectID == metadata.item.id) {
continue;
}
if (
!result.url ||
!compareUrls(result.url.split("://").pop(), storyLink)
) {
continue;
}
if (
!metadata.options.showDiscussionsWithNoComments &&
result.num_comments === 0
) {
continue;
}
const date = new Date(result.created_at);
const renderedDate = `${
monthNames[date.getMonth()]
} ${date.getDate()}, ${date.getFullYear()}`;
results.push({
link: `https://news.ycombinator.com/item?id=${result.objectID}`,
title: result.title,
date: renderedDate,
comments: result.num_comments,
points: result.points,
});
}
resolve(results);
});
}
async function init(metadata) {
if (metadata.item.type !== "story") {
return false;
}
const storyLink = document
.querySelector("span.titleline a")
.href.split("://")
.pop();
const results = await getSimilarSubmissions(storyLink, metadata);
if (results.length === 0) {
return false;
}
const discussionRow = document.createElement("tr");
discussionRow.innerHTML = `
<td class='__rhn__discussions-row'>
<p>Discussions on similar submissions:</p>
<ol></ol>
</td>
`;
const dicussionRowList = discussionRow.querySelector(":scope > td ol");
for (const result of results) {
dicussionRowList.innerHTML += `
<li><a href="${result.link}">${result.title}</a> (${result.date} — ${
result.points
} points, ${result.comments} comments)</li>
`;
}
const rowContainingFooter = document.querySelector("tr#pagespace").nextSibling
.nextSibling;
rowContainingFooter.parentElement.insertBefore(
discussionRow,
rowContainingFooter
);
return true;
}
const details = {
id: "show-similar-submissions",
pages: {
include: ["/item"],
exclude: [],
},
loginRequired: false,
init,
};
export default details;