-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
171 lines (151 loc) · 4.21 KB
/
server.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
import express from 'express';
import { createServer, type Server as HTTPServer } from 'http';
import { Server as SocketIOServer } from 'socket.io';
import { config } from '~/lib/config';
import { randomUUID } from '~/lib/utils';
import debug from 'debug'
import { NexaiChatMessage } from '~/chat-types';
const log = debug('nexai:server')
export type IoChatMsg = {
userUid: string;
projectId: string;
sessionKey: string;
message: string;
fromName: string;
toName: string;
sources?: string[];
aiMuted?: boolean;
avatarUrl?: string;
email?: string;
}
const PORT: number = parseInt(process.env.PORT as string, 10) || 8080;
const app: express.Application = express();
const server: HTTPServer = createServer(app);
const io = new SocketIOServer(server, {
cors: {
origin: "*",
},
});
const apiUrl = config.nexaiLocalApiUrl
// app.get('/', (_: Request, res: Response) => {
// res.sendFile(join(process.cwd(), 'index.html'));
// });
type AiApiResponse = { message: NexaiChatMessage, sources: string[] }
const sendChatToAi = async (msg: IoChatMsg) => {
const url = `${apiUrl}/chat`
log('sendChattoAi', { url, msg })
const resp = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
fromName: msg.fromName,
message: msg.message,
sessionId: msg.sessionKey,
projectId: msg.projectId
})
})
if (resp.ok) {
return await resp.json() as AiApiResponse
} else {
throw new Error('Failed to get AI chat response')
}
}
const sendSupportChat = async (msg: IoChatMsg) => {
const resp = await fetch(`${apiUrl}/chat/support`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userUid: 'support',
fromName: msg.fromName,
message: msg.message,
sessionId: msg.sessionKey,
projectId: msg.projectId
})
})
if (resp.ok) {
return await resp.json()
} else {
throw new Error('Failed to get support chat response')
}
}
const sessions = io.of(/^\/session\/\w+$/);
sessions.on("connection", socket => {
const session = socket.nsp;
log('session', session.name)
// socket.emit('chat', {
// uid: 'chat.hello',
// message: "hello from session " + session.name,
// fromName: "server"
// });
let sentEmailReq = false
socket.on('chat', async (msg: IoChatMsg) => {
log('session received chat', msg)
const chatMsg = {
...msg,
sessionId: msg.sessionKey, // @todo fix
createdAt: new Date(),
updatedAt: new Date()
}
if (!msg.email && !sentEmailReq) {
sentEmailReq = true
session.emit('chat', {
...chatMsg,
uid: randomUUID(),
userUid: 'nexai',
message: '💁 Provide an email if you need the team to reach out to you.',
})
}
session.emit('chat', chatMsg)
io.of('/project/' + msg.projectId).emit('chat', chatMsg)
try {
const resp = await sendChatToAi(msg)
log('ai resp', resp)
const aiMsg = {
...resp.message,
uid: randomUUID(),
userUid: 'nexai',
sources: resp.sources,
sessionKey: msg.sessionKey,
} as IoChatMsg
session.emit('chat', aiMsg)
io.of('/project/' + msg.projectId).emit('chat', aiMsg)
} catch(e) {
console.error(e)
}
})
});
const projects = io.of(/^\/project\/\w+$/);
projects.on("connection", socket => {
const project = socket.nsp;
log('project', project.name)
// socket.emit('chat', {
// uid: 'project.hello',
// message: "hello from project " + project.name,
// fromName: "server"
// });
socket.on('chat', async (msg: IoChatMsg) => {
const chatMsg = {
...msg,
sessionId: msg.sessionKey, // @todo fix
createdAt: new Date(),
updatedAt: new Date()
}
log('project received chat', chatMsg)
project.emit('chat', chatMsg)
log('emit', '/session/' + msg.sessionKey, chatMsg)
io.of('/session/' + msg.sessionKey).emit('chat', chatMsg)
try {
const resp = await sendSupportChat(chatMsg)
log('resp', resp)
} catch(e) {
console.error(e)
}
})
});
server.listen(PORT, () => {
console.log(`⛵ Nexai Chat Server at http://localhost:${PORT}`);
});