/
supporters.js
executable file
·291 lines (263 loc) · 8.36 KB
/
supporters.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
#!/usr/bin/env node
/**
* This script gathers metadata for supporters of Mocha from OpenCollective's API by
* aggregating order ("donation") information.
*
* It's intended to be used with 11ty, but can be run directly. Running directly
* enables debug output.
*
* - gathers logo/avatar images (they are always pngs)
* - gathers links
* - sorts by total contributions and tier
* - validates images
* - writes images to a temp dir
* @see https://docs.opencollective.com/help/contributing/development/api
*/
'use strict';
const {loadImage} = require('canvas');
const {writeFile, mkdir, rmdir} = require('fs').promises;
const {resolve} = require('path');
const debug = require('debug')('mocha:docs:data:supporters');
const needle = require('needle');
const blocklist = new Set(require('./blocklist.json'));
/**
* In addition to the blocklist, any account slug matching this regex will not
* be displayed on the website.
*/
const BLOCKED_STRINGS = /(?:vpn|[ck]a[sz]ino|seo|slots|gambl(?:e|ing)|crypto)/i;
/**
* Add a few Categories exposed by Open Collective to help moderation
*/
const BLOCKED_CATEGORIES = [
'adult',
'casino',
'credit',
'gambling',
'seo',
'writer'
];
/**
* The OC API endpoint
*/
const API_ENDPOINT = 'https://api.opencollective.com/graphql/v2';
const SPONSOR_TIER = 'sponsor';
const BACKER_TIER = 'backer';
// if this percent of fetches completes, the build will pass
const PRODUCTION_SUCCESS_THRESHOLD = 0.8;
const SUPPORTER_IMAGE_PATH = resolve(__dirname, '../images/supporters');
const SUPPORTER_QUERY = `query account($limit: Int, $offset: Int, $slug: String) {
account(slug: $slug) {
orders(limit: $limit, offset: $offset) {
limit
offset
totalCount
nodes {
fromAccount {
id
name
slug
website
imgUrlMed: imageUrl(height:64)
imgUrlSmall: imageUrl(height:32)
type
categories
}
totalDonations {
value
}
createdAt
}
}
}
}`;
const GRAPHQL_PAGE_SIZE = 1000;
const invalidSupporters = [];
const nodeToSupporter = node => ({
id: node.fromAccount.id,
name: node.fromAccount.name,
slug: node.fromAccount.slug,
website: node.fromAccount.website,
imgUrlMed: node.fromAccount.imgUrlMed,
imgUrlSmall: node.fromAccount.imgUrlSmall,
firstDonation: node.createdAt,
totalDonations: node.totalDonations.value * 100,
type: node.fromAccount.type,
categories: node.fromAccount.categories
});
const fetchImage = process.env.MOCHA_DOCS_SKIP_IMAGE_DOWNLOAD
? async supporter => {
invalidSupporters.push(supporter);
}
: async supporter => {
try {
const {avatar: url} = supporter;
const {body: imageBuf, headers} = await needle('get', url, {
timeout: 2000
});
if (headers['content-type'].startsWith('text/html')) {
throw new TypeError(
'received html and expected a png; outage likely'
);
}
debug('fetched %s', url);
const canvasImage = await loadImage(imageBuf);
debug('ok %s', url);
supporter.dimensions = {
width: canvasImage.width,
height: canvasImage.height
};
// debug('dimensions %s %dw %dh', url, canvasImage.width, canvasImage.height);
const filePath = resolve(SUPPORTER_IMAGE_PATH, supporter.id + '.png');
await writeFile(filePath, imageBuf);
debug('wrote %s', filePath);
} catch (err) {
console.error(
`failed to load ${supporter.avatar}; will discard ${supporter.tier} "${supporter.name} (${supporter.slug}). reason:\n`,
err
);
invalidSupporters.push(supporter);
}
};
/**
* Retrieves donation data from OC
*
* Handles pagination
* @param {string} slug - Collective slug to get donation data from
* @returns {Promise<Object[]>} Array of raw donation data
*/
const getAllOrders = async (slug = 'mochajs') => {
let allOrders = [];
const variables = {limit: GRAPHQL_PAGE_SIZE, offset: 0, slug};
// Handling pagination if necessary (2 pages for ~1400 results in May 2019)
while (true) {
const result = await needle(
'post',
API_ENDPOINT,
{query: SUPPORTER_QUERY, variables},
{json: true}
);
const orders = result.body.data.account.orders.nodes;
allOrders = [...allOrders, ...orders];
variables.offset += GRAPHQL_PAGE_SIZE;
if (orders.length < GRAPHQL_PAGE_SIZE) {
debug('retrieved %d orders', allOrders.length);
return allOrders;
} else {
debug(
'loading page %d of orders...',
Math.floor(variables.offset / GRAPHQL_PAGE_SIZE)
);
}
}
};
const isAllowed = ({slug, categories}) =>
!blocklist.has(slug) &&
!BLOCKED_STRINGS.test(slug) &&
!categories.some(category => BLOCKED_CATEGORIES.includes(category));
const getSupporters = async () => {
const orders = await getAllOrders();
// Deduplicating supporters with multiple orders
const uniqueSupporters = new Map();
const supporters = orders
// turn raw query result into a better data structure
.map(nodeToSupporter)
// aggregate total $ donated by unique supporter (using slug)
.reduce((supporters, supporter) => {
if (uniqueSupporters.has(supporter.slug)) {
uniqueSupporters.get(supporter.slug).totalDonations +=
supporter.totalDonations;
return supporters;
}
uniqueSupporters.set(supporter.slug, supporter);
return [...supporters, supporter];
}, [])
// discard spammy supporters
.filter(isAllowed)
// sort by total $ donated, descending
.sort((a, b) => b.totalDonations - a.totalDonations)
// determine which url to use depending on tier
.reduce(
(supporters, supporter) => {
if (supporter.type === 'INDIVIDUAL') {
if (supporter.name !== 'anonymous') {
supporters[BACKER_TIER] = [
...supporters[BACKER_TIER],
{
...supporter,
avatar: encodeURI(supporter.imgUrlSmall),
tier: BACKER_TIER
}
];
}
} else {
supporters[SPONSOR_TIER] = [
...supporters[SPONSOR_TIER],
{
...supporter,
avatar: encodeURI(supporter.imgUrlMed),
tier: SPONSOR_TIER
}
];
}
return supporters;
},
{
[SPONSOR_TIER]: [],
[BACKER_TIER]: []
}
);
await rmdir(SUPPORTER_IMAGE_PATH, {recursive: true});
debug('blasted %s', SUPPORTER_IMAGE_PATH);
await mkdir(SUPPORTER_IMAGE_PATH, {recursive: true});
debug('created %s', SUPPORTER_IMAGE_PATH);
// Fetch images for sponsors and save their image dimensions
await Promise.all([
...supporters[SPONSOR_TIER].map(fetchImage),
...supporters[BACKER_TIER].map(fetchImage)
]);
debug('fetched images');
invalidSupporters.forEach(supporter => {
supporters[supporter.tier].splice(
supporters[supporter.tier].indexOf(supporter),
1
);
});
debug('tossed out invalid supporters');
const backerCount = supporters[BACKER_TIER].length;
const sponsorCount = supporters[SPONSOR_TIER].length;
const totalValidSupportersCount = backerCount + sponsorCount;
const successRate = totalValidSupportersCount / invalidSupporters.length;
debug(
'found %d valid backers and %d valid sponsors (%d total; %d invalid; %d blocked)',
backerCount,
sponsorCount,
totalValidSupportersCount,
invalidSupporters.length,
uniqueSupporters.size - totalValidSupportersCount
);
if (successRate < PRODUCTION_SUCCESS_THRESHOLD) {
if (process.env.NETLIFY && process.env.CONTEXT !== 'deploy-preview') {
throw new Error(
`Failed to meet success threshold ${PRODUCTION_SUCCESS_THRESHOLD *
100}% (was ${successRate *
100}%) for a production deployment; refusing to deploy`
);
} else {
console.warn(
`WARNING: Success rate of ${successRate *
100}% fails to meet production threshold of ${PRODUCTION_SUCCESS_THRESHOLD *
100}%; would fail a production deployment!`
);
}
}
debug('supporter image pull completed');
return supporters;
};
module.exports = getSupporters;
if (require.main === module) {
require('debug').enable('mocha:docs:data:supporters');
process.on('unhandledRejection', err => {
throw err;
});
getSupporters();
}