-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathindex.js
executable file
·246 lines (218 loc) · 6.61 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
#!/usr/bin/env node
// @Author: Joshua Tanner
// @Date: 1/15/2018
// @Description: Easy way to convert ArcGIS Server service to GeoJSON
// and shapefile format. Good for backup solution.
// @services.txt format :: serviceLayerURL|layerName|throttle(ms)
// @githubURL : https://github.com/tannerjt/AGStoShapefile
// Node Modules
const fs = require('fs');
const rp = require('request-promise');
const request = require('request');
const _ = require('lodash');
const TerraformerArcGIS = require('terraformer-arcgis-parser');
const geojsonStream = require('geojson-stream');
const JSONStream = require('JSONStream');
const CombinedStream = require('combined-stream');
const queryString = require('query-string');
const merge2 = require('merge2');
const rimraf = require('rimraf');
const ogr2ogr = require('ogr2ogr');
// ./mixin.js
// merge user query params with default
const mixin = require('./mixin');
var program = require('commander');
program
.version('1.0.2')
.option('-o, --outdir [directory]', 'Output directory')
.option('-s, --services [path to txt file]', 'Text file containing service list to extract')
.option('-S, --shapefile', 'Optional export to shapefile')
.parse(process.argv);
const serviceFile = program.services || 'services.txt';
var outDir = program.outdir || './output/';
// Remove trailing '/'
outDir = outDir.replace(/\/$/, '');
fs.readFile(serviceFile, function (err, data) {
if (err) {
throw err;
}
data.toString().split('\n').forEach(function (service) {
var service = service.split('|');
if(service[0].split('').length == 0) return;
var baseUrl = getBaseUrl(service[0].trim());
var reqQS = {
where: '1=1',
returnIdsOnly: true,
f: 'json'
};
var userQS = getUrlVars(service[0].trim());
// mix one obj with another
var qs = mixin(userQS, reqQS);
qs = queryString.stringify(qs);
var url = decodeURIComponent(getBaseUrl(baseUrl) + '/query/?' + qs);
var throttle = 0;
if(service.length > 2) {
throttle = +service[2];
}
rp({
url : url,
method : 'GET',
json : true
}).then((body) => {
requestService(service[0].trim(), service[1].trim(), body.objectIds, throttle);
}).catch((err) => {
console.log(err);
});
})
});
// Resquest JSON from AGS
function requestService(serviceUrl, serviceName, objectIds, throttle) {
objectIds.sort();
const requests = Math.ceil(objectIds.length / 100);
var completedRequests = 0;
console.log(`Number of features for service ${serviceName}:`, objectIds.length);
console.log(`Getting chunks of 100 features, will make ${requests} total requests`);
for(let i = 0; i < Math.ceil(objectIds.length / 100); i++) {
var ids = [];
if ( ((i + 1) * 100) < objectIds.length ) {
ids = objectIds.slice(i * 100, (i * 100) + 100);
} else {
ids = objectIds.slice(i * 100, objectIds[objectIds.length]);
}
// we need these query params
const reqQS = {
objectIds : ids.join(','),
geometryType : 'esriGeometryEnvelope',
returnGeometry : true,
returnIdsOnly : false,
outFields : '*',
outSR : '4326',
f : 'json'
};
// user provided query params
const userQS = getUrlVars(serviceUrl);
// mix one obj with another
var qs = mixin(userQS, reqQS);
qs = queryString.stringify(qs);
const url = decodeURIComponent(getBaseUrl(serviceUrl) + '/query/?' + qs);
const partialsDir = `${outDir}/${serviceName}/partials`;
if(i == 0) {
// first pass, setup folders
if(!fs.existsSync(`${outDir}`)) {
fs.mkdirSync(`${outDir}`)
}
if(!fs.existsSync(`${outDir}/${serviceName}`)) {
fs.mkdirSync(`${outDir}/${serviceName}`);
}
if (!fs.existsSync(partialsDir)){
fs.mkdirSync(partialsDir);
} else {
rimraf.sync(partialsDir);
fs.mkdirSync(partialsDir);
}
}
const featureStream = JSONStream.parse('features.*', convert);
const outFile = fs.createWriteStream(`${partialsDir}/${i}.json`);
const options = {
url: url,
method: 'GET',
json: true,
};
// timeout for throttle
setTimeout(() => {
request(options)
.pipe(featureStream)
.pipe(geojsonStream.stringify())
.pipe(outFile)
.on('finish', () => {
completedRequests += 1;
console.log(`Completed ${completedRequests} of ${requests} requests for ${serviceName}`);
if(requests == completedRequests) {
mergeFiles();
}
})
.on('error', (err) => {
console.log(err);
});
}, i * throttle);
function convert (feature) {
if(!feature.geometry) {
console.log("Feature Missing Geometry and is Omitted: ", JSON.stringify(feature))
return null;
}
const gj = {
type: 'Feature',
properties: feature.attributes,
geometry: TerraformerArcGIS.parse(feature.geometry)
}
return gj
}
function mergeFiles() {
console.log(`Finished extracting chunks for ${serviceName}, merging files...`)
fs.readdir(partialsDir, (err, files) => {
const finalFilePath = `${outDir}/${serviceName}/${serviceName}_${Date.now()}.geojson`
const finalFile = fs.createWriteStream(finalFilePath);
let streams = CombinedStream.create();
_.each(files, (file) => {
streams.append((next) => {
next(
fs.createReadStream(`${partialsDir}/${file}`)
.pipe(JSONStream.parse('features.*'))
.on('error', (err) => {
console.log(err);
})
);
})
});
streams
.pipe(geojsonStream.stringify())
.pipe(finalFile)
.on('finish', () => {
rimraf(partialsDir, () => {
console.log(`${serviceName} is complete`);
console.log(`File Location: ${finalFilePath}`);
if(program.shapefile) {
makeShape(finalFilePath);
}
});
})
.on('error', (err) => {
console.log(err);
})
});
}
function makeShape(geojsonPath) {
console.log(`Generating shapefile for ${serviceName}`)
// todo: make optional with flag
const shpPath = `${outDir}/${serviceName}/${serviceName}_${Date.now()}.zip`;
const shpFile = fs.createWriteStream(shpPath);
var shapefile = ogr2ogr(geojsonPath)
.format('ESRI Shapefile')
.options(['-nln', serviceName])
.timeout(120000)
.skipfailures()
.stream();
shapefile.pipe(shpFile);
}
};
}
//http://stackoverflow.com/questions/4656843/jquery-get-querystring-from-url
function getUrlVars(url) {
var vars = {}, hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars[hash[0].toString()] = hash[1];
}
return vars;
}
// get base url for query
function getBaseUrl(url) {
// remove any query params
var url = url.split("?")[0];
if((/\/$/ig).test(url)) {
url = url.substring(0, url.length - 1);
}
return url;
}