-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChat.lua
248 lines (216 loc) · 5.49 KB
/
Chat.lua
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
local json = require("json")
local sqlite3 = require('lsqlite3')
ChatDb = ChatDb or sqlite3.open_memory()
ChatDbAdmin = ChatDbAdmin or require('DbAdmin').new(ChatDb)
--#region Initialization
SQLITE_TABLE_CHAT_MESSAGES = [[
CREATE TABLE IF NOT EXISTS Messages (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
MessageId TEXT UNIQUE NOT NULL,
Timestamp INTEGER NOT NULL,
AuthorId TEXT NOT NULL,
AuthorName TEXT DEFAULT NULL,
Recipient TEXT DEFAULT NULL,
Content TEXT
);
]]
function ChatDbInit()
ChatDb:exec(SQLITE_TABLE_CHAT_MESSAGES)
end
ChatInitialized = ChatInitialized or false
if (not ChatInitialized) then
ChatDbInit()
ChatInitialized = true
end
--#endregion
function ValidateAuthorName(authorName)
if (authorName == nil) then
return false
end
if (string.len(authorName) < 1) then
return false
end
if (string.len(authorName) > 20) then
return false
end
return true
end
function ValidateContent(content)
if (content == nil) then
return false
end
if (string.len(content) < 1) then
return false
end
if (string.len(content) > 1000) then
return false
end
-- Note: Input sanitization is not performed here, but by the bind function
return true
end
Handlers.add(
"ChatMessage",
Handlers.utils.hasMatchingTag("Action", "ChatMessage"),
function(msg)
-- print("ChatMessage")
local messageId = msg.Id
local timestamp = msg.Timestamp
local authorId = msg.From
local authorName = msg.Tags['Author-Name']
local recipient = msg.Tags['Recipient']
local content = msg.Data
-- Validate AuthorName
if (not ValidateAuthorName(authorName)) then
return print("Invalid Author Name")
end
-- Validate Content
if (not ValidateContent(content)) then
return print("Invalid Content")
end
-- Save message
local stmt = ChatDb:prepare([[
INSERT INTO Messages (MessageId, Timestamp, AuthorId, AuthorName, Recipient, Content)
VALUES (?, ?, ?, ?, ?, ?)
]])
stmt:bind_values(messageId, timestamp, authorId, authorName, recipient, content)
stmt:step()
stmt:finalize()
return print("Message saved")
end
)
function ValidateId(testId)
if (testId == nil) then
-- Allow nil ids
return true
end
if (type(testId) ~= "number") then
return false
end
if (testId < 0) then
return false
end
return true
end
function ValidateTimestamp(testTimestamp)
if (testTimestamp == nil) then
-- Allow nil timestamps
return true
end
if (testTimestamp < 0) then
return false
end
return true
end
function ValidateLimit(testLimit)
if (testLimit == nil) then
-- Allow nil limits
return true
end
if (testLimit < 1) then
return false
end
if (testLimit > 100) then
return false
end
return true
end
Handlers.add(
'ChatCount',
Handlers.utils.hasMatchingTag('Action', 'ChatCount'),
function(msg)
-- print("ChatCount")
local stmt = ChatDb:prepare("SELECT COUNT(*) FROM Messages")
stmt:step()
local count = stmt:get_value(0)
stmt:finalize()
Send({
Target = msg.From,
Tags = {
Action = 'ChatCountResponse',
},
Data = tostring(count)
})
end
)
Handlers.add(
"ChatHistory",
Handlers.utils.hasMatchingTag("Action", "ChatHistory"),
function(msg)
-- print("ChatHistory")
local idAfter = tonumber(msg.Tags['Id-After'])
local idBefore = tonumber(msg.Tags['Id-Before'])
local timestampStart = tonumber(msg.Tags['Timestamp-Start'])
local timestampEnd = tonumber(msg.Tags['Timestamp-End'])
local limit = tonumber(msg.Tags['Limit'])
-- Validate individual Ids
if (not ValidateId(idAfter)) then
return print("Invalid Id Start")
end
if (not ValidateId(idBefore)) then
return print("Invalid Id End")
end
-- Validate Ids range
if (idAfter ~= nil
and idBefore ~= nil
and idAfter > idBefore) then
return print("Invalid Id Range")
end
-- Validate Individual Timestamps
if (not ValidateTimestamp(timestampStart)) then
return print("Invalid Timestamp Start")
end
if (not ValidateTimestamp(timestampEnd)) then
return print("Invalid Timestamp End")
end
-- Validate timestamp range
if (timestampStart ~= nil
and timestampEnd ~= nil
and timestampStart > timestampEnd) then
return print("Invalid Timestamp Range")
end
-- Query messages
-- Any variable maybe be nil
-- Ids are EXclusive
-- Timestamps are INclusive
-- Most recent first
-- Default limit is 100
local stmt = ChatDb:prepare([[
SELECT * FROM Messages
WHERE (Id > ? OR ? IS NULL)
AND (Id < ? OR ? IS NULL)
AND (Timestamp >= ? OR ? IS NULL)
AND (Timestamp <= ? OR ? IS NULL)
ORDER BY Timestamp DESC
LIMIT ?
]])
stmt:bind_values(
idAfter, idAfter,
idBefore, idBefore,
timestampStart, timestampStart,
timestampEnd, timestampEnd,
limit or 100
)
local messages = {}
for row in stmt:nrows() do
table.insert(messages, {
Id = row.Id,
MessageId = row.MessageId,
Timestamp = row.Timestamp,
AuthorId = row.AuthorId,
AuthorName = row.AuthorName,
Recipient = row.Recipient,
Content = row.Content
})
end
stmt:finalize()
-- Reply with messages
Send({
Target = msg.From,
Tags = {
Action = "ChatHistoryResponse",
},
Data = json.encode(messages)
})
end
)
return "Loaded Chat Protocol"