-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
183 lines (170 loc) · 6.13 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
#!/usr/bin/env node
/* eslint-disable no-console */
/* eslint-disable camelcase */
require('dotenv').config();
const { argv } = require('yargs');
const fs = require('fs');
const path = require('path');
const https = require('https');
const { promisify } = require('util');
const axios = require('axios');
const ora = require('ora');
const { range, omit } = require('lodash');
const mapshaper = require('mapshaper');
const tippecanoe = require('tippecanoe');
const tilelive = require('@mapbox/tilelive');
const MBTiles = require('@mapbox/mbtiles');
const s3 = require('@mapbox/tilelive-s3');
const loadAsync = promisify(tilelive.load);
const copyAsync = promisify(tilelive.copy);
const STEP = 500;
let VECTOR_LAYERS = [];
const OMIT = [
'ViewConesPoly',
'SurveyExtentsPoly',
'AerialExtentsPoly',
'PlanExtentsPoly',
'MapExtentsPoly',
];
const spinner = ora('Generating vector tiles\n').start();
let access_token;
const loadFeatures = async (i, count, step, layer) => {
return axios
.get(
`https://gis.spatialstudieslab.org/server/rest/services/Hosted/${process.env.DATABASE}/FeatureServer/${layer.id}/query?where=objectid IS NOT NULL&outFields=objectid,nameshort,name,firstyear,lastyear,type&f=geojson&resultRecordCount=${step}&resultOffset=${i}&token=${access_token}`,
{ httpsAgent: new https.Agent({ rejectUnauthorized: false }) }
)
.then(async ({ data }) => {
console.log(`${layer.name}: Loading features ${i} / ${count}`);
let json = data;
if (typeof json === 'string') {
try {
json = JSON.parse(data);
} catch (e) {
console.log(e);
console.log(data);
}
}
const geojson = omit(json, 'exceededTransferLimit');
if (geojson.features) {
return fs.promises.writeFile(
path.join(__dirname, 'geojson/', `${layer.name}-${i}.geojson`),
JSON.stringify(omit(data, 'exceededTransferLimit'))
);
}
console.log('An error occurred. Retrying');
// eslint-disable-next-line no-use-before-define
return loadFeatures(i, count, step, layer);
})
.catch(err => {
console.log(err);
process.exit(1);
});
};
const loadLayer = async layer => {
spinner.start(`${layer.name}: Loading features`);
const {
data: { count },
} = await axios.get(
`https://gis.spatialstudieslab.org/server/rest/services/Hosted/${process.env.DATABASE}/FeatureServer/${layer.id}/query?where=objectid IS NOT NULL&f=json&returnCountOnly=true&token=${access_token}`,
{ httpsAgent: new https.Agent({ rejectUnauthorized: false }) }
);
const step = STEP;
return range(0, count || 1, step).reduce(async (previousPromise, next) => {
await previousPromise;
const exists = fs.existsSync(path.join(__dirname, 'geojson/', `${layer.name}-${next}.geojson`));
if (exists) return Promise.resolve();
return loadFeatures(next, count, step, layer);
}, Promise.resolve());
};
const upload = async () => {
tippecanoe(VECTOR_LAYERS, {
f: true,
Z: process.env.MIN_ZOOM || 9,
z: process.env.MAX_ZOOM || 17,
r1: true,
o: 'rio.mbtiles',
});
spinner.start('Uploading vector tiles to S3');
s3.registerProtocols(tilelive);
MBTiles.registerProtocols(tilelive);
const sourceUri = `mbtiles://${path.join(__dirname, 'rio.mbtiles')}`;
const sinkUri = process.env.AWS_BUCKET;
const src = await loadAsync(sourceUri);
const dest = await loadAsync(sinkUri);
const options = {
type: 'list',
listScheme: src.createZXYStream(),
};
return copyAsync(src, dest, options).then(() => spinner.succeed());
};
const main = () => {
spinner.text = 'Loading layer info';
axios
.get(
`https://gis.spatialstudieslab.org/server/rest/services/Hosted/${process.env.DATABASE}/FeatureServer/layers?f=json&token=${access_token}`,
{ httpsAgent: new https.Agent({ rejectUnauthorized: false }) }
)
.then(({ data: { layers } }) => {
spinner.succeed(`${layers.length} layers loaded`);
return layers
.filter(l => !OMIT.includes(l.name))
.reduce(async (previousPromise, layer) => {
await previousPromise;
return loadLayer(layer)
.then(() =>
mapshaper.runCommands(
`-i geojson/${layer.name}*.geojson combine-files -merge-layers -filter remove-empty
-o geojson/final/${layer.name.toLowerCase()}.geojson force format=geojson id-field=objectid`
)
)
.then(() => {
VECTOR_LAYERS.push(`geojson/final/${layer.name.toLowerCase()}.geojson`);
return spinner.succeed(`${layer.name} loaded`);
});
}, Promise.resolve());
})
.then(upload)
.catch(err => {
spinner.fail(err);
process.exit(1);
});
};
const authenticate = () => {
const { CLIENT_ID, USERNAME, PASSWORD } = process.env;
const httpsAgent = new https.Agent({ rejectUnauthorized: false });
return axios
.get(
`https://gis.spatialstudieslab.org/portal/sharing/rest/oauth2/authorize/?client_id=${CLIENT_ID}&response_type=code&expiration=3600&redirect_uri=urn:ietf:wg:oauth:2.0:oob`,
{ httpsAgent }
)
.then(({ data }) => {
const oauth = data.replace(/^.*"oauth_state":"(.*?)".*$/gs, '$1');
return axios
.post(
`https://gis.spatialstudieslab.org/portal/sharing/oauth2/signin?oauth_state=${oauth}&authorize=true&username=${USERNAME}&password=${PASSWORD}`,
{},
{ httpsAgent }
)
.then(res => {
const code = res.data.replace(/^.*id="code" value="(.*?)".*$/gs, '$1');
return axios
.post(
`https://gis.spatialstudieslab.org/portal/sharing/oauth2/token?client_id=${CLIENT_ID}&code=${code}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code`,
{},
{ httpsAgent }
)
.then(res2 => {
({ access_token } = res2.data);
return Promise.resolve();
});
});
});
};
if (argv.upload) {
const files = fs.readdirSync('geojson/final');
VECTOR_LAYERS = files.map(f => `geojson/final/${f}`);
upload();
} else {
authenticate().then(() => main());
}