6158cb8b046b87c30ae45996904dc39ea5a7f773
[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 "strings"
11 "time"
12
13 "golang.org/x/exp/inotify"
14 "srs.epita.fr/fic-server/libfic"
15 )
16
17 var SubmissionDir string
18 var BaseURL string
19
20 func watchsubdir(watcher *inotify.Watcher, pathname string) error {
21 log.Println("Watch new directory:", pathname)
22 if err := watcher.AddWatch(pathname, inotify.IN_CLOSE_WRITE|inotify.IN_CREATE); err != nil {
23 return err
24 }
25
26 if ds, err := ioutil.ReadDir(pathname); err != nil {
27 return err
28 } else {
29 for _, d := range ds {
30 p := path.Join(pathname, d.Name())
31 if d.IsDir() {
32 if err := watchsubdir(watcher, p); err != nil {
33 return err
34 }
35 }
36 }
37 return nil
38 }
39 }
40
41 func main() {
42 var dbfile = flag.String("db", "fic.db", "Path to the DB")
43 flag.StringVar(&BaseURL, "baseurl", "http://fic.srs.epita.fr/", "URL prepended to each URL")
44 flag.StringVar(&SubmissionDir, "submission", "./submissions", "Base directory where save submissions")
45 flag.Parse()
46
47 SubmissionDir = path.Clean(SubmissionDir)
48
49 rand.Seed(time.Now().UnixNano())
50
51 log.Println("Creating submission directory...")
52 if _, err := os.Stat(SubmissionDir); os.IsNotExist(err) {
53 if err := os.MkdirAll(SubmissionDir, 0777); err != nil {
54 log.Fatal("Unable to create submission directory: ", err)
55 }
56 }
57
58 log.Println("Opening DB...")
59 if err := fic.DBInit(*dbfile); err != nil {
60 log.Fatal("Cannot open the database: ", err)
61 os.Exit(1)
62
63 }
64 defer fic.DBClose()
65
66 log.Println("Registering directory events...")
67 watcher, err := inotify.NewWatcher()
68 if err != nil {
69 log.Fatal(err)
70 }
71
72 if err := watchsubdir(watcher, SubmissionDir); err != nil {
73 log.Fatal(err)
74 }
75
76 for {
77 select {
78 case ev := <-watcher.Event:
79 if ev.Mask&inotify.IN_CREATE == inotify.IN_CREATE {
80 // Register new subdirectory
81 if d, err := os.Stat(ev.Name); err == nil && d.IsDir() {
82 if err := watchsubdir(watcher, ev.Name); err != nil {
83 log.Println(err)
84 }
85 }
86 } else if ev.Mask&inotify.IN_CLOSE_WRITE == inotify.IN_CLOSE_WRITE {
87 // Extract
88 spath := strings.Split(strings.TrimPrefix(ev.Name, SubmissionDir), "/")
89
90 go treatSubmission(ev.Name, spath[1], spath[2])
91 }
92 case err := <-watcher.Error:
93 log.Println("error:", err)
94 }
95 }
96 }