OpenMediaCenter/apiGo/api/FileUpload.go

71 lines
1.4 KiB
Go
Raw Normal View History

2021-09-21 15:45:24 +00:00
package api
import (
"fmt"
"io"
"openmediacenter/apiGo/api/api"
"openmediacenter/apiGo/database"
"openmediacenter/apiGo/videoparser"
2021-09-21 15:45:24 +00:00
"os"
"path/filepath"
2021-09-21 15:45:24 +00:00
)
func addUploadHandler() {
api.AddHandler("fileupload", api.VideoNode, api.PermUser, func(ctx api.Context) {
// get path where to store videos to
mSettings, PathPrefix, _ := database.GetSettings()
2021-09-21 15:45:24 +00:00
req := ctx.GetRequest()
mr, err := req.MultipartReader()
if err != nil {
ctx.Errorf("incorrect request!")
2021-09-21 15:45:24 +00:00
return
}
videoparser.InitDeps(&mSettings)
2021-09-21 15:45:24 +00:00
for {
part, err := mr.NextPart()
if err == io.EOF {
break
}
// todo allow more video formats than mp4
// only allow valid extensions
if filepath.Ext(part.FileName()) != ".mp4" {
continue
}
vidpath := PathPrefix + mSettings.VideoPath + part.FileName()
dst, err := os.OpenFile(vidpath, os.O_WRONLY|os.O_CREATE, 0644)
2021-09-21 15:45:24 +00:00
if err != nil {
ctx.Error("error opening file")
2021-09-21 15:45:24 +00:00
return
}
fmt.Printf("Uploading file %s\n", part.FileName())
2021-09-21 15:45:24 +00:00
// so now loop through every appended file and upload
buffer := make([]byte, 100000)
for {
cBytes, err := part.Read(buffer)
if cBytes > 0 {
dst.Write(buffer[0:cBytes])
}
if err == io.EOF {
fmt.Printf("Finished uploading file %s\n", part.FileName())
go videoparser.ProcessVideo(part.FileName())
2021-09-21 15:45:24 +00:00
break
}
}
_ = dst.Close()
2021-09-21 15:45:24 +00:00
}
ctx.Json(struct {
Message string
}{Message: "finished all files"})
2021-09-21 15:45:24 +00:00
})
}