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