From 3df7e6f7479a27c9d173d4ba6940c4e2082cf702 Mon Sep 17 00:00:00 2001 From: RandomChars <random@chars.jp> Date: Wed, 4 Aug 2021 00:29:13 +0900 Subject: [PATCH] image file get via snowflake, check if file not exist in snowflake lookup --- api.go | 36 ++++++++++++++++++++++++++++++++++++ store/image.go | 6 ++++++ 2 files changed, 42 insertions(+) diff --git a/api.go b/api.go index 78979f7..e4bfea2 100644 --- a/api.go +++ b/api.go @@ -294,6 +294,42 @@ func registerAPI() { context.JSON(http.StatusOK, instance.ImageSnowflake(flake)) }) + router.GET("/api/image/snowflake/:flake/file", func(context *gin.Context) { + flake := context.Param("flake") + if _, err := strconv.Atoi(flake); err != nil { + context.JSON(http.StatusBadRequest, gin.H{ + "error": "invalid snowflake", + }) + return + } + image, data := instance.ImageData(instance.ImageSnowflakeHash(flake), false) + if image.Hash == "" { + context.JSON(http.StatusNotFound, gin.H{ + "error": "not found", + }) + return + } + context.Data(http.StatusOK, "image/"+image.Type, data) + }) + + router.GET("/api/image/snowflake/:flake/preview", func(context *gin.Context) { + flake := context.Param("flake") + if _, err := strconv.Atoi(flake); err != nil { + context.JSON(http.StatusBadRequest, gin.H{ + "error": "invalid snowflake", + }) + return + } + image, data := instance.ImageData(instance.ImageSnowflakeHash(flake), true) + if image.Hash == "" { + context.JSON(http.StatusNotFound, gin.H{ + "error": "not found", + }) + return + } + context.Data(http.StatusOK, "image/jpeg", data) + }) + router.GET("/api/image", func(context *gin.Context) { info, ok := getUser(context) diff --git a/store/image.go b/store/image.go index 6ef019d..5e57acf 100644 --- a/store/image.go +++ b/store/image.go @@ -64,6 +64,9 @@ func (s *Store) Image(hash string) Image { func (s *Store) ImageMetadataRead(path string) Image { var metadata Image if payload, err := os.ReadFile(path); err != nil { + if os.IsNotExist(err) { + return Image{} + } s.fatalClose(fmt.Sprintf("Error reading image metadata %s, %s", path, err)) } else { if err = json.Unmarshal(payload, &metadata); err != nil { @@ -246,6 +249,9 @@ func (s *Store) ImageSnowflakeHash(flake string) string { return s.ImageMetadataRead(s.ImageSnowflakePath(flake) + "/" + infoJson).Hash } else { if path, err := os.ReadFile(s.ImageSnowflakePath(flake)); err != nil { + if os.IsNotExist(err) { + return "" + } s.fatalClose(fmt.Sprintf("Error reading snowflake %s association file, %s", flake, err)) } else { return s.ImageMetadataRead(string(path) + "/" + infoJson).Hash -- GitLab