frontend: allow partial settings (used when publicly published)
[fic/server.git] / backend / main.go
1 package main
2
3 import (
4         "flag"
5         "io/ioutil"
6         "log"
7         "math/rand"
8         "os"
9         "path"
10         "strconv"
11         "strings"
12         "time"
13
14         "srs.epita.fr/fic-server/libfic"
15         "srs.epita.fr/fic-server/settings"
16
17         "gopkg.in/fsnotify.v1"
18 )
19
20 var TeamsDir string
21 var SubmissionDir string
22
23 func watchsubdir(watcher *fsnotify.Watcher, pathname string) error {
24         log.Println("Watch new directory:", pathname)
25         if err := watcher.Add(pathname); err != nil {
26                 return err
27         }
28
29         if ds, err := ioutil.ReadDir(pathname); err != nil {
30                 return err
31         } else {
32                 for _, d := range ds {
33                         p := path.Join(pathname, d.Name())
34                         if d.IsDir() && d.Name() != ".tmp" && d.Mode() & os.ModeSymlink == 0 {
35                                 if err := watchsubdir(watcher, p); err != nil {
36                                         return err
37                                 }
38                         } else if d.Mode().IsRegular() {
39                                 go treat(p)
40                         }
41                 }
42                 return nil
43         }
44 }
45
46 var ChStarted = false
47 var lastRegeneration time.Time
48 var skipInitialGeneration = false
49
50 func reloadSettings(config settings.FICSettings) {
51         allowRegistration = config.AllowRegistration
52         canJoinTeam = config.CanJoinTeam
53         fic.HintCoefficient = config.HintCurCoefficient
54         fic.WChoiceCoefficient = config.WChoiceCurCoefficient
55         fic.ExerciceCurrentCoefficient = config.ExerciceCurCoefficient
56         ChStarted = time.Since(config.Start) >= 0
57         if lastRegeneration != config.Generation || fic.PartialValidation != config.PartialValidation || fic.UnlockedChallengeDepth != config.UnlockedChallengeDepth || fic.DisplayAllFlags != config.DisplayAllFlags || fic.FirstBlood != config.FirstBlood || fic.SubmissionCostBase != config.SubmissionCostBase || fic.SubmissionUniqueness != config.SubmissionUniqueness {
58                 fic.PartialValidation = config.PartialValidation
59                 fic.UnlockedChallengeDepth = config.UnlockedChallengeDepth
60                 fic.DisplayAllFlags = config.DisplayAllFlags
61
62                 fic.FirstBlood = config.FirstBlood
63                 fic.SubmissionCostBase = config.SubmissionCostBase
64                 fic.SubmissionUniqueness = config.SubmissionUniqueness
65
66                 if !skipInitialGeneration {
67                         log.Println("Generating files...")
68                         go func() {
69                                 genAll()
70                                 log.Println("Full generation done")
71                         }()
72                 } else {
73                         skipInitialGeneration = false
74                         log.Println("Regeneration skipped by option.")
75                 }
76                 lastRegeneration = config.Generation
77         } else {
78                 log.Println("No change found. Skipping regeneration.")
79         }
80 }
81
82 func main() {
83         var dsn = flag.String("dsn", fic.DSNGenerator(), "DSN to connect to the MySQL server")
84         flag.StringVar(&settings.SettingsDir, "settings", settings.SettingsDir, "Base directory where load and save settings")
85         flag.StringVar(&SubmissionDir, "submission", "./submissions", "Base directory where save submissions")
86         flag.StringVar(&TeamsDir, "teams", "./TEAMS", "Base directory where save teams JSON files")
87         flag.StringVar(&fic.FilesDir, "files", "/files", "Request path prefix to reach files")
88         var debugINotify = flag.Bool("debuginotify", false, "Show skipped inotofy events")
89         flag.BoolVar(&skipInitialGeneration, "skipfullgeneration", skipInitialGeneration, "Skip the initial regeneration")
90         flag.Parse()
91
92         log.SetPrefix("[backend] ")
93
94         settings.SettingsDir = path.Clean(settings.SettingsDir)
95         SubmissionDir = path.Clean(SubmissionDir)
96         TeamsDir = path.Clean(TeamsDir)
97
98         rand.Seed(time.Now().UnixNano())
99
100         log.Println("Creating submission directory...")
101         if _, err := os.Stat(SubmissionDir); os.IsNotExist(err) {
102                 if err := os.MkdirAll(SubmissionDir, 0777); err != nil {
103                         log.Fatal("Unable to create submission directory: ", err)
104                 }
105         }
106
107         log.Println("Opening DB...")
108         if err := fic.DBInit(*dsn); err != nil {
109                 log.Fatal("Cannot open the database: ", err)
110         }
111         defer fic.DBClose()
112
113         // Load configuration
114         settings.LoadAndWatchSettings(path.Join(settings.SettingsDir, settings.SettingsFile), reloadSettings)
115
116         log.Println("Registering directory events...")
117         watcher, err := fsnotify.NewWatcher()
118         if err != nil {
119                 log.Fatal(err)
120         }
121         defer watcher.Close()
122
123         if err := watchsubdir(watcher, SubmissionDir); err != nil {
124                 log.Fatal(err)
125         }
126
127         watchedNotify := fsnotify.Create
128
129         for {
130                 select {
131                 case ev := <-watcher.Events:
132                         if d, err := os.Lstat(ev.Name); err == nil && ev.Op & fsnotify.Create == fsnotify.Create && d.Mode().IsDir() && d.Mode() & os.ModeSymlink == 0 && d.Name() != ".tmp" {
133                                 // Register new subdirectory
134                                 if err := watchsubdir(watcher, ev.Name); err != nil {
135                                         log.Println(err)
136                                 }
137                         } else if ev.Op & watchedNotify == watchedNotify && d.Mode().IsRegular() {
138                                 if *debugINotify {
139                                         log.Println("Treating event:", ev, "for", ev.Name)
140                                 }
141                                 go treat(ev.Name)
142                         } else if ev.Op & fsnotify.Write == fsnotify.Write {
143                                 log.Println("FSNOTIFY WRITE SEEN. Prefer looking at them, as it appears files are not atomically moved.")
144                                 watchedNotify = fsnotify.Write
145                         } else if *debugINotify {
146                                 log.Println("Skipped event:", ev, "for", ev.Name)
147                         }
148                 case err := <-watcher.Errors:
149                         log.Println("error:", err)
150                 }
151         }
152 }
153
154 func treat(raw_path string) {
155         // Extract
156         spath := strings.Split(strings.TrimPrefix(raw_path, SubmissionDir), "/")
157
158         if len(spath) == 3 {
159                 if spath[1] == "_registration" {
160                         treatRegistration(raw_path, spath[2])
161                         return
162                 }
163
164                 var teamid int64
165                 var err error
166
167                 if teamid, err = strconv.ParseInt(spath[1], 10, 64); err != nil {
168                         if lnk, err := os.Readlink(path.Join(TeamsDir, spath[1])); err != nil {
169                                 log.Println("[ERR]", err)
170                                 return
171                         } else if teamid, err = strconv.ParseInt(lnk, 10, 64); err != nil {
172                                 log.Println("[ERR]", err)
173                                 return
174                         }
175                 }
176
177                 var team fic.Team
178                 if team, err = fic.GetTeam(teamid); err != nil {
179                         log.Println("[ERR]", err)
180                         return
181                 }
182
183                 switch spath[2] {
184                 case "name":
185                         treatRename(raw_path, team)
186                 case "hint":
187                         treatOpeningHint(raw_path, team)
188                 case "choices":
189                         treatWantChoices(raw_path, team)
190                 default:
191                         treatSubmission(raw_path, team, spath[2])
192                 }
193         } else {
194                 log.Println("Invalid new file:", raw_path)
195         }
196 }