-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathapp.js
172 lines (133 loc) · 4.64 KB
/
app.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
let express = require('express');
let chalk = require('chalk');
let bodyParser = require('body-parser');
let request = require('request');
let path = require('path');
let http = require('http');
const port = process.env.PORT || 3000;
let app = express();
let chatbot = null;
let methodOverride = require('method-override');
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/style', express.static(path.join(__dirname, '/views/style')));
app.use('/img', express.static(path.join(__dirname, '/views/img')));
app.use('/js', express.static(path.join(__dirname, '/views/js')));
app.get('/', (req, res) => {
res.render('index.html');
})
app.post('/api/conversation', (req, res) => {
res.setHeader('Content-Type', 'application/json');
const configurations = req.body.configurations;
switch (configurations['type']) {
case 'Built-in-Conversation':
builtInConversation(req, res);
break;
case 'Api-Key':
case 'Custom-Conversation':
customConversation(req, res);
break;
case 'Node-Red':
nodeRed(req, res);
break;
}
})
const processChatMessage = (req, res, bot) => {
bot.sendMessage(req, (err, data) => {
if (err) {
console.log("Error in sending message: ", err);
res.status(err.code || 500).json(err);
} else {
console.log('Got response: ', JSON.stringify(data));
res.status(200).json(data);
}
});
}
const builtInConversation = (req, res) => {
console.log('Built in conversation api invoked method..');
const configurations = req.body.configurations;
const params = req.body.params;
if (chatbot != null && chatbot.isInitialized()) {
processChatMessage(req, res, chatbot);
} else {
chatbot = require('./config/bot.js');
chatbot.init(response => {
if (!response.error) {
processChatMessage(req, res, chatbot);
} else {
errorResponse(res, 500, 'Internal server error');
}
})
}
}
const customConversation = (req, res) => {
console.log('Custom conversation method invoked..');
const configurations = req.body.configurations;
const params = req.body.params;
let authentication_key;
let authorization_header;
if(configurations.type == 'Api-Key'){
authentication_key = new Buffer(`apikey:${configurations['api_key']}`).toString('base64');
authorization_header = `Basic ${authentication_key}`;
} else {
authentication_key = new Buffer(`${configurations['username']}:${configurations['password']}`).toString('base64');
authorization_header = `Basic ${authentication_key}`;
}
let options = {
url: `https://gateway.watsonplatform.net/assistant/api/v1/workspaces/${configurations['workspace_id']}/message?version=2018-09-20`,
method: 'POST',
headers: {
'Authorization': authorization_header,
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
}
request(options, (error, response, body) => {
if (!error && response.statusCode == 200) {
res.status(200).json(JSON.parse(body));
} else {
res.status(400).json({ error: true })
}
})
}
const nodeRed = (req, res) => {
console.log('Node red method invoked..');
const configurations = req.body.configurations;
const params = req.body.params;
const postData = {
params: params
}
let options = {
url: configurations['url'],
method: 'POST',
json: true,
headers: {
'Content-Type': 'application/json'
},
body: postData
}
request(options, (error, response, body) => {
if (!error && response.statusCode == 200) {
console.log('Got response from Node-Red..');
res.status(200).json(body);
} else {
console.log('Node red error');
console.log(error);
res.status(500).json({ error: true });
}
})
}
const errorResponse = (res, statusCode, message) => {
res.status(statusCode).json({ error: true, description: message, statusCode });
}
http.createServer(app).listen(app.get('port'), '0.0.0.0', function () {
console.log(chalk.cyan('Express server listening on port ' + app.get('port')));
})