-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.js
350 lines (312 loc) · 10.4 KB
/
index.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import * as fs from 'node:fs'
import * as fsp from 'node:fs/promises'
import { glob } from 'glob'
import glog from 'fancy-log'
import sharp from 'sharp'
import { sharpBmp } from '@misskey-dev/sharp-read-bmp'
import { fileTypeFromFile } from 'file-type'
import { createHash } from 'node:crypto'
import { mkdirp } from 'mkdirp'
import Queue from 'promise-queue'
import AbortController from 'abort-controller'
import fetch from 'node-fetch';
import { getInstancesInfos } from './getInstancesInfos.js'
import instanceq from './instanceq.js'
import loadyaml from './loadyaml.js'
function getHash(data, a, b, c) {
const hashv = createHash(a)
hashv.update(Buffer.from(data), b)
return hashv.digest(c)
}
async function downloadTemp(name, url, tempDir, alwaysReturn) {
function clean() {
fs.unlink(`${tempDir}${name}`, () => null)
return false
}
const request = await (async () => {
mkdirp.sync(tempDir)
const controller = new AbortController()
const timeout = setTimeout(
() => { controller.abort() },
10000
)
return fetch(url, {
encoding: null,
signal: controller.signal,
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0"
}
}).then(res => {
clearTimeout(timeout)
return res
}, () => {
clearTimeout(timeout)
return false
})
})();
if (typeof request !== 'object') {
glog.error(url, 'request fail!')
return clean()
}
if (!request.ok) {
glog.error(url, 'request ng!')
return clean()
}
const data = await Promise.race([
request.arrayBuffer(),
new Promise(resolve => setTimeout(() => resolve(false), 10000))
])
if (!data) {
glog.error(url, 'arrayBuffer is null or timeout!')
return clean()
}
function safeWriteFile(name, ab, status) {
const controller = new AbortController()
const timeout = setTimeout(
() => { controller.abort() },
30000
)
return fsp.writeFile(`${tempDir}${name}`, Buffer.from(ab), { signal: controller.signal })
.then(() => {
clearTimeout(timeout)
return { name, status }
})
.catch(e => {
glog.error('writeFile error', name, e)
return false
})
}
const local = await fsp.readFile(`${tempDir}${name}`).catch(() => null)
if (!local) {
return safeWriteFile(name, data, "created")
}
if (getHash(data, "sha384", "binary", "base64") !== getHash(local, "sha384", "binary", "base64")) {
await fsp.unlink(`${tempDir}${name}`).catch(() => null)
return safeWriteFile(name, data, "renewed")
}
if (alwaysReturn) return { name, status: "unchanged" }
return false
}
getInstancesInfos()
.then(async ({alives, deads, notMisskey, outdated, versions, versionOutput, langs}) => {
fs.writeFile('./dist/versions.json', JSON.stringify(versionOutput), () => { })
const stats = alives.reduce((prev, v) => (v.nodeinfo.usage && v.nodeinfo.usage.users) ? {
notesCount: (v.nodeinfo.usage.localPosts || 0) + prev.notesCount,
usersCount: (v.nodeinfo.usage.users.total || 0) + prev.usersCount,
mau: (v.nodeinfo.usage.users.activeMonth || 0) + prev.mau,
instancesCount: 1 + prev.instancesCount
} : { ...prev }, { notesCount: 0, usersCount: 0, mau: 0, instancesCount: 0 })
fs.writeFile('./dist/alives.txt', alives.map(v => v.url).join('\n'), () => { })
fs.writeFile('./dist/deads.txt', deads.map(v => v.url).join('\n'), () => { })
fs.writeFile('./dist/not-misskey.txt', notMisskey.map(v => v.url).join('\n'), () => { })
//fs.writeFile('./dist/outdated.txt', outdated.map(v => v.url).join('\n'), () => { })
await mkdirp('./dist/instance-banners')
await mkdirp('./dist/instance-backgrounds')
await mkdirp('./dist/instance-icons')
const infoQueue = new Queue(3)
const instancesInfosPromises = [];
for (const instance of alives) {
if (instance.meta.bannerUrl) {
instancesInfosPromises.push(infoQueue.add(async () => {
glog(`downloading banner for ${instance.url}`)
const res = await downloadTemp(`${instance.url}`, (new URL(instance.meta.bannerUrl, `https://${instance.url}`)).toString(), `./temp/instance-banners/`, true)
if (res) instance.banner = true
else instance.banner = false
if (res && res.status !== "unchanged") {
const base = sharp(`./temp/instance-banners/${res.name}`)
.resize({
width: 1024,
withoutEnlargement: true,
})
if (!base) {
instance.banner = false
return;
}
try {
await base.jpeg({ quality: 80, progressive: true })
.toFile(`./dist/instance-banners/${instance.url}.jpeg`)
await base.webp({ quality: 75 })
.toFile(`./dist/instance-banners/${instance.url}.webp`)
} catch (e) {
glog.error(`error while processing banner for ${instance.url}`, e);
instance.banner = false
}
}
}))
} else {
instance.banner = false
}
if (instance.meta.backgroundImageUrl) {
instancesInfosPromises.push(infoQueue.add(async () => {
glog(`downloading background image for ${instance.url}`)
const res = await downloadTemp(`${instance.url}`, (new URL(instance.meta.backgroundImageUrl, `https://${instance.url}`)).toString(), `./temp/instance-backgrounds/`, true)
if (res) instance.background = true
else instance.background = false
if (res && res.status !== "unchanged") {
const base = sharp(`./temp/instance-backgrounds/${res.name}`)
.resize({
width: 1024,
withoutEnlargement: true,
})
if (!base) {
instance.background = false
return;
}
try {
await base.jpeg({ quality: 80, progressive: true })
.toFile(`./dist/instance-backgrounds/${instance.url}.jpeg`)
await base.webp({ quality: 75 })
.toFile(`./dist/instance-backgrounds/${instance.url}.webp`)
} catch (e) {
glog.error(`error while processing background for ${instance.url}`, e);
instance.background = false
}
}
}))
} else {
instance.background = false
}
if (instance.meta.iconUrl) {
instancesInfosPromises.push(infoQueue.add(async () => {
glog(`downloading icon image for ${instance.url}`)
const res = await downloadTemp(`${instance.url}`, (new URL(instance.meta.iconUrl, `https://${instance.url}`)).toString(), `./temp/instance-icons/`, true)
if (res) instance.icon = true
else instance.icon = false
if (res && res.status !== "unchanged") {
const filename = `./temp/instance-icons/${res.name}`
const { mime } = await fileTypeFromFile(filename)
const base = (await sharpBmp(filename, mime))
.resize({
height: 200,
withoutEnlargement: true,
})
if (!base) {
instance.icon = false
return;
}
try {
await base.png()
.toFile(`./dist/instance-icons/${instance.url}.png`)
await base.webp({ quality: 75 })
.toFile(`./dist/instance-icons/${instance.url}.webp`)
} catch (e) {
glog.error(`error while processing icon for ${instance.url}`, e);
instance.icon = false
}
}
}))
} else {
instance.icon = false
}
}
await Promise.allSettled(instancesInfosPromises)
const INSTANCES_JSON = {
date: new Date(),
stats,
langs,
instancesInfos: alives
}
fs.writeFile('./dist/instances.json', JSON.stringify(INSTANCES_JSON), () => { })
//#region remove dead/ignored servers' assets
try {
const targets = new Set();
deads.forEach(v => targets.add(v.url))
notMisskey.forEach(v => targets.add(v.url))
loadyaml("./data/ignorehosts.yml").forEach(v => targets.add(v))
targets.forEach(v => {
glob.sync(`./dist/**/${v}.*`).forEach(file => {
glog(`removing ${file}`)
fs.unlink(file, () => null)
})
glob.sync(`./temp/**/${v}`).forEach(file => {
glog(`removing ${file}`)
fs.unlink(file, () => null)
})
})
} catch (e) {
glog.error(e)
}
//#endregion
glog('FINISHED!')
return INSTANCES_JSON;
})
.then(async INSTANCES_JSON => {
// 0. Statistics
let tree = await fetch("https://p1.a9z.dev/api/notes/create", {
method: "POST",
body: JSON.stringify({
i: process.env.MK_TOKEN,
text: `JoinMisskey servers api is updated at ${INSTANCES_JSON.date.toISOString()}.
Total Notes: ${INSTANCES_JSON.stats.notesCount}
Total Users: ${INSTANCES_JSON.stats.usersCount}
Total MAU: ${INSTANCES_JSON.stats.mau}
Total Servers: ${INSTANCES_JSON.stats.instancesCount}
https://misskey-hub.net/servers\n#bot #joinmisskeyupdate`,
}),
headers: {
"Content-Type": "application/json"
}
}).then(res => res.json());
// Instances
const sorted = INSTANCES_JSON.instancesInfos.sort((a, b) => (b.value - a.value));
const getInstancesList = instances => instances.map(
(instance, i) =>
`${i + 1}. ?[${
(instance.name || instance.name !== instance.url) ?
`<plain>${instance.name}</plain> (${instance.url})` :
instance.url
}](https://${instance.url})`
).join('\n')
// 1. Japanese
const japaneseInstances = [];
for (const instance of sorted) {
if (instance.langs.includes("ja")) {
japaneseInstances.push(instance)
}
if (japaneseInstances.length === 30) break;
}
tree = await fetch("https://p1.a9z.dev/api/notes/create", {
method: "POST",
body: JSON.stringify({
i: process.env.MK_TOKEN,
text: `日本語サーバー (トップ30)\n\n${getInstancesList(japaneseInstances)}`,
replyId: tree.createdNote.id,
}),
headers: {
"Content-Type": "application/json"
}
}).then(res => res.json());
// 2. English
const otherInstances = [];
for (const instance of sorted) {
if (instance.langs.includes("ja")) continue;
otherInstances.push(instance);
if (otherInstances.length === 30) break;
}
tree = await fetch("https://p1.a9z.dev/api/notes/create", {
method: "POST",
body: JSON.stringify({
i: process.env.MK_TOKEN,
text: `Top 30 instances (other than Japanese)\n\n${getInstancesList(otherInstances)}`,
replyId: tree.createdNote.id,
}),
headers: {
"Content-Type": "application/json"
}
}).then(res => res.json());
})
.then(async () => {
const notIncluded = await instanceq()
if (notIncluded.length === 0) return;
fs.writeFile('./dist/notincluded.txt', notIncluded.join('\n'), () => { })
return fetch("https://p1.a9z.dev/api/notes/create", {
method: "POST",
body: JSON.stringify({
i: process.env.MK_TOKEN,
text: `JoinMisskey servers api is now updated.\nUNLISTED INSTANCE(S) FOUND!\n\n${notIncluded.join('\n')}\n#bot`
}),
headers: {
"Content-Type": "application/json"
}
})
})