filegate/files/filemanager.go

92 lines
1.8 KiB
Go

package files
import (
"fmt"
"git.jmbit.de/filegate/filegate/database"
"github.com/gin-gonic/gin"
"io"
"log"
"net/http"
"net/url"
"os"
"strings"
)
func StorageDirectory() {
if _, err := os.Stat("./filesstore"); os.IsNotExist(err) {
err := os.Mkdir("./filestore", 770)
if err != nil {
log.Println(fmt.Sprintf("Could not create File directory: %s", err))
}
}
if os.Getenv("GIN_MODE") != "release" {
err := os.RemoveAll("./filestore/*")
if err != nil {
return
}
}
}
func DownloadFile(rawURL string, id string) error {
fileURL, err := url.Parse(rawURL)
if err != nil {
log.Println(err)
return err
}
response, err := http.Get(rawURL)
if err != nil {
log.Println(err)
return err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Println(err)
}
}(response.Body)
path := fileURL.Path
splitPath := strings.Split(path, "/")
fileName := splitPath[len(splitPath)-1]
fmt.Printf("Downloading file %s, OG Name: %s, Path: %s \n", id, fileName, path)
database.UpdateOriginalName(id, fileName)
targetFile, err := os.Create(fmt.Sprintf("./filestore/%s", id))
if err != nil {
log.Println(err)
return err
}
defer func(targetFile *os.File) {
err = targetFile.Close()
if err != nil {
log.Println(err)
}
}(targetFile)
contentType := response.Header.Get("content-type")
if contentType == "" {
contentType = "application/octet-stream"
}
_, err = io.Copy(targetFile, response.Body)
if err != nil {
log.Println(err)
return err
}
go RunStaticAnalysis(id)
return nil
}
func UploadFile(id string, c *gin.Context) error {
file, err := c.FormFile("file")
if err != nil {
return err
}
database.UpdateOriginalName(id, file.Filename)
err = c.SaveUploadedFile(file, fmt.Sprintf("./filestore/%s", id))
if err != nil {
return err
}
go RunStaticAnalysis(id)
return nil
}