forked from patrickjquinn/P-Brain.ai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
executable file
·164 lines (148 loc) · 4.96 KB
/
server.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
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http, { pingInterval: 2000, pingTimeout: 7000 });
const wrap = require('./api/wrap');
const compression = require('compression');
const search = require('./api/core-ask.js');
const skills = require('./skills/skills.js');
const settingsApi = require('./api/settings.js');
const usersApi = require('./api/users.js');
const cookieParser = require('cookie-parser');
global.auth = require('./authentication');
const Database = require('./db');
app.use(
compression({
threshold: 0,
level: 9,
memLevel: 9,
}),
);
app.use((req, res, next) => {
req.connection.setNoDelay(true);
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
next();
});
app.use(cookieParser());
app.get(
'/api/status',
wrap(async function(req, res) {
res.json({ status: 200, msg: 'OK' });
}),
);
app.use('/', [global.auth.filter(true), express.static('./src')]);
app.use('/api/settings', [global.auth.filter(false), settingsApi]);
app.use('/api/users', [global.auth.filter(false), usersApi]);
app.get(
'/api/user',
global.auth.filter(false),
wrap(async function(req, res) {
res.json(req.user);
}),
);
app.get(
'/api/token',
global.auth.filter(false),
wrap(async function(req, res) {
res.json(req.token);
}),
);
app.get(
'/api/status',
global.auth.filter(false),
wrap(async function(req, res) {
res.json({ status: 200, msg: 'OK' });
}),
);
// TODO parse services in query
app.get(
'/api/ask',
global.auth.filter(false),
wrap(async function(req, res) {
const input = req.query.q.toLowerCase();
try {
const result = await search.query(input, req.user, req.token);
res.json(result);
} catch (e) {
console.log(e);
res.json({ msg: { text: "Sorry, I didn't understand " + input }, type: 'error' });
}
}),
);
app.get('/api/login', global.auth.login);
app.get('/api/logout/:user?', [global.auth.filter(false), global.auth.logout]);
app.get('/api/tokens/:user?', [global.auth.filter(false), global.auth.viewTokens]);
app.get('/api/validate', [global.auth.filter(false), global.auth.validate]);
io.use(global.auth.verifyIO);
io.on('connect', socket => {
socket.on('ask', function(msg) {
search
.query(msg, socket.user, socket.token)
.then(result => {
socket.emit('response', result);
})
.catch(err => {
console.log(err);
socket.emit('response', {
msg: { text: "Sorry, I didn't understand " + msg.text.toLowerCase() },
type: 'error',
});
});
});
skills.registerClient(socket, socket.user).catch(err => {
console.warn('Failed to register client', err);
});
});
async function initialSetup() {
if ((await global.db.getGlobalValue('port')) == null) {
console.log('Setting default global values in database');
await global.db.setGlobalValue('port', 4567);
await global.db.setGlobalValue('promiscuous_mode', true);
await global.db.setGlobalValue('promiscuous_admins', true);
}
}
async function main() {
console.log('Setting up database.');
global.db = await Database.setup();
await initialSetup();
global.sendToUser = function(user, type, message) {
const sockets = global.auth.getSocketsByUser(user);
sockets.map(socket => {
socket.emit(type, message);
});
};
global.sendToDevice = function(token, type, message) {
const socket = global.auth.getSocketByToken(token);
if (socket) {
socket.emit(type, message);
} else {
console.log('Failed to send to device: ' + JSON.stringify(token));
}
};
console.log('Loading skills.');
await skills.loadSkills();
console.log('Training recognizer.');
await search.train_recognizer(skills.getSkills());
console.log('Starting server.');
const port = await global.db.getGlobalValue('port');
http.listen(port, () => {
console.log(`Server started on http://localhost:${port}`);
});
const promiscuous = await global.db.getGlobalValue('promiscuous_mode');
const promiscuous_admins = await global.db.getGlobalValue('promiscuous_admins');
if (promiscuous) {
console.log('Warning! Promiscuous mode is enabled all logins will succeed.');
if (promiscuous_admins) {
console.log(
'Possibly deadly warning! Promiscuous admins is enabled.' +
' All new users will be admins and can view each others data.',
);
}
console.log(`Settings can be changed at http://localhost:${port}/settings.html`);
}
}
main().catch(err => {
console.log(err);
process.exit(1);
});