github.com/cloudreve/Cloudreve/v3@v3.0.0-20240224133659-3edb00a6484c/models/scripts/storage.go (about)

     1  package scripts
     2  
     3  import (
     4  	"context"
     5  	model "github.com/cloudreve/Cloudreve/v3/models"
     6  	"github.com/cloudreve/Cloudreve/v3/pkg/util"
     7  )
     8  
     9  type UserStorageCalibration int
    10  
    11  type storageResult struct {
    12  	Total uint64
    13  }
    14  
    15  // Run 运行脚本校准所有用户容量
    16  func (script UserStorageCalibration) Run(ctx context.Context) {
    17  	// 列出所有用户
    18  	var res []model.User
    19  	model.DB.Model(&model.User{}).Find(&res)
    20  
    21  	// 逐个检查容量
    22  	for _, user := range res {
    23  		// 计算正确的容量
    24  		var total storageResult
    25  		model.DB.Model(&model.File{}).Where("user_id = ?", user.ID).Select("sum(size) as total").Scan(&total)
    26  		// 更新用户的容量
    27  		if user.Storage != total.Total {
    28  			util.Log().Info("Calibrate used storage for user %q, from %d to %d.", user.Email,
    29  				user.Storage, total.Total)
    30  		}
    31  		model.DB.Model(&user).Update("storage", total.Total)
    32  	}
    33  }