server/admin/api_file.go

76 lines
1.6 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"
)
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")
}
hash := sha512.Sum512([]byte(uf.URI))
pathname := path.Join(fic.FilesDir, strings.ToLower(base32.StdEncoding.EncodeToString(hash[:])), path.Base(uf.URI))
2016-01-20 21:44:34 +00:00
if _, err := os.Stat(pathname); os.IsNotExist(err) {
log.Println("Import file from Cloud:", uf.URI, "=>", 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 := getCloudFile(uf.URI, 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, uf.URI)
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
}