2020-02-20 13:08:13 +01:00
|
|
|
const express = require('express')
|
|
|
|
const app = express()
|
|
|
|
const axios = require('axios').default;
|
|
|
|
const fs = require('fs');
|
|
|
|
var mustacheExpress = require('mustache-express');
|
|
|
|
|
|
|
|
const port = 7659;
|
|
|
|
const apiKey = "trnsl.1.1.20200219T163804Z.dd385eb08e22b0a9.628dfdf2e50cf9faa61898cb7195740bb3ac3b86";
|
|
|
|
|
|
|
|
// Register '.mustache' extension with The Mustache Express
|
|
|
|
app.engine('mustache', mustacheExpress());
|
|
|
|
|
|
|
|
app.set('view engine', 'mustache');
|
|
|
|
app.set('views', __dirname + '/views');
|
|
|
|
|
|
|
|
app.use(express.urlencoded());
|
|
|
|
|
|
|
|
app.get('/', function(req, res) {
|
|
|
|
axios.get('https://translate.yandex.net/api/v1.5/tr.json/getLangs', {
|
|
|
|
params: {
|
|
|
|
key: apiKey
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.then(function (response) {
|
|
|
|
res.render('index', response.data)
|
|
|
|
})
|
|
|
|
.catch(function (error) {
|
|
|
|
data = {
|
|
|
|
error: error
|
|
|
|
};
|
|
|
|
res.render('error', data)
|
|
|
|
})
|
|
|
|
});
|
|
|
|
|
|
|
|
app.get('/css/:file', function(req, res) {
|
|
|
|
res.sendFile(__dirname + '/./css/' + req.params.file);
|
|
|
|
});
|
|
|
|
|
|
|
|
app.get('/result/:file', function(req, res) {
|
|
|
|
res.sendFile(__dirname + '/./result/' + req.params.file);
|
|
|
|
});
|
|
|
|
|
|
|
|
app.post('/', function(req, res) {
|
|
|
|
var filename = "/result/" + Math.floor(Date.now() / 1000) + ".json";
|
|
|
|
axios.get(req.body.sourceUrl)
|
|
|
|
.then(function (response) {
|
|
|
|
var json = response.data;
|
|
|
|
var result = {};
|
|
|
|
let promises = [];
|
|
|
|
for (var key in json) {
|
|
|
|
if (json.hasOwnProperty(key)) {
|
|
|
|
promises.push(
|
|
|
|
axios.get('https://translate.yandex.net/api/v1.5/tr.json/translate', {
|
|
|
|
params: {
|
|
|
|
key: apiKey,
|
|
|
|
lang: req.body.target,
|
|
|
|
text: json[key],
|
|
|
|
target: key
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.then(function (response) {
|
|
|
|
targetKey = response.request.path.match("(target=)(.+)")[2];
|
|
|
|
result[targetKey] = response.data.text[0]
|
|
|
|
})
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Promise.all(promises).then(function () {
|
|
|
|
fs.writeFile(__dirname + filename, JSON.stringify(result));
|
|
|
|
var data = {
|
|
|
|
'link': filename
|
|
|
|
}
|
|
|
|
res.render('result', data);
|
|
|
|
});
|
|
|
|
})
|
|
|
|
.catch(function (error) {
|
|
|
|
data = {
|
|
|
|
error: error
|
|
|
|
};
|
|
|
|
res.render('error', data)
|
|
|
|
})
|
|
|
|
});
|
|
|
|
|
|
|
|
app.listen(port, () => console.log(`App listening on port ${port}`))
|