github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/web/settings/disk_usage.go (about) 1 // Package settings regroups some API methods to facilitate the usage of the 2 // io.cozy settings documents. 3 package settings 4 5 import ( 6 "net/http" 7 8 "github.com/cozy/cozy-stack/model/permission" 9 "github.com/cozy/cozy-stack/pkg/consts" 10 "github.com/cozy/cozy-stack/pkg/couchdb" 11 "github.com/cozy/cozy-stack/pkg/jsonapi" 12 "github.com/cozy/cozy-stack/web/middlewares" 13 "github.com/labstack/echo/v4" 14 ) 15 16 type apiDiskUsage struct { 17 Used int64 `json:"used,string"` 18 Quota int64 `json:"quota,string,omitempty"` 19 Files int64 `json:"files,string"` 20 Trash *int64 `json:"trash,string,omitempty"` 21 Versions int64 `json:"versions,string"` 22 } 23 24 func (j *apiDiskUsage) ID() string { return consts.DiskUsageID } 25 func (j *apiDiskUsage) Rev() string { return "" } 26 func (j *apiDiskUsage) DocType() string { return consts.Settings } 27 func (j *apiDiskUsage) Clone() couchdb.Doc { return j } 28 func (j *apiDiskUsage) SetID(_ string) {} 29 func (j *apiDiskUsage) SetRev(_ string) {} 30 func (j *apiDiskUsage) Relationships() jsonapi.RelationshipMap { return nil } 31 func (j *apiDiskUsage) Included() []jsonapi.Object { return nil } 32 func (j *apiDiskUsage) Links() *jsonapi.LinksList { 33 return &jsonapi.LinksList{Self: "/settings/disk-usage"} 34 } 35 36 // Settings objects permissions are only on ID 37 func (j *apiDiskUsage) Fetch(field string) []string { return nil } 38 39 // checkAccessToDiskUsage validates the access control for the disk-usage. It 40 // checks if there is an explicit permission on this document, but also allow 41 // every request from the logged-in user as this route is used by the cozy-bar 42 // from all the client-side apps. And there is a third case where it is 43 // allowed: when an anonymous user comes from a shared by link directory with 44 // write access. 45 func checkAccessToDiskUsage(c echo.Context, result *apiDiskUsage) error { 46 if err := middlewares.Allow(c, permission.GET, result); err == nil { 47 return nil 48 } 49 if middlewares.IsLoggedIn(c) && middlewares.HasWebAppToken(c) { 50 return nil 51 } 52 return middlewares.CanWriteToAnyDirectory(c) 53 } 54 55 func (h *HTTPHandler) diskUsage(c echo.Context) error { 56 instance := middlewares.GetInstance(c) 57 var result apiDiskUsage 58 59 if err := checkAccessToDiskUsage(c, &result); err != nil { 60 return err 61 } 62 63 fs := instance.VFS() 64 if c.QueryParam("include") == "trash" { 65 if trash, err := fs.TrashUsage(); err == nil { 66 result.Trash = &trash 67 } 68 } 69 70 versions, err := fs.VersionsUsage() 71 if err != nil { 72 return err 73 } 74 75 files, err := fs.FilesUsage() 76 if err != nil { 77 return err 78 } 79 80 used := files + versions 81 quota := fs.DiskQuota() 82 83 result.Used = used 84 result.Quota = quota 85 result.Files = files 86 result.Versions = versions 87 return jsonapi.Data(c, http.StatusOK, &result, nil) 88 }