-
Notifications
You must be signed in to change notification settings - Fork 0
/
guild.go
109 lines (87 loc) · 2.44 KB
/
guild.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
package guild
import (
"net/http"
"github.com/diamondburned/csufbot/csufbot"
"github.com/diamondburned/csufbot/csufbot/lms"
"github.com/diamondburned/csufbot/internal/config"
"github.com/diamondburned/csufbot/internal/web"
"github.com/diamondburned/csufbot/internal/web/routes/admin/guild/adminonly"
"github.com/diamondburned/csufbot/internal/web/routes/oauth"
"github.com/go-chi/chi"
"github.com/pkg/errors"
)
var guild = web.Templater.Register("guild", "routes/admin/guild/guild.html")
func Mount(guildIDParam string) http.Handler {
r := chi.NewRouter()
r.Use(adminonly.Require(guildIDParam))
r.Get("/", render)
r.Post("/refresh", refresh)
return r
}
func refresh(w http.ResponseWriter, r *http.Request) {
client := oauth.Client(r.Context())
client.InvalidateCache()
if referer := r.Referer(); referer != "" {
http.Redirect(w, r, referer, http.StatusFound)
}
}
type data struct {
web.RenderConfig
adminonly.Data
Client *oauth.UserClient
CourseMap map[lms.CourseID]csufbot.Course
Services []csufbot.UserInService
Error error
}
type enrolled struct {
Service *config.Service
Courses []csufbot.Course
}
func (d *data) EnrolledCourses() []enrolled {
u, err := d.Users.User(d.Data.UserID)
if err != nil { // Invalid user ID.
d.Error = errors.Wrap(err, "failed to get this user")
return nil
}
var courseMap = make(map[lms.CourseID]csufbot.Course, 10)
for _, svc := range u.Services {
for _, id := range svc.Enrolled {
courseMap[id] = csufbot.Course{}
}
}
if err := d.Courses.Courses(courseMap); err != nil {
d.Error = errors.Wrap(err, "failed to get courses")
return nil
}
var enrolleds = make([]enrolled, 0, len(u.Services))
for _, svc := range u.Services {
service := d.Service(svc.ServiceHost)
if service == nil {
// Unknown service, probably removed. Ignore.
continue
}
courses := make([]csufbot.Course, 0, len(svc.Enrolled))
for _, id := range svc.Enrolled {
// A course may have been removed; we don't show them.
course, ok := courseMap[id]
if ok {
courses = append(courses, course)
}
}
enrolleds = append(enrolleds, enrolled{
Service: service,
Courses: courses,
})
}
return enrolleds
}
func render(w http.ResponseWriter, r *http.Request) {
// TODO: button to link more classes
cfg := web.GetRenderConfig(r.Context())
dat := adminonly.GetData(r.Context())
guild.Execute(w, &data{
RenderConfig: cfg,
Data: dat,
Client: oauth.Client(r.Context()),
})
}