package main import ( "encoding/json" "errors" "fmt" "net/http" "strconv" "strings" "time" "github.com/julienschmidt/httprouter" ) var ( _score_cache = map[int64]map[int64]*float64{} ) func init() { router.GET("/api/surveys", apiAuthHandler( func(u *User, _ httprouter.Params, _ []byte) HTTPResponse { if u == nil { return formatApiResponse(getSurveys(fmt.Sprintf("WHERE (shown = TRUE OR direct IS NOT NULL) AND NOW() > start_availability AND promo = %d ORDER BY start_availability ASC", currentPromo))) } else if u.IsAdmin { return formatApiResponse(getSurveys("ORDER BY promo DESC, start_availability ASC")) } else { surveys, err := getSurveys(fmt.Sprintf("WHERE (shown = TRUE OR direct IS NOT NULL) AND promo = %d ORDER BY start_availability ASC", u.Promo)) if err != nil { return APIErrorResponse{err: err} } var response []Survey for _, s := range surveys { if s.Group == "" || strings.Contains(u.Groups, ","+s.Group+",") { response = append(response, s) } } return formatApiResponse(response, nil) } })) router.POST("/api/surveys", apiHandler(func(_ httprouter.Params, body []byte) HTTPResponse { var new Survey if err := json.Unmarshal(body, &new); err != nil { return APIErrorResponse{err: err} } if new.Promo == 0 { new.Promo = currentPromo } return formatApiResponse(NewSurvey(new.Title, new.Promo, new.Group, new.Shown, new.Direct, new.StartAvailability, new.EndAvailability)) }, adminRestricted)) router.GET("/api/surveys/:sid", apiAuthHandler(surveyAuthHandler( func(s Survey, u *User, _ []byte) HTTPResponse { if u == nil { return APIErrorResponse{ status: http.StatusUnauthorized, err: errors.New("Veuillez vous connecter pour accéder à cette page."), } } else if (s.Promo == u.Promo && (s.Group == "" || strings.Contains(u.Groups, ","+s.Group+",") && s.Shown)) || u.IsAdmin { return APIResponse{s} } else { return APIErrorResponse{ status: http.StatusForbidden, err: errors.New("Not accessible"), } } }))) router.PUT("/api/surveys/:sid", apiHandler(surveyHandler(func(current Survey, body []byte) HTTPResponse { var new Survey if err := json.Unmarshal(body, &new); err != nil { return APIErrorResponse{err: err} } new.Id = current.Id if new.Direct != current.Direct { if new.Direct == nil { current.WSCloseAll("") } else if *new.Direct == 0 { current.WSWriteAll(WSMessage{ Action: "pause", }) } else { current.WSWriteAll(WSMessage{ Action: "new_question", QuestionId: new.Direct, }) } } return formatApiResponse(new.Update()) }), adminRestricted)) router.DELETE("/api/surveys/:sid", apiHandler(surveyHandler( func(s Survey, _ []byte) HTTPResponse { return formatApiResponse(s.Delete()) }), adminRestricted)) router.GET("/api/surveys/:sid/score", apiAuthHandler(surveyAuthHandler( func(s Survey, u *User, _ []byte) HTTPResponse { if (s.Promo == u.Promo && s.Shown) || (u != nil && u.IsAdmin) { if score, err := s.GetScore(u); err != nil { return APIErrorResponse{err: err} } else if score == nil { return APIResponse{map[string]string{"score": "N/A"}} } else { return APIResponse{map[string]float64{"score": *score}} } } else { return APIErrorResponse{ status: http.StatusForbidden, err: errors.New("Not accessible"), } } }), loggedUser)) router.GET("/api/users/:uid/surveys/:sid/score", apiAuthHandler(func(uauth *User, ps httprouter.Params, body []byte) HTTPResponse { return surveyAuthHandler(func(s Survey, uauth *User, _ []byte) HTTPResponse { return userHandler(func(u User, _ []byte) HTTPResponse { if uauth != nil && ((s.Promo == u.Promo && s.Shown && u.Id == uauth.Id) || uauth.IsAdmin) { if score, err := s.GetScore(&u); err != nil { return APIErrorResponse{err: err} } else if score == nil { return APIResponse{map[string]string{"score": "N/A"}} } else { return APIResponse{map[string]float64{"score": *score}} } } else { return APIErrorResponse{ status: http.StatusForbidden, err: errors.New("Not accessible"), } } })(ps, body) })(uauth, ps, body) }, loggedUser)) } func surveyHandler(f func(Survey, []byte) HTTPResponse) func(httprouter.Params, []byte) HTTPResponse { return func(ps httprouter.Params, body []byte) HTTPResponse { if sid, err := strconv.Atoi(string(ps.ByName("sid"))); err != nil { return APIErrorResponse{err: err} } else if survey, err := getSurvey(sid); err != nil { return APIErrorResponse{err: err} } else { return f(survey, body) } } } func surveyAuthHandler(f func(Survey, *User, []byte) HTTPResponse) func(*User, httprouter.Params, []byte) HTTPResponse { return func(u *User, ps httprouter.Params, body []byte) HTTPResponse { if sid, err := strconv.Atoi(string(ps.ByName("sid"))); err != nil { return APIErrorResponse{err: err} } else if survey, err := getSurvey(sid); err != nil { return APIErrorResponse{err: err} } else { return f(survey, u, body) } } } type Survey struct { Id int64 `json:"id"` Title string `json:"title"` Promo uint `json:"promo"` Group string `json:"group"` Shown bool `json:"shown"` Direct *int64 `json:"direct"` Corrected bool `json:"corrected"` StartAvailability time.Time `json:"start_availability"` EndAvailability time.Time `json:"end_availability"` } func getSurveys(cnd string, param ...interface{}) (surveys []Survey, err error) { if rows, errr := DBQuery("SELECT id_survey, title, promo, grp, shown, direct, corrected, start_availability, end_availability FROM surveys "+cnd, param...); errr != nil { return nil, errr } else { defer rows.Close() for rows.Next() { var s Survey if err = rows.Scan(&s.Id, &s.Title, &s.Promo, &s.Group, &s.Shown, &s.Direct, &s.Corrected, &s.StartAvailability, &s.EndAvailability); err != nil { return } surveys = append(surveys, s) } if err = rows.Err(); err != nil { return } return } } func getSurvey(id int) (s Survey, err error) { err = DBQueryRow("SELECT id_survey, title, promo, grp, shown, direct, corrected, start_availability, end_availability FROM surveys WHERE id_survey=?", id).Scan(&s.Id, &s.Title, &s.Promo, &s.Group, &s.Shown, &s.Direct, &s.Corrected, &s.StartAvailability, &s.EndAvailability) return } func NewSurvey(title string, promo uint, group string, shown bool, direct *int64, startAvailability time.Time, endAvailability time.Time) (*Survey, error) { if res, err := DBExec("INSERT INTO surveys (title, promo, grp, shown, direct, start_availability, end_availability) VALUES (?, ?, ?, ?, ?, ?, ?)", title, promo, group, shown, direct, startAvailability, endAvailability); err != nil { return nil, err } else if sid, err := res.LastInsertId(); err != nil { return nil, err } else { return &Survey{sid, title, promo, group, shown, direct, false, startAvailability, endAvailability}, nil } } func (s Survey) GetScore(u *User) (score *float64, err error) { if _, ok := _score_cache[u.Id]; !ok { _score_cache[u.Id] = map[int64]*float64{} } if v, ok := _score_cache[u.Id][s.Id]; ok { score = v } else { err = DBQueryRow("SELECT SUM(score)/COUNT(*) FROM student_scores WHERE id_survey=? AND id_user=?", s.Id, u.Id).Scan(&score) if score != nil { *score = *score / 5.0 } _score_cache[u.Id][s.Id] = score } return } func (s Survey) GetScores() (scores map[int64]*float64, err error) { if rows, errr := DBQuery("SELECT id_user, SUM(score)/COUNT(*) FROM student_scores WHERE id_survey=? GROUP BY id_user", s.Id); err != nil { return nil, errr } else { defer rows.Close() scores = map[int64]*float64{} for rows.Next() { var id_user int64 var score *float64 if err = rows.Scan(&id_user, &score); err != nil { return } scores[id_user] = score } if err = rows.Err(); err != nil { return } } return } func (s *Survey) Update() (*Survey, error) { if _, err := DBExec("UPDATE surveys SET title = ?, promo = ?, grp = ?, shown = ?, direct = ?, corrected = ?, start_availability = ?, end_availability = ? WHERE id_survey = ?", s.Title, s.Promo, s.Group, s.Shown, s.Direct, s.Corrected, s.StartAvailability, s.EndAvailability, s.Id); err != nil { return nil, err } else { return s, err } } func (s Survey) Delete() (int64, error) { if res, err := DBExec("DELETE FROM surveys WHERE id_survey = ?", s.Id); err != nil { return 0, err } else if nb, err := res.RowsAffected(); err != nil { return 0, err } else { return nb, err } } func ClearSurveys() (int64, error) { if res, err := DBExec("DELETE FROM surveys"); err != nil { return 0, err } else if nb, err := res.RowsAffected(); err != nil { return 0, err } else { return nb, err } }