forked from HabitRPG/habitica
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.js
448 lines (400 loc) · 14 KB
/
user.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
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
// User.js
// =======
// Defines the user data model (schema) for use via the API.
// Dependencies
// ------------
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var shared = require('habitrpg-shared');
var _ = require('lodash');
var TaskSchemas = require('./task');
var Challenge = require('./challenge').model;
// User Schema
// -----------
var UserSchema = new Schema({
// ### UUID and API Token
_id: {
type: String,
'default': shared.uuid
},
apiToken: {
type: String,
'default': shared.uuid
},
// ### Mongoose Update Object
// We want to know *every* time an object updates. Mongoose uses __v to designate when an object contains arrays which
// have been updated (http://goo.gl/gQLz41), but we want *every* update
_v: { type: Number, 'default': 0 },
achievements: {
originalUser: Boolean,
helpedHabit: Boolean,
ultimateGear: Boolean,
beastMaster: Boolean,
veteran: Boolean,
snowball: Number,
streak: Number,
challenges: Array,
quests: Schema.Types.Mixed,
rebirths: Number,
rebirthLevel: Number,
perfect: Number,
habitBirthday: Boolean,
valentine: Number
},
auth: {
facebook: Schema.Types.Mixed,
local: {
email: String,
hashed_password: String,
salt: String,
username: String
},
timestamps: {
created: {type: Date,'default': Date.now},
loggedin: {type: Date,'default': Date.now}
}
},
backer: {
tier: Number,
npc: String,
tokensApplied: Boolean
},
contributor: {
level: Number, // 1-7, see https://trello.com/c/wkFzONhE/277-contributor-gear
admin: Boolean,
sudo: Boolean,
text: String, // Artisan, Friend, Blacksmith, etc
contributions: String, // a markdown textarea to list their contributions + links
critical: String
},
balance: {type: Number, 'default':0},
filters: {type: Schema.Types.Mixed, 'default': {}},
purchased: {
ads: {type: Boolean, 'default': false},
skin: {type: Schema.Types.Mixed, 'default': {}}, // eg, {skeleton: true, pumpkin: true, eb052b: true}
hair: {type: Schema.Types.Mixed, 'default': {}},
shirt: {type: Schema.Types.Mixed, 'default': {}},
background: {type: Schema.Types.Mixed, 'default': {}},
txnCount: {type: Number, 'default':0},
mobileChat: Boolean,
plan: {
planId: String,
paymentMethod: String, //enum: ['Paypal','Stripe', '']}
customerId: String,
dateCreated: Date,
dateTerminated: Date,
dateUpdated: Date,
gemsBought: {type: Number, 'default': 0},
mysteryItems: {type: Array, 'default': []}
}
},
flags: {
customizationsNotification: {type: Boolean, 'default': false},
showTour: {type: Boolean, 'default': true},
dropsEnabled: {type: Boolean, 'default': false},
itemsEnabled: {type: Boolean, 'default': false},
newStuff: {type: Boolean, 'default': false},
rewrite: {type: Boolean, 'default': true},
partyEnabled: Boolean, // FIXME do we need this?
contributor: Boolean,
classSelected: {type: Boolean, 'default': false},
mathUpdates: Boolean,
rebirthEnabled: {type: Boolean, 'default': false},
freeRebirth: {type: Boolean, 'default': false},
levelDrops: {type:Schema.Types.Mixed, 'default':{}},
chatRevoked: Boolean
},
history: {
exp: Array, // [{date: Date, value: Number}], // big peformance issues if these are defined
todos: Array //[{data: Date, value: Number}] // big peformance issues if these are defined
},
// FIXME remove?
invitations: {
guilds: {type: Array, 'default': []},
party: Schema.Types.Mixed
},
items: {
gear: {
owned: _.transform(shared.content.gear.flat, function(m,v,k){
m[v.key] = {type: Boolean};
if (v.key.match(/[weapon|armor|head|shield]_warrior_0/))
m[v.key]['default'] = true;
}),
equipped: {
weapon: {type: String, 'default': 'weapon_warrior_0'},
armor: {type: String, 'default': 'armor_base_0'},
head: {type: String, 'default': 'head_base_0'},
shield: {type: String, 'default': 'shield_base_0'},
back: String,
headAccessory: String,
body: String
},
costume: {
weapon: {type: String, 'default': 'weapon_base_0'},
armor: {type: String, 'default': 'armor_base_0'},
head: {type: String, 'default': 'head_base_0'},
shield: {type: String, 'default': 'shield_base_0'},
back: String,
headAccessory: String,
body: String
},
},
special:{
snowball: {type: Number, 'default': 0},
valentine: Number,
valentineReceived: Array // array of strings, by sender name
},
// -------------- Animals -------------------
// Complex bit here. The result looks like:
// pets: {
// 'Wolf-Desert': 0, // 0 means does not own
// 'PandaCub-Red': 10, // Number represents "Growth Points"
// etc...
// }
pets:
_.defaults(
// First transform to a 1D eggs/potions mapping
_.transform(shared.content.pets, function(m,v,k){ m[k] = Number; }),
// Then add quest pets
_.transform(shared.content.questPets, function(m,v,k){ m[k] = Number; }),
// Then add additional pets (backer, contributor)
_.transform(shared.content.specialPets, function(m,v,k){ m[k] = Number; })
),
currentPet: String, // Cactus-Desert
// eggs: {
// 'PandaCub': 0, // 0 indicates "doesn't own"
// 'Wolf': 5 // Number indicates "stacking"
// }
eggs: _.transform(shared.content.eggs, function(m,v,k){ m[k] = Number; }),
// hatchingPotions: {
// 'Desert': 0, // 0 indicates "doesn't own"
// 'CottonCandyBlue': 5 // Number indicates "stacking"
// }
hatchingPotions: _.transform(shared.content.hatchingPotions, function(m,v,k){ m[k] = Number; }),
// Food: {
// 'Watermelon': 0, // 0 indicates "doesn't own"
// 'RottenMeat': 5 // Number indicates "stacking"
// }
food: _.transform(shared.content.food, function(m,v,k){ m[k] = Number; }),
// mounts: {
// 'Wolf-Desert': true,
// 'PandaCub-Red': false,
// etc...
// }
mounts: _.defaults(
// First transform to a 1D eggs/potions mapping
_.transform(shared.content.pets, function(m,v,k){ m[k] = Boolean; }),
// Then add quest pets
_.transform(shared.content.questPets, function(m,v,k){ m[k] = Boolean; }),
// Then add additional pets (backer, contributor)
_.transform(shared.content.specialMounts, function(m,v,k){ m[k] = Boolean; })
),
currentMount: String,
// Quests: {
// 'boss_0': 0, // 0 indicates "doesn't own"
// 'collection_honey': 5 // Number indicates "stacking"
// }
quests: _.transform(shared.content.quests, function(m,v,k){ m[k] = Number; }),
lastDrop: {
date: {type: Date, 'default': Date.now},
count: {type: Number, 'default': 0}
}
},
lastCron: {type: Date, 'default': Date.now},
// {GROUP_ID: Boolean}, represents whether they have unseen chat messages
newMessages: {type: Schema.Types.Mixed, 'default': {}},
party: {
// id // FIXME can we use a populated doc instead of fetching party separate from user?
order: {type:String, 'default':'level'},
quest: {
key: String,
progress: {
up: {type: Number, 'default': 0},
down: {type: Number, 'default': 0},
collect: {type: Schema.Types.Mixed, 'default': {}} // {feather:1, ingot:2}
},
completed: String // When quest is done, we move it from key => completed, and it's a one-time flag (for modal) that they unset by clicking "ok" in browser
}
},
preferences: {
armorSet: String,
dayStart: {type:Number, 'default': 0, min: 0, max: 23},
size: {type:String, enum: ['broad','slim'], 'default': 'broad'},
hair: {
color: {type: String, 'default': 'blond'},
base: {type: Number, 'default': 0},
bangs: {type: Number, 'default': 0},
beard: {type: Number, 'default': 0},
mustache: {type: Number, 'default': 0},
flower: Number
},
hideHeader: {type:Boolean, 'default':false},
skin: {type:String, 'default':'c06534'},
shirt: {type: String, 'default': 'white'},
timezoneOffset: Number,
language: String,
automaticAllocation: Boolean,
allocationMode: {type:String, enum: ['flat','classbased','taskbased'], 'default': 'flat'},
costume: Boolean,
sleep: {type: Boolean, 'default': false},
stickyHeader: {type: Boolean, 'default': true},
disableClasses: {type: Boolean, 'default': false},
newTaskEdit: {type: Boolean, 'default': false},
tagsCollapsed: {type: Boolean, 'default': false},
advancedCollapsed: {type: Boolean, 'default': false},
toolbarCollapsed: {type:Boolean, 'default':false},
background: String
},
profile: {
blurb: String,
imageUrl: String,
name: String,
},
stats: {
hp: {type: Number, 'default': 50},
mp: {type: Number, 'default': 10},
exp: {type: Number, 'default': 0},
gp: {type: Number, 'default': 0},
lvl: {type: Number, 'default': 1},
// Class System
'class': {type: String, enum: ['warrior','rogue','wizard','healer'], 'default': 'warrior'},
points: {type: Number, 'default': 0},
str: {type: Number, 'default': 0},
con: {type: Number, 'default': 0},
int: {type: Number, 'default': 0},
per: {type: Number, 'default': 0},
buffs: {
str: {type: Number, 'default': 0},
int: {type: Number, 'default': 0},
per: {type: Number, 'default': 0},
con: {type: Number, 'default': 0},
stealth: {type: Number, 'default': 0},
streaks: {type: Boolean, 'default': false},
snowball: {type: Boolean, 'default': false}
},
training: {
int: {type: Number, 'default': 0},
per: {type: Number, 'default': 0},
str: {type: Number, 'default': 0},
con: {type: Number, 'default': 0}
}
},
tags: {type: [{
_id: false,
id: { type: String, 'default': shared.uuid },
name: String,
challenge: String
}]},
challenges: [{type: 'String', ref:'Challenge'}],
habits: {type:[TaskSchemas.HabitSchema]},
dailys: {type:[TaskSchemas.DailySchema]},
todos: {type:[TaskSchemas.TodoSchema]},
rewards: {type:[TaskSchemas.RewardSchema]},
extra: Schema.Types.Mixed
}, {
strict: true,
minimize: false // So empty objects are returned
});
UserSchema.methods.deleteTask = function(tid) {
this.ops.deleteTask({params:{id:tid}},function(){}); // TODO remove this whole method, since it just proxies, and change all references to this method
}
UserSchema.methods.toJSON = function() {
var doc = this.toObject();
doc.id = doc._id;
// FIXME? Is this a reference to `doc.filters` or just disabled code? Remove?
doc.filters = {};
doc._tmp = this._tmp; // be sure to send down drop notifs
return doc;
};
//UserSchema.virtual('tasks').get(function () {
// var tasks = this.habits.concat(this.dailys).concat(this.todos).concat(this.rewards);
// var tasks = _.object(_.pluck(tasks,'id'), tasks);
// return tasks;
//});
UserSchema.post('init', function(doc){
shared.wrap(doc);
})
UserSchema.pre('save', function(next) {
// Populate new users with default content
if (this.isNew){
//TODO for some reason this doesn't work here: `_.merge(this, shared.content.userDefaults);`
var self = this;
_.each(['habits', 'dailys', 'todos', 'rewards', 'tags'], function(taskType){
self[taskType] = _.map(shared.content.userDefaults[taskType], function(task){
var newTask = _.cloneDeep(task);
// Render task's text and notes in user's language
if(taskType === 'tags'){
// tasks automatically get id=helpers.uuid() from TaskSchema id.default, but tags are Schema.Types.Mixed - so we need to manually invoke here
newTask.id = shared.uuid();
newTask.name = newTask.name(self.preferences.language);
}else{
newTask.text = newTask.text(self.preferences.language);
newTask.notes = newTask.notes(self.preferences.language);
if(newTask.checklist){
newTask.checklist = _.map(newTask.checklist, function(checklistItem){
checklistItem.text = checklistItem.text(self.preferences.language);
return checklistItem;
});
}
}
return newTask;
});
});
this.preferences.language = undefined;
}
//this.markModified('tasks');
if (_.isNaN(this.preferences.dayStart) || this.preferences.dayStart < 0 || this.preferences.dayStart > 23) {
this.preferences.dayStart = 0;
}
if (!this.profile.name) {
var fb = this.auth.facebook;
this.profile.name =
(this.auth.local && this.auth.local.username) ||
(fb && (fb.displayName || fb.name || fb.username || (fb.first_name && fb.first_name + ' ' + fb.last_name))) ||
'Anonymous';
}
var petCount = shared.countPets(_.reduce(this.items.pets,function(m,v){
//HOTFIX - Remove when solution is found, the first argument passed to reduce is a function
if(_.isFunction(v)) return m;
return m+(v?1:0)},0), this.items.pets);
this.achievements.beastMaster = petCount >= 90;
//our own version incrementer
this._v++;
next();
});
UserSchema.methods.unlink = function(options, cb) {
var cid = options.cid, keep = options.keep, tid = options.tid;
var self = this;
switch (keep) {
case 'keep':
self.tasks[tid].challenge = {};
break;
case 'remove':
self.deleteTask(tid);
break;
case 'keep-all':
_.each(self.tasks, function(t){
if (t.challenge && t.challenge.id == cid) {
t.challenge = {};
}
});
break;
case 'remove-all':
_.each(self.tasks, function(t){
if (t.challenge && t.challenge.id == cid) {
self.deleteTask(t.id);
}
})
break;
}
self.markModified('habits');
self.markModified('dailys');
self.markModified('todos');
self.markModified('rewards');
self.save(cb);
}
module.exports.schema = UserSchema;
module.exports.model = mongoose.model("User", UserSchema);
mongoose.model("User").find({'contributor.admin':true},function(err,mods){
module.exports.mods = _.map(mods,function(m){return ' '+ m.profile.name});
});