package main import ( "crypto/sha512" "encoding/base32" "encoding/json" "errors" "io/ioutil" "net/http" "os" "path" "strings" "srs.epita.fr/fic-server/libfic" ) type uploadedFile struct { URI string } func createExerciceFile(theme fic.Theme, exercice fic.Exercice, args []string, body []byte) (interface{}, error) { var uf uploadedFile if err := json.Unmarshal(body, &uf); err != nil { return nil, err } if len(uf.URI) == 0 { return nil, errors.New("URI not filled") } if body, err := getCloudFile(uf.URI); err != nil { return nil, err } else { hash := sha512.Sum512([]byte(uf.URI)) pathname := path.Join(fic.FilesDir, strings.ToLower(base32.StdEncoding.EncodeToString(hash[:])), path.Base(uf.URI)) if err := os.MkdirAll(path.Dir(pathname), 0777); err != nil { return nil, err } if err := ioutil.WriteFile(pathname, body, 0777); err != nil { return nil, err } return exercice.ImportFile(pathname, uf.URI) } } func getCloudFile(pathname string) ([]byte, error) { client := http.Client{} if req, err := http.NewRequest("GET", CloudDAVBase+pathname, nil); err != nil { return nil, err } else { req.SetBasicAuth(CloudUsername, CloudPassword) if resp, err := client.Do(req); err != nil { return nil, err } else { defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, errors.New(resp.Status) } else if body, err := ioutil.ReadAll(resp.Body); err != nil { return nil, err } else { return body, nil } } } }