-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.js
80 lines (64 loc) · 1.99 KB
/
build.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
'use strict'
const fetch = require('isomorphic-fetch')
const cheerio = require('cheerio')
const {parse} = require('acorn')
const {traverse} = require('estraverse')
const natsort = require('natsort')
const uniqBy = require('lodash.uniqby')
const {parseCountry, parseStation} = require('./parse')
const setterName = 'tbAutoCompleteStops'
const isSetterCall = (node) =>
node.type === 'CallExpression'
&& node.callee.type === 'MemberExpression'
&& node.callee.property.type === 'Identifier'
&& node.callee.property.name === setterName
&& Array.isArray(node.arguments)
&& node.arguments[0].type === 'Literal'
&& node.arguments[0].value === 'setData'
&& node.arguments[1].type === 'ArrayExpression'
&& node.arguments[2].type === 'ArrayExpression'
&& node.arguments[3].type === 'ArrayExpression'
const setterCallData = (node) => ({
stations: node.arguments[1].elements,
countries: node.arguments[2].elements
// todo: third arg
// countryIDs: node.arguments[3].elements
})
const showError = (err) => {
console.error(err)
process.exit(1)
}
fetch('https://m.nettbuss.se/m/sok-kop-resa', {
redirect: 'follow'
})
.then((res) => res.text())
.then((html) => { // find the right <script> tag
const $ = cheerio.load(html)
const scripts = Array.from($('script'))
for (let script of scripts) {
for (let js of script.children) {
if (js.type === 'text' && js.data.indexOf(setterName) >= 0) return js.data
}
}
throw new Error('no matching <script> found')
})
.then((js) => { // find the fn call containing the data
const ast = parse(js)
traverse(ast, {
enter: (node, parent) => {
if (!isSetterCall(node)) return
const data = setterCallData(node)
const countries = data.countries.map(parseCountry(js))
const sort = natsort()
const stations =
uniqBy(
data.stations
.map(parseStation(js, countries))
.filter((s) => s.id !== null && s.name)
, (s) => s.id)
.sort((a, b) => sort(a.id, b.id))
process.stdout.write(JSON.stringify(stations) + '\n')
}
})
})
.catch(showError)