mediaapi/writers/upload: Move file first as db is source of truth

The database is the source of truth. If we add the metadata to the
database and it succeeds, and then the file fails to be moved, we think
we have a file when we actually don't.
This commit is contained in:
Robert Swain 2017-05-18 11:10:41 +02:00
parent 3f904e1cdb
commit deee6f84c7

View file

@ -209,9 +209,14 @@ func Upload(req *http.Request, cfg *config.MediaAPI, db *storage.Database) util.
// TODO: generate thumbnails
err = db.StoreMediaMetadata(r.MediaMetadata)
finalPath := getPathFromMediaMetadata(r.MediaMetadata, cfg.BasePath)
err = moveFile(
types.Path(path.Join(string(tmpDir), "content")),
types.Path(finalPath),
)
if err != nil {
logger.Warnf("Failed to store metadata: %q\n", err)
logger.Warnf("Failed to move file to final destination: %q\n", err)
removeDir(tmpDir, logger)
return util.JSONResponse{
Code: 400,
@ -219,13 +224,10 @@ func Upload(req *http.Request, cfg *config.MediaAPI, db *storage.Database) util.
}
}
err = moveFile(
types.Path(path.Join(string(tmpDir), "content")),
types.Path(getPathFromMediaMetadata(r.MediaMetadata, cfg.BasePath)),
)
err = db.StoreMediaMetadata(r.MediaMetadata)
if err != nil {
logger.Warnf("Failed to move file to final destination: %q\n", err)
removeDir(tmpDir, logger)
logger.Warnf("Failed to store metadata: %q\n", err)
removeDir(types.Path(path.Dir(finalPath)), logger)
return util.JSONResponse{
Code: 400,
JSON: jsonerror.Unknown(fmt.Sprintf("Failed to upload")),