-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.mjs
275 lines (253 loc) · 7.14 KB
/
main.mjs
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
import * as fs from "fs"
import * as path from "path"
import { fileURLToPath } from "url"
const TERM_DAYS = 2
const MAX_ITERATIONS = 20
const OFFICIAL_URL_SUFFIX = ".bsky.network"
const NOW = new Date()
async function main () {
const currentData = await makeCurrentData()
createDirectory("./log")
createLogFile(currentData)
const entireData = makeEntireData("./log")
createJsonFile(entireData)
createReadMe(entireData)
}
async function makeCurrentData() {
const startedAt = new Date(NOW)
startedAt.setDate(startedAt.getDate() - TERM_DAYS)
const currentLogs = await fetchCurrentLogs(startedAt, MAX_ITERATIONS)
const endpoints = makeEndpoints(currentLogs)
await injectServerInfo(endpoints)
return {
startedAt: startedAt.toISOString(),
endpoints,
}
}
async function fetchCurrentLogs (startedAt, maxIterations) {
const currentLogs = []
for (let i = 0; i < maxIterations; i ++) {
const logs = await fetchLogs(startedAt.toISOString(), 1000)
// console.log(startedAt, i, logs.length)
if (logs == null ||
logs.length <= 1
) {
return currentLogs
}
const createdAt = logs.at(- 1)?.createdAt
if (createdAt == null) {
console.error("createdAt is null/undefined.", logs.at(- 1))
return currentLogs
}
startedAt = new Date(createdAt)
currentLogs.push(...logs)
// 💕 Drive safely...
await wait(1000)
}
return currentLogs
}
async function fetchLogs (after, count = 1000) {
const response = await fetch(
// SEE: https://web.plc.directory/spec/v0.1/did-plc
`https://plc.directory/export?after=${after}&count=${count}`,
{
headers: {
"Content-Type": "application/json",
},
}
)
.then((response) => response)
.catch((error) => error)
if (response == null ||
response instanceof Error
) {
console.error("fetchLogs failed.", response)
return
}
return (await response.text())
?.split("\n")
?.map((text) => JSON.parse(text))
}
function makeEndpoints (currentLogs) {
const endpointMap = new Map()
currentLogs.forEach((doc) => {
const pds = doc.operation?.services?.atproto_pds
if (pds?.type !== "AtprotoPersonalDataServer" ||
!(pds?.endpoint)
) {
return
}
const existing = endpointMap.get(pds.endpoint)
if (existing != null) {
existing.createdAt = doc.createdAt
} else {
endpointMap.set(pds.endpoint, {
createdAt: doc.createdAt,
})
}
})
const endpoints = Object.keys(Object.fromEntries(endpointMap))
.map((key) => {
const endpoint = endpointMap.get(key)
return {
url: key,
createdAt: endpoint.createdAt,
}
})
sortEndpoints(endpoints)
return endpoints
}
async function injectServerInfo (endpoints) {
for (const endpoint of endpoints) {
// Skip official server
if (endpoint.url.endsWith(OFFICIAL_URL_SUFFIX)) {
continue
}
const response = await fetch(
// SEE: https://docs.bsky.app/docs/api/com-atproto-server-describe-server
`${endpoint.url}/xrpc/com.atproto.server.describeServer`,
{
headers: {
"Content-Type": "application/json",
},
}
)
.then((response) => response)
.catch((error) => error)
if (response == null ||
response instanceof Error
) {
console.error("describeServer failed.", response)
endpoint.alive = false
continue
}
const json = await response.json()
.then((response) => response)
.catch((error) => error)
if (json == null ||
json instanceof Error
) {
console.error("response.json() failed.", json)
endpoint.alive = false
continue
}
endpoint.alive = true
endpoint.inviteCodeRequired = json.inviteCodeRequired ?? false
endpoint.phoneVerificationRequired = json.phoneVerificationRequired ?? false
}
}
function sortEndpoints (endpoints) {
endpoints
// Sort by createdAt
.sort((a, b) => {
return a.createdAt < b.createdAt
? 1
: a.createdAt > b.createdAt
? - 1
: 0
})
// Sort by official servers
.sort((a, b) => {
const isAOfficial = a.url.endsWith(OFFICIAL_URL_SUFFIX)
const isBOfficial = b.url.endsWith(OFFICIAL_URL_SUFFIX)
return isAOfficial && !isBOfficial
? - 1
: !isAOfficial && isBOfficial
? 1
: 0
})
}
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
function createDirectory (dirPath) {
const directoryPath = path.join(__dirname, dirPath)
if (!fs.existsSync(directoryPath)) {
fs.mkdirSync(directoryPath)
}
}
function createLogFile (currentData) {
const suffix = NOW.getTime()
fs.writeFileSync(`./log/list-${suffix}.json`, JSON.stringify(currentData), "utf8")
}
function makeEntireData (dirPath) {
const filePaths = []
fs.readdirSync(dirPath).forEach((file) => {
const filePath = path.join(dirPath, file)
const stat = fs.statSync(filePath)
if (!(stat?.isFile())) {
return
}
filePaths.push(filePath)
})
filePaths.sort((a, b) => {
return a < b
? 1
: a > b
? - 1
: 0
})
const endpointMap = new Map()
filePaths.forEach((filePath) => {
const text = fs.readFileSync(filePath, { encoding: "utf8" })
const json = JSON.parse(text)
json.endpoints.forEach((endpoint) => {
const existing = endpointMap.get(endpoint.url)
if (existing != null) {
existing.createdAt = endpoint.createdAt
if (endpoint.alive != null) {
existing.alive = endpoint.alive
}
if (endpoint.inviteCodeRequired != null) {
existing.inviteCodeRequired = endpoint.inviteCodeRequired
}
if (endpoint.phoneVerificationRequired != null) {
existing.phoneVerificationRequired = endpoint.phoneVerificationRequired
}
} else {
endpointMap.set(endpoint.url, endpoint)
}
})
})
const endpoints = Object.keys(Object.fromEntries(endpointMap))
.map((key) => ({ ...endpointMap.get(key) }))
sortEndpoints(endpoints)
removeDeadEndpoints(endpoints)
return {
startedAt: NOW.toISOString(),
endpoints,
}
}
function removeDeadEndpoints (endpoints) {
endpoints.splice(
0,
endpoints.length,
...endpoints.filter((endpoint) => endpoint.alive !== false)
)
}
function createJsonFile (entireData) {
fs.writeFileSync(`./list.json`, JSON.stringify(entireData), "utf8")
}
function createReadMe (currentData) {
const updatedAt = NOW.toLocaleString()
const list = [
"|URL|Invite|Phone|",
"|-|-|-|",
...currentData.endpoints.map((endpoint) => {
return `|${endpoint.url}|${endpoint.inviteCodeRequired ? "🎫" : ""}|${endpoint.phoneVerificationRequired ? "📞" : ""}|`
}),
].join("\n")
const readMe = `# ⭐ Klearlist
Klearlist is ATProtocol's PDS list. Note, this list is a partial, not an all.
JSON file is [here](./list.json) .
Updated at ${updatedAt}
${list}
Klearlist © 2024 [mimonelu](https://bsky.app/profile/mimonelu.net)
`
fs.writeFileSync("./README.md", readMe, "utf8")
}
async function wait (interval) {
return new Promise((resolve) => {
setTimeout(resolve, interval)
})
}
await main()