This repository has been archived by the owner on Jun 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
AnimeListItemAPI.go
95 lines (76 loc) · 2.29 KB
/
AnimeListItemAPI.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
package arn
import (
"errors"
"fmt"
"reflect"
"time"
"github.com/aerogo/aero"
"github.com/aerogo/api"
)
// Force interface implementations
var (
_ api.CustomEditable = (*AnimeListItem)(nil)
_ api.AfterEditable = (*AnimeListItem)(nil)
)
// Edit ...
func (item *AnimeListItem) Edit(ctx aero.Context, key string, value reflect.Value, newValue reflect.Value) (bool, error) {
user := GetUserFromContext(ctx)
if user == nil {
return true, errors.New("Not logged in")
}
switch key {
case "Episodes":
if !newValue.IsValid() {
return true, errors.New("Invalid episode number")
}
oldEpisodes := item.Episodes
newEpisodes := int(newValue.Float())
// Fetch last activity
lastActivity := user.LastActivityConsumeAnime(item.AnimeID)
if lastActivity == nil || time.Since(lastActivity.GetCreatedTime()) > 1*time.Hour {
// If there is no last activity for the given anime,
// or if the last activity happened more than an hour ago,
// create a new activity.
if newEpisodes > oldEpisodes {
activity := NewActivityConsumeAnime(item.AnimeID, newEpisodes, newEpisodes, user.ID)
activity.Save()
// Broadcast event to all users so they can reload the activity page if needed.
for receiver := range StreamUsers() {
receiverIsFollowing := Contains(receiver.Follows().Items, user.ID)
receiver.BroadcastEvent(&aero.Event{
Name: "activity",
Data: receiverIsFollowing,
})
}
}
} else if newEpisodes >= lastActivity.FromEpisode {
// Otherwise, update the last activity.
lastActivity.ToEpisode = newEpisodes
lastActivity.Created = DateTimeUTC()
lastActivity.Save()
}
item.Episodes = newEpisodes
if item.Episodes < 0 {
item.Episodes = 0
}
item.OnEpisodesChange()
return true, nil
case "Status":
newStatus := newValue.String()
switch newStatus {
case AnimeListStatusWatching, AnimeListStatusCompleted, AnimeListStatusPlanned, AnimeListStatusHold, AnimeListStatusDropped:
item.Status = newStatus
item.OnStatusChange()
return true, nil
default:
return true, fmt.Errorf("Invalid anime list item status: %s", newStatus)
}
}
return false, nil
}
// AfterEdit is called after the item is edited.
func (item *AnimeListItem) AfterEdit(ctx aero.Context) error {
item.Rating.Clamp()
item.Edited = DateTimeUTC()
return nil
}