server/admin/api_file.go

86 lines
2.0 KiB
Go

package main
import (
"bufio"
"crypto/sha512"
"encoding/base32"
"encoding/json"
"errors"
"log"
"net/http"
"os"
"path"
"strings"
"srs.epita.fr/fic-server/libfic"
)
func createExerciceFile(theme fic.Theme, exercice fic.Exercice, args []string, body []byte) (interface{}, error) {
var uf map[string]string
if err := json.Unmarshal(body, &uf); err != nil {
return nil, err
}
var hash [sha512.Size]byte
var logStr string
var fromURI string
var getFile func(string) error
if URI, ok := uf["URI"]; ok {
hash = sha512.Sum512([]byte(URI))
logStr = "Import file from Cloud: " + URI + " =>"
fromURI = URI
getFile = func(dest string) error { return getCloudFile(URI, dest) }
} else if path, ok := uf["path"]; ok {
hash = sha512.Sum512([]byte(path))
logStr = "Import file from local FS: " + path + " =>"
fromURI = path
getFile = func(dest string) error { return os.Symlink(path, dest) }
} else {
return nil, errors.New("URI or path not filled")
}
pathname := path.Join(fic.FilesDir, strings.ToLower(base32.StdEncoding.EncodeToString(hash[:])), path.Base(fromURI))
if _, err := os.Stat(pathname); os.IsNotExist(err) {
log.Println(logStr, pathname)
if err := os.MkdirAll(path.Dir(pathname), 0777); err != nil {
return nil, err
} else if err := getFile(pathname); err != nil {
return nil, err
}
}
return exercice.ImportFile(pathname, fromURI)
}
func getCloudFile(pathname string, dest string) error {
client := http.Client{}
if req, err := http.NewRequest("GET", CloudDAVBase+pathname, nil); err != nil {
return err
} else {
req.SetBasicAuth(CloudUsername, CloudPassword)
if resp, err := client.Do(req); err != nil {
return err
} else {
defer resp.Body.Close()
if fd, err := os.Create(dest); err != nil {
return err
} else {
defer fd.Close()
if resp.StatusCode != http.StatusOK {
return errors.New(resp.Status)
} else {
writer := bufio.NewWriter(fd)
reader := bufio.NewReader(resp.Body)
reader.WriteTo(writer)
writer.Flush()
}
}
}
}
return nil
}