-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfilters.js
101 lines (84 loc) · 2.52 KB
/
filters.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
const { URL } = require("url");
const defaults = {
mentionTypes: {
likes: ["like-of"],
reposts: ["repost-of"],
comments: ["mention-of", "in-reply-to"],
},
};
function stripOuterSlashes(str) {
let start = 0;
while (str[start++] === "/");
let end = str.length;
while (str[--end] === "/");
return str.slice(start - 1, end + 1);
}
const filters = ({
mentionTypes = defaults.mentionTypes,
pageAliases = {},
}) => {
const cleanedAliases = Object.keys(pageAliases).reduce((cleaned, key) => {
cleaned[stripOuterSlashes(key.toLowerCase())] =
typeof pageAliases[key] === "string"
? [stripOuterSlashes(pageAliases[key].toLowerCase())]
: pageAliases[key].map((alias) =>
stripOuterSlashes(alias.toLowerCase())
);
return cleaned;
}, {});
function filterWebmentions(webmentions, page) {
const pageUrl = new URL(page, "https://lukeb.co.uk");
const normalizedPagePath = stripOuterSlashes(
pageUrl.pathname.toLowerCase()
);
const flattenedMentionTypes = Object.values(mentionTypes).flat();
return webmentions
.filter((mention) => {
const target = new URL(mention["wm-target"]);
const normalisedTargetPath = stripOuterSlashes(
target.pathname.toLowerCase()
);
return (
normalizedPagePath === normalisedTargetPath ||
cleanedAliases[normalizedPagePath]?.includes(normalisedTargetPath)
);
})
.filter(
(entry) => !!entry.author && (!!entry.author.name || entry.author.url)
)
.filter((mention) =>
flattenedMentionTypes.includes(mention["wm-property"])
);
}
function count(webmentions, pageUrl) {
const page =
pageUrl ||
this.page?.url ||
this.ctx?.page?.url ||
this.context?.environments?.page?.url;
return filterWebmentions(webmentions, page).length;
}
function mentions(webmentions, pageUrl) {
const page =
pageUrl ||
this.page?.url ||
this.ctx?.page?.url ||
this.context?.environments?.page?.url;
const filteredWebmentions = filterWebmentions(webmentions, page);
const returnedWebmentions = {
total: filteredWebmentions.length,
};
Object.keys(mentionTypes).map((type) => {
returnedWebmentions[type] = filteredWebmentions.filter((mention) =>
mentionTypes[type].includes(mention["wm-property"])
);
});
return returnedWebmentions;
}
return {
count,
mentions,
};
};
filters.defaults = defaults;
module.exports = filters;