Compare commits

..
23 Commits
Author SHA1 Message Date
HFO4 d10639fd19 release: 3.5.1 2022-04-24 15:33:29 +08:00
HFO4 ba0e3278e3 fix: signature error when finishing oss upload 2022-04-24 15:16:47 +08:00
HFO4 0fb31f4523 fix: deadlock while creating default user in SQLite 2022-04-24 15:16:25 +08:00
HFO4 d0779f564e release: 3.5.0 2022-04-22 20:29:53 +08:00
HFO4 350954911e fix: add no-cache option to service worker file 2022-04-22 16:18:20 +08:00
HFO4 b8bc5bed13 test: new overwrite param in CreateUploadSession 2022-04-22 16:05:57 +08:00
HFO4 91377f4676 fix: cached folder props should ignore date and policy 2022-04-22 15:58:39 +08:00
HFO4 b1803fa51f fix: cannot overwrite file to slave policy / fix: remove lock system for webdav to resolve Windows Explorer issue. 2022-04-22 15:57:21 +08:00
HFO4 f8b7e086ba fix: database is locked when using sqlite 2022-04-22 15:56:45 +08:00
HFO4 ff22f5c8b9 Merge remote-tracking branch 'origin/master' 2022-04-21 14:49:10 +08:00
HFO4 aaf8a793ee test: new changes related to filesystem.CreateDirectory 2022-04-21 14:29:10 +08:00
HFO4 2ab2662fcd fix: cannot upload file to onedrive because file info not match (fix #1215)
Path in onedrive is not case-sensitive while Cloudreve cares, thus file size is not matching when finishing upload.
2022-04-21 13:58:54 +08:00
HFO4 71df067a76 fix: create directory now ignore conflict error, it will return the existed folder 2022-04-21 13:58:22 +08:00
AaronLiuandGitHub d34cb3e5d3 Update README.md 2022-04-20 19:20:26 +08:00
AaronLiuandGitHub b5e8e4843f chore: add codecov to test workflow 2022-04-20 19:05:21 +08:00
HFO4 86877aef4b fix: failed ut 2022-04-20 18:59:09 +08:00
HFO4 3d9b9ae5d6 Merge remote-tracking branch 'origin/master' 2022-04-20 18:52:39 +08:00
HFO4 8741c3cc78 feat: return create date while list files 2022-04-20 18:51:43 +08:00
HFO4 6c93e37777 Update version number 2022-04-20 18:50:46 +08:00
HFO4 841a2e258d fix: ignore folder name conflict while creating upload session 2022-04-20 18:50:07 +08:00
HFO4 da2f6c5b07 chore: upgrade gin to 1.7.7 2022-04-20 11:50:15 +08:00
HFO4 a26183875f fix: in decompress, file stream should be closed after copy it to temp file. 2022-04-20 11:49:01 +08:00
vvisionnnandGitHub 79913a5dfa fix: Dockerfile build issue (#1217) 2022-04-20 09:14:17 +08:00
33 changed files with 469 additions and 332 deletions
+2 -11
View File
@@ -31,14 +31,5 @@ jobs:
- name: Test
run: go test -coverprofile=coverage.txt -covermode=atomic ./...
- name: Upload binary files (linux_arm)
uses: actions/upload-artifact@v2
with:
name: cloudreve_linux_arm
path: release/cloudreve*linux_arm.*
- name: Upload binary files (linux_arm64)
uses: actions/upload-artifact@v2
with:
name: cloudreve_linux_arm64
path: release/cloudreve*linux_arm64.*
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v2
+3 -5
View File
@@ -1,4 +1,4 @@
FROM golang:1.17.7-alpine as cloudreve_builder
FROM golang:1.17-alpine as cloudreve_builder
# install dependencies and build tools
@@ -10,13 +10,11 @@ RUN git clone --recurse-submodules https://github.com/cloudreve/Cloudreve.git
# build frontend
WORKDIR /cloudreve_builder/Cloudreve/assets
RUN yarn install --network-timeout 1000000
RUN yarn run build
RUN yarn run build && rm -rf build/*.map
# build backend
WORKDIR /cloudreve_builder/Cloudreve
RUN go get github.com/rakyll/statik \
&& statik -src=assets/build/ -include=*.html,*.js,*.json,*.css,*.png,*.svg,*.ico -f \
&& tag_name=$(git describe --tags) \
RUN tag_name=$(git describe --tags) \
&& export COMMIT_SHA=$(git rev-parse --short HEAD) \
&& go build -a -o cloudreve -ldflags " -X 'github.com/HFO4/cloudreve/pkg/conf.BackendVersion=$tag_name' -X 'github.com/HFO4/cloudreve/pkg/conf.LastCommit=$COMMIT_SHA'"
+7 -4
View File
@@ -9,16 +9,19 @@
<h4 align="center">支持多家云存储驱动的公有云文件系统.</h4>
<p align="center">
<a href="https://travis-ci.com/github/cloudreve/Cloudreve/">
<img src="https://img.shields.io/travis/com/cloudreve/Cloudreve?style=flat-square"
alt="travis">
<a href="https://github.com/cloudreve/Cloudreve/actions/workflows/test.yml">
<img src="https://img.shields.io/github/workflow/status/cloudreve/Cloudreve/Test?style=flat-square"
alt="GitHub Test Workflow">
</a>
<a href="https://codecov.io/gh/cloudreve/Cloudreve"><img src="https://img.shields.io/codecov/c/github/cloudreve/Cloudreve?style=flat-square"></a>
<a href="https://goreportcard.com/report/github.com/cloudreve/Cloudreve">
<img src="https://goreportcard.com/badge/github.com/cloudreve/Cloudreve?style=flat-square">
</a>
<a href="https://github.com/cloudreve/Cloudreve/releases">
<img src="https://img.shields.io/github/v/release/cloudreve/Cloudreve?include_prereleases&style=flat-square">
<img src="https://img.shields.io/github/v/release/cloudreve/Cloudreve?include_prereleases&style=flat-square" />
</a>
<a href="https://hub.docker.com/r/cloudreve/cloudreve">
<img src="https://img.shields.io/docker/image-size/cloudreve/cloudreve?style=flat-square"/>
</a>
</p>
+1 -1
Submodule assets updated: 4ca2d3696b...1daecbfe7e
+1 -1
View File
@@ -12,7 +12,7 @@ require (
github.com/gin-contrib/gzip v0.0.2-0.20200226035851-25bef2ef21e8
github.com/gin-contrib/sessions v0.0.1
github.com/gin-contrib/static v0.0.0-20191128031702-f81c604d8ac2
github.com/gin-gonic/gin v1.7.0
github.com/gin-gonic/gin v1.7.7
github.com/go-ini/ini v1.50.0
github.com/go-mail/mail v2.3.1+incompatible
github.com/gofrs/uuid v4.0.0+incompatible
+2 -2
View File
@@ -62,8 +62,8 @@ github.com/gin-contrib/static v0.0.0-20191128031702-f81c604d8ac2 h1:xLG16iua01X7
github.com/gin-contrib/static v0.0.0-20191128031702-f81c604d8ac2/go.mod h1:VhW/Ch/3FhimwZb8Oj+qJmdMmoB8r7lmJ5auRjm50oQ=
github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/3rZdM=
github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmCsR2Do=
github.com/gin-gonic/gin v1.7.0 h1:jGB9xAJQ12AIGNB4HguylppmDK1Am9ppF7XnGXXJuoU=
github.com/gin-gonic/gin v1.7.0/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY=
github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs=
github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U=
github.com/globalsign/mgo v0.0.0-20181015135952-eeefdecb41b8/go.mod h1:xkRDCp4j0OGD1HRkm4kmhM+pmpv3AKq5SU7GMg4oO/Q=
github.com/go-ini/ini v1.50.0 h1:ogX6RS8VstVN8MJcwhEP78hHhWaI3klN02+97bByabY=
github.com/go-ini/ini v1.50.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
+4
View File
@@ -62,6 +62,10 @@ func FrontendFileHandler() gin.HandlerFunc {
return
}
if path == "/service-worker.js" {
c.Header("Cache-Control", "public, no-cache")
}
// 存在的静态文件
fileServer.ServeHTTP(c.Writer, c.Request)
c.Abort()
+6 -2
View File
@@ -102,12 +102,16 @@ func (folder *Folder) GetChildFiles() ([]File, error) {
// GetFilesByIDs 根据文件ID批量获取文件,
// UID为0表示忽略用户,只根据文件ID检索
func GetFilesByIDs(ids []uint, uid uint) ([]File, error) {
return GetFilesByIDsFromTX(DB, ids, uid)
}
func GetFilesByIDsFromTX(tx *gorm.DB, ids []uint, uid uint) ([]File, error) {
var files []File
var result *gorm.DB
if uid == 0 {
result = DB.Where("id in (?)", ids).Find(&files)
result = tx.Where("id in (?)", ids).Find(&files)
} else {
result = DB.Where("id in (?) AND user_id = ?", ids, uid).Find(&files)
result = tx.Where("id in (?) AND user_id = ?", ids, uid).Find(&files)
}
return files, result.Error
}
+6 -2
View File
@@ -23,11 +23,15 @@ type Folder struct {
// Create 创建目录
func (folder *Folder) Create() (uint, error) {
if err := DB.Create(folder).Error; err != nil {
tx := DB.Begin()
if err := tx.FirstOrCreate(folder, *folder).Error; err != nil {
tx.Rollback()
util.Log().Warning("无法插入目录记录, %s", err)
return 0, err
}
return folder.ID, nil
err := tx.Commit().Error
return folder.ID, err
}
// GetChild 返回folder下名为name的子目录,不存在则返回错误
+12 -1
View File
@@ -17,8 +17,9 @@ func TestFolder_Create(t *testing.T) {
Name: "new folder",
}
// 插入成功
// 不存在,插入成功
mock.ExpectBegin()
mock.ExpectQuery("SELECT(.+)folders(.+)").WillReturnRows(sqlmock.NewRows([]string{"id"}))
mock.ExpectExec("INSERT(.+)").WillReturnResult(sqlmock.NewResult(5, 1))
mock.ExpectCommit()
fid, err := folder.Create()
@@ -28,12 +29,22 @@ func TestFolder_Create(t *testing.T) {
// 插入失败
mock.ExpectBegin()
mock.ExpectQuery("SELECT(.+)folders(.+)").WillReturnRows(sqlmock.NewRows([]string{"id"}))
mock.ExpectExec("INSERT(.+)").WillReturnError(errors.New("error"))
mock.ExpectRollback()
fid, err = folder.Create()
asserts.Error(err)
asserts.Equal(uint(0), fid)
asserts.NoError(mock.ExpectationsWereMet())
// 存在,直接返回
mock.ExpectBegin()
mock.ExpectQuery("SELECT(.+)folders(.+)").WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(5))
mock.ExpectCommit()
fid, err = folder.Create()
asserts.NoError(err)
asserts.Equal(uint(5), fid)
asserts.NoError(mock.ExpectationsWereMet())
}
func TestFolder_GetChild(t *testing.T) {
+6 -3
View File
@@ -73,10 +73,13 @@ func Init() {
}
//设置连接池
//空闲
db.DB().SetMaxIdleConns(50)
//打开
db.DB().SetMaxOpenConns(100)
if conf.DatabaseConfig.Type == "sqlite" || conf.DatabaseConfig.Type == "sqlite3" || conf.DatabaseConfig.Type == "UNSET" {
db.DB().SetMaxOpenConns(1)
} else {
db.DB().SetMaxOpenConns(100)
}
//超时
db.DB().SetConnMaxLifetime(time.Second * 30)
+15 -5
View File
@@ -23,6 +23,11 @@ func IsTrueVal(val string) bool {
// GetSettingByName 用 Name 获取设置值
func GetSettingByName(name string) string {
return GetSettingByNameFromTx(DB, name)
}
// GetSettingByNameFromTx 用 Name 获取设置值,使用事务
func GetSettingByNameFromTx(tx *gorm.DB, name string) string {
var setting Setting
// 优先从缓存中查找
@@ -32,14 +37,19 @@ func GetSettingByName(name string) string {
}
// 尝试数据库中查找
if DB != nil {
result := DB.Where("name = ?", name).First(&setting)
if result.Error == nil {
_ = cache.Set(cacheKey, setting.Value, -1)
return setting.Value
if tx == nil {
tx = DB
if tx == nil {
return ""
}
}
result := tx.Where("name = ?", name).First(&setting)
if result.Error == nil {
_ = cache.Set(cacheKey, setting.Value, -1)
return setting.Value
}
return ""
}
+3 -3
View File
@@ -1,13 +1,13 @@
package conf
// BackendVersion 当前后端版本号
var BackendVersion = "3.5.0-beta1"
var BackendVersion = "3.5.1"
// RequiredDBVersion 与当前版本匹配的数据库版本
var RequiredDBVersion = "3.5.0-beta1"
var RequiredDBVersion = "3.5.0"
// RequiredStaticVersion 与当前版本匹配的静态资源版本
var RequiredStaticVersion = "3.5.0-beta1"
var RequiredStaticVersion = "3.5.1"
// IsPro 是否为Pro版本
var IsPro = "false"
+3
View File
@@ -190,6 +190,8 @@ func (fs *FileSystem) Decompress(ctx context.Context, src, dst string) error {
return err
}
defer fileStream.Close()
tempZipFilePath = filepath.Join(
util.RelativePath(model.GetSettingByName("temp_path")),
"decompress",
@@ -211,6 +213,7 @@ func (fs *FileSystem) Decompress(ctx context.Context, src, dst string) error {
}
zipFile.Close()
fileStream.Close()
// 解压缩文件
r, err := zip.OpenReader(tempZipFilePath)
+2 -3
View File
@@ -4,7 +4,6 @@ import (
"bytes"
"context"
"errors"
"github.com/cloudreve/Cloudreve/v3/pkg/request"
"github.com/cloudreve/Cloudreve/v3/pkg/util"
testMock "github.com/stretchr/testify/mock"
"io"
@@ -173,7 +172,7 @@ func TestFileSystem_Decompress(t *testing.T) {
fs.FileTarget = []model.File{{SourceName: "1.zip", Policy: model.Policy{Type: "mock"}}}
fs.FileTarget[0].Policy.ID = 1
testHandler := new(FileHeaderMock)
testHandler.On("Get", testMock.Anything, "1.zip").Return(request.NopRSCloser{}, errors.New("error"))
testHandler.On("Get", testMock.Anything, "1.zip").Return(MockRSC{}, errors.New("error"))
fs.Handler = testHandler
err := fs.Decompress(ctx, "/1.zip", "/")
asserts.NoError(mock.ExpectationsWereMet())
@@ -187,7 +186,7 @@ func TestFileSystem_Decompress(t *testing.T) {
fs.FileTarget = []model.File{{SourceName: "1.zip", Policy: model.Policy{Type: "mock"}}}
fs.FileTarget[0].Policy.ID = 1
testHandler := new(FileHeaderMock)
testHandler.On("Get", testMock.Anything, "1.zip").Return(request.NopRSCloser{}, nil)
testHandler.On("Get", testMock.Anything, "1.zip").Return(MockRSC{}, nil)
fs.Handler = testHandler
err := fs.Decompress(ctx, "/1.zip", "/")
asserts.NoError(mock.ExpectationsWereMet())
+1
View File
@@ -461,6 +461,7 @@ func (handler *Driver) Token(ctx context.Context, ttl int64, uploadSession *seri
// 签名完成分片上传的URL
completeURL, err := handler.bucket.SignURL(fileInfo.SavePath, oss.HTTPPost, ttl,
oss.ContentType("application/octet-stream"),
oss.UploadID(imur.UploadID),
oss.Expires(time.Now().Add(time.Duration(ttl)*time.Second)),
oss.CompleteAll("yes"),
+7 -7
View File
@@ -30,7 +30,7 @@ const (
// Client to operate uploading to remote slave server
type Client interface {
// CreateUploadSession creates remote upload session
CreateUploadSession(ctx context.Context, session *serializer.UploadSession, ttl int64) error
CreateUploadSession(ctx context.Context, session *serializer.UploadSession, ttl int64, overwrite bool) error
// GetUploadURL signs an url for uploading file
GetUploadURL(ttl int64, sessionID string) (string, string, error)
// Upload uploads file to remote server
@@ -82,12 +82,11 @@ func (c *remoteClient) Upload(ctx context.Context, file fsctx.FileHeader) error
}
// Create upload session
if err := c.CreateUploadSession(ctx, session, int64(ttl)); err != nil {
overwrite := fileInfo.Mode&fsctx.Overwrite == fsctx.Overwrite
if err := c.CreateUploadSession(ctx, session, int64(ttl), overwrite); err != nil {
return fmt.Errorf("failed to create upload session: %w", err)
}
overwrite := fileInfo.Mode&fsctx.Overwrite == fsctx.Overwrite
// Initial chunk groups
chunks := chunk.NewChunkGroup(file, c.policy.OptionsSerialized.ChunkSize, &backoff.ConstantBackoff{
Max: model.GetIntSetting("chunk_retries", 5),
@@ -130,10 +129,11 @@ func (c *remoteClient) DeleteUploadSession(ctx context.Context, sessionID string
return nil
}
func (c *remoteClient) CreateUploadSession(ctx context.Context, session *serializer.UploadSession, ttl int64) error {
func (c *remoteClient) CreateUploadSession(ctx context.Context, session *serializer.UploadSession, ttl int64, overwrite bool) error {
reqBodyEncoded, err := json.Marshal(map[string]interface{}{
"session": session,
"ttl": ttl,
"session": session,
"ttl": ttl,
"overwrite": overwrite,
})
if err != nil {
return err
+1 -1
View File
@@ -281,7 +281,7 @@ func (handler *Driver) Token(ctx context.Context, ttl int64, uploadSession *seri
// 在从机端创建上传会话
uploadSession.Callback = apiURL.String()
if err := handler.uploadClient.CreateUploadSession(ctx, uploadSession, ttl); err != nil {
if err := handler.uploadClient.CreateUploadSession(ctx, uploadSession, ttl, false); err != nil {
return nil, err
}
+3 -3
View File
@@ -391,7 +391,7 @@ func TestHandler_Token(t *testing.T) {
{
clientMock := &remoteclientmock.RemoteClientMock{}
handler.uploadClient = clientMock
clientMock.On("CreateUploadSession", testMock.Anything, testMock.Anything, int64(10)).Return(errors.New("error"))
clientMock.On("CreateUploadSession", testMock.Anything, testMock.Anything, int64(10), false).Return(errors.New("error"))
res, err := handler.Token(context.Background(), 10, &serializer.UploadSession{}, &fsctx.FileStream{})
a.Error(err)
a.Contains(err.Error(), "error")
@@ -403,7 +403,7 @@ func TestHandler_Token(t *testing.T) {
{
clientMock := &remoteclientmock.RemoteClientMock{}
handler.uploadClient = clientMock
clientMock.On("CreateUploadSession", testMock.Anything, testMock.Anything, int64(10)).Return(nil)
clientMock.On("CreateUploadSession", testMock.Anything, testMock.Anything, int64(10), false).Return(nil)
clientMock.On("GetUploadURL", int64(10), "").Return("", "", errors.New("error"))
res, err := handler.Token(context.Background(), 10, &serializer.UploadSession{}, &fsctx.FileStream{})
a.Error(err)
@@ -416,7 +416,7 @@ func TestHandler_Token(t *testing.T) {
{
clientMock := &remoteclientmock.RemoteClientMock{}
handler.uploadClient = clientMock
clientMock.On("CreateUploadSession", testMock.Anything, testMock.Anything, int64(10)).Return(nil)
clientMock.On("CreateUploadSession", testMock.Anything, testMock.Anything, int64(10), false).Return(nil)
clientMock.On("GetUploadURL", int64(10), "").Return("1", "2", nil)
res, err := handler.Token(context.Background(), 10, &serializer.UploadSession{}, &fsctx.FileStream{})
a.NoError(err)
+4 -8
View File
@@ -203,14 +203,10 @@ func SlaveAfterUpload(session *serializer.UploadSession) Hook {
func GenericAfterUpload(ctx context.Context, fs *FileSystem, fileHeader fsctx.FileHeader) error {
fileInfo := fileHeader.Info()
// 检查路径是否存在,不存在就创建
isExist, folder := fs.IsPathExist(fileInfo.VirtualPath)
if !isExist {
newFolder, err := fs.CreateDirectory(ctx, fileInfo.VirtualPath)
if err != nil {
return err
}
folder = newFolder
// 创建或查找根目录
folder, err := fs.CreateDirectory(ctx, fileInfo.VirtualPath)
if err != nil {
return err
}
// 检查文件是否存在
+24 -12
View File
@@ -113,10 +113,15 @@ func TestGenericAfterUpload(t *testing.T) {
mock.ExpectQuery("SELECT(.+)").
WithArgs(1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(1, 1))
mock.ExpectQuery("SELECT(.+)files").
WithArgs(1, "我的文件").
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}))
// 1
mock.ExpectBegin()
mock.ExpectQuery("SELECT(.+)").
WithArgs(1, 1, "我的文件").
WithArgs("我的文件", 1, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(2, 1))
mock.ExpectCommit()
mock.ExpectQuery("SELECT(.+)files(.+)").WillReturnError(errors.New("not found"))
mock.ExpectBegin()
mock.ExpectExec("INSERT(.+)files(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
@@ -127,22 +132,19 @@ func TestGenericAfterUpload(t *testing.T) {
asserts.NoError(err)
asserts.NoError(mock.ExpectationsWereMet())
// 路径不存在
mock.ExpectQuery("SELECT(.+)folders(.+)").WillReturnRows(
mock.NewRows([]string{"name"}),
)
err = GenericAfterUpload(ctx, &fs, file)
asserts.Equal(ErrRootProtected, err)
asserts.NoError(mock.ExpectationsWereMet())
// 文件已存在
mock.ExpectQuery("SELECT(.+)").
WithArgs(1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(1, 1))
mock.ExpectQuery("SELECT(.+)files").
WithArgs(1, "我的文件").
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}))
// 1
mock.ExpectBegin()
mock.ExpectQuery("SELECT(.+)").
WithArgs(1, 1, "我的文件").
WithArgs("我的文件", 1, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(2, 1))
mock.ExpectCommit()
mock.ExpectQuery("SELECT(.+)files(.+)").WillReturnRows(
mock.NewRows([]string{"name"}).AddRow("test.txt"),
)
@@ -154,10 +156,15 @@ func TestGenericAfterUpload(t *testing.T) {
mock.ExpectQuery("SELECT(.+)").
WithArgs(1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(1, 1))
mock.ExpectQuery("SELECT(.+)files").
WithArgs(1, "我的文件").
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}))
// 1
mock.ExpectBegin()
mock.ExpectQuery("SELECT(.+)").
WithArgs(1, 1, "我的文件").
WithArgs("我的文件", 1, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(2, 1))
mock.ExpectCommit()
mock.ExpectQuery("SELECT(.+)files(.+)").WillReturnRows(
mock.NewRows([]string{"name", "upload_session_id"}).AddRow("test.txt", "1"),
)
@@ -169,10 +176,15 @@ func TestGenericAfterUpload(t *testing.T) {
mock.ExpectQuery("SELECT(.+)").
WithArgs(1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(1, 1))
mock.ExpectQuery("SELECT(.+)files").
WithArgs(1, "我的文件").
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}))
// 1
mock.ExpectBegin()
mock.ExpectQuery("SELECT(.+)").
WithArgs(1, 1, "我的文件").
WithArgs("我的文件", 1, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(2, 1))
mock.ExpectCommit()
mock.ExpectQuery("SELECT(.+)files(.+)").WillReturnError(errors.New("not found"))
mock.ExpectBegin()
+18 -17
View File
@@ -334,13 +334,14 @@ func (fs *FileSystem) listObjects(ctx context.Context, parent string, files []mo
}
objects = append(objects, serializer.Object{
ID: hashid.HashID(subFolder.ID, hashid.FolderID),
Name: subFolder.Name,
Path: processedPath,
Pic: "",
Size: 0,
Type: "dir",
Date: subFolder.UpdatedAt,
ID: hashid.HashID(subFolder.ID, hashid.FolderID),
Name: subFolder.Name,
Path: processedPath,
Pic: "",
Size: 0,
Type: "dir",
Date: subFolder.UpdatedAt,
CreateDate: subFolder.CreatedAt,
})
}
@@ -363,6 +364,7 @@ func (fs *FileSystem) listObjects(ctx context.Context, parent string, files []mo
Type: "file",
Date: file.UpdatedAt,
SourceEnabled: file.GetPolicy().IsOriginLinkEnable,
CreateDate: file.CreatedAt,
}
if shareKey != "" {
newFile.Key = shareKey
@@ -374,12 +376,17 @@ func (fs *FileSystem) listObjects(ctx context.Context, parent string, files []mo
return objects
}
// CreateDirectory 根据给定的完整创建目录,支持递归创建
// CreateDirectory 根据给定的完整创建目录,支持递归创建。如果目录已存在,则直接
// 返回已存在的目录。
func (fs *FileSystem) CreateDirectory(ctx context.Context, fullPath string) (*model.Folder, error) {
if fullPath == "/" || fullPath == "." || fullPath == "" {
if fullPath == "." || fullPath == "" {
return nil, ErrRootProtected
}
if fullPath == "/" {
return fs.User.Root()
}
// 获取要创建目录的父路径和目录名
fullPath = path.Clean(fullPath)
base := path.Dir(fullPath)
@@ -396,10 +403,6 @@ func (fs *FileSystem) CreateDirectory(ctx context.Context, fullPath string) (*mo
// 父目录是否存在
isExist, parent := fs.IsPathExist(base)
if !isExist {
// 递归创建父目录
if _, ok := ctx.Value(fsctx.IgnoreDirectoryConflictCtx).(bool); !ok {
ctx = context.WithValue(ctx, fsctx.IgnoreDirectoryConflictCtx, true)
}
newParent, err := fs.CreateDirectory(ctx, base)
if err != nil {
return nil, err
@@ -421,11 +424,9 @@ func (fs *FileSystem) CreateDirectory(ctx context.Context, fullPath string) (*mo
_, err := newFolder.Create()
if err != nil {
if _, ok := ctx.Value(fsctx.IgnoreDirectoryConflictCtx).(bool); !ok {
return nil, ErrFolderExisted
}
return nil, fmt.Errorf("failed to create folder: %w", err)
}
return &newFolder, nil
}
+77 -11
View File
@@ -214,7 +214,7 @@ func TestFileSystem_CreateDirectory(t *testing.T) {
asserts.Equal(ErrFileExisted, err)
asserts.NoError(mock.ExpectationsWereMet())
// 存在同名目录
// 存在同名目录,直接返回
mock.ExpectQuery("SELECT(.+)").
WithArgs(1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(1, 1))
@@ -225,13 +225,37 @@ func TestFileSystem_CreateDirectory(t *testing.T) {
mock.ExpectQuery("SELECT(.+)files").WillReturnRows(sqlmock.NewRows([]string{"id", "name"}))
mock.ExpectBegin()
mock.ExpectExec("INSERT(.+)").WillReturnError(errors.New("s"))
mock.ExpectRollback()
_, err = fs.CreateDirectory(ctx, "/ad/ab")
asserts.Error(err)
// ab
mock.ExpectQuery("SELECT(.+)").
WithArgs("ab", 2, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(3, 1))
mock.ExpectCommit()
res, err := fs.CreateDirectory(ctx, "/ad/ab")
asserts.NoError(err)
asserts.EqualValues(3, res.ID)
asserts.NoError(mock.ExpectationsWereMet())
// 成功创建
mock.ExpectQuery("SELECT(.+)").
WithArgs(1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(1, 1))
// ad
mock.ExpectQuery("SELECT(.+)").
WithArgs(1, 1, "ad").
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(2, 1))
mock.ExpectQuery("SELECT(.+)files").WillReturnRows(sqlmock.NewRows([]string{"id", "name"}))
mock.ExpectBegin()
mock.ExpectQuery("SELECT(.+)").
WithArgs("ab", 2, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}))
mock.ExpectExec("INSERT(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()
_, err = fs.CreateDirectory(ctx, "/ad/ab")
asserts.NoError(err)
asserts.NoError(mock.ExpectationsWereMet())
// 成功创建, 递归创建父目录
// 根目录
mock.ExpectQuery("SELECT(.+)").
WithArgs(1).
@@ -239,20 +263,62 @@ func TestFileSystem_CreateDirectory(t *testing.T) {
// ad
mock.ExpectQuery("SELECT(.+)").
WithArgs(1, 1, "ad").
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(2, 1))
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}))
// 根目录
mock.ExpectQuery("SELECT(.+)").
WithArgs(1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(1, 1))
mock.ExpectQuery("SELECT(.+)files").WillReturnRows(sqlmock.NewRows([]string{"id", "name"}))
// 创建ad
mock.ExpectBegin()
mock.ExpectQuery("SELECT(.+)").
WithArgs("ad", 1, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}))
mock.ExpectExec("INSERT(.+)").WillReturnResult(sqlmock.NewResult(2, 1))
mock.ExpectCommit()
mock.ExpectQuery("SELECT(.+)files").WillReturnRows(sqlmock.NewRows([]string{"id", "name"}))
// 创建ab
mock.ExpectBegin()
mock.ExpectQuery("SELECT(.+)").
WithArgs("ab", 2, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}))
mock.ExpectExec("INSERT(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()
_, err = fs.CreateDirectory(ctx, "/ad/ab")
asserts.NoError(err)
asserts.NoError(mock.ExpectationsWereMet())
// 父目录不存在
mock.ExpectQuery("SELECT(.+)folders").WillReturnRows(sqlmock.NewRows([]string{"id", "name"}))
_, err = fs.CreateDirectory(ctx, "/ad")
asserts.Equal(ErrRootProtected, err)
// 底层创建失败
// 成功创建
mock.ExpectQuery("SELECT(.+)").
WithArgs(1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(1, 1))
// ad
mock.ExpectQuery("SELECT(.+)").
WithArgs(1, 1, "ad").
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}))
// 根目录
mock.ExpectQuery("SELECT(.+)").
WithArgs(1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(1, 1))
mock.ExpectQuery("SELECT(.+)files").WillReturnRows(sqlmock.NewRows([]string{"id", "name"}))
// 创建ad
mock.ExpectBegin()
mock.ExpectQuery("SELECT(.+)").
WithArgs("ad", 1, 1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}))
mock.ExpectExec("INSERT(.+)").WillReturnResult(sqlmock.NewResult(2, 1)).WillReturnError(errors.New("error"))
mock.ExpectRollback()
_, err = fs.CreateDirectory(ctx, "/ad/ab")
asserts.Error(err)
asserts.NoError(mock.ExpectationsWereMet())
// 直接创建根目录
mock.ExpectQuery("SELECT(.+)").
WithArgs(1).
WillReturnRows(sqlmock.NewRows([]string{"id", "owner_id"}).AddRow(1, 1))
_, err = fs.CreateDirectory(ctx, "/")
asserts.NoError(err)
asserts.NoError(mock.ExpectationsWereMet())
}
+1
View File
@@ -171,6 +171,7 @@ func (fs *FileSystem) CreateUploadSession(ctx context.Context, file *fsctx.FileS
fs.Use("AfterUpload", HookClearFileHeaderSize)
}
fs.Use("AfterUpload", GenericAfterUpload)
ctx = context.WithValue(ctx, fsctx.IgnoreDirectoryConflictCtx, true)
if err := fs.Upload(ctx, file); err != nil {
return nil, err
}
+2 -2
View File
@@ -11,8 +11,8 @@ type RemoteClientMock struct {
mock.Mock
}
func (r *RemoteClientMock) CreateUploadSession(ctx context.Context, session *serializer.UploadSession, ttl int64) error {
return r.Called(ctx, session, ttl).Error(0)
func (r *RemoteClientMock) CreateUploadSession(ctx context.Context, session *serializer.UploadSession, ttl int64, overwrite bool) error {
return r.Called(ctx, session, ttl, overwrite).Error(0)
}
func (r *RemoteClientMock) GetUploadURL(ttl int64, sessionID string) (string, string, error) {
+1
View File
@@ -40,6 +40,7 @@ type Object struct {
Size uint64 `json:"size"`
Type string `json:"type"`
Date time.Time `json:"date"`
CreateDate time.Time `json:"create_date"`
Key string `json:"key,omitempty"`
SourceEnabled bool `json:"source_enabled"`
}
+7 -11
View File
@@ -150,18 +150,14 @@ func (job *ImportTask) Do() {
if parent, ok := pathCache[virtualPath]; ok {
parentFolder = parent
} else {
exist, folder := fs.IsPathExist(virtualPath)
if exist {
parentFolder = folder
} else {
folder, err := fs.CreateDirectory(context.Background(), virtualPath)
if err != nil {
util.Log().Warning("导入任务无法创建用户目录[%s], %s",
virtualPath, err)
continue
}
parentFolder = folder
folder, err := fs.CreateDirectory(context.Background(), virtualPath)
if err != nil {
util.Log().Warning("导入任务无法创建用户目录[%s], %s",
virtualPath, err)
continue
}
parentFolder = folder
}
// 插入文件记录
+2
View File
@@ -147,6 +147,7 @@ func TestImportTask_Do(t *testing.T) {
mock.ExpectQuery("SELECT(.+)folders").WillReturnRows(sqlmock.NewRows([]string{"id"}))
// 创建文件时查找父目录,仍然不存在
mock.ExpectQuery("SELECT(.+)folders").WillReturnRows(sqlmock.NewRows([]string{"id"}))
mock.ExpectQuery("SELECT(.+)folders").WillReturnRows(sqlmock.NewRows([]string{"id"}))
task.Do()
@@ -177,6 +178,7 @@ func TestImportTask_Do(t *testing.T) {
mock.ExpectQuery("SELECT(.+)files").WillReturnRows(sqlmock.NewRows([]string{"id"}))
// 创建目录
mock.ExpectBegin()
mock.ExpectQuery("SELECT(.+)folders").WillReturnRows(sqlmock.NewRows([]string{"id"}))
mock.ExpectExec("INSERT(.+)folders(.+)").WillReturnResult(sqlmock.NewResult(2, 1))
mock.ExpectCommit()
// 插入文件记录
+233 -208
View File
@@ -14,6 +14,7 @@ import (
"path"
"strconv"
"strings"
"sync"
"time"
model "github.com/cloudreve/Cloudreve/v3/models"
@@ -30,6 +31,7 @@ type Handler struct {
// Logger is an optional error logger. If non-nil, it will be called
// for all HTTP requests.
Logger func(*http.Request, error)
Mutex *sync.Mutex
}
func (h *Handler) stripPrefix(p string, uid uint) (string, int, error) {
@@ -60,13 +62,19 @@ func isPathExist(ctx context.Context, fs *filesystem.FileSystem, path string) (b
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, fs *filesystem.FileSystem) {
status, err := http.StatusBadRequest, errUnsupportedMethod
h.Mutex.Lock()
if h.LockSystem == nil {
h.Mutex.Unlock()
status, err = http.StatusInternalServerError, errNoLockSystem
} else {
// 检查并新建LockSystem
if _, ok := h.LockSystem[fs.User.ID]; !ok {
// 检查并新建 LockSystem
ls, ok := h.LockSystem[fs.User.ID]
if !ok {
h.LockSystem[fs.User.ID] = NewMemLS()
ls = h.LockSystem[fs.User.ID]
}
h.Mutex.Unlock()
switch r.Method {
case "OPTIONS":
status, err = h.handleOptions(w, r, fs)
@@ -81,13 +89,13 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, fs *filesyst
case "COPY", "MOVE":
status, err = h.handleCopyMove(w, r, fs)
case "LOCK":
status, err = h.handleLock(w, r, fs)
status, err = h.handleLock(w, r, fs, ls)
case "UNLOCK":
status, err = h.handleUnlock(w, r, fs)
status, err = h.handleUnlock(w, r, fs, ls)
case "PROPFIND":
status, err = h.handlePropfind(w, r, fs)
status, err = h.handlePropfind(w, r, fs, ls)
case "PROPPATCH":
status, err = h.handleProppatch(w, r, fs)
status, err = h.handleProppatch(w, r, fs, ls)
}
}
@@ -103,98 +111,111 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, fs *filesyst
}
// OK
func (h *Handler) lock(now time.Time, root string, fs *filesystem.FileSystem) (token string, status int, err error) {
token, err = h.LockSystem[fs.User.ID].Create(now, LockDetails{
Root: root,
Duration: infiniteTimeout,
ZeroDepth: true,
})
if err != nil {
if err == ErrLocked {
return "", StatusLocked, err
}
return "", http.StatusInternalServerError, err
}
return token, 0, nil
func (h *Handler) lock(now time.Time, root string, fs *filesystem.FileSystem, ls LockSystem) (token string, status int, err error) {
//token, err = ls.Create(now, LockDetails{
// Root: root,
// Duration: infiniteTimeout,
// ZeroDepth: true,
//})
//if err != nil {
// if err == ErrLocked {
// return "", StatusLocked, err
// }
// return "", http.StatusInternalServerError, err
//}
return fmt.Sprintf("%d", time.Now().Unix()), 0, nil
}
// ok
func (h *Handler) confirmLocks(r *http.Request, src, dst string, fs *filesystem.FileSystem) (release func(), status int, err error) {
hdr := r.Header.Get("If")
if hdr == "" {
// An empty If header means that the client hasn't previously created locks.
// Even if this client doesn't care about locks, we still need to check that
// the resources aren't locked by another client, so we create temporary
// locks that would conflict with another client's locks. These temporary
// locks are unlocked at the end of the HTTP request.
now, srcToken, dstToken := time.Now(), "", ""
if src != "" {
srcToken, status, err = h.lock(now, src, fs)
if err != nil {
return nil, status, err
}
}
if dst != "" {
dstToken, status, err = h.lock(now, dst, fs)
if err != nil {
if srcToken != "" {
h.LockSystem[fs.User.ID].Unlock(now, srcToken)
}
return nil, status, err
}
}
return func() {
if dstToken != "" {
h.LockSystem[fs.User.ID].Unlock(now, dstToken)
}
if srcToken != "" {
h.LockSystem[fs.User.ID].Unlock(now, srcToken)
}
}, 0, nil
}
//hdr := r.Header.Get("If")
//h.Mutex.Lock()
//ls,ok := h.LockSystem[fs.User.ID]
//h.Mutex.Unlock()
//if !ok{
// return nil, http.StatusInternalServerError, errNoLockSystem
//}
//
//if hdr == "" {
// // An empty If header means that the client hasn't previously created locks.
// // Even if this client doesn't care about locks, we still need to check that
// // the resources aren't locked by another client, so we create temporary
// // locks that would conflict with another client's locks. These temporary
// // locks are unlocked at the end of the HTTP request.
// now, srcToken, dstToken := time.Now(), "", ""
// if src != "" {
// srcToken, status, err = h.lock(now, src, fs,ls)
// if err != nil {
// return nil, status, err
// }
// }
// if dst != "" {
// dstToken, status, err = h.lock(now, dst, fs,ls)
// if err != nil {
// if srcToken != "" {
// ls.Unlock(now, srcToken)
// }
// return nil, status, err
// }
// }
//
// return func() {
// if dstToken != "" {
// ls.Unlock(now, dstToken)
// }
// if srcToken != "" {
// ls.Unlock(now, srcToken)
// }
// }, 0, nil
//}
//
//ih, ok := parseIfHeader(hdr)
//if !ok {
// return nil, http.StatusBadRequest, errInvalidIfHeader
//}
//// ih is a disjunction (OR) of ifLists, so any ifList will do.
//for _, l := range ih.lists {
// lsrc := l.resourceTag
// if lsrc == "" {
// lsrc = src
// } else {
// u, err := url.Parse(lsrc)
// if err != nil {
// continue
// }
// //if u.Host != r.Host {
// // continue
// //}
// lsrc, status, err = h.stripPrefix(u.Path, fs.User.ID)
// if err != nil {
// return nil, status, err
// }
// }
// release, err = ls.Confirm(
// time.Now(),
// lsrc,
// dst,
// l.conditions...,
// )
// if err == ErrConfirmationFailed {
// continue
// }
// if err != nil {
// return nil, http.StatusInternalServerError, err
// }
// return release, 0, nil
//}
//// Section 10.4.1 says that "If this header is evaluated and all state lists
//// fail, then the request must fail with a 412 (Precondition Failed) status."
//// We follow the spec even though the cond_put_corrupt_token test case from
//// the litmus test warns on seeing a 412 instead of a 423 (Locked).
//return nil, http.StatusPreconditionFailed, ErrLocked
ih, ok := parseIfHeader(hdr)
if !ok {
return nil, http.StatusBadRequest, errInvalidIfHeader
}
// ih is a disjunction (OR) of ifLists, so any ifList will do.
for _, l := range ih.lists {
lsrc := l.resourceTag
if lsrc == "" {
lsrc = src
} else {
u, err := url.Parse(lsrc)
if err != nil {
continue
}
//if u.Host != r.Host {
// continue
//}
lsrc, status, err = h.stripPrefix(u.Path, fs.User.ID)
if err != nil {
return nil, status, err
}
}
release, err = h.LockSystem[fs.User.ID].Confirm(
time.Now(),
lsrc,
dst,
l.conditions...,
)
if err == ErrConfirmationFailed {
continue
}
if err != nil {
return nil, http.StatusInternalServerError, err
}
return release, 0, nil
}
// Section 10.4.1 says that "If this header is evaluated and all state lists
// fail, then the request must fail with a 412 (Precondition Failed) status."
// We follow the spec even though the cond_put_corrupt_token test case from
// the litmus test warns on seeing a 412 instead of a 423 (Locked).
return nil, http.StatusPreconditionFailed, ErrLocked
return func() {
}, 0, nil
}
//OK
@@ -245,7 +266,7 @@ func (h *Handler) handleGetHeadPost(w http.ResponseWriter, r *http.Request, fs *
return http.StatusInternalServerError, err
}
etag, err := findETag(ctx, fs, h.LockSystem[fs.User.ID], reqPath, &fs.FileTarget[0])
etag, err := findETag(ctx, fs, nil, reqPath, &fs.FileTarget[0])
if err != nil {
return http.StatusInternalServerError, err
}
@@ -271,6 +292,7 @@ func (h *Handler) handleDelete(w http.ResponseWriter, r *http.Request, fs *files
if err != nil {
return status, err
}
release, status, err := h.confirmLocks(r, reqPath, "", fs)
if err != nil {
return status, err
@@ -373,7 +395,7 @@ func (h *Handler) handlePut(w http.ResponseWriter, r *http.Request, fs *filesyst
return http.StatusMethodNotAllowed, err
}
etag, err := findETag(ctx, fs, h.LockSystem[fs.User.ID], reqPath, fileData.Model.(*model.File))
etag, err := findETag(ctx, fs, nil, reqPath, fileData.Model.(*model.File))
if err != nil {
return http.StatusInternalServerError, err
}
@@ -400,11 +422,7 @@ func (h *Handler) handleMkcol(w http.ResponseWriter, r *http.Request, fs *filesy
if r.ContentLength > 0 {
return http.StatusUnsupportedMediaType, nil
}
if strings.Contains(r.UserAgent(), "rclone") {
if _, ok := ctx.Value(fsctx.IgnoreDirectoryConflictCtx).(bool); !ok {
ctx = context.WithValue(ctx, fsctx.IgnoreDirectoryConflictCtx, true)
}
}
if _, err := fs.CreateDirectory(ctx, reqPath); err != nil {
return http.StatusConflict, err
}
@@ -498,130 +516,137 @@ func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request, fs *fil
}
// OK
func (h *Handler) handleLock(w http.ResponseWriter, r *http.Request, fs *filesystem.FileSystem) (retStatus int, retErr error) {
func (h *Handler) handleLock(w http.ResponseWriter, r *http.Request, fs *filesystem.FileSystem, ls LockSystem) (retStatus int, retErr error) {
defer fs.Recycle()
duration, err := parseTimeout(r.Header.Get("Timeout"))
if err != nil {
return http.StatusBadRequest, err
}
li, status, err := readLockInfo(r.Body)
reqPath, status, err := h.stripPrefix(r.URL.Path, fs.User.ID)
if err != nil {
return status, err
}
//ctx := r.Context()
token, ld, now, created := "", LockDetails{}, time.Now(), false
if li == (lockInfo{}) {
// An empty lockInfo means to refresh the lock.
ih, ok := parseIfHeader(r.Header.Get("If"))
if !ok {
return http.StatusBadRequest, errInvalidIfHeader
}
if len(ih.lists) == 1 && len(ih.lists[0].conditions) == 1 {
token = ih.lists[0].conditions[0].Token
}
if token == "" {
return http.StatusBadRequest, errInvalidLockToken
}
ld, err = h.LockSystem[fs.User.ID].Refresh(now, token, duration)
if err != nil {
if err == ErrNoSuchLock {
return http.StatusPreconditionFailed, err
}
return http.StatusInternalServerError, err
}
////ctx := r.Context()
//token, ld, now, created := "", LockDetails{}, time.Now(), false
//if li == (lockInfo{}) {
// // An empty lockInfo means to refresh the lock.
// ih, ok := parseIfHeader(r.Header.Get("If"))
// if !ok {
// return http.StatusBadRequest, errInvalidIfHeader
// }
// if len(ih.lists) == 1 && len(ih.lists[0].conditions) == 1 {
// token = ih.lists[0].conditions[0].Token
// }
// if token == "" {
// return http.StatusBadRequest, errInvalidLockToken
// }
// ld, err = ls.Refresh(now, token, duration)
// if err != nil {
// if err == ErrNoSuchLock {
// return http.StatusPreconditionFailed, err
// }
// return http.StatusInternalServerError, err
// }
//
//} else {
// // Section 9.10.3 says that "If no Depth header is submitted on a LOCK request,
// // then the request MUST act as if a "Depth:infinity" had been submitted."
// depth := infiniteDepth
// if hdr := r.Header.Get("Depth"); hdr != "" {
// depth = parseDepth(hdr)
// if depth != 0 && depth != infiniteDepth {
// // Section 9.10.3 says that "Values other than 0 or infinity must not be
// // used with the Depth header on a LOCK method".
// return http.StatusBadRequest, errInvalidDepth
// }
// }
// reqPath, status, err := h.stripPrefix(r.URL.Path, fs.User.ID)
// if err != nil {
// return status, err
// }
// ld = LockDetails{
// Root: reqPath,
// Duration: duration,
// OwnerXML: li.Owner.InnerXML,
// ZeroDepth: depth == 0,
// }
// token, err = ls.Create(now, ld)
// if err != nil {
// if err == ErrLocked {
// return StatusLocked, err
// }
// return http.StatusInternalServerError, err
// }
// defer func() {
// if retErr != nil {
// ls.Unlock(now, token)
// }
// }()
//
// // Create the resource if it didn't previously exist.
// //if _, err := h.FileSystem.Stat(ctx, reqPath); err != nil {
// // f, err := h.FileSystem.OpenFile(ctx, reqPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
// // if err != nil {
// // // TODO: detect missing intermediate dirs and return http.StatusConflict?
// // return http.StatusInternalServerError, err
// // }
// // f.Close()
// // created = true
// //}
//
// // http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the
// // Lock-Token value is a Coded-URL. We add angle brackets.
// w.Header().Set("Lock-Token", "<"+token+">")
//}
//
//w.Header().Set("Content-Type", "application/xml; charset=utf-8")
//if created {
// // This is "w.WriteHeader(http.StatusCreated)" and not "return
// // http.StatusCreated, nil" because we write our own (XML) response to w
// // and Handler.ServeHTTP would otherwise write "Created".
// w.WriteHeader(http.StatusCreated)
//}
} else {
// Section 9.10.3 says that "If no Depth header is submitted on a LOCK request,
// then the request MUST act as if a "Depth:infinity" had been submitted."
depth := infiniteDepth
if hdr := r.Header.Get("Depth"); hdr != "" {
depth = parseDepth(hdr)
if depth != 0 && depth != infiniteDepth {
// Section 9.10.3 says that "Values other than 0 or infinity must not be
// used with the Depth header on a LOCK method".
return http.StatusBadRequest, errInvalidDepth
}
}
reqPath, status, err := h.stripPrefix(r.URL.Path, fs.User.ID)
if err != nil {
return status, err
}
ld = LockDetails{
Root: reqPath,
Duration: duration,
OwnerXML: li.Owner.InnerXML,
ZeroDepth: depth == 0,
}
token, err = h.LockSystem[fs.User.ID].Create(now, ld)
if err != nil {
if err == ErrLocked {
return StatusLocked, err
}
return http.StatusInternalServerError, err
}
defer func() {
if retErr != nil {
h.LockSystem[fs.User.ID].Unlock(now, token)
}
}()
// Create the resource if it didn't previously exist.
//if _, err := h.FileSystem.Stat(ctx, reqPath); err != nil {
// f, err := h.FileSystem.OpenFile(ctx, reqPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
// if err != nil {
// // TODO: detect missing intermediate dirs and return http.StatusConflict?
// return http.StatusInternalServerError, err
// }
// f.Close()
// created = true
//}
// http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the
// Lock-Token value is a Coded-URL. We add angle brackets.
w.Header().Set("Lock-Token", "<"+token+">")
}
w.Header().Set("Content-Type", "application/xml; charset=utf-8")
if created {
// This is "w.WriteHeader(http.StatusCreated)" and not "return
// http.StatusCreated, nil" because we write our own (XML) response to w
// and Handler.ServeHTTP would otherwise write "Created".
w.WriteHeader(http.StatusCreated)
}
writeLockInfo(w, token, ld)
writeLockInfo(w, fmt.Sprintf("%d", time.Now().UnixNano()), LockDetails{
Duration: duration,
OwnerXML: fs.User.Email,
Root: reqPath,
})
return 0, nil
}
// OK
func (h *Handler) handleUnlock(w http.ResponseWriter, r *http.Request, fs *filesystem.FileSystem) (status int, err error) {
func (h *Handler) handleUnlock(w http.ResponseWriter, r *http.Request, fs *filesystem.FileSystem, ls LockSystem) (status int, err error) {
defer fs.Recycle()
return http.StatusNoContent, err
// http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the
// Lock-Token value is a Coded-URL. We strip its angle brackets.
t := r.Header.Get("Lock-Token")
if len(t) < 2 || t[0] != '<' || t[len(t)-1] != '>' {
return http.StatusBadRequest, errInvalidLockToken
}
t = t[1 : len(t)-1]
switch err = h.LockSystem[fs.User.ID].Unlock(time.Now(), t); err {
case nil:
return http.StatusNoContent, err
case ErrForbidden:
return http.StatusForbidden, err
case ErrLocked:
return StatusLocked, err
case ErrNoSuchLock:
return http.StatusConflict, err
default:
return http.StatusInternalServerError, err
}
//// http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the
//// Lock-Token value is a Coded-URL. We strip its angle brackets.
//t := r.Header.Get("Lock-Token")
//if len(t) < 2 || t[0] != '<' || t[len(t)-1] != '>' {
// return http.StatusBadRequest, errInvalidLockToken
//}
//t = t[1 : len(t)-1]
//
//switch err = ls.Unlock(time.Now(), t); err {
//case nil:
// return http.StatusNoContent, err
//case ErrForbidden:
// return http.StatusForbidden, err
//case ErrLocked:
// return StatusLocked, err
//case ErrNoSuchLock:
// return http.StatusConflict, err
//default:
// return http.StatusInternalServerError, err
//}
}
// OK
func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request, fs *filesystem.FileSystem) (status int, err error) {
func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request, fs *filesystem.FileSystem, ls LockSystem) (status int, err error) {
defer fs.Recycle()
reqPath, status, err := h.stripPrefix(r.URL.Path, fs.User.ID)
@@ -655,7 +680,7 @@ func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request, fs *fil
}
var pstats []Propstat
if pf.Propname != nil {
pnames, err := propnames(ctx, fs, h.LockSystem[fs.User.ID], info)
pnames, err := propnames(ctx, fs, ls, info)
if err != nil {
return err
}
@@ -665,9 +690,9 @@ func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request, fs *fil
}
pstats = append(pstats, pstat)
} else if pf.Allprop != nil {
pstats, err = allprop(ctx, fs, h.LockSystem[fs.User.ID], info, pf.Prop)
pstats, err = allprop(ctx, fs, ls, info, pf.Prop)
} else {
pstats, err = props(ctx, fs, h.LockSystem[fs.User.ID], info, pf.Prop)
pstats, err = props(ctx, fs, ls, info, pf.Prop)
}
if err != nil {
return err
@@ -690,7 +715,7 @@ func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request, fs *fil
return 0, nil
}
func (h *Handler) handleProppatch(w http.ResponseWriter, r *http.Request, fs *filesystem.FileSystem) (status int, err error) {
func (h *Handler) handleProppatch(w http.ResponseWriter, r *http.Request, fs *filesystem.FileSystem, ls LockSystem) (status int, err error) {
defer fs.Recycle()
reqPath, status, err := h.stripPrefix(r.URL.Path, fs.User.ID)
@@ -712,7 +737,7 @@ func (h *Handler) handleProppatch(w http.ResponseWriter, r *http.Request, fs *fi
if err != nil {
return status, err
}
pstats, err := patch(ctx, fs, h.LockSystem[fs.User.ID], reqPath, patches)
pstats, err := patch(ctx, fs, ls, reqPath, patches)
if err != nil {
return http.StatusInternalServerError, err
}
+2
View File
@@ -7,6 +7,7 @@ import (
"github.com/cloudreve/Cloudreve/v3/pkg/webdav"
"github.com/cloudreve/Cloudreve/v3/service/setting"
"github.com/gin-gonic/gin"
"sync"
)
var handler *webdav.Handler
@@ -15,6 +16,7 @@ func init() {
handler = &webdav.Handler{
Prefix: "/dav",
LockSystem: make(map[uint]webdav.LockSystem),
Mutex: &sync.Mutex{},
}
}
+1 -1
View File
@@ -179,7 +179,7 @@ func (service *OneDriveCallback) PreProcess(c *gin.Context) serializer.Response
isSizeCheckFailed = false
}
if isSizeCheckFailed || info.GetSourcePath() != actualPath {
if isSizeCheckFailed || !strings.EqualFold(info.GetSourcePath(), actualPath) {
fs.Handler.(onedrive.Driver).Client.Delete(context.Background(), []string{info.GetSourcePath()})
return serializer.Err(serializer.CodeUploadFailed, "文件信息不一致", err)
}
+8 -5
View File
@@ -391,11 +391,6 @@ func (service *ItemPropertyService) GetProperty(ctx context.Context, c *gin.Cont
return serializer.Err(serializer.CodeNotFound, "对象不存在", err)
}
// 如果对象是目录, 先尝试返回缓存结果
if cacheRes, ok := cache.Get(fmt.Sprintf("folder_props_%d", res)); ok {
return serializer.Response{Data: cacheRes.(serializer.ObjectProps)}
}
folder, err := model.GetFoldersByIDs([]uint{res}, user.ID)
if err != nil {
return serializer.DBErr("找不到目录", err)
@@ -404,6 +399,14 @@ func (service *ItemPropertyService) GetProperty(ctx context.Context, c *gin.Cont
props.CreatedAt = folder[0].CreatedAt
props.UpdatedAt = folder[0].UpdatedAt
// 如果对象是目录, 先尝试返回缓存结果
if cacheRes, ok := cache.Get(fmt.Sprintf("folder_props_%d", res)); ok {
res := cacheRes.(serializer.ObjectProps)
res.CreatedAt = props.CreatedAt
res.UpdatedAt = props.UpdatedAt
return serializer.Response{Data: res}
}
// 统计子目录
childFolders, err := model.GetRecursiveChildFolder([]uint{folder[0].ID},
user.ID, true)
+4 -3
View File
@@ -167,13 +167,14 @@ func CreateTransferTask(c *gin.Context, req *serializer.SlaveTransferReq) serial
// SlaveListService 从机上传会话服务
type SlaveCreateUploadSessionService struct {
Session serializer.UploadSession `json:"session" binding:"required"`
TTL int64 `json:"ttl"`
Session serializer.UploadSession `json:"session" binding:"required"`
TTL int64 `json:"ttl"`
Overwrite bool `json:"overwrite"`
}
// Create 从机创建上传会话
func (service *SlaveCreateUploadSessionService) Create(ctx context.Context, c *gin.Context) serializer.Response {
if util.Exists(service.Session.SavePath) {
if !service.Overwrite && util.Exists(service.Session.SavePath) {
return serializer.Err(serializer.CodeConflict, "placeholder file already exist", nil)
}