forked from juice-shop/juice-shop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatbot.ts
216 lines (190 loc) · 5.94 KB
/
chatbot.ts
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
211
212
213
214
215
216
/*
* Copyright (c) 2014-2021 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const { Bot } = require('juicy-chat-bot')
const security = require('../lib/insecurity')
const jwt = require('jsonwebtoken')
const utils = require('../lib/utils')
const botUtils = require('../lib/botUtils')
const config = require('config')
import fs = require('fs')
const download = require('download')
const models = require('../models/index')
const challenges = require('../data/datacache').challenges
let trainingFile = config.get('application.chatBot.trainingData')
let testCommand, bot
async function initialize () {
if (utils.startsWith(trainingFile, 'http')) {
const file = utils.extractFilename(trainingFile)
const data = await download(trainingFile)
fs.writeFileSync('data/chatbot/' + file, data)
}
fs.copyFileSync(
'data/static/botDefaultTrainingData.json',
'data/chatbot/botDefaultTrainingData.json'
)
trainingFile = utils.extractFilename(trainingFile)
const trainingSet = fs.readFileSync(`data/chatbot/${trainingFile}`, 'utf8')
require('../lib/startup/validateChatBot')(JSON.parse(trainingSet))
testCommand = JSON.parse(trainingSet).data[0].utterances[0]
bot = new Bot(config.get('application.chatBot.name'), config.get('application.chatBot.greeting'), trainingSet, config.get('application.chatBot.defaultResponse'))
return bot.train()
}
initialize()
async function processQuery (user, req, res) {
const username = user.username
if (!username) {
res.status(200).json({
action: 'namequery',
body: 'I\'m sorry I didn\'t get your name. What shall I call you?'
})
return
}
if (!bot.factory.run(`currentUser('${user.id}')`)) {
bot.addUser(`${user.id}`, username)
res.status(200).json({
action: 'response',
body: bot.greet(`${user.id}`)
})
return
}
if (bot.factory.run(`currentUser('${user.id}')`) !== username) {
bot.addUser(`${user.id}`, username)
}
if (!req.body.query) {
res.status(200).json({
action: 'response',
body: bot.greet(`${user.id}`)
})
return
}
try {
const response = await bot.respond(req.body.query, user.id)
if (response.action === 'function') {
if (response.handler && botUtils[response.handler]) {
res.status(200).json(await botUtils[response.handler](req.body.query, user))
} else {
res.status(200).json({
action: 'response',
body: config.get('application.chatBot.defaultResponse')
})
}
} else {
res.status(200).json(response)
}
} catch (err) {
try {
await bot.respond(testCommand, user.id)
res.status(200).json({
action: 'response',
body: config.get('application.chatBot.defaultResponse')
})
} catch (err) {
utils.solveIf(challenges.killChatbotChallenge, () => { return true })
res.status(200).json({
action: 'response',
body: 'Oh no... Remember to stay hydrated when I\'m gone...'
})
}
}
}
function setUserName (user, req, res) {
models.User.findByPk(user.id).then(user => {
user.update({ username: req.body.query }).then(newuser => {
newuser = utils.queryResultToJson(newuser)
const updatedToken = security.authorize(newuser)
security.authenticatedUsers.put(updatedToken, newuser)
bot.addUser(`${newuser.id}`, req.body.query)
res.status(200).json({
action: 'response',
body: bot.greet(`${newuser.id}`),
token: updatedToken
})
})
})
}
module.exports.initialize = initialize
module.exports.bot = bot
module.exports.status = function status () {
return async (req, res, next) => {
if (!bot) {
res.status(200).json({
status: false,
body: `${config.get('application.chatBot.name')} isn't ready at the moment, please wait while I set things up`
})
return
}
const token = req.cookies.token || utils.jwtFrom(req)
if (token) {
const user = await new Promise((resolve, reject) => {
jwt.verify(token, security.publicKey, (err, decoded) => {
if (err !== null) {
res.status(401).json({
error: 'Unauthenticated user'
})
} else {
resolve(decoded.data)
}
})
})
if (!user) {
return
}
const username = user.username
if (!username) {
res.status(200).json({
action: 'namequery',
body: 'I\'m sorry I didn\'t get your name. What shall I call you?'
})
return
}
bot.addUser(`${user.id}`, username)
res.status(200).json({
status: bot.training.state,
body: bot.training.state ? bot.greet(`${user.id}`) : `${config.get('application.chatBot.name')} isn't ready at the moment, please wait while I set things up`
})
return
}
res.status(200).json({
status: bot.training.state,
body: `Hi, I can't recognize you. Sign in to talk to ${config.get('application.chatBot.name')}`
})
}
}
module.exports.process = function respond () {
return async (req, res, next) => {
if (!bot) {
res.status(200).json({
action: 'response',
body: `${config.get('application.chatBot.name')} isn't ready at the moment, please wait while I set things up`
})
}
const token = req.cookies.token || utils.jwtFrom(req)
if (!bot.training.state || !token) {
res.status(400).json({
error: 'Unauthenticated user'
})
return
}
const user = await new Promise((resolve, reject) => {
jwt.verify(token, security.publicKey, (err, decoded) => {
if (err !== null) {
res.status(401).json({
error: 'Unauthenticated user'
})
} else {
resolve(decoded.data)
}
})
})
if (!user) {
return
}
if (req.body.action === 'query') {
await processQuery(user, req, res)
} else if (req.body.action === 'setname') {
setUserName(user, req, res)
}
}
}