server/libfic/file.go

86 lines
2.1 KiB
Go

package fic
import (
"crypto/sha1"
"io"
"os"
"path"
)
type EFile struct {
Id int64 `json:"id"`
Path string `json:"path"`
IdExercice int64 `json:"idExercice"`
Name string `json:"name"`
Checksum []byte `json:"checksum"`
}
func (e Exercice) GetFiles() ([]EFile, error) {
if rows, err := DBQuery("SELECT id_file, path, name, sha1 FROM exercice_files WHERE id_exercice = ?", e.Id); err != nil {
return nil, err
} else {
defer rows.Close()
var files = make([]EFile, 0)
for rows.Next() {
var f EFile
f.IdExercice = e.Id
if err := rows.Scan(&f.Id, &f.Path, &f.Name, &f.Checksum); err != nil {
return nil, err
}
files = append(files, f)
}
if err := rows.Err(); err != nil {
return nil, err
}
return files, nil
}
}
func (e Exercice) ImportFile(filePath string) (EFile, error) {
if fd, err := os.Open(filePath); err != nil {
return EFile{}, err
} else {
defer fd.Close()
hash := sha1.New()
if _, err := io.Copy(hash, fd); err != nil {
return EFile{}, err
}
var result []byte
return e.AddFile(filePath, path.Base(filePath), hash.Sum(result))
}
}
func (e Exercice) AddFile(path string, name string, checksum []byte) (EFile, error) {
if res, err := DBExec("INSERT INTO exercice_files (id_exercice, path, name, sha1) VALUES (?, ?, ?, ?)", e.Id, path, name, checksum); err != nil {
return EFile{}, err
} else if fid, err := res.LastInsertId(); err != nil {
return EFile{}, err
} else {
return EFile{fid, path, e.Id, name, checksum}, nil
}
}
func (f EFile) Update() (int64, error) {
if res, err := DBExec("UPDATE exercice_files SET id_exercice = ?, path = ?, name = ?, sha1 = ? WHERE id_file = ?", f.IdExercice, f.Path, f.Name, f.Checksum, f.Id); err != nil {
return 0, err
} else if nb, err := res.RowsAffected(); err != nil {
return 0, err
} else {
return nb, err
}
}
func (f EFile) Delete() (int64, error) {
if res, err := DBExec("DELETE FROM exercice_files WHERE id_file = ?", f.Id); err != nil {
return 0, err
} else if nb, err := res.RowsAffected(); err != nil {
return 0, err
} else {
return nb, err
}
}