-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtranslates.js
53 lines (44 loc) · 1.4 KB
/
translates.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
/**
* This translator using Google Translate free services
* It's better if you switch to the paid API of Google Services
* Or use your own implementation
*/
var _ = null;
var transTimer = 0;
var timerSet = new Set();
var resetTimer = null
var translate = null;
var options = null;
var left = 0;
module.exports = function(from, target, text, callback){
if(translate === null){
_ = require('lodash');
resetTimer = _.debounce(function(){transTimer = 0}, 2000);
translate = require('@vitalets/google-translate-api');
}
if(target.indexOf('zh_') !== -1)
target = target.replace('_', '-');
var timer = setTimeout(function(){
process.stdout.write("\r\033[K[sf-lang] Translating ("+target+"): "+text.slice(0, 8)+'...');
translate(text, {
from: from.split('_')[0],
to: target.split('_')[0]
}, options).then(function(res){
if(res.text === text)
res.text += ''; // Add empty character for marking
callback(res.text);
timerSet.delete(timer);
process.stdout.write("\r\033[K[sf-lang] Translated ("+target+"): "+text.slice(0, 8)+'...');
if(timerSet.size === 0)
process.stdout.write("\r\033[K[sf-lang] Translation finished\n");
}).catch(function(err){
callback(text);
console.error("\nCan't translate:", target, err.message);
for(var val of timerSet.values())
clearTimeout(val);
timerSet.clear();
});
}, 2000*(transTimer++));
timerSet.add(timer);
resetTimer();
}