File size: 1,982 Bytes
5893f8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Created by isuru on 3/16/17.
 */
var express = require('express');
var request = require('request');
var config = require('../conf/config.json');
var stations = require('../stations.json');
var buffer = require('buffer');
var moment = require('moment');

var router = express.Router();

router.get('/', function (req, res, next) {

    if (!config.TOKEN ||
        config.TOKEN && moment(Date.now()).diff(moment(config.TOKEN.timestamp), 'seconds') > (config.TOKEN.expires_in - 30)) {
        getCredentials(req, res, getData);
    } else {
        getData(req, res);
    }
});

function getCredentials(req, res, next) {
    var key = config.CONSUMER_KEY + ':' + config.CONSUMER_SECRET;
    var auth = 'Basic ' + buffer.Buffer.from(key).toString('base64');
    var authBody = "grant_type=client_credentials";

    request({
        uri: "http://api.lankagate.gov.lk:8280/token",
        method: "POST",
        headers: {
            Authorization: auth,
            'Content-Length': authBody.length,
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: authBody
    }, function (error, response, body) {
        if (!error) {
            config.TOKEN = body;
            config.TOKEN.timestamp = Date.now();
            next(req, res);
        } else {
            res.sendStatus(500);
        }

    });
}

function getData(req, res) {
    var token = JSON.parse(config.TOKEN);
    request({
        uri: "http://api.lankagate.gov.lk:8280/railway/1.0/train/searchTrain?startStationID=" + req.query.from + "&endStationID=" +
            req.query.to + "&searchDate=" + req.query.date + "&startTime=00:00:00&endTime=23:59:00&lang=en",
        method: "GET",
        headers: {
            Authorization: 'Bearer ' + token.access_token
        },
        timeout: 10000,
        followRedirect: true,
        maxRedirects: 10
    }, function (error, response, body) {
        res.type('json').send(body);
    });
}

module.exports = router;