100 lines
2.5 KiB
Go

package session
import (
"crypto/rand"
"encoding/hex"
"fmt"
"net/http"
"strconv"
"streifling.com/jason/sicherheitsunterweisung/packages/data"
)
func (mux *Mux) handleParticipants(db *data.DB, cp <-chan *data.Participant, s *Session) {
for p := range cp {
sessionParticipant := new(SessionParticipant)
sessionParticipant.Participant = p
sessionParticipant.GivenAnswers = make([]int, len(s.Questions))
mux.HandleFunc("/submit-participant/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(p.Login)+"/", s.HandleParticipant(db, p, &s.Questions))
var i int
for i = range s.Questions {
mux.HandleFunc("/submit-answer/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(p.Login)+"/"+fmt.Sprint(i+1)+"/", s.HandleAnswer(db, sessionParticipant, &s.Questions, int64(i+1)))
}
mux.HandleFunc("/retry/"+fmt.Sprint(s.ID)+"/"+fmt.Sprint(p.Login)+"/", s.HandleRetry(p, &s.Questions, &i))
}
}
func generateLogin() (string, error) {
bs := make([]byte, 4)
if _, err := rand.Read(bs); err != nil {
return "", fmt.Errorf("generateLogin: rand.Read(bs): %v\n", err)
}
return hex.EncodeToString(bs), nil
}
func findCorrectLogin(l string, ss *[]*Session) (*Session, *data.Participant, bool) {
for _, session := range *ss {
for _, p := range session.Participants {
if l == p.Login {
return session, p, true
}
}
}
return nil, nil, false
}
func newParticipant(l string) (*data.Participant, error) {
var err error
p := new(data.Participant)
p.ID, err = strconv.ParseInt(l, 10, 64)
if err != nil {
return nil, fmt.Errorf("newParticipant: strconv.Atoi(idString): %v\n", err)
}
return p, nil
}
func handleGivenAnswer(s *Session, p *SessionParticipant, i int64, r *http.Request) error {
answer, err := strconv.Atoi(r.PostFormValue("answer"))
if err != nil {
return fmt.Errorf("handleGivenAnswer: strconv.Atoi(): %v\n", err)
}
p.GivenAnswers[i] = answer
return nil
}
func makeHTMLQuestions(sq []data.Question, givenAnswers []int) []htmlQuestion {
questions := make([]htmlQuestion, 0)
for i, q := range sq {
question := new(htmlQuestion)
question.Text = q.Text
question.Answers = make([]htmlAnswer, 0)
for j, a := range q.Answers {
answer := new(htmlAnswer)
answer.Text = a.Text
if j+1 == q.Correct {
answer.Correct = true
} else {
answer.Correct = false
}
if j+1 == givenAnswers[i] {
answer.Chosen = true
} else {
answer.Chosen = false
}
question.Answers = append(question.Answers, *answer)
}
questions = append(questions, *question)
}
return questions
}