sync: Extract function that import flags from importer

This commit is contained in:
nemunaire 2019-07-05 22:28:56 +02:00
parent 3f55845374
commit 4039a394b5
8 changed files with 454 additions and 310 deletions

View file

@ -407,13 +407,8 @@ func deleteExerciceFlag(flag fic.FlagKey, _ fic.Exercice, _ []byte) (interface{}
return flag.Delete() return flag.Delete()
} }
type uploadedChoice struct {
Label string
Value string
}
func createFlagChoice(flag fic.FlagKey, exercice fic.Exercice, body []byte) (interface{}, error) { func createFlagChoice(flag fic.FlagKey, exercice fic.Exercice, body []byte) (interface{}, error) {
var uc uploadedChoice var uc fic.FlagChoice
if err := json.Unmarshal(body, &uc); err != nil { if err := json.Unmarshal(body, &uc); err != nil {
return nil, err return nil, err
} }
@ -422,7 +417,7 @@ func createFlagChoice(flag fic.FlagKey, exercice fic.Exercice, body []byte) (int
uc.Label = uc.Value uc.Label = uc.Value
} }
return flag.AddChoice(uc.Label, uc.Value) return flag.AddChoice(uc)
} }
func showFlagChoice(choice fic.FlagChoice, _ fic.Exercice, body []byte) (interface{}, error) { func showFlagChoice(choice fic.FlagChoice, _ fic.Exercice, body []byte) (interface{}, error) {
@ -430,7 +425,7 @@ func showFlagChoice(choice fic.FlagChoice, _ fic.Exercice, body []byte) (interfa
} }
func updateFlagChoice(choice fic.FlagChoice, _ fic.Exercice, body []byte) (interface{}, error) { func updateFlagChoice(choice fic.FlagChoice, _ fic.Exercice, body []byte) (interface{}, error) {
var uc uploadedChoice var uc fic.FlagChoice
if err := json.Unmarshal(body, &uc); err != nil { if err := json.Unmarshal(body, &uc); err != nil {
return nil, err return nil, err
} }
@ -503,7 +498,7 @@ func updateExerciceQuiz(quiz fic.MCQ, exercice fic.Exercice, body []byte) (inter
// Add new choices // Add new choices
for _, choice := range uq.Entries { for _, choice := range uq.Entries {
if choice.Id == 0 { if choice.Id == 0 {
if c, err := quiz.AddEntry(choice.Label, choice.Response); err != nil { if c, err := quiz.AddEntry(choice); err != nil {
return nil, err return nil, err
} else { } else {
quiz.Entries = append(quiz.Entries, c) quiz.Entries = append(quiz.Entries, c)
@ -553,7 +548,6 @@ func deleteExerciceFile(file fic.EFile, _ []byte) (interface{}, error) {
return file.Delete() return file.Delete()
} }
func listExerciceTags(exercice fic.Exercice, _ []byte) (interface{}, error) { func listExerciceTags(exercice fic.Exercice, _ []byte) (interface{}, error) {
return exercice.GetTags() return exercice.GetTags()
} }

View file

@ -1,9 +1,11 @@
package sync package sync
import ( import (
"fmt"
"path" "path"
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"srs.epita.fr/fic-server/libfic"
) )
// ExerciceHintParams holds EHint definition infomation. // ExerciceHintParams holds EHint definition infomation.
@ -70,3 +72,45 @@ func parseExerciceParams(i Importer, exPath string) (p ExerciceParams, err error
return return
} }
// getExerciceParams returns normalized
func getExerciceParams(i Importer, exercice fic.Exercice) (params ExerciceParams, errs []string) {
var err error
if params, err = parseExerciceParams(i, exercice.Path); err != nil {
errs = append(errs, fmt.Sprintf("%q: challenge.txt: %s", path.Base(exercice.Path), err))
} else if len(params.Flags) == 0 && len(params.FlagsUCQ) == 0 && len(params.FlagsMCQ) == 0 {
errs = append(errs, fmt.Sprintf("%q: has no flag", path.Base(exercice.Path)))
} else {
// Treat legacy UCQ flags as ExerciceFlag
for _, flag := range params.FlagsUCQ {
params.Flags = append(params.Flags, ExerciceFlag{
Id: flag.Id,
Label: flag.Label,
Type: "ucq",
Raw: flag.Raw,
ValidatorRe: flag.ValidatorRe,
Help: flag.Help,
ChoicesCost: flag.ChoicesCost,
Choice: flag.Choice,
LockedFile: flag.LockedFile,
NeedFlag: flag.NeedFlag,
})
}
params.FlagsUCQ = []ExerciceFlag{}
// Treat legacy MCQ flags as ExerciceFlag
for _, flag := range params.FlagsMCQ {
params.Flags = append(params.Flags, ExerciceFlag{
Id: flag.Id,
Label: flag.Label,
Type: "mcq",
ChoicesCost: flag.ChoicesCost,
Choice: flag.Choice,
LockedFile: flag.LockedFile,
NeedFlag: flag.NeedFlag,
})
}
params.FlagsMCQ = []ExerciceFlag{}
}
return
}

View file

@ -82,59 +82,112 @@ func getRawKey(input interface{}, validatorRe string, ordered bool) (raw string,
return return
} }
// SyncExerciceFlags reads the content of challenge.txt and import "classic" flags as Key for the given challenge. func buildKeyFlag(exercice fic.Exercice, flag ExerciceFlag, flagline int, defaultLabel string) (f *fic.Flag, choices []fic.FlagChoice, errs []string) {
func SyncExerciceFlags(i Importer, exercice fic.Exercice) (errs []string) {
if _, err := exercice.WipeFlags(); err != nil {
errs = append(errs, err.Error())
} else if _, err := exercice.WipeMCQs(); err != nil {
errs = append(errs, err.Error())
} else if params, err := parseExerciceParams(i, exercice.Path); err != nil {
errs = append(errs, fmt.Sprintf("%q: challenge.txt: %s", path.Base(exercice.Path), err))
} else if len(params.Flags) == 0 && len(params.FlagsUCQ) == 0 && len(params.FlagsMCQ) == 0 {
errs = append(errs, fmt.Sprintf("%q: has no flag", path.Base(exercice.Path)))
} else {
kmap := map[int64]fic.Flag{}
// Import UCQ flags
for _, flag := range params.FlagsUCQ {
params.Flags = append(params.Flags, ExerciceFlag{
Id: flag.Id,
Label: flag.Label,
Type: "ucq",
Raw: flag.Raw,
ValidatorRe: flag.ValidatorRe,
Help: flag.Help,
ChoicesCost: flag.ChoicesCost,
Choice: flag.Choice,
LockedFile: flag.LockedFile,
NeedFlag: flag.NeedFlag,
})
}
// Import MCQ flags
for _, flag := range params.FlagsMCQ {
params.Flags = append(params.Flags, ExerciceFlag{
Id: flag.Id,
Label: flag.Label,
Type: "mcq",
ChoicesCost: flag.ChoicesCost,
Choice: flag.Choice,
LockedFile: flag.LockedFile,
NeedFlag: flag.NeedFlag,
})
}
// Import normal flags
for nline, flag := range params.Flags {
if len(flag.Label) == 0 { if len(flag.Label) == 0 {
flag.Label = "Flag" flag.Label = defaultLabel
} }
if flag.Label[0] == '`' { if flag.Label[0] == '`' {
errs = append(errs, fmt.Sprintf("%q: flag #%d: Label should not begin with `.", path.Base(exercice.Path), nline + 1)) errs = append(errs, fmt.Sprintf("%q: flag #%d: Label should not begin with `.", path.Base(exercice.Path), flagline))
flag.Label = flag.Label[1:] flag.Label = flag.Label[1:]
} }
raw, prep, terrs := getRawKey(flag.Raw, flag.ValidatorRe, flag.Ordered)
if len(terrs) > 0 {
for _, err := range terrs {
errs = append(errs, fmt.Sprintf("%q: flag #%d: %s", path.Base(exercice.Path), flagline, err))
}
f = nil
return
}
flag.Label = prep + flag.Label
if !isFullGraphic(raw) {
errs = append(errs, fmt.Sprintf("%q: WARNING flag #%d: non-printable characters in flag, is this really expected?", path.Base(exercice.Path), flagline))
}
hashedFlag := fic.ComputeHashedFlag([]byte(raw))
fl := fic.Flag(fic.FlagKey{
IdExercice: exercice.Id,
Label: flag.Label,
Help: flag.Help,
IgnoreCase: flag.IgnoreCase,
ValidatorRegexp: validatorRegexp(flag.ValidatorRe),
Checksum: hashedFlag[:],
ChoicesCost: flag.ChoicesCost,
})
f = &fl
if len(flag.Choice) > 0 || flag.Type == "ucq" {
// Import choices
hasOne := false
if !flag.NoShuffle {
rand.Shuffle(len(flag.Choice), func(i, j int) {
flag.Choice[i], flag.Choice[j] = flag.Choice[j], flag.Choice[i]
})
}
for _, choice := range flag.Choice {
val, prep, terrs := getRawKey(choice.Value, "", false)
if len(terrs) > 0 {
for _, err := range terrs {
errs = append(errs, fmt.Sprintf("%q: flag #%d: %s", path.Base(exercice.Path), flagline, err))
}
continue
}
if len(choice.Label) == 0 {
choice.Label = val
}
choice.Label = prep + choice.Label
choices = append(choices, fic.FlagChoice{
Label: choice.Label,
Value: val,
})
if val == raw {
hasOne = true
}
}
if !hasOne {
errs = append(errs, fmt.Sprintf("%q: error in flag #%d: no valid answer defined.", path.Base(exercice.Path), flagline))
}
}
return
}
type importFlag struct {
Line int
Flag fic.Flag
Choices []fic.FlagChoice
FilesDeps []string
FlagsDeps []int64
}
// buildExerciceFlags read challenge.txt and extract all flags.
func buildExerciceFlags(i Importer, exercice fic.Exercice) (flags map[int64]importFlag, errs []string) {
params, gerrs := getExerciceParams(i, exercice)
if len(gerrs) > 0 {
return flags, gerrs
}
flags = map[int64]importFlag{}
for nline, flag := range params.Flags {
if flag.Id == 0 {
// TODO: should be more smart than that. Perhaps search to increment if possible.
flag.Id = rand.Int63()
}
// Ensure flag ID is unique
for _, ok := flags[flag.Id]; ok; _, ok = flags[flag.Id] {
errs = append(errs, fmt.Sprintf("%q: flag #%d: identifier already used (%d), using a random one.", path.Base(exercice.Path), nline+1, flag.Id))
flag.Id = rand.Int63()
}
switch strings.ToLower(flag.Type) { switch strings.ToLower(flag.Type) {
case "": case "":
flag.Type = "key" flag.Type = "key"
@ -145,76 +198,29 @@ func SyncExerciceFlags(i Importer, exercice fic.Exercice) (errs []string) {
case "mcq": case "mcq":
flag.Type = "mcq" flag.Type = "mcq"
default: default:
errs = append(errs, fmt.Sprintf("%q: flag #%d: invalid type of flag: should be 'key', 'mcq' or 'ucq'.", path.Base(exercice.Path), nline + 1)) errs = append(errs, fmt.Sprintf("%q: flag #%d: invalid type of flag: should be 'key', 'mcq' or 'ucq'.", path.Base(exercice.Path), nline+1))
continue continue
} }
var addedFlag fic.Flag
if flag.Type == "key" || flag.Type == "ucq" { if flag.Type == "key" || flag.Type == "ucq" {
raw, prep, terrs := getRawKey(flag.Raw, flag.ValidatorRe, flag.Ordered) addedFlag, choices, berrs := buildKeyFlag(exercice, flag, nline+1, "Flag")
if len(berrs) > 0 {
if len(terrs) > 0 { errs = append(errs, berrs...)
for _, err := range terrs {
errs = append(errs, fmt.Sprintf("%q: flag #%d: %s", path.Base(exercice.Path), nline + 1, err))
}
continue
}
flag.Label = prep + flag.Label
if !isFullGraphic(raw) {
errs = append(errs, fmt.Sprintf("%q: WARNING flag #%d: non-printable characters in flag, is this really expected?", path.Base(exercice.Path), nline + 1))
}
if k, err := exercice.AddRawFlagKey(flag.Label, flag.Help, flag.IgnoreCase, validatorRegexp(flag.ValidatorRe), []byte(raw), flag.ChoicesCost); err != nil {
errs = append(errs, fmt.Sprintf("%q: error flag #%d: %s", path.Base(exercice.Path), nline + 1, err))
continue
} else {
addedFlag = k
if len(flag.Choice) > 0 || flag.Type == "ucq" {
// Import choices
hasOne := false
if !flag.NoShuffle {
rand.Shuffle(len(flag.Choice), func(i, j int) {
flag.Choice[i], flag.Choice[j] = flag.Choice[j], flag.Choice[i]
})
}
for cid, choice := range flag.Choice {
val, prep, terrs := getRawKey(choice.Value, "", false)
if len(terrs) > 0 {
for _, err := range terrs {
errs = append(errs, fmt.Sprintf("%q: flag UCQ #%d: %s", path.Base(exercice.Path), nline + 1, err))
}
continue
}
if len(choice.Label) == 0 {
choice.Label = val
}
choice.Label = prep + choice.Label
if _, err := k.AddChoice(choice.Label, val); err != nil {
errs = append(errs, fmt.Sprintf("%q: error in UCQ %d choice %d: %s", path.Base(exercice.Path), nline + 1, cid, err))
continue
}
if val == raw {
hasOne = true
}
}
if !hasOne {
errs = append(errs, fmt.Sprintf("%q: error in UCQ %d: no valid answer defined.", path.Base(exercice.Path), nline + 1))
} }
if addedFlag != nil {
flags[flag.Id] = importFlag{
Line: nline + 1,
Flag: *addedFlag,
Choices: choices,
} }
} }
} else if flag.Type == "mcq" { } else if flag.Type == "mcq" {
if f, err := exercice.AddMCQ(flag.Label); err != nil { addedFlag := fic.MCQ{
errs = append(errs, fmt.Sprintf("%q: error flag MCQ #%d: %s", path.Base(exercice.Path), nline + 1, err)) IdExercice: exercice.Id,
continue Title: flag.Label,
} else { Entries: []fic.MCQ_entry{},
addedFlag = f }
hasOne := false hasOne := false
isJustified := false isJustified := false
@ -226,11 +232,10 @@ func SyncExerciceFlags(i Importer, exercice fic.Exercice) (errs []string) {
for cid, choice := range flag.Choice { for cid, choice := range flag.Choice {
var val bool var val bool
var justify string
if choice.Justification != nil { if choice.Justification != nil {
if hasOne && !isJustified { if hasOne && !isJustified {
errs = append(errs, fmt.Sprintf("%q: error MCQ #%d: all true items has to be justified in this MCQ.", path.Base(exercice.Path), nline + 1)) errs = append(errs, fmt.Sprintf("%q: error MCQ #%d: all true items has to be justified in this MCQ.", path.Base(exercice.Path), nline+1))
continue continue
} }
@ -239,77 +244,137 @@ func SyncExerciceFlags(i Importer, exercice fic.Exercice) (errs []string) {
} else if p, ok := choice.Value.(bool); ok { } else if p, ok := choice.Value.(bool); ok {
val = p val = p
if isJustified { if isJustified {
errs = append(errs, fmt.Sprintf("%q: error MCQ #%d: all true items has to be justified in this MCQ.", path.Base(exercice.Path), nline + 1)) errs = append(errs, fmt.Sprintf("%q: error MCQ #%d: all true items has to be justified in this MCQ.", path.Base(exercice.Path), nline+1))
continue continue
} }
} else if choice.Value == nil { } else if choice.Value == nil {
val = false val = false
} else { } else {
errs = append(errs, fmt.Sprintf("%q: error in MCQ %d choice %d: incorrect type for value: %T is not boolean.", path.Base(exercice.Path), nline + 1, cid, choice.Value)) errs = append(errs, fmt.Sprintf("%q: error in MCQ %d choice %d: incorrect type for value: %T is not boolean.", path.Base(exercice.Path), nline+1, cid, choice.Value))
continue continue
} }
if e, err := f.AddEntry(choice.Label, val); err != nil { addedFlag.Entries = append(addedFlag.Entries, fic.MCQ_entry{
errs = append(errs, fmt.Sprintf("%q: error in MCQ %d choice %d: %s", path.Base(exercice.Path), nline + 1, cid, err)) Label: choice.Label,
continue Response: val,
} else if isJustified && choice.Justification != nil { })
var prep string
var terrs []string
justify, prep, terrs = getRawKey(choice.Justification.Raw, choice.Justification.ValidatorRe, choice.Justification.Ordered)
if len(terrs) > 0 {
for _, err := range terrs {
errs = append(errs, fmt.Sprintf("%q: flag MCQ #%d, choice #%d: %s", path.Base(exercice.Path), nline + 1, cid, err))
}
continue
}
if len(choice.Justification.Label) == 0 { if isJustified && choice.Justification != nil {
choice.Justification.Label = "Flag correspondant" addedFlag, choices, berrs := buildKeyFlag(exercice, *choice.Justification, nline+1, "Flag correspondant")
if len(berrs) > 0 {
errs = append(errs, berrs...)
} }
choice.Justification.Label = prep + choice.Justification.Label if addedFlag != nil {
flags[flag.Id] = importFlag{
if _, err := exercice.AddRawFlagKey(fmt.Sprintf("%%%d%%%s", e.Id, choice.Justification.Label), choice.Justification.Help, choice.Justification.IgnoreCase, validatorRegexp(choice.Justification.ValidatorRe), []byte(justify), flag.ChoicesCost); err != nil { Line: nline,
errs = append(errs, fmt.Sprintf("%q: error MCQ #%d: %s", path.Base(exercice.Path), nline + 1, err)) Flag: *addedFlag,
continue Choices: choices,
} }
} }
if val {
hasOne = true
}
}
if !hasOne {
errs = append(errs, fmt.Sprintf("%q: warning MCQ %d: no valid answer defined, is this really expected?", path.Base(exercice.Path), nline + 1))
} }
} }
} }
if flag.Id != 0 { // Read dependency to flag
kmap[flag.Id] = addedFlag for _, nf := range flag.NeedFlag {
if v, ok := flags[flag.Id]; ok {
v.FlagsDeps = append(v.FlagsDeps, nf.Id)
flags[flag.Id] = v
} }
}
// Read dependency to file
for _, lf := range flag.LockedFile {
if v, ok := flags[flag.Id]; ok {
v.FilesDeps = append(v.FilesDeps, lf.Filename)
flags[flag.Id] = v
}
}
}
return
}
// CheckExerciceFlags checks if all flags for the given challenge are correct.
func CheckExerciceFlags(i Importer, exercice fic.Exercice, files []fic.EFile) (rf []fic.Flag, errs []string) {
flags, berrs := buildExerciceFlags(i, exercice)
errs = append(errs, berrs...)
for _, flag := range flags {
// Check dependency to flag
for _, nf := range flag.FlagsDeps {
if _, ok := flags[nf]; !ok {
errs = append(errs, fmt.Sprintf("%q: error flag #%d dependency to flag id=%d: id not defined", path.Base(exercice.Path), flag.Line, nf))
}
}
// Check dependency to file
for _, lf := range flag.FilesDeps {
found := false
for _, f := range files {
if f.Name == lf {
found = true
break
}
}
if !found {
errs = append(errs, fmt.Sprintf("%q: error flag #%d dependency to %s: No such file", path.Base(exercice.Path), flag.Line, lf))
}
}
rf = append(rf, flag.Flag)
}
return
}
// SyncExerciceFlags imports all kind of flags for the given challenge.
func SyncExerciceFlags(i Importer, exercice fic.Exercice) (errs []string) {
if _, err := exercice.WipeFlags(); err != nil {
errs = append(errs, err.Error())
} else if _, err := exercice.WipeMCQs(); err != nil {
errs = append(errs, err.Error())
} else {
flags, berrs := buildExerciceFlags(i, exercice)
errs = append(errs, berrs...)
kmap := map[int64]fic.Flag{}
// Import flags
for flagid, flag := range flags {
if addedFlag, err := exercice.AddFlag(flag.Flag); err != nil {
errs = append(errs, fmt.Sprintf("%q: error flag #%d: %s", path.Base(exercice.Path), flag.Line, err))
} else {
if f, ok := addedFlag.(fic.FlagKey); ok {
for _, choice := range flag.Choices {
if _, err := f.AddChoice(choice); err != nil {
errs = append(errs, fmt.Sprintf("%q: error in flag #%d choice #FIXME: %s", path.Base(exercice.Path), flag.Line, err))
}
}
}
kmap[flagid] = addedFlag
// Import dependency to flag // Import dependency to flag
for _, nf := range flag.NeedFlag { for _, nf := range flag.FlagsDeps {
if rf, ok := kmap[nf.Id]; !ok { if rf, ok := kmap[nf]; !ok {
errs = append(errs, fmt.Sprintf("%q: error flag #%d dependency to flag id=%d: id not defined, perhaps not available at time of processing", path.Base(exercice.Path), nline + 1, nf.Id)) errs = append(errs, fmt.Sprintf("%q: error flag #%d dependency to flag id=%d: id not defined, perhaps not available at time of processing", path.Base(exercice.Path), flag.Line, nf))
continue
} else if err := addedFlag.AddDepend(rf); err != nil { } else if err := addedFlag.AddDepend(rf); err != nil {
errs = append(errs, fmt.Sprintf("%q: error flag #%d dependency to id=%d: %s", path.Base(exercice.Path), nline + 1, nf.Id, err)) errs = append(errs, fmt.Sprintf("%q: error flag #%d dependency to id=%d: %s", path.Base(exercice.Path), flag.Line, nf, err))
continue
} }
} }
// Import dependency to file // Import dependency to file
for _, lf := range flag.LockedFile { for _, lf := range flag.FilesDeps {
if rf, err := exercice.GetFileByFilename(lf.Filename); err != nil { if rf, err := exercice.GetFileByFilename(lf); err != nil {
errs = append(errs, fmt.Sprintf("%q: error flag #%d dependency to %s: %s", path.Base(exercice.Path), nline + 1, lf.Filename, err)) errs = append(errs, fmt.Sprintf("%q: error flag #%d dependency to %s: %s", path.Base(exercice.Path), flag.Line, lf, err))
continue
} else if err := rf.AddDepend(addedFlag); err != nil { } else if err := rf.AddDepend(addedFlag); err != nil {
errs = append(errs, fmt.Sprintf("%q: error flag #%d dependency to %s: %s", path.Base(exercice.Path), nline + 1, lf.Filename, err)) errs = append(errs, fmt.Sprintf("%q: error flag #%d dependency to %s: %s", path.Base(exercice.Path), flag.Line, lf, err))
continue
} }
} }
} }
} }
}
return return
} }

View file

@ -163,7 +163,7 @@ func (t Theme) addExercice(e *Exercice) (err error) {
cc = fmt.Sprintf("%f", e.Coefficient) cc = fmt.Sprintf("%f", e.Coefficient)
} }
if res, err := DBExec("INSERT INTO exercices (id_theme, title, url_id, path, statement, overview, finished, headline, issue, depend, gain, video_uri, issue_kind, coefficient_cur) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + ik + ", " + cc + ")", t.Id, e.Title, e.URLId, e.Path, e.Statement, e.Overview, e.Finished, e.Headline, e.Issue, e.Depend, e.Gain, e.VideoURI); err != nil { if res, err := DBExec("INSERT INTO exercices (id_theme, title, url_id, path, statement, overview, finished, headline, issue, depend, gain, video_uri, issue_kind, coefficient_cur) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "+ik+", "+cc+")", t.Id, e.Title, e.URLId, e.Path, e.Statement, e.Overview, e.Finished, e.Headline, e.Issue, e.Depend, e.Gain, e.VideoURI); err != nil {
return err return err
} else if eid, err := res.LastInsertId(); err != nil { } else if eid, err := res.LastInsertId(); err != nil {
return err return err
@ -313,7 +313,7 @@ func (e Exercice) UpdateTry(t Team, nbdiff int) error {
// Solved registers that the given Team solves the challenge. // Solved registers that the given Team solves the challenge.
func (e Exercice) Solved(t Team) error { func (e Exercice) Solved(t Team) error {
if _, err := DBExec("INSERT INTO exercice_solved (id_exercice, id_team, time, coefficient) VALUES (?, ?, ?, ?)", e.Id, t.Id, time.Now(), e.Coefficient * ExerciceCurrentCoefficient); err != nil { if _, err := DBExec("INSERT INTO exercice_solved (id_exercice, id_team, time, coefficient) VALUES (?, ?, ?, ?)", e.Id, t.Id, time.Now(), e.Coefficient*ExerciceCurrentCoefficient); err != nil {
return err return err
} else { } else {
return nil return nil
@ -338,7 +338,7 @@ func (e Exercice) TriedTeamCount() int64 {
} }
var nb int64 var nb int64
if err := DBQueryRow("SELECT COUNT(DISTINCT id_team) FROM " + tries_table + " WHERE id_exercice = ?", e.Id).Scan(&nb); err != nil { if err := DBQueryRow("SELECT COUNT(DISTINCT id_team) FROM "+tries_table+" WHERE id_exercice = ?", e.Id).Scan(&nb); err != nil {
return 0 return 0
} else { } else {
return nb return nb
@ -353,7 +353,7 @@ func (e Exercice) TriedCount() int64 {
} }
var nb int64 var nb int64
if err := DBQueryRow("SELECT COUNT(id_team) FROM " + tries_table + " WHERE id_exercice = ?", e.Id).Scan(&nb); err != nil { if err := DBQueryRow("SELECT COUNT(id_team) FROM "+tries_table+" WHERE id_exercice = ?", e.Id).Scan(&nb); err != nil {
return 0 return 0
} else { } else {
return nb return nb

View file

@ -3,9 +3,11 @@ package fic
import () import ()
type Flag interface { type Flag interface {
GetId() int64
Create(e Exercice) (Flag, error)
Update() (int64, error) Update() (int64, error)
Delete() (int64, error) Delete() (int64, error)
AddDepend(d Flag) (error) AddDepend(d Flag) error
GetDepends() ([]Flag, error) GetDepends() ([]Flag, error)
Check(val interface{}) int Check(val interface{}) int
FoundBy(t Team) FoundBy(t Team)
@ -34,6 +36,11 @@ func (e Exercice) GetFlags() ([]Flag, error) {
return flags, nil return flags, nil
} }
// AddFlag add the given flag and eventually its entries (from MCQ).
func (e Exercice) AddFlag(flag Flag) (f Flag, err error) {
return flag.Create(e)
}
// WipeFlags deletes flags coming with the challenge. // WipeFlags deletes flags coming with the challenge.
func (e Exercice) WipeFlags() (int64, error) { func (e Exercice) WipeFlags() (int64, error) {
if _, err := DBExec("DELETE FROM exercice_files_deps WHERE id_flag IN (SELECT id_flag FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil { if _, err := DBExec("DELETE FROM exercice_files_deps WHERE id_flag IN (SELECT id_flag FROM exercice_flags WHERE id_exercice = ?)", e.Id); err != nil {

View file

@ -48,13 +48,12 @@ func (f FlagKey) GetChoice(id int64) (c FlagChoice, err error) {
} }
// AddChoice creates and fills a new struct FlagChoice, from a label and a value. // AddChoice creates and fills a new struct FlagChoice, from a label and a value.
func (f FlagKey) AddChoice(label string, value string) (FlagChoice, error) { func (f FlagKey) AddChoice(c FlagChoice) (FlagChoice, error) {
if res, err := DBExec("INSERT INTO flag_choices (id_flag, label, response) VALUES (?, ?, ?)", f.Id, label, value); err != nil { if res, err := DBExec("INSERT INTO flag_choices (id_flag, label, response) VALUES (?, ?, ?)", f.Id, c.Label, c.Value); err != nil {
return FlagChoice{}, err return c, err
} else if cid, err := res.LastInsertId(); err != nil {
return FlagChoice{}, err
} else { } else {
return FlagChoice{cid, f.Id, label, value}, nil c.Id, err = res.LastInsertId()
return c, err
} }
} }

View file

@ -67,14 +67,14 @@ func (e Exercice) GetFlagKeyByLabel(label string) (k FlagKey, err error) {
return return
} }
// getHashedFlag calculates the expected checksum for the given raw_value. // ComputeHashedFlag calculates the expected checksum for the given raw_value.
func getHashedFlag(raw_value []byte) [blake2b.Size]byte { func ComputeHashedFlag(raw_value []byte) [blake2b.Size]byte {
hash := blake2b.Sum512(raw_value) hash := blake2b.Sum512(raw_value)
return hash return hash
} }
func ExecValidatorRegexp(vre string, val []byte, ignorecase bool) ([]byte, error) { func ExecValidatorRegexp(vre string, val []byte, ignorecase bool) ([]byte, error) {
if (ignorecase) { if ignorecase {
vre = "(?i)" + vre vre = "(?i)" + vre
} }
if re, err := regexp.Compile(vre); err != nil { if re, err := regexp.Compile(vre); err != nil {
@ -87,38 +87,55 @@ func ExecValidatorRegexp(vre string, val []byte, ignorecase bool) ([]byte, error
} }
// AddRawFlagKey creates and fills a new struct FlagKey, from a non-hashed flag, and registers it into the database. // AddRawFlagKey creates and fills a new struct FlagKey, from a non-hashed flag, and registers it into the database.
func (e Exercice) AddRawFlagKey(name string, help string, ignorecase bool, validator_regexp *string, raw_value []byte, choicescost int64) (FlagKey, error) { func (e Exercice) AddRawFlagKey(name string, help string, ignorecase bool, validator_regexp *string, raw_value []byte, choicescost int64) (f FlagKey, err error) {
if ignorecase { if ignorecase {
raw_value = bytes.ToLower(raw_value) raw_value = bytes.ToLower(raw_value)
} }
// Check that raw value passes through the regexp // Check that raw value passes through the regexp
if validator_regexp != nil { if validator_regexp != nil {
var err error
if raw_value, err = ExecValidatorRegexp(*validator_regexp, raw_value, ignorecase); err != nil { if raw_value, err = ExecValidatorRegexp(*validator_regexp, raw_value, ignorecase); err != nil {
return FlagKey{}, err return
} }
} }
hash := getHashedFlag(raw_value) hash := ComputeHashedFlag(raw_value)
return e.AddFlagKey(name, help, ignorecase, validator_regexp, hash[:], choicescost)
f = FlagKey{
Label: name,
Help: help,
IgnoreCase: ignorecase,
ValidatorRegexp: validator_regexp,
Checksum: hash[:],
ChoicesCost: choicescost,
}
_, err = f.Create(e)
return
}
// GetId returns the Flag identifier.
func (k FlagKey) GetId() int64 {
return k.Id
} }
// AddFlagKey creates and fills a new struct Flag, from a hashed flag, and registers it into the database. // AddFlagKey creates and fills a new struct Flag, from a hashed flag, and registers it into the database.
func (e Exercice) AddFlagKey(name string, help string, ignorecase bool, validator_regexp *string, checksum []byte, choicescost int64) (FlagKey, error) { func (k FlagKey) Create(e Exercice) (Flag, error) {
// Check the regexp compile // Check the regexp compile
if validator_regexp != nil { if k.ValidatorRegexp != nil {
if _, err := regexp.Compile(*validator_regexp); err != nil { if _, err := regexp.Compile(*k.ValidatorRegexp); err != nil {
return FlagKey{}, err return k, err
} }
} }
if res, err := DBExec("INSERT INTO exercice_flags (id_exercice, type, help, ignorecase, validator_regexp, cksum, choices_cost) VALUES (?, ?, ?, ?, ?, ?, ?)", e.Id, name, help, ignorecase, validator_regexp, checksum, choicescost); err != nil { if res, err := DBExec("INSERT INTO exercice_flags (id_exercice, type, help, ignorecase, validator_regexp, cksum, choices_cost) VALUES (?, ?, ?, ?, ?, ?, ?)", e.Id, k.Label, k.Help, k.IgnoreCase, k.ValidatorRegexp, k.Checksum, k.ChoicesCost); err != nil {
return FlagKey{}, err return k, err
} else if kid, err := res.LastInsertId(); err != nil { } else if kid, err := res.LastInsertId(); err != nil {
return FlagKey{}, err return k, err
} else { } else {
return FlagKey{kid, e.Id, name, help, ignorecase, validator_regexp, checksum, choicescost}, nil k.Id = kid
k.IdExercice = e.Id
return k, nil
} }
} }
@ -140,7 +157,7 @@ func (k FlagKey) ComputeChecksum(val []byte) (cksum []byte, err error) {
err = errors.New("Empty flag after applying filters") err = errors.New("Empty flag after applying filters")
} }
hash := getHashedFlag(val) hash := ComputeHashedFlag(val)
return hash[:], err return hash[:], err
} }

View file

@ -97,14 +97,31 @@ func GetMCQbyChoice(cid int64) (m MCQ, c MCQ_entry, err error) {
return return
} }
// AddMCQ creates and fills a new struct MCQ and registers it into the database. // GetId returns the MCQ identifier.
func (e Exercice) AddMCQ(title string) (MCQ, error) { func (m MCQ) GetId() int64 {
if res, err := DBExec("INSERT INTO exercice_mcq (id_exercice, title) VALUES (?, ?)", e.Id, title); err != nil { return m.Id
return MCQ{}, err }
// Create registers a MCQ into the database and recursively add its entries.
func (m MCQ) Create(e Exercice) (Flag, error) {
if res, err := DBExec("INSERT INTO exercice_mcq (id_exercice, title) VALUES (?, ?)", e.Id, m.Title); err != nil {
return m, err
} else if qid, err := res.LastInsertId(); err != nil { } else if qid, err := res.LastInsertId(); err != nil {
return MCQ{}, err return m, err
} else { } else {
return MCQ{qid, e.Id, title, []MCQ_entry{}}, nil m.Id = qid
m.IdExercice = e.Id
// Add entries
for k, entry := range m.Entries {
if entry, err = m.AddEntry(entry); err != nil {
return m, err
} else {
m.Entries[k] = entry
}
}
return m, nil
} }
} }
@ -135,13 +152,14 @@ func (m MCQ) Delete() (int64, error) {
} }
// AddEntry creates and fills a new struct MCQ_entry and registers it into the database. // AddEntry creates and fills a new struct MCQ_entry and registers it into the database.
func (m MCQ) AddEntry(label string, response bool) (MCQ_entry, error) { func (m MCQ) AddEntry(e MCQ_entry) (MCQ_entry, error) {
if res, err := DBExec("INSERT INTO mcq_entries (id_mcq, label, response) VALUES (?, ?, ?)", m.Id, label, response); err != nil { if res, err := DBExec("INSERT INTO mcq_entries (id_mcq, label, response) VALUES (?, ?, ?)", m.Id, e.Label, e.Response); err != nil {
return MCQ_entry{}, err return e, err
} else if nid, err := res.LastInsertId(); err != nil { } else if nid, err := res.LastInsertId(); err != nil {
return MCQ_entry{}, err return e, err
} else { } else {
return MCQ_entry{nid, label, response}, nil e.Id = nid
return e, nil
} }
} }