Add more things for file handling

This commit is contained in:
Melody Becker 2025-06-18 15:36:33 +02:00
parent c813c4784a
commit 1fcf47bffc
Signed by: mstar
SSH key fingerprint: SHA256:9VAo09aaVNTWKzPW7Hq2LW+ox9OdwmTSHRoD4mlz1yI
14 changed files with 284 additions and 59 deletions

72
web/debug/media.go Normal file
View file

@ -0,0 +1,72 @@
package webdebug
import (
"database/sql"
"net/http"
webutils "git.mstar.dev/mstar/goutils/http"
"git.mstar.dev/mstar/goutils/sliceutils"
"github.com/rs/zerolog/hlog"
"git.mstar.dev/mstar/linstrom/media"
"git.mstar.dev/mstar/linstrom/storage-new/dbgen"
"git.mstar.dev/mstar/linstrom/storage-new/models"
)
func uploadMedia(w http.ResponseWriter, r *http.Request) {
log := hlog.FromRequest(r)
_ = r.ParseMultipartForm(10 << 20) // 10MB
userId := r.FormValue("user-id")
blurred := r.FormValue("blurred") != ""
altText := r.FormValue("alt-text")
file, handler, err := r.FormFile("file")
if err != nil {
log.Warn().Err(err).Msg("Failed to get file from form")
_ = webutils.ProblemDetailsStatusOnly(w, http.StatusBadRequest)
return
}
defer func() { _ = file.Close() }()
_, err = media.GlobalServer.AddFile(file, handler.Filename, userId, blurred, altText)
if err != nil {
log.Error().Err(err).Msg("Failed to upload file to storage")
_ = webutils.ProblemDetailsStatusOnly(w, http.StatusInternalServerError)
}
}
func forceMediaSync(w http.ResponseWriter, r *http.Request) {
go media.GlobalServer.ServiceEnsureFileSynchronisation()
}
func getOwnedFiles(w http.ResponseWriter, r *http.Request) {
type File struct {
Name, Id, Mime string
}
type Outbound struct {
Files []File
}
log := hlog.FromRequest(r)
userId := r.FormValue("id")
mm := dbgen.MediaMetadata
files, err := mm.Where(mm.OwnedById.Eq(sql.NullString{Valid: true, String: userId})).
Select(mm.Name, mm.Type, mm.ID).
Find()
if err != nil {
log.Error().Err(err).Str("user-id", userId).Msg("Failed to get files of user")
_ = webutils.ProblemDetailsStatusOnly(w, http.StatusInternalServerError)
return
}
err = webutils.SendJson(w, Outbound{
Files: sliceutils.Map(files, func(t *models.MediaMetadata) File {
return File{
Name: t.Name,
Id: t.ID,
Mime: t.Type,
}
}),
})
if err != nil {
log.Error().Err(err).Msg("Failed to marshal response to json")
}
}

View file

@ -37,6 +37,9 @@ func New(addr string) *Server {
handler.HandleFunc("GET /replies-to/{id}", inReplyTo)
handler.HandleFunc("POST /fetch", requestAs)
handler.HandleFunc("POST /follow", requestFollow)
handler.HandleFunc("POST /upload-file", uploadMedia)
handler.HandleFunc("/force-media-sync", forceMediaSync)
handler.HandleFunc("GET /files-owned-by", getOwnedFiles)
web := http.Server{
Addr: addr,
Handler: webutils.ChainMiddlewares(