Import file from owncloud
This commit is contained in:
parent
97bb149eb6
commit
69ad64715c
6 changed files with 104 additions and 28 deletions
65
admin/api_file.go
Normal file
65
admin/api_file.go
Normal file
|
@ -0,0 +1,65 @@
|
|||
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 body, err := ioutil.ReadAll(resp.Body); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return body, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in a new issue