Backend: Add API endpoint for getting files by sha1 hash (#259)

* Backend: Add API endpoint for getting files by sha1 hash

* Test: Add test for Api.GetFile
This commit is contained in:
thielepaul 2020-02-26 17:50:28 +01:00 committed by GitHub
parent 01527c180e
commit 1d89858e4c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 57 additions and 0 deletions

32
internal/api/file.go Normal file
View file

@ -0,0 +1,32 @@
package api
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/photoprism/photoprism/internal/config"
"github.com/photoprism/photoprism/internal/query"
)
// GET /api/v1/files/:hash
//
// Parameters:
// hash: string The sha1 hash of a file
func GetFile(router *gin.RouterGroup, conf *config.Config) {
router.GET("/files/:hash", func(c *gin.Context) {
if Unauthorized(c, conf) {
c.AbortWithStatusJSON(http.StatusUnauthorized, ErrUnauthorized)
return
}
q := query.New(conf.OriginalsPath(), conf.Db())
p, err := q.FindFileByHash(c.Param("hash"))
if err != nil {
c.AbortWithStatusJSON(http.StatusNotFound, ErrPhotoNotFound)
return
}
c.JSON(http.StatusOK, p)
})
}

24
internal/api/file_test.go Normal file
View file

@ -0,0 +1,24 @@
package api
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetFile(t *testing.T) {
t.Run("search for existing file", func(t *testing.T) {
app, router, ctx := NewApiTest()
GetFile(router, ctx)
result := PerformRequest(app, "GET", "/api/v1/files/123xxx")
assert.Equal(t, http.StatusOK, result.Code)
assert.Contains(t, result.Body.String(), "\"FileName\":\"exampleFileName.jpg\"")
})
t.Run("search for not existing file", func(t *testing.T) {
app, router, ctx := NewApiTest()
GetFile(router, ctx)
result := PerformRequest(app, "GET", "/api/v1/files/111")
assert.Equal(t, http.StatusNotFound, result.Code)
})
}

View file

@ -37,6 +37,7 @@ func registerRoutes(router *gin.Engine, conf *config.Config) {
api.AddPhotoLabel(v1, conf)
api.RemovePhotoLabel(v1, conf)
api.GetMomentsTime(v1, conf)
api.GetFile(v1, conf)
api.GetLabels(v1, conf)
api.UpdateLabel(v1, conf)