125 lines
2.4 KiB
Go
125 lines
2.4 KiB
Go
package sessionmanager
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
|
|
"git.andreafazzi.eu/andrea/probo/pkg/models"
|
|
"git.andreafazzi.eu/andrea/probo/pkg/store"
|
|
"git.andreafazzi.eu/andrea/probo/pkg/store/file"
|
|
)
|
|
|
|
type SessionManager struct {
|
|
ParticipantStore *store.ParticipantStore
|
|
QuizStore *store.QuizStore
|
|
|
|
ParticipantFilter map[string]string
|
|
QuizFilter map[string]string
|
|
ServerURL string
|
|
Token int
|
|
|
|
examFileStore *file.ExamFileStore
|
|
}
|
|
|
|
func NewSessionManager(url string, pStore *store.ParticipantStore, qStore *store.QuizStore, pFilter map[string]string, qFilter map[string]string) (*SessionManager, error) {
|
|
sm := new(SessionManager)
|
|
|
|
sm.ServerURL = url
|
|
|
|
var err error
|
|
|
|
sm.examFileStore, err = file.NewDefaultExamFileStore()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
for _, p := range pStore.ReadAll() {
|
|
_, err := sm.examFileStore.Create(&models.Exam{
|
|
Participant: p,
|
|
Quizzes: qStore.ReadAll(),
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
return sm, nil
|
|
}
|
|
|
|
func (sm *SessionManager) GetExams() []*models.Exam {
|
|
return sm.examFileStore.ReadAll()
|
|
}
|
|
|
|
func (sm *SessionManager) Pull(rStore *file.ResponseFileStore, sessionID string) error {
|
|
url, err := url.JoinPath(sm.ServerURL, "responses/", sessionID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
rr, err := http.Get(url)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
responseBody, err := io.ReadAll(rr.Body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
responses := make([]*models.Response, 0)
|
|
|
|
err = json.Unmarshal(responseBody, &responses)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, response := range responses {
|
|
_, err := rStore.Create(response)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (sm *SessionManager) Push(name string) (*models.Session, error) {
|
|
session := &models.Session{
|
|
Name: name,
|
|
Exams: make(map[string]*models.Exam),
|
|
}
|
|
|
|
for _, e := range sm.GetExams() {
|
|
session.Exams[e.Participant.Token] = e
|
|
}
|
|
|
|
payload, err := session.Marshal()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
url, err := url.JoinPath(sm.ServerURL, "create")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
response, err := http.Post(url, "application/json", bytes.NewReader(payload))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
responseBody, err := io.ReadAll(response.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
err = json.Unmarshal(responseBody, &session)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return session, nil
|
|
}
|