forked from mashirozx/google-translate-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
96 lines (85 loc) · 2.43 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
const translate = require("google-translate-cn-api");
const stdio = require("stdio");
const express = require("express");
const date = require("date-and-time");
const bodyParser = require('body-parser');
const he = require('he');
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}))
// parse application/json
app.use(bodyParser.json())
const ops = stdio.getopt({
port: {
key: "p",
args: 1,
description: "running port",
default: 30031
},
domain: {
key: "d",
args: 1,
description: "google translate port",
default: "com",
},
});
const port = parseInt(ops.port);
const domain = ops.domain;
// log functionalities
const timeFormat = date.compile("YYYY/MM/DD HH:mm:ss");
const prettyJson = (object) =>
JSON.stringify(object)
.replace(/"/g, "")
.replace(/([,:])/g, "$1 ");
function log(req, text, status) {
const now = date.format(new Date(), timeFormat);
let ip = req.connection.remoteAddress;
const params = prettyJson(req.query);
console.log(`${now} [${ip}] ${status} "${text}" ${params}`);
}
// express server
app.get("/", function (req, res) {
const text = he.decode(req.query.text);
// delete req.query.text;
translate(text, {
...{
domain: domain
},
...req.query
})
.then((resp) => res.json(resp) && log(req, text, 200))
.catch((resp) => res.status(400).json(resp) && log(req, text, 400));
});
function logPost(req, text, status) {
const now = date.format(new Date(), timeFormat);
let ip = req.connection.remoteAddress;
const params = prettyJson(req.body);
console.log(`${now} [${ip}] ${status} "${text}" ${params}`);
}
app.post("/", function (req, res) {
const text = he.decode(req.body.text);
// delete req.body.text;
translate(text, {
...{
domain: domain
},
...req.body
})
.then((resp) => res.json(resp) && logPost(req, text, 200))
.catch((resp) => res.status(400).json(resp) && logPost(req, text, 400));
});
app.listen(port, function () {
console.log(
"\n ___ _____ ___\n" +
" / __|_ _| / __| ___ _ ___ _____ _ _\n" +
" | (_ | | | \\__ \\/ -_) '_\\ V / -_) '_|\n" +
" \\___| |_| |___/\\___|_| \\_/\\___|_|\n\n"
);
console.log(`App listening on port ${port}!`);
console.log(
`Default Google Translate domain: https://translate.google.${domain}/`
);
console.log("Incoming requests will be listed below:\n");
});