diff --git a/http.go b/http.go index c9d1657..7f458e5 100644 --- a/http.go +++ b/http.go @@ -8,10 +8,12 @@ import ( "net/http" "os" "strings" + "time" ) type Context struct { - User string + DB DB + User IDU } func HTTP(port int, db DB) error { @@ -24,6 +26,7 @@ func HTTP(port int, db DB) error { } } foo = withAuth(foo) + foo = withDB(foo, db) return http.ListenAndServe(fmt.Sprintf(":%d", port), http.HandlerFunc(foo)) } @@ -37,6 +40,15 @@ func inject(ctx context.Context, v Context) context.Context { return context.WithValue(ctx, "__context", v) } +func withDB(foo http.HandlerFunc, db DB) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + c := extract(r.Context()) + c.DB = db + r = r.WithContext(inject(r.Context(), c)) + foo(w, r) + } +} + func withAuth(foo http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { u, _, ok := r.BasicAuth() @@ -46,7 +58,7 @@ func withAuth(foo http.HandlerFunc) http.HandlerFunc { return } c := extract(r.Context()) - c.User = u + c.User = IDU(u) r = r.WithContext(inject(r.Context(), c)) foo(w, r) } @@ -62,8 +74,26 @@ func httpRoot(w http.ResponseWriter, r *http.Request) { body = string(b) } ctx := extract(r.Context()) - body = strings.ReplaceAll(body, "{{USER}}", ctx.User) - assignments, _ := json.Marshal(nil) - body = strings.ReplaceAll(body, "{{ASSIGNMENTS_JSON}}", string(assignments)) + body = strings.ReplaceAll(body, "{{USER}}", string(ctx.User)) + assignments, err := httpAssignments(r.Context()) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + assignmentsB, _ := json.Marshal(assignments) + body = strings.ReplaceAll(body, "{{ASSIGNMENTS_JSON}}", string(assignmentsB)) w.Write([]byte(body)) } + +func httpAssignments(ctx context.Context) (interface{}, error) { + db := extract(ctx).DB + user := extract(ctx).User + todo := map[IDQ]Question{} + for q, _ := range db.HistoryOf(user) { + if time.Until(db.Next(user, q)) > 0 { + continue + } + todo[q] = db.Question(q) + } + return todo, nil +} diff --git a/public/root.html b/public/root.html index 7c73025..bd44566 100644 --- a/public/root.html +++ b/public/root.html @@ -13,22 +13,51 @@ ).toString(36); console.log("session", session); - - {{USER}} -
+ +
+