Commit d32334cd authored by Saturnino Abril's avatar Saturnino Abril Committed by enahum

Endpoint for APIv4: /files/{file_id}/link (#5607)

* APIv4: /files/{file_id}/link

* updated public link
parent ce772b87
...@@ -316,5 +316,5 @@ func getPublicLink(c *Context, w http.ResponseWriter, r *http.Request) { ...@@ -316,5 +316,5 @@ func getPublicLink(c *Context, w http.ResponseWriter, r *http.Request) {
return return
} }
w.Write([]byte(model.StringToJson(app.GeneratePublicLink(c.GetSiteURL(), info)))) w.Write([]byte(model.StringToJson(app.GeneratePublicLinkV3(c.GetSiteURL(), info))))
} }
...@@ -24,6 +24,7 @@ func InitFile() { ...@@ -24,6 +24,7 @@ func InitFile() {
BaseRoutes.Files.Handle("", ApiSessionRequired(uploadFile)).Methods("POST") BaseRoutes.Files.Handle("", ApiSessionRequired(uploadFile)).Methods("POST")
BaseRoutes.File.Handle("", ApiSessionRequired(getFile)).Methods("GET") BaseRoutes.File.Handle("", ApiSessionRequired(getFile)).Methods("GET")
BaseRoutes.File.Handle("/thumbnail", ApiSessionRequired(getFileThumbnail)).Methods("GET") BaseRoutes.File.Handle("/thumbnail", ApiSessionRequired(getFileThumbnail)).Methods("GET")
BaseRoutes.File.Handle("/link", ApiSessionRequired(getFileLink)).Methods("GET")
} }
...@@ -125,6 +126,41 @@ func getFileThumbnail(c *Context, w http.ResponseWriter, r *http.Request) { ...@@ -125,6 +126,41 @@ func getFileThumbnail(c *Context, w http.ResponseWriter, r *http.Request) {
} }
} }
func getFileLink(c *Context, w http.ResponseWriter, r *http.Request) {
c.RequireFileId()
if c.Err != nil {
return
}
if !utils.Cfg.FileSettings.EnablePublicLink {
c.Err = model.NewLocAppError("getPublicLink", "api.file.get_public_link.disabled.app_error", nil, "")
c.Err.StatusCode = http.StatusNotImplemented
return
}
info, err := app.GetFileInfo(c.Params.FileId)
if err != nil {
c.Err = err
return
}
if info.CreatorId != c.Session.UserId && !app.SessionHasPermissionToChannelByPost(c.Session, info.PostId, model.PERMISSION_READ_CHANNEL) {
c.SetPermissionError(model.PERMISSION_READ_CHANNEL)
return
}
if len(info.PostId) == 0 {
c.Err = model.NewLocAppError("getPublicLink", "api.file.get_public_link.no_post.app_error", nil, "file_id="+info.Id)
c.Err.StatusCode = http.StatusBadRequest
return
}
resp := make(map[string]string)
resp["link"] = app.GeneratePublicLink(c.GetSiteURL(), info)
w.Write([]byte(model.MapToJson(resp)))
}
func writeFileResponse(filename string, contentType string, bytes []byte, w http.ResponseWriter, r *http.Request) *model.AppError { func writeFileResponse(filename string, contentType string, bytes []byte, w http.ResponseWriter, r *http.Request) *model.AppError {
w.Header().Set("Cache-Control", "max-age=2592000, public") w.Header().Set("Cache-Control", "max-age=2592000, public")
w.Header().Set("Content-Length", strconv.Itoa(len(bytes))) w.Header().Set("Content-Length", strconv.Itoa(len(bytes)))
......
...@@ -10,6 +10,7 @@ import ( ...@@ -10,6 +10,7 @@ import (
"github.com/mattermost/platform/app" "github.com/mattermost/platform/app"
"github.com/mattermost/platform/model" "github.com/mattermost/platform/model"
"github.com/mattermost/platform/store"
"github.com/mattermost/platform/utils" "github.com/mattermost/platform/utils"
) )
...@@ -201,3 +202,78 @@ func TestGetFileThumbnail(t *testing.T) { ...@@ -201,3 +202,78 @@ func TestGetFileThumbnail(t *testing.T) {
_, resp = th.SystemAdminClient.GetFileThumbnail(fileId) _, resp = th.SystemAdminClient.GetFileThumbnail(fileId)
CheckNoError(t, resp) CheckNoError(t, resp)
} }
func TestGetFileLink(t *testing.T) {
th := Setup().InitBasic().InitSystemAdmin()
defer TearDown()
Client := th.Client
channel := th.BasicChannel
if utils.Cfg.FileSettings.DriverName == "" {
t.Skip("skipping because no file driver is enabled")
}
enablePublicLink := utils.Cfg.FileSettings.EnablePublicLink
publicLinkSalt := *utils.Cfg.FileSettings.PublicLinkSalt
defer func() {
utils.Cfg.FileSettings.EnablePublicLink = enablePublicLink
*utils.Cfg.FileSettings.PublicLinkSalt = publicLinkSalt
}()
utils.Cfg.FileSettings.EnablePublicLink = true
*utils.Cfg.FileSettings.PublicLinkSalt = model.NewId()
fileId := ""
if data, err := readTestFile("test.png"); err != nil {
t.Fatal(err)
} else {
fileResp, resp := Client.UploadFile(data, channel.Id, "test.png")
CheckNoError(t, resp)
fileId = fileResp.FileInfos[0].Id
}
link, resp := Client.GetFileLink(fileId)
CheckBadRequestStatus(t, resp)
// Hacky way to assign file to a post (usually would be done by CreatePost call)
store.Must(app.Srv.Store.FileInfo().AttachToPost(fileId, th.BasicPost.Id))
utils.Cfg.FileSettings.EnablePublicLink = false
_, resp = Client.GetFileLink(fileId)
CheckNotImplementedStatus(t, resp)
// Wait a bit for files to ready
time.Sleep(2 * time.Second)
utils.Cfg.FileSettings.EnablePublicLink = true
link, resp = Client.GetFileLink(fileId)
CheckNoError(t, resp)
if link == "" {
t.Fatal("should've received public link")
}
_, resp = Client.GetFileLink("junk")
CheckBadRequestStatus(t, resp)
_, resp = Client.GetFileLink(model.NewId())
CheckNotFoundStatus(t, resp)
Client.Logout()
_, resp = Client.GetFileLink(fileId)
CheckUnauthorizedStatus(t, resp)
otherUser := th.CreateUser()
Client.Login(otherUser.Email, otherUser.Password)
_, resp = Client.GetFileLink(fileId)
CheckForbiddenStatus(t, resp)
Client.Logout()
_, resp = th.SystemAdminClient.GetFileLink(fileId)
CheckNoError(t, resp)
if result := <-app.Srv.Store.FileInfo().Get(fileId); result.Err != nil {
t.Fatal(result.Err)
} else {
cleanupTestFile(result.Data.(*model.FileInfo))
}
}
...@@ -359,6 +359,11 @@ func MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo { ...@@ -359,6 +359,11 @@ func MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo {
} }
func GeneratePublicLink(siteURL string, info *model.FileInfo) string { func GeneratePublicLink(siteURL string, info *model.FileInfo) string {
hash := GeneratePublicLinkHash(info.Id, *utils.Cfg.FileSettings.PublicLinkSalt)
return fmt.Sprintf("%s/files/%v/public?h=%s", siteURL, info.Id, hash)
}
func GeneratePublicLinkV3(siteURL string, info *model.FileInfo) string {
hash := GeneratePublicLinkHash(info.Id, *utils.Cfg.FileSettings.PublicLinkSalt) hash := GeneratePublicLinkHash(info.Id, *utils.Cfg.FileSettings.PublicLinkSalt)
return fmt.Sprintf("%s%s/public/files/%v/get?h=%s", siteURL, model.API_URL_SUFFIX_V3, info.Id, hash) return fmt.Sprintf("%s%s/public/files/%v/get?h=%s", siteURL, model.API_URL_SUFFIX_V3, info.Id, hash)
} }
......
...@@ -903,6 +903,15 @@ func (c *Client4) GetFileThumbnail(fileId string) ([]byte, *Response) { ...@@ -903,6 +903,15 @@ func (c *Client4) GetFileThumbnail(fileId string) ([]byte, *Response) {
} }
} }
// GetFileLink gets the public link of a file by id.
func (c *Client4) GetFileLink(fileId string) (string, *Response) {
if r, err := c.DoApiGet(c.GetFileRoute(fileId)+"/link", ""); err != nil {
return "", &Response{StatusCode: r.StatusCode, Error: err}
} else {
return MapFromJson(r.Body)["link"], BuildResponse(r)
}
}
// GetFileInfosForPost gets all the file info objects attached to a post. // GetFileInfosForPost gets all the file info objects attached to a post.
func (c *Client4) GetFileInfosForPost(postId string, etag string) ([]*FileInfo, *Response) { func (c *Client4) GetFileInfosForPost(postId string, etag string) ([]*FileInfo, *Response) {
if r, err := c.DoApiGet(c.GetPostRoute(postId)+"/files/info", etag); err != nil { if r, err := c.DoApiGet(c.GetPostRoute(postId)+"/files/info", etag); err != nil {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment