This repository has been archived by the owner on Jun 3, 2019. It is now read-only.
/
User.go
575 lines (453 loc) · 14.1 KB
/
User.go
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
package arn
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/aerogo/aero"
"github.com/aerogo/http/client"
"github.com/animenotifier/arn/autocorrect"
"github.com/animenotifier/arn/validate"
"github.com/animenotifier/ffxiv"
"github.com/animenotifier/osu"
"github.com/animenotifier/overwatch"
gravatar "github.com/ungerik/go-gravatar"
)
var setNickMutex sync.Mutex
var setEmailMutex sync.Mutex
// Register data lists.
func init() {
DataLists["genders"] = []*Option{
// &Option{"", "Prefer not to say"},
{"male", "Male"},
{"female", "Female"},
}
}
// UserID represents a user ID.
type UserID = string
// User is a registered person.
type User struct {
ID UserID `json:"id"`
Nick string `json:"nick" editable:"true"`
FirstName string `json:"firstName" private:"true"`
LastName string `json:"lastName" private:"true"`
Email string `json:"email" editable:"true" private:"true"`
Role string `json:"role"`
Registered string `json:"registered"`
LastLogin string `json:"lastLogin" private:"true"`
LastSeen string `json:"lastSeen" private:"true"`
ProExpires string `json:"proExpires" editable:"true"`
Gender string `json:"gender" editable:"true" private:"true" datalist:"genders"`
Language string `json:"language"`
Introduction string `json:"introduction" editable:"true" type:"textarea"`
Website string `json:"website" editable:"true"`
BirthDay string `json:"birthDay" editable:"true" private:"true"`
IP string `json:"ip" private:"true"`
UserAgent string `json:"agent" private:"true"`
Balance int `json:"balance" private:"true"`
Avatar UserAvatar `json:"avatar"`
Cover UserCover `json:"cover"`
Accounts UserAccounts `json:"accounts" private:"true"`
Browser UserBrowser `json:"browser" private:"true"`
OS UserOS `json:"os" private:"true"`
Location *Location `json:"location" private:"true"`
hasPosts
eventStreams struct {
sync.Mutex
value []*aero.EventStream
}
}
// NewUser creates an empty user object with a unique ID.
func NewUser() *User {
user := &User{
ID: GenerateID("User"),
// Avoid nil value fields
Location: &Location{},
}
return user
}
// RegisterUser registers a new user in the database and sets up all the required references.
func RegisterUser(user *User) {
user.Registered = DateTimeUTC()
user.LastLogin = user.Registered
user.LastSeen = user.Registered
// Save nick in NickToUser collection
DB.Set("NickToUser", user.Nick, &NickToUser{
Nick: user.Nick,
UserID: user.ID,
})
// Save email in EmailToUser collection
if user.Email != "" {
DB.Set("EmailToUser", user.Email, &EmailToUser{
Email: user.Email,
UserID: user.ID,
})
}
// Create default settings
NewSettings(user).Save()
// Add empty anime list
DB.Set("AnimeList", user.ID, &AnimeList{
UserID: user.ID,
Items: []*AnimeListItem{},
})
// Add empty inventory
NewInventory(user.ID).Save()
// Add draft index
NewDraftIndex(user.ID).Save()
// Add empty push subscriptions
DB.Set("PushSubscriptions", user.ID, &PushSubscriptions{
UserID: user.ID,
Items: []*PushSubscription{},
})
// Add empty follow list
NewUserFollows(user.ID).Save()
// Add empty notifications list
NewUserNotifications(user.ID).Save()
// Fetch gravatar
if user.Email != "" && !IsDevelopment() {
gravatarURL := gravatar.Url(user.Email) + "?s=" + fmt.Sprint(AvatarMaxSize) + "&d=404&r=pg"
gravatarURL = strings.Replace(gravatarURL, "http://", "https://", 1)
response, err := client.Get(gravatarURL).End()
if err == nil && response.StatusCode() == http.StatusOK {
data := response.Bytes()
err = user.SetAvatarBytes(data)
if err != nil {
fmt.Println(err)
}
}
}
}
// SendNotification accepts a PushNotification and generates a new Notification object.
// The notification is then sent to all registered push devices.
func (user *User) SendNotification(pushNotification *PushNotification) {
// Don't ever send notifications in development mode
if IsDevelopment() && user.ID != "4J6qpK1ve" {
return
}
// Save notification in database
notification := NewNotification(user.ID, pushNotification)
notification.Save()
userNotifications := user.Notifications()
err := userNotifications.Add(notification.ID)
if err != nil {
fmt.Println(err)
return
}
userNotifications.Save()
// Send push notification
subs := user.PushSubscriptions()
expired := []*PushSubscription{}
for _, sub := range subs.Items {
resp, err := sub.SendNotification(pushNotification)
if resp != nil && resp.StatusCode == http.StatusGone {
expired = append(expired, sub)
continue
}
// Print errors
if err != nil {
fmt.Println(err)
continue
}
// Print bad status codes
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(resp.StatusCode, string(body))
continue
}
sub.LastSuccess = DateTimeUTC()
}
// Remove expired items
if len(expired) > 0 {
for _, sub := range expired {
subs.Remove(sub.ID())
}
}
// Save changes
subs.Save()
// Send an event to the user's open tabs
user.BroadcastEvent(&aero.Event{
Name: "notificationCount",
Data: userNotifications.CountUnseen(),
})
}
// RealName returns the real name of the user.
func (user *User) RealName() string {
if user.LastName == "" {
return user.FirstName
}
if user.FirstName == "" {
return user.LastName
}
return user.FirstName + " " + user.LastName
}
// RegisteredTime returns the time the user registered his account.
func (user *User) RegisteredTime() time.Time {
reg, _ := time.Parse(time.RFC3339, user.Registered)
return reg
}
// LastSeenTime returns the time the user was last seen on the site.
func (user *User) LastSeenTime() time.Time {
lastSeen, _ := time.Parse(time.RFC3339, user.LastSeen)
return lastSeen
}
// AgeInYears returns the user's age in years.
func (user *User) AgeInYears() int {
return AgeInYears(user.BirthDay)
}
// IsActive tells you whether the user is active.
func (user *User) IsActive() bool {
lastSeen, _ := time.Parse(time.RFC3339, user.LastSeen)
twoWeeksAgo := time.Now().Add(-14 * 24 * time.Hour)
if lastSeen.Unix() < twoWeeksAgo.Unix() {
return false
}
if len(user.AnimeList().Items) == 0 {
return false
}
return true
}
// IsPro returns whether the user is a PRO user or not.
func (user *User) IsPro() bool {
if user.ProExpires == "" {
return false
}
return DateTimeUTC() < user.ProExpires
}
// ExtendProDuration extends the PRO account duration by the given duration.
func (user *User) ExtendProDuration(duration time.Duration) {
now := time.Now().UTC()
expires, _ := time.Parse(time.RFC3339, user.ProExpires)
// If the user never had a PRO account yet,
// or if it already expired,
// use the current time as the start time.
if user.ProExpires == "" || now.Unix() > expires.Unix() {
expires = now
}
user.ProExpires = expires.Add(duration).Format(time.RFC3339)
}
// TimeSinceRegistered returns the duration since the user registered his account.
func (user *User) TimeSinceRegistered() time.Duration {
registered, _ := time.Parse(time.RFC3339, user.Registered)
return time.Since(registered)
}
// HasNick returns whether the user has a custom nickname.
func (user *User) HasNick() bool {
return !strings.HasPrefix(user.Nick, "g") && !strings.HasPrefix(user.Nick, "fb") && !strings.HasPrefix(user.Nick, "t") && user.Nick != ""
}
// WebsiteURL adds https:// to the URL.
func (user *User) WebsiteURL() string {
return "https://" + user.WebsiteShortURL()
}
// WebsiteShortURL returns the user website without the protocol.
func (user *User) WebsiteShortURL() string {
return strings.Replace(strings.Replace(user.Website, "https://", "", 1), "http://", "", 1)
}
// Link returns the URI to the user page.
func (user *User) Link() string {
return "/+" + user.Nick
}
// GetID returns the ID.
func (user *User) GetID() string {
return user.ID
}
// HasAvatar tells you whether the user has an avatar or not.
func (user *User) HasAvatar() bool {
return user.Avatar.Extension != ""
}
// AvatarLink returns the URL to the user avatar.
// Expects "small" (50 x 50) or "large" (560 x 560) for the size parameter.
func (user *User) AvatarLink(size string) string {
if user.HasAvatar() {
return fmt.Sprintf("//%s/images/avatars/%s/%s%s?%v", MediaHost, size, user.ID, user.Avatar.Extension, user.Avatar.LastModified)
}
return fmt.Sprintf("//%s/images/elements/no-avatar.svg", MediaHost)
}
// CoverLink ...
func (user *User) CoverLink(size string) string {
if user.Cover.Extension != "" && user.IsPro() {
return fmt.Sprintf("//%s/images/covers/%s/%s%s?%v", MediaHost, size, user.ID, user.Cover.Extension, user.Cover.LastModified)
}
return "/images/elements/default-cover.jpg"
}
// Gravatar returns the URL to the gravatar if an email has been registered.
func (user *User) Gravatar() string {
if user.Email == "" {
return ""
}
return gravatar.SecureUrl(user.Email) + "?s=" + fmt.Sprint(AvatarMaxSize)
}
// EditorScore returns the editor score.
func (user *User) EditorScore() int {
ignoreDifferences := FilterIgnoreAnimeDifferences(func(entry *IgnoreAnimeDifference) bool {
return entry.CreatedBy == user.ID
})
score := len(ignoreDifferences) * IgnoreAnimeDifferenceEditorScore
logEntries := FilterEditLogEntries(func(entry *EditLogEntry) bool {
return entry.UserID == user.ID
})
for _, entry := range logEntries {
score += entry.EditorScore()
}
return score
}
// ActivateItemEffect activates an item in the user inventory by the given item ID.
func (user *User) ActivateItemEffect(itemID string) error {
month := 30 * 24 * time.Hour
switch itemID {
case "pro-account-1":
user.ExtendProDuration(1 * month)
user.Save()
return nil
case "pro-account-3":
user.ExtendProDuration(3 * month)
user.Save()
return nil
case "pro-account-6":
user.ExtendProDuration(6 * month)
user.Save()
return nil
case "pro-account-12":
user.ExtendProDuration(12 * month)
user.Save()
return nil
case "pro-account-24":
user.ExtendProDuration(24 * month)
user.Save()
return nil
default:
return errors.New("Can't activate unknown item: " + itemID)
}
}
// SetNick changes the user's nickname safely.
func (user *User) SetNick(newName string) error {
setNickMutex.Lock()
defer setNickMutex.Unlock()
newName = autocorrect.UserNick(newName)
if !validate.Nick(newName) {
return errors.New("Invalid nickname")
}
if newName == user.Nick {
return nil
}
// Make sure the nickname doesn't exist already
_, err := GetUserByNick(newName)
// If there was no error: the username exists.
// If "not found" is not included in the error message it's a different error type.
if err == nil || !strings.Contains(err.Error(), "not found") {
return errors.New("Username '" + newName + "' is taken already")
}
user.ForceSetNick(newName)
return nil
}
// ForceSetNick forces a nickname overwrite.
func (user *User) ForceSetNick(newName string) {
// Delete old nick reference
DB.Delete("NickToUser", user.Nick)
// Set new nick
user.Nick = newName
DB.Set("NickToUser", user.Nick, &NickToUser{
Nick: user.Nick,
UserID: user.ID,
})
}
// CleanNick only returns the nickname if it was set by user, otherwise empty string.
func (user *User) CleanNick() string {
if user.HasNick() {
return user.Nick
}
return ""
}
// Creator needs to be implemented for the PostParent interface.
func (user *User) Creator() *User {
return user
}
// CreatorID needs to be implemented for the PostParent interface.
func (user *User) CreatorID() UserID {
return user.ID
}
// TitleByUser returns the username.
func (user *User) TitleByUser(viewUser *User) string {
return user.Nick
}
// SetEmail changes the user's email safely.
func (user *User) SetEmail(newEmail string) error {
setEmailMutex.Lock()
defer setEmailMutex.Unlock()
if !validate.Email(newEmail) {
return errors.New("Invalid email address")
}
// Delete old email reference
DB.Delete("EmailToUser", user.Email)
// Set new email
user.Email = newEmail
DB.Set("EmailToUser", user.Email, &EmailToUser{
Email: user.Email,
UserID: user.ID,
})
return nil
}
// HasBasicInfo returns true if the user has a username, an avatar and an introduction.
func (user *User) HasBasicInfo() bool {
return user.HasAvatar() && user.HasNick() && user.Introduction != ""
}
// TypeName returns the type name.
func (user *User) TypeName() string {
return "User"
}
// Self returns the object itself.
func (user *User) Self() Loggable {
return user
}
// RefreshOsuInfo refreshes a user's Osu information.
func (user *User) RefreshOsuInfo() error {
if user.Accounts.Osu.Nick == "" {
return nil
}
osu, err := osu.GetUser(user.Accounts.Osu.Nick)
if err != nil {
return err
}
user.Accounts.Osu.PP, _ = strconv.ParseFloat(osu.PPRaw, 64)
user.Accounts.Osu.Level, _ = strconv.ParseFloat(osu.Level, 64)
user.Accounts.Osu.Accuracy, _ = strconv.ParseFloat(osu.Accuracy, 64)
return nil
}
// RefreshFFXIVInfo refreshes a user's FFXIV information.
func (user *User) RefreshFFXIVInfo() error {
if user.Accounts.FinalFantasyXIV.Nick == "" || user.Accounts.FinalFantasyXIV.Server == "" {
return nil
}
characterID, err := ffxiv.GetCharacterID(user.Accounts.FinalFantasyXIV.Nick, user.Accounts.FinalFantasyXIV.Server)
if err != nil {
return err
}
character, err := ffxiv.GetCharacter(characterID)
if err != nil {
return err
}
user.Accounts.FinalFantasyXIV.Class = character.Class
user.Accounts.FinalFantasyXIV.Level = character.Level
user.Accounts.FinalFantasyXIV.ItemLevel = character.ItemLevel
return nil
}
// RefreshOverwatchInfo refreshes a user's Overwatch information.
func (user *User) RefreshOverwatchInfo() error {
if user.Accounts.Overwatch.BattleTag == "" {
return nil
}
stats, err := overwatch.GetPlayerStats(user.Accounts.Overwatch.BattleTag)
if err != nil {
return err
}
skillRating, tier := stats.HighestSkillRating()
// Only show career highest skill rating
if skillRating > user.Accounts.Overwatch.SkillRating {
user.Accounts.Overwatch.SkillRating = skillRating
user.Accounts.Overwatch.Tier = tier
}
return nil
}