/
node_helper.js
98 lines (79 loc) · 3.31 KB
/
node_helper.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
97
98
const NodeHelper = require('node_helper');
const translate = require('google-translate-api');
const bodyParser = require('body-parser');
const axios = require('axios').default;
module.exports = NodeHelper.create({
start: function () {
console.log(this.name + ' helper started');
this.handleApiRequest();
this.quoteConfig = {}
},
getNewQuote: function () {
let self = this;
let needToTranslate = this.needToTranslate(this.quoteConfig.language);
self.url = this.quoteConfig.url;
self.language = needToTranslate ? "en" : this.quoteConfig.language;
axios.get(self.url, {
params: {
lang: self.language
}
})
.then(function (response) {
console.log(response);
self.returned_data = response.data;
if (needToTranslate) {
translate(self.returned_data.quoteText, {
to: self.language
}).then(res => {
// console.log(res.text);
self.returned_data.quoteText = res.text;
self.sendSocketNotification('QUOTE_RESULT', self.returned_data);
}).catch(err => {
console.error(err);
self.sendSocketNotification('QUOTE_RESULT', self.returned_data);
});
} else {
// return the quote directly without translating it
self.sendSocketNotification('QUOTE_RESULT', self.returned_data);
}
})
.catch(function (error) {
console.log(error);
});
},
socketNotificationReceived: function (notification, payload) {
let self = this;
console.log(this.name + " received a socket notification: " + notification + " - Payload: " + payload);
if (notification === 'INIT_HELPER') {
this.quoteConfig = payload
}
if (notification === 'GET_QUOTE') {
this.getNewQuote();
}
},
handleApiRequest: function () {
this.expressApp.use(bodyParser.json()); // support json encoded bodies
this.expressApp.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
this.expressApp.post('/quote-of-the-day', (req, res) => {
if (req.body.notification && req.body.notification === "QUOTE-OF-THE-DAY"){
if (req.body.payload){
let payload = req.body.payload;
console.log("[MMM-quote-of-the-day] payload received: " + payload);
if (payload === "getNewQuote") {
this.getNewQuote();
res.send({"status": "success"});
}else{
res.send({"status": "failed", "error": "non recognized payload"});
}
}else{
res.send({"status": "failed", "error": "No payload given."});
}
}else{
res.send({"status": "failed", "error": "No notification given."});
}
});
},
needToTranslate: function(language) {
return !(language == "en" || language == "ru");
}
});