2022-07-06 23:19:05 +02:00
|
|
|
package apis
|
|
|
|
|
|
|
|
import (
|
2023-12-04 16:40:35 +02:00
|
|
|
"context"
|
2023-04-04 19:33:35 +02:00
|
|
|
"errors"
|
2023-02-18 19:33:42 +02:00
|
|
|
"fmt"
|
2023-12-04 16:40:35 +02:00
|
|
|
"log/slog"
|
2023-04-04 19:33:35 +02:00
|
|
|
"net/http"
|
2023-12-04 16:40:35 +02:00
|
|
|
"runtime"
|
2023-04-04 19:33:35 +02:00
|
|
|
"strings"
|
2023-12-04 16:40:35 +02:00
|
|
|
"time"
|
2023-02-18 19:33:42 +02:00
|
|
|
|
2022-07-06 23:19:05 +02:00
|
|
|
"github.com/labstack/echo/v5"
|
|
|
|
"github.com/pocketbase/pocketbase/core"
|
|
|
|
"github.com/pocketbase/pocketbase/models"
|
|
|
|
"github.com/pocketbase/pocketbase/models/schema"
|
2023-04-04 19:33:35 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tokens"
|
2023-12-04 16:40:35 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tools/filesystem"
|
2022-07-06 23:19:05 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tools/list"
|
2023-04-04 19:33:35 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tools/security"
|
|
|
|
"github.com/spf13/cast"
|
2023-12-04 16:40:35 +02:00
|
|
|
"golang.org/x/sync/semaphore"
|
|
|
|
"golang.org/x/sync/singleflight"
|
2022-07-06 23:19:05 +02:00
|
|
|
)
|
|
|
|
|
2022-10-30 10:28:14 +02:00
|
|
|
var imageContentTypes = []string{"image/png", "image/jpg", "image/jpeg", "image/gif"}
|
2022-07-06 23:19:05 +02:00
|
|
|
var defaultThumbSizes = []string{"100x100"}
|
|
|
|
|
2022-10-30 10:28:14 +02:00
|
|
|
// bindFileApi registers the file api endpoints and the corresponding handlers.
|
|
|
|
func bindFileApi(app core.App, rg *echo.Group) {
|
2023-12-04 16:40:35 +02:00
|
|
|
api := fileApi{
|
|
|
|
app: app,
|
2024-01-31 11:08:40 +02:00
|
|
|
thumbGenSem: semaphore.NewWeighted(int64(runtime.NumCPU() + 2)), // the value is arbitrary chosen and may change in the future
|
2023-12-04 16:40:35 +02:00
|
|
|
thumbGenPending: new(singleflight.Group),
|
|
|
|
thumbGenMaxWait: 60 * time.Second,
|
|
|
|
}
|
2022-07-06 23:19:05 +02:00
|
|
|
|
|
|
|
subGroup := rg.Group("/files", ActivityLogger(app))
|
2023-04-17 21:04:58 +02:00
|
|
|
subGroup.POST("/token", api.fileToken)
|
2023-03-05 15:37:50 +02:00
|
|
|
subGroup.HEAD("/:collection/:recordId/:filename", api.download, LoadCollectionContext(api.app))
|
2022-07-06 23:19:05 +02:00
|
|
|
subGroup.GET("/:collection/:recordId/:filename", api.download, LoadCollectionContext(api.app))
|
|
|
|
}
|
|
|
|
|
|
|
|
type fileApi struct {
|
|
|
|
app core.App
|
2023-12-04 16:40:35 +02:00
|
|
|
|
|
|
|
// thumbGenSem is a semaphore to prevent too much concurrent
|
|
|
|
// requests generating new thumbs at the same time.
|
|
|
|
thumbGenSem *semaphore.Weighted
|
|
|
|
|
|
|
|
// thumbGenPending represents a group of currently pending
|
|
|
|
// thumb generation processes.
|
|
|
|
thumbGenPending *singleflight.Group
|
|
|
|
|
|
|
|
// thumbGenMaxWait is the maximum waiting time for starting a new
|
|
|
|
// thumb generation process.
|
|
|
|
thumbGenMaxWait time.Duration
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
2023-04-04 19:33:35 +02:00
|
|
|
func (api *fileApi) fileToken(c echo.Context) error {
|
|
|
|
event := new(core.FileTokenEvent)
|
|
|
|
event.HttpContext = c
|
|
|
|
|
|
|
|
if admin, _ := c.Get(ContextAdminKey).(*models.Admin); admin != nil {
|
|
|
|
event.Model = admin
|
|
|
|
event.Token, _ = tokens.NewAdminFileToken(api.app, admin)
|
|
|
|
} else if record, _ := c.Get(ContextAuthRecordKey).(*models.Record); record != nil {
|
|
|
|
event.Model = record
|
|
|
|
event.Token, _ = tokens.NewRecordFileToken(api.app, record)
|
|
|
|
}
|
|
|
|
|
2023-05-29 20:50:07 +02:00
|
|
|
return api.app.OnFileBeforeTokenRequest().Trigger(event, func(e *core.FileTokenEvent) error {
|
2023-04-17 21:04:58 +02:00
|
|
|
if e.Model == nil || e.Token == "" {
|
2023-04-04 19:33:35 +02:00
|
|
|
return NewBadRequestError("Failed to generate file token.", nil)
|
|
|
|
}
|
|
|
|
|
2023-07-18 14:31:36 +02:00
|
|
|
return api.app.OnFileAfterTokenRequest().Trigger(event, func(e *core.FileTokenEvent) error {
|
2023-07-20 09:40:03 +02:00
|
|
|
if e.HttpContext.Response().Committed {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-07-18 14:31:36 +02:00
|
|
|
return e.HttpContext.JSON(http.StatusOK, map[string]string{
|
|
|
|
"token": e.Token,
|
|
|
|
})
|
2023-04-04 19:33:35 +02:00
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-07-06 23:19:05 +02:00
|
|
|
func (api *fileApi) download(c echo.Context) error {
|
|
|
|
collection, _ := c.Get(ContextCollectionKey).(*models.Collection)
|
|
|
|
if collection == nil {
|
2022-10-30 10:28:14 +02:00
|
|
|
return NewNotFoundError("", nil)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
recordId := c.PathParam("recordId")
|
|
|
|
if recordId == "" {
|
2022-10-30 10:28:14 +02:00
|
|
|
return NewNotFoundError("", nil)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
2022-10-30 10:28:14 +02:00
|
|
|
record, err := api.app.Dao().FindRecordById(collection.Id, recordId)
|
2022-07-06 23:19:05 +02:00
|
|
|
if err != nil {
|
2022-10-30 10:28:14 +02:00
|
|
|
return NewNotFoundError("", err)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
filename := c.PathParam("filename")
|
|
|
|
|
|
|
|
fileField := record.FindFileFieldByFile(filename)
|
|
|
|
if fileField == nil {
|
2022-10-30 10:28:14 +02:00
|
|
|
return NewNotFoundError("", nil)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
2023-02-18 19:33:42 +02:00
|
|
|
|
2023-04-04 19:33:35 +02:00
|
|
|
options, ok := fileField.Options.(*schema.FileOptions)
|
|
|
|
if !ok {
|
2024-07-09 21:18:04 +02:00
|
|
|
return NewBadRequestError("", errors.New("failed to load file options"))
|
2023-04-04 19:33:35 +02:00
|
|
|
}
|
|
|
|
|
2023-04-15 12:27:42 +02:00
|
|
|
// check whether the request is authorized to view the protected file
|
|
|
|
if options.Protected {
|
2023-04-04 19:33:35 +02:00
|
|
|
token := c.QueryParam("token")
|
|
|
|
|
|
|
|
adminOrAuthRecord, _ := api.findAdminOrAuthRecordByFileToken(token)
|
|
|
|
|
2023-07-16 23:08:06 +02:00
|
|
|
// create a copy of the cached request data and adjust it for the current auth model
|
2023-07-17 22:13:39 +02:00
|
|
|
requestInfo := *RequestInfo(c)
|
2024-02-17 15:01:09 +02:00
|
|
|
requestInfo.Context = models.RequestInfoContextProtectedFile
|
2023-07-17 22:13:39 +02:00
|
|
|
requestInfo.Admin = nil
|
|
|
|
requestInfo.AuthRecord = nil
|
2023-07-16 23:03:09 +02:00
|
|
|
if adminOrAuthRecord != nil {
|
|
|
|
if admin, _ := adminOrAuthRecord.(*models.Admin); admin != nil {
|
2023-07-17 22:13:39 +02:00
|
|
|
requestInfo.Admin = admin
|
2023-07-16 23:03:09 +02:00
|
|
|
} else if record, _ := adminOrAuthRecord.(*models.Record); record != nil {
|
2023-07-17 22:13:39 +02:00
|
|
|
requestInfo.AuthRecord = record
|
2023-07-16 23:03:09 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-17 22:13:39 +02:00
|
|
|
if ok, _ := api.app.Dao().CanAccessRecord(record, &requestInfo, record.Collection().ViewRule); !ok {
|
2023-04-17 21:22:41 +02:00
|
|
|
return NewForbiddenError("Insufficient permissions to access the file resource.", nil)
|
2023-04-04 19:33:35 +02:00
|
|
|
}
|
|
|
|
}
|
2022-07-06 23:19:05 +02:00
|
|
|
|
2023-02-18 19:33:42 +02:00
|
|
|
baseFilesPath := record.BaseFilesPath()
|
|
|
|
|
|
|
|
// fetch the original view file field related record
|
|
|
|
if collection.IsView() {
|
|
|
|
fileRecord, err := api.app.Dao().FindRecordByViewFile(collection.Id, fileField.Name, filename)
|
|
|
|
if err != nil {
|
|
|
|
return NewNotFoundError("", fmt.Errorf("Failed to fetch view file field record: %w", err))
|
|
|
|
}
|
|
|
|
baseFilesPath = fileRecord.BaseFilesPath()
|
|
|
|
}
|
|
|
|
|
2023-12-04 16:40:35 +02:00
|
|
|
fsys, err := api.app.NewFilesystem()
|
2022-07-06 23:19:05 +02:00
|
|
|
if err != nil {
|
2022-10-30 10:28:14 +02:00
|
|
|
return NewBadRequestError("Filesystem initialization failure.", err)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
2023-12-04 16:40:35 +02:00
|
|
|
defer fsys.Close()
|
2022-07-06 23:19:05 +02:00
|
|
|
|
2023-02-18 19:33:42 +02:00
|
|
|
originalPath := baseFilesPath + "/" + filename
|
2022-07-06 23:19:05 +02:00
|
|
|
servedPath := originalPath
|
|
|
|
servedName := filename
|
|
|
|
|
|
|
|
// check for valid thumb size param
|
|
|
|
thumbSize := c.QueryParam("thumb")
|
|
|
|
if thumbSize != "" && (list.ExistInSlice(thumbSize, defaultThumbSizes) || list.ExistInSlice(thumbSize, options.Thumbs)) {
|
|
|
|
// extract the original file meta attributes and check it existence
|
2023-12-04 16:40:35 +02:00
|
|
|
oAttrs, oAttrsErr := fsys.Attributes(originalPath)
|
2022-07-06 23:19:05 +02:00
|
|
|
if oAttrsErr != nil {
|
2022-10-30 10:28:14 +02:00
|
|
|
return NewNotFoundError("", err)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// check if it is an image
|
|
|
|
if list.ExistInSlice(oAttrs.ContentType, imageContentTypes) {
|
|
|
|
// add thumb size as file suffix
|
|
|
|
servedName = thumbSize + "_" + filename
|
2023-02-18 19:33:42 +02:00
|
|
|
servedPath = baseFilesPath + "/thumbs_" + filename + "/" + servedName
|
2022-07-06 23:19:05 +02:00
|
|
|
|
2023-12-04 16:40:35 +02:00
|
|
|
// create a new thumb if it doesn't exist
|
|
|
|
if exists, _ := fsys.Exists(servedPath); !exists {
|
|
|
|
if err := api.createThumb(c, fsys, originalPath, servedPath, thumbSize); err != nil {
|
|
|
|
api.app.Logger().Warn(
|
|
|
|
"Fallback to original - failed to create thumb "+servedName,
|
|
|
|
slog.Any("error", err),
|
|
|
|
slog.String("original", originalPath),
|
|
|
|
slog.String("thumb", servedPath),
|
|
|
|
)
|
|
|
|
|
|
|
|
// fallback to the original
|
|
|
|
servedName = filename
|
|
|
|
servedPath = originalPath
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-27 22:19:08 +02:00
|
|
|
event := new(core.FileDownloadEvent)
|
|
|
|
event.HttpContext = c
|
|
|
|
event.Collection = collection
|
|
|
|
event.Record = record
|
|
|
|
event.FileField = fileField
|
|
|
|
event.ServedPath = servedPath
|
|
|
|
event.ServedName = servedName
|
2022-07-06 23:19:05 +02:00
|
|
|
|
2023-01-30 12:54:51 +02:00
|
|
|
// clickjacking shouldn't be a concern when serving uploaded files,
|
|
|
|
// so it safe to unset the global X-Frame-Options to allow files embedding
|
|
|
|
// (note: it is out of the hook to allow users to customize the behavior)
|
|
|
|
c.Response().Header().Del("X-Frame-Options")
|
|
|
|
|
2022-07-06 23:19:05 +02:00
|
|
|
return api.app.OnFileDownloadRequest().Trigger(event, func(e *core.FileDownloadEvent) error {
|
2023-07-20 09:40:03 +02:00
|
|
|
if e.HttpContext.Response().Committed {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-12-04 16:40:35 +02:00
|
|
|
if err := fsys.Serve(e.HttpContext.Response(), e.HttpContext.Request(), e.ServedPath, e.ServedName); err != nil {
|
2022-10-30 10:28:14 +02:00
|
|
|
return NewNotFoundError("", err)
|
2022-07-06 23:19:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
}
|
2023-04-04 19:33:35 +02:00
|
|
|
|
|
|
|
func (api *fileApi) findAdminOrAuthRecordByFileToken(fileToken string) (models.Model, error) {
|
|
|
|
fileToken = strings.TrimSpace(fileToken)
|
|
|
|
if fileToken == "" {
|
|
|
|
return nil, errors.New("missing file token")
|
|
|
|
}
|
|
|
|
|
|
|
|
claims, _ := security.ParseUnverifiedJWT(strings.TrimSpace(fileToken))
|
|
|
|
tokenType := cast.ToString(claims["type"])
|
|
|
|
|
|
|
|
switch tokenType {
|
|
|
|
case tokens.TypeAdmin:
|
|
|
|
admin, err := api.app.Dao().FindAdminByToken(
|
|
|
|
fileToken,
|
|
|
|
api.app.Settings().AdminFileToken.Secret,
|
|
|
|
)
|
|
|
|
if err == nil && admin != nil {
|
|
|
|
return admin, nil
|
|
|
|
}
|
|
|
|
case tokens.TypeAuthRecord:
|
|
|
|
record, err := api.app.Dao().FindAuthRecordByToken(
|
|
|
|
fileToken,
|
|
|
|
api.app.Settings().RecordFileToken.Secret,
|
|
|
|
)
|
|
|
|
if err == nil && record != nil {
|
|
|
|
return record, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, errors.New("missing or invalid file token")
|
|
|
|
}
|
2023-12-04 16:40:35 +02:00
|
|
|
|
|
|
|
func (api *fileApi) createThumb(
|
|
|
|
c echo.Context,
|
|
|
|
fsys *filesystem.System,
|
|
|
|
originalPath string,
|
|
|
|
thumbPath string,
|
|
|
|
thumbSize string,
|
|
|
|
) error {
|
|
|
|
ch := api.thumbGenPending.DoChan(thumbPath, func() (any, error) {
|
|
|
|
ctx, cancel := context.WithTimeout(c.Request().Context(), api.thumbGenMaxWait)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
if err := api.thumbGenSem.Acquire(ctx, 1); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer api.thumbGenSem.Release(1)
|
|
|
|
|
|
|
|
return nil, fsys.CreateThumb(originalPath, thumbPath, thumbSize)
|
|
|
|
})
|
|
|
|
|
|
|
|
res := <-ch
|
|
|
|
|
|
|
|
api.thumbGenPending.Forget(thumbPath)
|
|
|
|
|
|
|
|
return res.Err
|
|
|
|
}
|