-
Notifications
You must be signed in to change notification settings - Fork 10
/
server.coffee
336 lines (279 loc) · 9.78 KB
/
server.coffee
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
App = require 'app'
Comments = require 'comments'
Db = require 'db'
Event = require 'event'
Timer = require 'timer'
Util = require 'util'
{tr} = require 'i18n'
questions = Util.questions()
userCnt = App.userIds().length
topCnt = Math.min(3, userCnt-1)
exports.onInstall = exports.onConfig = (config) !->
Db.shared.set 'adult', config.adult if config?
if !Db.shared.get('rounds')
newRound()
else if maxId = Db.shared.get('rounds', 'maxId')
if Db.shared.get('rounds', maxId, 'results')?
newRound() # newest round should always be open (otherwise questions depleted)
###
exports.technicalIssue = !->
Event.create
text: 'No results problem fixed, our apologies!'
###
exports.onUpgrade = !->
log 'onUpgrade'
if !Db.shared.get('rounds')
newRound()
else
# (run-once!) test for borked rounds; when the case, trigger delayed notification
###
if (maxId = Db.shared.get('rounds', 'maxId'))
for id in [maxId..1]
if 1441206000 < Db.shared.get('rounds', id, 'time') < 1441375000
log 'had a round during issue-window'
Timer.set 3*3600*1000, 'technicalIssue'
break
###
# Restart ranking games that exhausted all questions
maxId = Db.shared.get('rounds', 'maxId')
lastRoundTime = Db.shared.get('rounds', maxId, 'time')
if !Db.shared.get('questionIds') and lastRoundTime > 0 and lastRoundTime < (App.time() - 24*60*60)
#newRound()
log 'schedule new round restart'
Timer.set(Math.floor(Math.random()*6*3600*1000), 'newRound')
# restart somewhere the next 6 hours
### done
if curId = Db.shared.get('rounds', 'maxId')
curRoundTime = Db.shared.get('rounds', curId, 'time')
roundDuration = Util.getRoundDuration(curRoundTime)
stillDuration = curRoundTime+roundDuration-App.time()
if stillDuration <= 0
newRound()
else
Timer.cancel()
Timer.set stillDuration*1000, 'newRound'
Timer.set (stillDuration-30*60)*1000, 'reminder'
Db.shared.set 'next', curRoundTime+roundDuration
###
exports.onJoin = !->
if userCnt >= 3 and !Db.shared.get('rounds', 'maxId')
newRound()
exports.client_closeRound = exports.closeRound = closeRound = !->
maxId = Db.shared.get('rounds', 'maxId') || 0
if maxId and !Db.shared.get('rounds', maxId, 'results')
calcResults maxId
# give users three questions to pick from for the next round
questionIds = selectNewQuestions()
if questionIds.length
Db.shared.set 'questionIds', questionIds
exports.client_selectNewQuestions = selectNewQuestions = (single) ->
maxId = Db.shared.get('rounds', 'maxId') || 0
# find questions already used, select new one:
used = []
for i in [1..maxId]
qid = Db.shared.get 'rounds', i, 'qid'
used.push +qid
allowAdult = Db.shared.get 'adult'
available = []
for q, nr in questions
if +nr not in used and (allowAdult or q[1] is false) and q[1] isnt null
available.push +nr
amount = if single then 1 else 3
selected = []
while available.length and amount-->0
rndPos = Math.floor(Math.random()*available.length)
selected.push available[rndPos]
available.splice(rndPos, 1)
if selected.length is 0
return -1 # no question found
if single then selected[0] else selected
exports.client_newRound = exports.newRound = newRound = (pickedQuestionId) !->
return if userCnt < 3 or +Db.shared.get('next') is -1
# -1 is for my plugins and master happenings
maxId = Db.shared.get('rounds', 'maxId') || 0
log 'maxId', maxId
# only start a new round when a question still needs to be selected (so no round currently active)
if pickedQuestionId?
qIds = Db.shared.get('questionIds')
return if !qIds or qIds.indexOf(pickedQuestionId)<0
Db.shared.remove 'questionIds'
# current round results should have been determined, but make sure
if maxId and !Db.shared.get('rounds', maxId, 'results')
calcResults maxId
if pickedQuestionId?
newQuestionId = pickedQuestionId
else
newQuestionId = selectNewQuestions(true) # select a single question randomly
if newQuestionId>=0
maxId = maxId + 1
Db.shared.set 'rounds', 'maxId', maxId
time = 0|App.time()
Db.shared.set 'rounds', maxId,
qid: newQuestionId
by: App.userId()
question: questions[newQuestionId][0]
time: time
roundDuration = Util.getRoundDuration(time)
Timer.cancel()
if roundDuration > 3600
Timer.set roundDuration*1000, 'closeRound'
Timer.set (roundDuration-120*60)*1000, 'reminder'
Db.shared.set 'next', time+roundDuration
if !pickedQuestionId?
Event.create
text: "New ranking round: " + Util.qToQuestion(questions[newQuestionId][0])
exports.reminder = !->
roundId = Db.shared.get('rounds', 'maxId')
remind = []
for userId in App.userIds()
rankings = Db.personal(userId).get 'rankings', roundId
if !rankings or !rankings[1]
remind.push userId
if remind.length
qId = Db.shared.get 'rounds', roundId, 'qid'
time = 0|App.time()
minsLeft = (Db.shared.get('next') - time) / 60
if minsLeft<60
leftText = tr("30 minutes")
else
leftText = tr("2 hours")
if pickedBy = Db.shared.get('rounds', roundId, 'by')
pickedByText = tr("Picked by %1, %2 left to vote!", App.userName(pickedBy), leftText)
else
pickedByText = tr("%1 left to vote!", leftText)
Comments.post
legacyStore: roundId
u: pickedBy
s: pickedByText
path: [roundId]
for: remind
pushText: Util.qToQuestion(questions[qId][0]) + ' ' + pickedByText
exports.client_getVoteCnt = (cb) !->
voteCnt = 0
maxId = Db.shared.get('rounds', 'maxId')
for userId in App.userIds()
rankings = Db.personal(userId).get 'rankings', maxId
if rankings and rankings[1] and rankings[2]
voteCnt++
cb.reply voteCnt
calcResults = (roundId = false) !->
roundId = roundId || Db.shared.get('rounds', 'maxId')
log 'calculating result for round', roundId
# calculate results here using personal data (we only take into account current users)
scores = {}
hasVoted = {}
voteCnt = 0
groupCnt = 0
for userId in App.userIds()
# make sure everyone is represented
if !scores[userId]?
scores[userId] = 0
rankings = Db.personal(userId).get 'rankings', roundId
if rankings and rankings[1] and rankings[2]
scores[rankings[1]] = (scores[rankings[1]]||0) + 3 # this max-score is used below as well!
scores[rankings[2]] = (scores[rankings[2]]||0) + 2
if rankings[3] # only two positions to vote for in groups of three members
scores[rankings[3]] = (scores[rankings[3]]||0) + 1
voteCnt++
hasVoted[userId] = true
else
hasVoted[userId] = false
groupCnt++
Db.shared.set 'rounds', roundId, 'votes', voteCnt
if !voteCnt
log 'no scores', roundId
Db.shared.set 'rounds', roundId, 'results', false
return false
results = []
for userId, score of scores when voteCnt>0
# calculate percentage for each, correcting for voter/non-voter differences
if score>0
correction = ((groupCnt - voteCnt - (if hasVoted[userId] then 0 else 1)) * 6) / (groupCnt - 1)
max = (voteCnt - (if hasVoted[userId] then 1 else 0)) * 3 + correction
score = score + correction
perc = Math.round(score / max * 100)
else
perc = 0
results.push([userId, perc, perc + (Math.random() * 0.5 - 0.25)])
# some jitter is added to randomize same-percentages order
results.sort (a, b) -> b[2] - a[2]
resultsObj = { 1: 0, 2: 0, 3: 0 }
percsObj = { 1: 0, 2: 0, 3: 0 }
log 'sorted results', JSON.stringify(results)
# top 3 (also works for top 2)
for value, pos in results
userId = +value[0]
perc = value[1]
resultsObj[pos+1] = userId # one-based
percsObj[pos+1] = perc
break if pos is 2 # pos 0, 1, 2
Db.shared.set 'rounds', roundId, 'percs', percsObj
# now divide remaining 4...x over bucket 4 and 5
resultsObj[4] = []
resultsObj[5] = []
if results.length is 4
resultsObj[4].push(+results[3][0])
else if results.length > 4
resultCnt = results.length
middle = 3+(resultCnt-4)/2
best = {diff: resultCnt, pos: if results[3][1] then results.length else 3}
for pos in [4...resultCnt] when results[pos-1][1] > results[pos][1]
# the score is lower than the prev result
if best.diff > (diff = Math.abs(pos-middle))
# it's closer to the middle then the former best result
best = {diff, pos}
#resultsObj[4] = results.slice 3, best.pos-3
#resultsObj[5] = results.slice best.pos
#log 'best pos', best.pos
for i in [3...best.pos] when 3<best.pos
resultsObj[4].push(+results[i][0])
for i in [best.pos...results.length] when best.pos<results.length
resultsObj[5].push(+results[i][0])
log 'resultsObj', JSON.stringify(resultsObj)
Db.shared.set 'rounds', roundId, 'results', resultsObj
# calculate personal score
for userId in App.userIds()
self = Db.personal(userId).get 'rankings', roundId, 'self'
curScore = Db.shared.get 'competition', userId
if !curScore?
# new user, initialize on 2 points per round score
curScore = (roundId-1) * 2
score = 2
if self
# participating user
rank = 0
for i in [1..5]
if i>3
rank = i if +userId in resultsObj[i]
else
rank = i if +userId is resultsObj[i]
if rank
diff = Math.min(3, Math.abs(rank - self))
scoring = Util.scoring()
score = scoring[diff]
Db.shared.set 'competition', userId, curScore + score
if results.length
qid = Db.shared.get('rounds', roundId, 'qid')
winnerText = App.userName(resultsObj[1]) + ' ' + questions[qid][0] + '!'
Comments.post
u: false
legacyStore: roundId
s: winnerText
path: [roundId]
pushText: winnerText
exports.client_rankSelf = (roundId, self) !->
self = +self
return if Db.shared.get('rounds', roundId, 'results') or self not in [1..5]
# round no longer active
Db.personal().set 'rankings', roundId, 'self', self
exports.client_rankTop = (roundId, values) !->
return if Db.shared.get('rounds', roundId, 'results') or !values[1] or !values[2] or (topCnt isnt 2 and !values[3])
# round no longer active
if values is 'remove'
Db.personal().remove 'rankings', roundId
else
resObj =
1: +values[1]
2: +values[2]
3: +values[3]
Db.personal().merge 'rankings', roundId, resObj