Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
alist-org
GitHub Repository: alist-org/alist
Path: blob/main/internal/op/meta.go
1560 views
1
package op
2
3
import (
4
stdpath "path"
5
"time"
6
7
"github.com/Xhofe/go-cache"
8
"github.com/alist-org/alist/v3/internal/db"
9
"github.com/alist-org/alist/v3/internal/errs"
10
"github.com/alist-org/alist/v3/internal/model"
11
"github.com/alist-org/alist/v3/pkg/singleflight"
12
"github.com/alist-org/alist/v3/pkg/utils"
13
"github.com/pkg/errors"
14
"gorm.io/gorm"
15
)
16
17
var metaCache = cache.NewMemCache(cache.WithShards[*model.Meta](2))
18
19
// metaG maybe not needed
20
var metaG singleflight.Group[*model.Meta]
21
22
func GetNearestMeta(path string) (*model.Meta, error) {
23
return getNearestMeta(utils.FixAndCleanPath(path))
24
}
25
func getNearestMeta(path string) (*model.Meta, error) {
26
meta, err := GetMetaByPath(path)
27
if err == nil {
28
return meta, nil
29
}
30
if errors.Cause(err) != errs.MetaNotFound {
31
return nil, err
32
}
33
if path == "/" {
34
return nil, errs.MetaNotFound
35
}
36
return getNearestMeta(stdpath.Dir(path))
37
}
38
39
func GetMetaByPath(path string) (*model.Meta, error) {
40
return getMetaByPath(utils.FixAndCleanPath(path))
41
}
42
func getMetaByPath(path string) (*model.Meta, error) {
43
meta, ok := metaCache.Get(path)
44
if ok {
45
if meta == nil {
46
return meta, errs.MetaNotFound
47
}
48
return meta, nil
49
}
50
meta, err, _ := metaG.Do(path, func() (*model.Meta, error) {
51
_meta, err := db.GetMetaByPath(path)
52
if err != nil {
53
if errors.Is(err, gorm.ErrRecordNotFound) {
54
metaCache.Set(path, nil)
55
return nil, errs.MetaNotFound
56
}
57
return nil, err
58
}
59
metaCache.Set(path, _meta, cache.WithEx[*model.Meta](time.Hour))
60
return _meta, nil
61
})
62
return meta, err
63
}
64
65
func DeleteMetaById(id uint) error {
66
old, err := db.GetMetaById(id)
67
if err != nil {
68
return err
69
}
70
metaCache.Del(old.Path)
71
return db.DeleteMetaById(id)
72
}
73
74
func UpdateMeta(u *model.Meta) error {
75
u.Path = utils.FixAndCleanPath(u.Path)
76
old, err := db.GetMetaById(u.ID)
77
if err != nil {
78
return err
79
}
80
metaCache.Del(old.Path)
81
return db.UpdateMeta(u)
82
}
83
84
func CreateMeta(u *model.Meta) error {
85
u.Path = utils.FixAndCleanPath(u.Path)
86
metaCache.Del(u.Path)
87
return db.CreateMeta(u)
88
}
89
90
func GetMetaById(id uint) (*model.Meta, error) {
91
return db.GetMetaById(id)
92
}
93
94
func GetMetas(pageIndex, pageSize int) (metas []model.Meta, count int64, err error) {
95
return db.GetMetas(pageIndex, pageSize)
96
}
97
98