-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
executable file
·210 lines (174 loc) · 6.75 KB
/
Copy pathapp.js
File metadata and controls
executable file
·210 lines (174 loc) · 6.75 KB
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/**
* Copyright 2015 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var express = require('express'),
app = express(),
pkg = require('./package.json'),
Q = require('q'),
fs = require('fs'),
watson = require('watson-developer-cloud');
// Bootstrap application settings
require('./config/express')(app);
var log = console.log.bind(null, ' ');
var conversation;
var discovery;
var serviceCredentials;
var intentConfidence;
var allowCrossDomain = function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
};
app.use(allowCrossDomain);
// set credentials from bluemix or local .env file
if (process.env.VCAP_SERVICES) {
console.log("setting vcap services");
var services = JSON.parse(process.env.VCAP_SERVICES);
serviceCredentials = null;
conversation = new watson.ConversationV1({
url: services.conversation[0].credentials.url || 'https://gateway.watsonplatform.net/conversation/api',
username: services.conversation[0].credentials.username || '<username>',
password: services.conversation[0].credentials.password || '<password>',
version_date: process.env.conversation_version,
version: 'v1'
});
discovery = new watson.DiscoveryV1({
url: services.discovery[0].credentials.url || 'https://gateway.watsonplatform.net/discovery/api',
username: services.discovery[0].credentials.username || '<username>',
password: services.discovery[0].credentials.password || '<password>',
version_date: process.env.discovery_version
});
intentConfidence = process.env.intent_confidence;
} else {
// load the environment variables - for local testing
if (fs.existsSync('./.env.js')) {
Object.assign(process.env, require('./.env.js'));
}
serviceCredentials = JSON.parse(process.env.VCAP_SERVICES);
conversation = new watson.ConversationV1({
url: serviceCredentials.conversation[0].credentials.url || 'https://gateway.watsonplatform.net/conversation/api',
username: serviceCredentials.conversation[0].credentials.username || '<username>',
password: serviceCredentials.conversation[0].credentials.password || '<password>',
version_date: process.env.conversation_version,
version: 'v1'
});
discovery = new watson.DiscoveryV1({
url: serviceCredentials.discovery[0].credentials.url || 'https://gateway.watsonplatform.net/discovery/api',
username: serviceCredentials.discovery[0].credentials.username || '<username>',
password: serviceCredentials.discovery[0].credentials.password || '<password>',
version_date: process.env.discovery_version
});
intentConfidence = .75;
}
// main endpoint
var previousContext = null;
app.post('/api/message', function (req, res) {
var workspace = process.env.workspace_id;
if (!workspace) {
return res.json({
'output': {
'text': 'The app has not been configured with a <b>WORKSPACE_ID</b> environment variable. Please refer to the ' +
'<a href="https://github.com/watson-developer-cloud/conversation-simple">README</a> documentation on how to set this variable. <br>' +
'Once a workspace has been defined the intents may be imported from ' +
'<a href="https://github.com/watson-developer-cloud/conversation-simple/blob/master/training/car_workspace.json">here</a> in order to get a working application.'
}
});
}
var payload = {
workspace_id: workspace,
context: {},
input: {}
};
if (req.body) {
if (req.body.input) {
payload.input = req.body.input;
}
if (req.body.context) {
// The client must maintain context/state
payload.context = req.body.context;
}
}
if (!payload.context) {
payload.context = previousContext;
}
(function () {
var deferred = Q.defer();
conversation.message(payload, function (err, data) {
if (err) {
console.log("ERROR");
console.log(err);
return res.status(err.code || 500).json(err);
}
deferred.resolve(data);
})
return deferred.promise;
})().then(function (data) {
if(data.intents.length > 0 && data.intents[0].intent == "subject_filter") {
// return discovery data
var response = {
"input": {"text": req.body.input.text},
"context": data.context,
"output": {"text": []}
};
var version_date = process.env.discovery_version;
var environment_id = process.env.environment_id;
var collection_id = process.env.collection_id;
discovery.query({
version_date: version_date,
environment_id: environment_id,
collection_id: collection_id,
query: req.body.input.text,
count: 10
},
(err, data) => {
if (err) {
console.log("Error: ");
console.log(err);
return res.status(err.code || 500).json(err);
}
if (data.results.length > 0) {
var randomInt = Math.floor(Math.random() * data.results.length/2);
var firstResult = data.results[randomInt];
// Find a new article if a field is missing to prevent crash
while(firstResult.date === undefined || firstResult.title === undefined) {
randomInt = Math.floor(Math.random() * data.results.length/2);
firstResult = data.results[randomInt];
}
var splitDate = firstResult.date.split('-');
splitDate[2] = splitDate[2].slice(0, 2);
var joinedDate = splitDate.join("/");
var title = firstResult.title.toLowerCase().split(' ').join('_');
response.output.text.push(`<a href="https://poly.rpi.edu/${joinedDate}/${title}/">` + firstResult.title + "</a>");
}
else {
response.output.text.push("I cannot find an answer to your question.");
}
return res.json(response);
}
);
}
else {
return res.json(data);
}
});
});
// error-handler application settings
require('./config/error-handler')(app);
var port = process.env.PORT || 3000;
//var host = process.env.VCAP_APP_HOST || 'localhost';
app.listen(port);
//console.log(pkg.name + ':' + pkg.version, host + ':' + port);