5d59b50912
Signed-off-by: Michael Mayer <michael@liquidbytes.net>
111 lines
2.5 KiB
Go
111 lines
2.5 KiB
Go
package api
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"github.com/photoprism/photoprism/internal/acl"
|
|
"github.com/photoprism/photoprism/internal/event"
|
|
"github.com/photoprism/photoprism/internal/service"
|
|
"github.com/photoprism/photoprism/pkg/txt"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// POST /api/v1/upload/:path
|
|
func Upload(router *gin.RouterGroup) {
|
|
router.POST("/upload/:path", func(c *gin.Context) {
|
|
conf := service.Config()
|
|
if conf.ReadOnly() || !conf.Settings().Features.Upload {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, ErrReadOnly)
|
|
return
|
|
}
|
|
|
|
s := Auth(SessionID(c), acl.ResourcePhotos, acl.ActionUpload)
|
|
|
|
if s.Invalid() {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, ErrUnauthorized)
|
|
return
|
|
}
|
|
|
|
start := time.Now()
|
|
subPath := c.Param("path")
|
|
|
|
f, err := c.MultipartForm()
|
|
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": txt.UcFirst(err.Error())})
|
|
return
|
|
}
|
|
|
|
event.Publish("upload.start", event.Data{"time": start})
|
|
|
|
files := f.File["files"]
|
|
uploaded := len(files)
|
|
var uploads []string
|
|
|
|
p := path.Join(conf.ImportPath(), "upload", subPath)
|
|
|
|
if err := os.MkdirAll(p, os.ModePerm); err != nil {
|
|
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": txt.UcFirst(err.Error())})
|
|
return
|
|
}
|
|
|
|
for _, file := range files {
|
|
filename := path.Join(p, filepath.Base(file.Filename))
|
|
|
|
log.Debugf("upload: saving file %s", txt.Quote(file.Filename))
|
|
|
|
if err := c.SaveUploadedFile(file, filename); err != nil {
|
|
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": txt.UcFirst(err.Error())})
|
|
return
|
|
}
|
|
|
|
uploads = append(uploads, filename)
|
|
}
|
|
|
|
if !conf.UploadNSFW() {
|
|
nd := service.NsfwDetector()
|
|
|
|
containsNSFW := false
|
|
|
|
for _, filename := range uploads {
|
|
labels, err := nd.File(filename)
|
|
|
|
if err != nil {
|
|
log.Debug(err)
|
|
continue
|
|
}
|
|
|
|
if labels.IsSafe() {
|
|
continue
|
|
}
|
|
|
|
log.Infof("nsfw: %s might be offensive", txt.Quote(filename))
|
|
|
|
containsNSFW = true
|
|
}
|
|
|
|
if containsNSFW {
|
|
for _, filename := range uploads {
|
|
if err := os.Remove(filename); err != nil {
|
|
log.Errorf("nsfw: could not delete %s", txt.Quote(filename))
|
|
}
|
|
}
|
|
|
|
c.AbortWithStatusJSON(http.StatusForbidden, ErrUploadNSFW)
|
|
return
|
|
}
|
|
}
|
|
|
|
elapsed := time.Since(start)
|
|
|
|
log.Infof("%d files uploaded in %s", uploaded, elapsed)
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": fmt.Sprintf("%d files uploaded in %s", uploaded, elapsed)})
|
|
})
|
|
}
|