-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathversion-position-crawler.js
271 lines (248 loc) · 6.63 KB
/
version-position-crawler.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
const fs = require('fs')
const path = require('path')
const cheerio = require('cheerio')
const got = require('got')
const Crawler = require('crawler')
const { getopt } = require('stdio')
const {
VersionUrl,
VersionPositionUrl,
FileName,
Dir,
VerRegex,
} = require('./constants')
const Modes = {
inc: 'inc',
all: 'all',
}
const AllDefaultOpts = {
mode: Modes.inc,
maxConnections: 10,
loopTimes: 10,
loopInterval: 5,
}
const IncDefaultOpts = {
mode: Modes.inc,
maxConnections: 3,
loopTimes: 3,
loopInterval: 3,
}
const receivedOpts = getopt({
mode: {
key: 'm',
description:
'`all`: first crawl positions of all version, or `inc`: incremental mode(much less request and less error)',
default: Modes.inc,
},
maxConnections: {
key: 'c',
description:
'max connections of crawling positions, default `all`: 10, `inc`: 3',
},
loopTimes: {
key: 'l',
description:
'times to loop all needed fetch versions, default `all`: 10, `inc`: 3',
},
loopInterval: {
key: 'i',
description: 'seconds between each loop, default `all`: 5, `inc`: 3',
},
beginVerIndex: {
key: 'b',
default: 0,
},
saveStepSize: {
key: 's',
description:
'used for `all` only, save to file after this count of request',
default: 1000,
},
})
let opts =
receivedOpts.mode === Modes.all
? { ...AllDefaultOpts }
: { ...IncDefaultOpts }
opts = { ...opts, ...receivedOpts }
// entry
main()
async function main() {
if (!fs.existsSync(Dir.base)) {
fs.mkdirSync(Dir.base, { recursive: true })
}
if (opts.mode === Modes.all) {
console.log('mode: all')
await mainFirstFull()
} else {
console.log('mode: increment')
await mainIncreace()
}
console.log('all finished --------------------')
}
// -------------------------
async function mainIncreace() {
for (let i = 1; i <= opts.loopTimes; i++) {
console.log(`round ${i} begin ...`)
try {
const isFinish = await doIt(opts.beginVerIndex)
if (isFinish) {
break
}
} catch (e) {
console.error(e)
}
await sleep(opts.loopInterval * 1000)
console.error(`round ${i} end ---------------`)
}
}
async function mainFirstFull() {
for (let i = 1; i <= opts.loopTimes; i++) {
console.log(`round ${i} begin ...`)
const MaxVerCount = 30000
const halfStep = Math.floor(opts.saveStepSize / 2)
for (let j = opts.beginVerIndex; j < MaxVerCount; j += halfStep) {
try {
await doIt(j)
} catch (e) {
console.error(e)
}
}
await sleep(opts.loopInterval * 1000)
console.error(`round ${i} end ---------------`)
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
// about sort: https://stackoverflow.com/a/38641281/2752670
const collator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: 'base',
})
async function doIt(beginIdx) {
const resp = await got(VersionUrl)
const $ = cheerio.load(resp.body)
const $titles = $('.RefList-title')
let $RefListItems = []
$titles.each(function (i, item) {
const $item = $(this)
const text = $item.text()
console.log(`version page: ${text}`)
if (text === 'Tags') {
$RefListItems = $item.next().children('li')
}
})
if ($RefListItems.length === 0) {
console.error('no version data')
return false
}
console.log(`version count raw: ${$RefListItems.length}`)
let versions = []
$RefListItems.each(function (i, item) {
const $item = $(this)
const ver = $item.text()
const v = ver.trim()
if (VerRegex.test(v)) {
versions.push(ver.trim())
} else {
console.log(`invalid version: ${ver}`)
}
})
console.log(`version count valid: ${versions.length}`)
versions.sort((a, b) => collator.compare(b, a))
fs.writeFileSync(
path.join(Dir.base, FileName.allVersion),
JSON.stringify(versions, null, 2)
)
// ---- begin to find position ---------------
let verPosMap = {}
const crawler = new Crawler({
jQuery: false,
maxConnections: 3,
// This will be called for each crawled data
callback: function (error, res, done) {
if (error) {
console.log(error)
done()
return
}
let $ = res.$
let bodyObj = ''
const v = res.options.myData
if (res.body.includes('Traceback')) {
console.log(`----- ${v} ---- ${res.body} ----`)
verPosMap[v] = 'ErrorWithTraceback'
done()
return
}
try {
bodyObj = JSON.parse(res.body)
} catch (e) {
console.log(`----- ${v} ---- ${res.body} ----`)
done()
return
}
const pos = bodyObj.chromium_base_position
if (!pos) {
// `null` pos will also be recorded
// `null` pos is not changed after any times of request
console.log(`version ${v} position ${pos}`)
} else {
console.log(`version ${v} match position ${pos}`)
}
verPosMap[v] = pos
done()
},
})
// read cached json, can avoid lots of request
const oldVerPosStr = fs.readFileSync(
path.join(Dir.base, FileName.versionPosition),
'utf8'
)
const oldVerPosMap = JSON.parse(oldVerPosStr)
versions = versions.filter((v) => !oldVerPosMap.hasOwnProperty(v))
const needToFetchCount = versions.length
console.log(`need to fetch count: ${needToFetchCount}`)
if (versions.length === 0) {
return true
}
let count = 0
for (let i = beginIdx; i < versions.length; i++) {
const v = versions[i]
if (i === 1) {
console.log(`first fetch version: ${v}`)
}
const url = `${VersionPositionUrl}${v}`
crawler.queue({ uri: url, myData: v })
count++
if (opts.mode === Modes.all) {
// each step size save to file, in case of loss of crawled data
if (count >= opts.saveStepSize) {
break
}
}
}
return await new Promise((resolve, reject) => {
crawler.on('drain', function () {
console.log('crawler drain event')
let allVerPosMap = Object.assign({}, oldVerPosMap, verPosMap)
const successCount =
Object.keys(allVerPosMap).length - Object.keys(oldVerPosMap).length
console.log(`success count: ${successCount}`)
// sort keys
allVerPosMap = Object.entries(allVerPosMap)
.sort((a, b) => collator.compare(b, a))
.reduce((o, [k, v]) => ((o[k] = v), o), {})
fs.writeFileSync(
path.join(Dir.base, FileName.versionPosition),
JSON.stringify(allVerPosMap, null, 2)
)
const FName = __filename.slice(__dirname.length + 1)
console.log(`${FName}: finish`)
// remember to resolve
resolve(successCount === needToFetchCount)
})
})
}