server/admin/api_file.go

86 lines
2.0 KiB
Go
Raw Normal View History

2016-01-20 21:44:34 +00:00
package main
import (
2016-01-23 11:19:47 +00:00
"bufio"
2016-01-20 21:44:34 +00:00
"crypto/sha512"
"encoding/base32"
"encoding/json"
"errors"
"log"
2016-01-20 21:44:34 +00:00
"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
2016-01-20 21:44:34 +00:00
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")
2016-01-20 21:44:34 +00:00
}
pathname := path.Join(fic.FilesDir, strings.ToLower(base32.StdEncoding.EncodeToString(hash[:])), path.Base(fromURI))
2016-01-20 21:44:34 +00:00
if _, err := os.Stat(pathname); os.IsNotExist(err) {
log.Println(logStr, pathname)
2016-01-23 11:19:47 +00:00
if err := os.MkdirAll(path.Dir(pathname), 0777); err != nil {
return nil, err
} else if err := getFile(pathname); err != nil {
2016-01-20 21:44:34 +00:00
return nil, err
}
2016-01-20 21:44:34 +00:00
}
return exercice.ImportFile(pathname, fromURI)
2016-01-20 21:44:34 +00:00
}
2016-01-23 12:19:28 +00:00
func getCloudFile(pathname string, dest string) error {
2016-01-20 21:44:34 +00:00
client := http.Client{}
if req, err := http.NewRequest("GET", CloudDAVBase+pathname, nil); err != nil {
2016-01-23 11:19:47 +00:00
return err
2016-01-20 21:44:34 +00:00
} else {
req.SetBasicAuth(CloudUsername, CloudPassword)
if resp, err := client.Do(req); err != nil {
2016-01-23 11:19:47 +00:00
return err
2016-01-20 21:44:34 +00:00
} else {
defer resp.Body.Close()
2016-01-23 11:19:47 +00:00
if fd, err := os.Create(dest); err != nil {
return err
2016-01-20 21:44:34 +00:00
} else {
2016-01-23 12:19:28 +00:00
defer fd.Close()
2016-01-23 11:19:47 +00:00
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()
}
2016-01-20 21:44:34 +00:00
}
}
}
2016-01-23 11:19:47 +00:00
return nil
2016-01-20 21:44:34 +00:00
}