/
User.coffee
484 lines (407 loc) · 17.4 KB
/
User.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
cache = {}
CocoModel = require './CocoModel'
ThangTypeConstants = require 'lib/ThangTypeConstants'
LevelConstants = require 'lib/LevelConstants'
utils = require 'core/utils'
# Pure functions for use in Vue
# First argument is always a raw User.attributes
# Accessible via eg. `User.broadName(userObj)`
UserLib = {
broadName: (user) ->
return '(deleted)' if user.deleted
name = _.filter([user.firstName, user.lastName]).join(' ')
return name if name
name = user.name
return name if name
[emailName, emailDomain] = user.email?.split('@') or []
return emailName if emailName
return 'Anonymous'
isSmokeTestUser: (user) -> utils.isSmokeTestEmail(user.email)
}
module.exports = class User extends CocoModel
@className: 'User'
@schema: require 'schemas/models/user'
urlRoot: '/db/user'
notyErrors: false
isAdmin: -> 'admin' in @get('permissions', true)
isLicensor: -> 'licensor' in @get('permissions', true)
isArtisan: -> 'artisan' in @get('permissions', true)
isInGodMode: -> 'godmode' in @get('permissions', true)
isAnonymous: -> @get('anonymous', true)
isSmokeTestUser: -> User.isSmokeTestUser(@attributes)
displayName: -> @get('name', true)
broadName: -> User.broadName(@attributes)
inEU: (defaultIfUnknown=true) -> unless @get('country') then defaultIfUnknown else utils.inEU(@get('country'))
getPhotoURL: (size=80) ->
return '' if application.testing
return "/db/user/#{@id}/avatar?s=#{size}"
getRequestVerificationEmailURL: ->
@url() + "/request-verify-email"
getSlugOrID: -> @get('slug') or @get('_id')
@getUnconflictedName: (name, done) ->
# deprecate in favor of @checkNameConflicts, which uses Promises and returns the whole response
$.ajax "/auth/name/#{encodeURIComponent(name)}",
cache: false
success: (data) -> done(data.suggestedName)
@checkNameConflicts: (name) ->
new Promise (resolve, reject) ->
$.ajax "/auth/name/#{encodeURIComponent(name)}",
cache: false
success: resolve
error: (jqxhr) -> reject(jqxhr.responseJSON)
@checkEmailExists: (email) ->
new Promise (resolve, reject) ->
$.ajax "/auth/email/#{encodeURIComponent(email)}",
cache: false
success: resolve
error: (jqxhr) -> reject(jqxhr.responseJSON)
getEnabledEmails: ->
(emailName for emailName, emailDoc of @get('emails', true) when emailDoc.enabled)
setEmailSubscription: (name, enabled) ->
newSubs = _.clone(@get('emails')) or {}
(newSubs[name] ?= {}).enabled = enabled
@set 'emails', newSubs
isEmailSubscriptionEnabled: (name) -> (@get('emails') or {})[name]?.enabled
isStudent: -> @get('role') is 'student'
isTeacher: (includePossibleTeachers=false) ->
return true if includePossibleTeachers and @get('role') is 'possible teacher' # They maybe haven't created an account but we think they might be a teacher based on behavior
return @get('role') in ['teacher', 'technology coordinator', 'advisor', 'principal', 'superintendent', 'parent']
isSessionless: ->
Boolean((utils.getQueryVariable('dev', false) or me.isTeacher()) and utils.getQueryVariable('course', false) and not utils.getQueryVariable('course-instance'))
onChinaInfra: -> features?.chinaInfra ? false
setRole: (role, force=false) ->
oldRole = @get 'role'
return if oldRole is role or (oldRole and not force)
@set 'role', role
@patch()
application.tracker?.updateRole()
return @get 'role'
a = 5
b = 100
c = b
# y = a * ln(1/b * (x + c)) + 1
@levelFromExp: (xp) ->
if xp > 0 then Math.floor(a * Math.log((1 / b) * (xp + c))) + 1 else 1
# x = b * e^((y-1)/a) - c
@expForLevel: (level) ->
if level > 1 then Math.ceil Math.exp((level - 1)/ a) * b - c else 0
@tierFromLevel: (level) ->
# TODO: math
# For now, just eyeball it.
tiersByLevel[Math.min(level, tiersByLevel.length - 1)]
@levelForTier: (tier) ->
# TODO: math
for tierThreshold, level in tiersByLevel
return level if tierThreshold >= tier
level: ->
totalPoint = @get('points')
totalPoint = totalPoint + 1000000 if me.isInGodMode()
User.levelFromExp(totalPoint)
tier: ->
User.tierFromLevel @level()
gems: ->
gemsEarned = @get('earned')?.gems ? 0
gemsEarned = gemsEarned + 100000 if me.isInGodMode()
gemsEarned += 1000 if me.get('hourOfCode')
gemsPurchased = @get('purchased')?.gems ? 0
gemsSpent = @get('spent') ? 0
Math.floor gemsEarned + gemsPurchased - gemsSpent
heroes: ->
heroes = (me.get('purchased')?.heroes ? []).concat([ThangTypeConstants.heroes.captain, ThangTypeConstants.heroes.knight, ThangTypeConstants.heroes.champion, ThangTypeConstants.heroes.duelist])
heroes.push ThangTypeConstants.heroes['code-ninja'] if window.serverConfig.codeNinjas
#heroes = _.values ThangTypeConstants.heroes if me.isAdmin()
heroes
items: -> (me.get('earned')?.items ? []).concat(me.get('purchased')?.items ? []).concat([ThangTypeConstants.items['simple-boots']])
levels: -> (me.get('earned')?.levels ? []).concat(me.get('purchased')?.levels ? []).concat(LevelConstants.levels['dungeons-of-kithgard'])
ownsHero: (heroOriginal) -> me.isInGodMode() || heroOriginal in @heroes()
ownsItem: (itemOriginal) -> itemOriginal in @items()
ownsLevel: (levelOriginal) -> levelOriginal in @levels()
getHeroClasses: ->
idsToSlugs = _.invert ThangTypeConstants.heroes
myHeroSlugs = (idsToSlugs[id] for id in @heroes())
myHeroClasses = []
myHeroClasses.push heroClass for heroClass, heroSlugs of ThangTypeConstants.heroClasses when _.intersection(myHeroSlugs, heroSlugs).length
myHeroClasses
validate: ->
errors = super()
if errors and @_revertAttributes
# Do not return errors if they were all present when last marked to revert.
# This is so that if a user has an invalid property, that does not prevent
# them from editing their settings.
definedAttributes = _.pick @_revertAttributes, (v) -> v isnt undefined
oldResult = tv4.validateMultiple(definedAttributes, @constructor.schema or {})
mapper = (error) -> [error.code.toString(),error.dataPath,error.schemaPath].join(':')
originalErrors = _.map(oldResult.errors, mapper)
currentErrors = _.map(errors, mapper)
newErrors = _.difference(currentErrors, originalErrors)
if _.size(newErrors) is 0
return
return errors
getCampaignAdsGroup: ->
return @campaignAdsGroup if @campaignAdsGroup
# group = me.get('testGroupNumber') % 2
# @campaignAdsGroup = switch group
# when 0 then 'no-ads'
# when 1 then 'leaderboard-ads'
@campaignAdsGroup = 'leaderboard-ads'
@campaignAdsGroup = 'no-ads' if me.isAdmin()
application.tracker.identify campaignAdsGroup: @campaignAdsGroup unless me.isAdmin()
@campaignAdsGroup
# TODO: full removal of sub modal test
getSubModalGroup: () ->
return @subModalGroup if @subModalGroup
@subModalGroup = 'both-subs'
@subModalGroup
setSubModalGroup: (val) ->
@subModalGroup = if me.isAdmin() then 'both-subs' else val
@subModalGroup
# Signs and Portents was receiving updates after test started, and also had a big bug on March 4, so just look at test from March 5 on.
# ... and stopped working well until another update on March 10, so maybe March 11+...
# ... and another round, and then basically it just isn't completing well, so we pause the test until we can fix it.
getFourthLevelGroup: ->
return 'forgetful-gemsmith'
return @fourthLevelGroup if @fourthLevelGroup
group = me.get('testGroupNumber') % 8
@fourthLevelGroup = switch group
when 0, 1, 2, 3 then 'signs-and-portents'
when 4, 5, 6, 7 then 'forgetful-gemsmith'
@fourthLevelGroup = 'signs-and-portents' if me.isAdmin()
application.tracker.identify fourthLevelGroup: @fourthLevelGroup unless me.isAdmin()
@fourthLevelGroup
getVideoTutorialStylesIndex: (numVideos=0)->
# A/B Testing video tutorial styles
# Not a constant number of videos available (e.g. could be 0, 1, 3, or 4 currently)
return 0 unless numVideos > 0
return me.get('testGroupNumber') % numVideos
hasSubscription: ->
return false if me.isStudent() or me.isTeacher()
if payPal = @get('payPal')
return true if payPal.billingAgreementID
if stripe = @get('stripe')
return true if stripe.sponsorID
return true if stripe.subscriptionID
return true if stripe.free is true
return true if _.isString(stripe.free) and new Date() < new Date(stripe.free)
false
isPremium: ->
return true if me.isInGodMode()
return true if me.isAdmin()
return true if me.hasSubscription()
return false
isForeverPremium: ->
return @get('stripe')?.free is true
isOnPremiumServer: ->
return true if me.get('country') in ['brazil']
return true if me.get('country') in ['china'] and (me.isPremium() or me.get('stripe'))
return false
sendVerificationCode: (code) ->
$.ajax({
method: 'POST'
url: "/db/user/#{@id}/verify/#{code}"
success: (attributes) =>
this.set attributes
@trigger 'email-verify-success'
error: =>
@trigger 'email-verify-error'
})
sendKeepMeUpdatedVerificationCode: (code) ->
$.ajax({
method: 'POST'
url: "/db/user/#{@id}/keep-me-updated/#{code}"
success: (attributes) =>
this.set attributes
@trigger 'user-keep-me-updated-success'
error: =>
@trigger 'user-keep-me-updated-error'
})
sendNoDeleteEUVerificationCode: (code) ->
$.ajax({
method: 'POST'
url: "/db/user/#{@id}/no-delete-eu/#{code}"
success: (attributes) =>
this.set attributes
@trigger 'user-no-delete-eu-success'
error: =>
@trigger 'user-no-delete-eu-error'
})
isEnrolled: -> @prepaidStatus() is 'enrolled'
prepaidStatus: -> # 'not-enrolled', 'enrolled', 'expired'
coursePrepaid = @get('coursePrepaid')
return 'not-enrolled' unless coursePrepaid
return 'enrolled' unless coursePrepaid.endDate
return if coursePrepaid.endDate > new Date().toISOString() then 'enrolled' else 'expired'
prepaidType: ->
# TODO: remove once legacy prepaidIDs are migrated to objects
return undefined unless @get('coursePrepaid') or @get('coursePrepaidID')
# NOTE: Default type is 'course' if no type is marked on the user's copy
return @get('coursePrepaid')?.type or 'course'
prepaidIncludesCourse: (course) ->
return false unless @get('coursePrepaid') or @get('coursePrepaidID')
includedCourseIDs = @get('coursePrepaid')?.includedCourseIDs
courseID = course.id or course
# NOTE: Full licenses implicitly include all courses
return !includedCourseIDs or courseID in includedCourseIDs
fetchCreatorOfPrepaid: (prepaid) ->
@fetch({url: "/db/prepaid/#{prepaid.id}/creator"})
fetchNameForClassmate: (options={}) ->
options.method = 'GET'
options.contentType = 'application/json'
options.url = "/db/user/#{@id}/name-for-classmate"
$.ajax options
# Function meant for "me"
spy: (user, options={}) ->
user = user.id or user # User instance, user ID, email or username
options.url = '/auth/spy'
options.type = 'POST'
options.data ?= {}
options.data.user = user
@fetch(options)
stopSpying: (options={}) ->
options.url = '/auth/stop-spying'
options.type = 'POST'
@fetch(options)
logout: (options={}) ->
options.type = 'POST'
options.url = '/auth/logout'
FB?.logout?()
options.success ?= ->
location = _.result(window.currentView, 'logoutRedirectURL')
if location
window.location = location
else
window.location.reload()
@fetch(options)
signupWithPassword: (name, email, password, options={}) ->
options.url = _.result(@, 'url') + '/signup-with-password'
options.type = 'POST'
options.data ?= {}
_.extend(options.data, {name, email, password})
options.contentType = 'application/json'
options.data = JSON.stringify(options.data)
jqxhr = @fetch(options)
jqxhr.then ->
window.tracker?.trackEvent 'Finished Signup', category: "Signup", label: 'CodeCombat'
return jqxhr
signupWithFacebook: (name, email, facebookID, options={}) ->
options.url = _.result(@, 'url') + '/signup-with-facebook'
options.type = 'POST'
options.data ?= {}
_.extend(options.data, {name, email, facebookID, facebookAccessToken: application.facebookHandler.token()})
options.contentType = 'application/json'
options.data = JSON.stringify(options.data)
jqxhr = @fetch(options)
jqxhr.then ->
window.tracker?.trackEvent 'Facebook Login', category: "Signup", label: 'Facebook'
window.tracker?.trackEvent 'Finished Signup', category: "Signup", label: 'Facebook'
return jqxhr
signupWithGPlus: (name, email, gplusID, options={}) ->
options.url = _.result(@, 'url') + '/signup-with-gplus'
options.type = 'POST'
options.data ?= {}
_.extend(options.data, {name, email, gplusID, gplusAccessToken: application.gplusHandler.token()})
options.contentType = 'application/json'
options.data = JSON.stringify(options.data)
jqxhr = @fetch(options)
jqxhr.then ->
window.tracker?.trackEvent 'Google Login', category: "Signup", label: 'GPlus'
window.tracker?.trackEvent 'Finished Signup', category: "Signup", label: 'GPlus'
return jqxhr
fetchGPlusUser: (gplusID, options={}) ->
options.data ?= {}
options.data.gplusID = gplusID
options.data.gplusAccessToken = application.gplusHandler.token()
@fetch(options)
loginGPlusUser: (gplusID, options={}) ->
options.url = '/auth/login-gplus'
options.type = 'POST'
options.data ?= {}
options.data.gplusID = gplusID
options.data.gplusAccessToken = application.gplusHandler.token()
@fetch(options)
fetchFacebookUser: (facebookID, options={}) ->
options.data ?= {}
options.data.facebookID = facebookID
options.data.facebookAccessToken = application.facebookHandler.token()
@fetch(options)
loginFacebookUser: (facebookID, options={}) ->
options.url = '/auth/login-facebook'
options.type = 'POST'
options.data ?= {}
options.data.facebookID = facebookID
options.data.facebookAccessToken = application.facebookHandler.token()
@fetch(options)
loginPasswordUser: (usernameOrEmail, password, options={}) ->
options.url = '/auth/login'
options.type = 'POST'
options.data ?= {}
_.extend(options.data, { username: usernameOrEmail, password })
@fetch(options)
makeCoursePrepaid: ->
coursePrepaid = @get('coursePrepaid')
return null unless coursePrepaid
Prepaid = require 'models/Prepaid'
return new Prepaid(coursePrepaid)
# TODO: Probably better to denormalize this into the user
getLeadPriority: ->
request = $.get('/db/user/-/lead-priority')
request.then ({ priority }) ->
application.tracker.identify({ priority })
request
becomeStudent: (options={}) ->
options.url = '/db/user/-/become-student'
options.type = 'PUT'
@fetch(options)
remainTeacher: (options={}) ->
options.url = '/db/user/-/remain-teacher'
options.type = 'PUT'
@fetch(options)
destudent: (options={}) ->
options.url = _.result(@, 'url') + '/destudent'
options.type = 'POST'
@fetch(options)
deteacher: (options={}) ->
options.url = _.result(@, 'url') + '/deteacher'
options.type = 'POST'
@fetch(options)
checkForNewAchievement: (options={}) ->
options.url = _.result(@, 'url') + '/check-for-new-achievement'
options.type = 'POST'
jqxhr = @fetch(options)
# Setting @loading to false because otherwise, if the user tries to edit their settings while checking
# for new achievements, the changes won't be saved. This is because AccountSettingsView relies on
# hasLocalChanges, and that is only true if, when set is called, the model isn't "loading".
@loading = false
return jqxhr
finishedAnyLevels: -> Boolean((@get('stats') or {}).gamesCompleted)
isFromUk: -> @get('country') is 'united-kingdom' or @get('preferredLanguage') is 'en-GB'
isFromIndia: -> @get('country') is 'india'
setToGerman: -> _.string.startsWith((@get('preferredLanguage') or ''), 'de')
setToSpanish: -> _.string.startsWith((@get('preferredLanguage') or ''), 'es')
freeOnly: ->
return features.freeOnly and not me.isPremium()
subscribe: (token, options={}) ->
stripe = _.clone(@get('stripe') ? {})
stripe.planID = 'basic'
stripe.token = token.id
stripe.couponID = options.couponID if options.couponID
@set({stripe})
return me.patch({headers: {'X-Change-Plan': 'true'}}).then =>
unless utils.isValidEmail(@get('email'))
@set({email: token.email})
me.patch()
return Promise.resolve()
unsubscribe: ->
stripe = _.clone(@get('stripe') ? {})
return unless stripe.planID
delete stripe.planID
@set({stripe})
return me.patch({headers: {'X-Change-Plan': 'true'}})
unsubscribeRecipient: (id, options={}) ->
options.url = _.result(@, 'url') + "/stripe/recipients/#{id}"
options.method = 'DELETE'
return $.ajax(options)
tiersByLevel = [-1, 0, 0.05, 0.14, 0.18, 0.32, 0.41, 0.5, 0.64, 0.82, 0.91, 1.04, 1.22, 1.35, 1.48, 1.65, 1.78, 1.96, 2.1, 2.24, 2.38, 2.55, 2.69, 2.86, 3.03, 3.16, 3.29, 3.42, 3.58, 3.74, 3.89, 4.04, 4.19, 4.32, 4.47, 4.64, 4.79, 4.96,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 10, 10.5, 11, 11.5, 12, 12.5, 13, 13.5, 14, 14.5, 15
]
# Make UserLib accessible via eg. User.broadName(userObj)
_.assign(User, UserLib)