Skip to content

Commit af4b9ef

Browse files
committed
Cache Shapes.txt
1 parent d85540e commit af4b9ef

File tree

11 files changed

+82
-125
lines changed

11 files changed

+82
-125
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ cache/*.txt
4545
cache/*/*.txt
4646
cache/stops/*/*.txt
4747
cache/*.zip
48+
cache/*/*
4849
cache/maps/*.png
4950
cache/maps/*.webp
5051
dist/generated/*

package-lock.json

Lines changed: 7 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@
7777
"react-transition-group": "^2.2.0",
7878
"request": "^2.74.0",
7979
"resolve-url-loader": "^2.1.0",
80+
"rimraf": "^2.6.2",
8081
"sendgrid": "^4.3.0",
8182
"stream-transform": "^0.1.2",
8283
"style-loader": "^0.18.2",

server/agencies/at.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ const config = {
2929
name: 'calendar_dates.txt',
3030
table: 'calendar_dates'
3131
},
32-
]
32+
],
33+
shapeFile: 'shapes.txt'
3334
}
3435
module.exports = config

server/cache-new.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
1+
const fs = require('fs')
2+
const path = require('path')
3+
const rimraf = require('rimraf')
4+
15
const connection = require('./db/connection.js')
26
const gtfsImport = require('./db/gtfs-import.js')
7+
const createShapes = require('./db/create-shapes.js')
38

49
const metlink = require('./agencies/metlink.js')
510
const at = require('./agencies/at.js')
@@ -19,5 +24,18 @@ async function doShit() {
1924
console.log(err)
2025
})
2126
})
27+
28+
const outputDir = '../cache/metlink.zipunarchived/shapes'
29+
// cleans up old import if exists
30+
if (fs.existsSync(outputDir)) {
31+
await new Promise((resolve, reject) => {
32+
rimraf(outputDir, resolve)
33+
})
34+
}
35+
fs.mkdirSync(outputDir)
36+
37+
let metlinkShapes = new createShapes()
38+
await metlinkShapes.create('../cache/metlink.zipunarchived/shapes.txt', outputDir, ['20170828_20170808-090059'])
39+
await metlinkShapes.upload('nz-wlg-20170828-20170808-090059', path.resolve(outputDir, '20170828_20170808-090059'))
2240
}
2341
connection.isReady.then(doShit)

server/cache.js

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
var azure = require('azure-storage');
1+
var azure = require('azure-storage')
22
var request = require('request')
33
var moment = require('moment-timezone')
44
var fs = require('fs')
55
const extract = require('extract-zip')
66
const csvparse = require('csv-parse')
77
const transform = require('stream-transform')
8+
const rimraf = require('rimraf')
89

910
const Queue = require('./queue.js')
1011
const path = require('path')
@@ -16,6 +17,7 @@ var tableSvc = azure.createTableService()
1617
const sql = require('mssql')
1718
const connection = require('./db/connection.js')
1819
const gtfsImport = require('./db/gtfs-import.js')
20+
const createShapes = require('./db/create-shapes.js')
1921

2022
const zipLocation = path.resolve(__dirname, '../cache/at.zip')
2123

@@ -183,6 +185,28 @@ async function importAt() {
183185
await importer.upload(zipLocation + 'unarchived', file, at.prefix, version, ignoreVersions)
184186
}
185187

188+
let atShapes = new createShapes()
189+
const inputDir = path.resolve(zipLocation + 'unarchived', 'shapes.txt')
190+
const outputDir = path.resolve(zipLocation + 'unarchived', 'shapes')
191+
192+
// cleans up old import if exists
193+
if (fs.existsSync(outputDir)) {
194+
await new Promise((resolve, reject) => {
195+
rimraf(outputDir, resolve)
196+
})
197+
}
198+
fs.mkdirSync(outputDir)
199+
200+
// creates the new datas
201+
await atShapes.create(inputDir, outputDir, version)
202+
203+
const shapeFiles = fs.readdirSync(outputDir)
204+
for (let singleVersion of shapeFiles) {
205+
const containerName = (at.prefix + '-' + singleVersion).replace('.', '-').replace('_', '-')
206+
await atShapes.upload(containerName, path.resolve(outputDir, singleVersion))
207+
}
208+
console.log('Uploaded All Shapes')
209+
186210
// It was a success
187211
for (let v in version) {
188212
const vRequest = connection.get().request()

server/db/create-shapes.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ const azure = require('azure-storage')
88
const blobSvc = azure.createBlobService()
99

1010
class createShapes {
11-
create(inputFile, outputDirectory) {
11+
create(inputFile, outputDirectory, versions) {
1212
return new Promise((resolve, reject) => {
1313
const input = fs.createReadStream(inputFile)
1414
const parser = csvparse({delimiter: ','})
@@ -46,7 +46,17 @@ class createShapes {
4646
}).on('finish', () => {
4747
console.log('Created Shapes. Writing to disk...')
4848
Object.keys(output).forEach((key) => {
49-
fs.writeFileSync(path.resolve(outputDirectory, `${key}.json`), JSON.stringify(output[key]))
49+
let subfolder = (versions.length === 1 ? versions[0] : versions[0] + '-extra')
50+
versions.forEach((version) => {
51+
if (key.match(version)) {
52+
subfolder = version
53+
}
54+
})
55+
let dir = path.resolve(outputDirectory, subfolder)
56+
if (!fs.existsSync(dir)){
57+
fs.mkdirSync(dir)
58+
}
59+
fs.writeFileSync(path.resolve(dir, `${key}.json`), JSON.stringify(output[key]))
5060
})
5161
console.log('Written to disk!')
5262
resolve()
@@ -87,6 +97,9 @@ class createShapes {
8797
}
8898
console.log(container.green +':', 'Blob Container Created.')
8999
fs.readdir(directory, function(err, files) {
100+
if (err) {
101+
console.error(err)
102+
}
90103
uploadSingle(files, 0, uploadSingle)
91104
})
92105
})

server/db/manual-shape-create.js

Lines changed: 0 additions & 8 deletions
This file was deleted.

server/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ router.get('/:prefix/line/:line', line.getLine)
4646
router.get('/:prefix/stops/trip/:trip_id', line.getStopsFromTrip)
4747
router.get('/:prefix/stops/shape/:shape_id', line.getStopsFromShape)
4848
router.get('/:prefix/shape/:shape_id', line.getShape)
49+
router.get('/:prefix/shapejson/:shape_id', line.getShapeJSON)
4950
router.post('/:prefix/realtime', realtime.getTripsEndpoint)
5051
router.post('/:prefix/realtimebypass', realtime.endpointBypass)
5152
router.post('/:prefix/vehicle_location', realtime.getVehicleLocation)

server/lines/index.js

Lines changed: 12 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -65,21 +65,6 @@ function cacheOperatorsAndShapes(prefix = 'nz-akl') {
6565
}
6666
getOperator(index + 1)
6767
}).catch(err => console.warn(err))
68-
69-
// caches the shape
70-
line._getLine(todo[index], function(err, data) {
71-
if (err) {
72-
console.warn(err)
73-
}
74-
shapeCount++
75-
if (typeof(data[0]) !== 'undefined') {
76-
shapesToCache.push({shape_id: data[0].shape_id})
77-
}
78-
if (todo.length === shapeCount) {
79-
console.log('nz-akl:'.green, 'Collected List of Shapes To Cache')
80-
line.cacheShapes(shapesToCache)
81-
}
82-
}, 'nz-akl')
8368
}
8469
getOperator(0)
8570
}
@@ -126,7 +111,7 @@ var line = {
126111
_getLine(lineId, cb, prefix = 'nz-akl') {
127112
const sqlRequest = connection.get().request()
128113
sqlRequest.input('prefix', sql.VarChar(50), prefix)
129-
sqlRequest.input('version', sql.VarChar(50), cache.currentVersion())
114+
sqlRequest.input('version', sql.VarChar(50), cache.currentVersion(prefix))
130115
sqlRequest.input('route_short_name', sql.VarChar(50), lineId)
131116
sqlRequest.query(`
132117
SELECT
@@ -210,61 +195,18 @@ var line = {
210195
})
211196
})
212197
},
213-
getShapeFromAt(arrayOfShapeId, cb) {
214-
if (arrayOfShapeId.length === 0) {
215-
return
216-
}
217-
218-
var newOpts = JSON.parse(JSON.stringify(shapeWKBOptions))
219-
let shape_id = arrayOfShapeId[0]
220-
newOpts.url += shape_id
221-
request(newOpts, function(err, response, body) {
222-
if (err) {
223-
console.warn(err)
224-
console.log(`${shape_id} : Failed to get Shape`)
225-
return line.getShapeFromAt(arrayOfShapeId.slice(1), cb)
198+
getShapeJSON: function(req, res) {
199+
let prefix = req.params.prefix
200+
const containerName = encodeURIComponent((prefix+'-'+cache.currentVersion(prefix)).replace('_','-').replace('.','-'))
201+
const shape_id = req.params.shape_id
202+
const fileName = encodeURIComponent(shape_id+'.json')
203+
blobSvc.getBlobToStream(containerName, fileName, res, function(blobError) {
204+
if (blobError) {
205+
res.status(404)
226206
}
227-
228-
// if AT doesn't send back a shape
229-
let wkb = JSON.parse(body).response
230-
if (wkb.length < 1) {
231-
console.log(`${shape_id} : Shape not found!`)
232-
return nextItem()
233-
}
234-
235-
let nextItem = function() {
236-
if (arrayOfShapeId.length === 1) {
237-
// only calls back the last shape, for immediate return
238-
if (cb) {
239-
cb(wkb)
240-
}
241-
return
242-
} else {
243-
return line.getShapeFromAt(arrayOfShapeId.slice(1), cb)
244-
}
245-
}
246-
247-
blobSvc.createBlockBlobFromText('shapewkb', shape_id, wkb[0].the_geom, function(blobErr, blobResult, blobResponse) {
248-
if (blobErr) {
249-
console.warn(blobErr)
250-
return nextItem()
251-
}
252-
nextItem()
253-
254-
// informs table storage that there is an item there
255-
var task = {
256-
PartitionKey: {'_': 'shapewkb'},
257-
RowKey: {'_': shape_id},
258-
date: {'_': new Date(), '$':'Edm.DateTime'}
259-
}
260-
tableSvc.insertOrReplaceEntity('meta', task, function (error) {
261-
if (error) {
262-
return console.warn(error)
263-
}
264-
console.log(`${shape_id} : Shape Saved from AT`)
265-
})
266-
})
267-
})
207+
res.end()
208+
return
209+
})
268210
},
269211

270212
exceptionCheck: function(route, bestMatchMode = false) {
@@ -352,41 +294,6 @@ var line = {
352294
req.params.trip_id = trip_id
353295
line.getStopsFromTrip(req, res)
354296
})
355-
},
356-
357-
cacheShapes: function(trips) {
358-
// makes a priority list
359-
let allShapes = {}
360-
trips.forEach(function(trip) {
361-
let shape = trip.shape_id
362-
if (shape in allShapes) {
363-
allShapes[shape] +=1
364-
} else {
365-
allShapes[shape] = 1
366-
}
367-
})
368-
// flattens to priority array
369-
let sorted = Object.keys(allShapes).sort(function(a, b) {
370-
return allShapes[b] - allShapes[a]
371-
}).map(function(sortedKey) {
372-
return sortedKey
373-
})
374-
let promises = []
375-
let requests = []
376-
sorted.forEach(function(shape) {
377-
promises.push(new Promise(function(resolve, reject) {
378-
tableSvc.retrieveEntity('meta', 'shapewkb', shape, function(err, result, response) {
379-
if (err) {
380-
requests.push(shape)
381-
}
382-
resolve()
383-
})
384-
}))
385-
})
386-
// after it sees if they exist, fire the cache
387-
Promise.all(promises).then(function() {
388-
line.getShapeFromAt(requests)
389-
})
390297
}
391298
}
392299

0 commit comments

Comments
 (0)