inventory

package
v4.0.0-...-95865ad Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 15, 2026 License: GPL-3.0 Imports: 58 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DBVersionPrefix           = "db_version_"
	EnvDefaultOverwritePrefix = "CR_SETTING_DEFAULT_"
	EnvEnableAria2            = "CR_ENABLE_ARIA2"
)
View Source
const (
	OrderDirectionAsc  = OrderDirection("asc")
	OrderDirectionDesc = OrderDirection("desc")
)
View Source
const (
	RootFolderName = ""
	SearchWildcard = "*"
	MaxMetadataLen = 65535
)
View Source
const (
	OAuthClientDesktopGUID        = "393a1839-f52e-498e-9972-e77cc2241eee"
	OAuthClientDesktopSecret      = "8GaQIu3lOSdqYoDHi9cR8IZ4pvuMH8ya"
	OAuthClientDesktopName        = "application:oauth.desktop"
	OAuthClientDesktopRedirectURI = "/callback/desktop"
	OAuthClientiOSGUID            = "220db97a-44a3-44f7-99b6-d767262b4daa"
	OAuthClientiOSSecret          = "1kxOW4IyVOkPlsKCnTwzfHyP8XrbpfaF"
	OAuthClientiOSName            = "application:setting.iOSApp"
	OAuthClientiOSRedirectURI     = "/callback/ios"
)
View Source
const (
	AnonymousGroupID = 3
)
View Source
const (
	// StoragePolicyCacheKey is the cache key of storage policy.
	StoragePolicyCacheKey = "storage_policy_"
)

Variables

View Source
var (
	ErrShareLinkExpired  = fmt.Errorf("share link expired")
	ErrOwnerInactive     = fmt.Errorf("owner is inactive")
	ErrSourceFileInvalid = fmt.Errorf("source file is deleted")
)
View Source
var (
	ErrUserEmailExisted      = errors.New("user email has been registered")
	ErrInactiveUserExisted   = errors.New("email already registered but not activated")
	ErrorUnknownPasswordType = errors.New("unknown password type")
	ErrorIncorrectPassword   = errors.New("incorrect password")
	ErrInsufficientPoints    = errors.New("insufficient points")
)
View Source
var DefaultSettings = map[string]string{}/* 200 elements not displayed */
View Source
var (
	ErrTooManyArguments = fmt.Errorf("too many arguments")
)
View Source
var RedactedSettings = map[string]struct{}{
	"encrypt_master_key": {},
	"secret_key":         {},
}

Functions

func CheckPassword

func CheckPassword(u *ent.User, password string) error

CheckPassword 根据明文校验密码

func Commit

func Commit(tx *Tx) error

func CommitWithStorageDiff

func CommitWithStorageDiff(ctx context.Context, tx *Tx, l logging.Logger, uc UserClient) error

CommitWithStorageDiff commits the transaction and applies the storage diff, only if the transaction is not inherited.

func InitializeDBClient

func InitializeDBClient(l logging.Logger,
	client *ent.Client, kv cache.Driver, requiredDbVersion string) (*ent.Client, error)

InitializeDBClient runs migration and returns a new ent.Client with additional configurations for hooks and interceptors.

func IsAnonymousUser

func IsAnonymousUser(u *ent.User) bool

IsAnonymousUser check if given user is anonymous user.

func IsShareExpired

func IsShareExpired(share *ent.Share) error

func IsValidShare

func IsValidShare(share *ent.Share) error

func NewRawEntClient

func NewRawEntClient(l logging.Logger, config conf.ConfigProvider) (*ent.Client, error)

NewRawEntClient returns a new ent.Client without additional configurations.

func Rollback

func Rollback(tx *Tx) error

func UserFromContext

func UserFromContext(ctx context.Context) *ent.User

UserFromContext get user from context

func UserIDFromContext

func UserIDFromContext(ctx context.Context) int

UserIDFromContext get user id from context.

Types

type CopyParameter

type CopyParameter struct {
	Files                []*ent.File
	DstMap               map[int][]*ent.File
	ExcludedMetadataKeys []string
}

type CreateDavAccountParams

type CreateDavAccountParams struct {
	UserID   int
	Name     string
	URI      string
	Password string
	Options  *boolset.BooleanSet
}

type CreateFileParameters

type CreateFileParameters struct {
	FileType            types.FileType
	Name                string
	Metadata            map[string]string
	MetadataPrivateMask map[string]bool
	IsSymbolic          bool
	StoragePolicyID     int
	*EntityParameters
}

type CreateFolderParameters

type CreateFolderParameters struct {
	Owner               int
	Name                string
	IsSymbolic          bool
	Metadata            map[string]string
	MetadataPrivateMask map[string]bool
}

type CreateShareParams

type CreateShareParams struct {
	Existed         *ent.Share
	Password        string
	RemainDownloads int
	Expires         *time.Time
	OwnerID         int
	FileID          int
	Props           *types.ShareProps
}

type CreateStoragePackArgs

type CreateStoragePackArgs struct {
	UserID   int
	Name     string
	Size     int64
	ExpireAt time.Time
}

type DavAccountClient

type DavAccountClient interface {
	TxOperator
	// List returns a list of dav accounts with the given args.
	List(ctx context.Context, args *ListDavAccountArgs) (*ListDavAccountResult, error)
	// Create creates a new dav account.
	Create(ctx context.Context, params *CreateDavAccountParams) (*ent.DavAccount, error)
	// Update updates a dav account.
	Update(ctx context.Context, id int, params *CreateDavAccountParams) (*ent.DavAccount, error)
	// GetByIDAndUserID returns the dav account with given id and user id.
	GetByIDAndUserID(ctx context.Context, id, userID int) (*ent.DavAccount, error)
	// Delete deletes the dav account.
	Delete(ctx context.Context, id int) error
}

func NewDavAccountClient

func NewDavAccountClient(client *ent.Client, dbType conf.DBType, hasher hashid.Encoder) DavAccountClient

type DeleteTaskArgs

type DeleteTaskArgs struct {
	NotAfter time.Time
	Types    []string
	Status   []task.Status
}

type DirectLinkClient

type DirectLinkClient interface {
	TxOperator
	// GetByNameID get direct link by name and id
	GetByNameID(ctx context.Context, id int, name string) (*ent.DirectLink, error)
	// GetByID get direct link by id
	GetByID(ctx context.Context, id int) (*ent.DirectLink, error)
	// Delete delete direct link by id
	Delete(ctx context.Context, id int) error
}

func NewDirectLinkClient

func NewDirectLinkClient(client *ent.Client, dbType conf.DBType, hasher hashid.Encoder) DirectLinkClient

type EntityParameters

type EntityParameters struct {
	ModifiedAt      *time.Time
	OwnerID         int
	EntityType      types.EntityType
	StoragePolicyID int
	Source          string
	Size            int64
	UploadSessionID uuid.UUID
	Importing       bool
	EncryptMetadata *types.EncryptMetadata
}

type FileClient

type FileClient interface {
	TxOperator
	// GetByHashID returns a file by its hashID.
	GetByHashID(ctx context.Context, hashID string) (*ent.File, error)
	// GetParentFile returns the parent folder of a given file
	GetParentFile(ctx context.Context, root *ent.File, eagerLoading bool) (*ent.File, error)
	// Search file by name from a given root. eagerLoading indicates whether to load edges determined by ctx.
	GetChildFile(ctx context.Context, root *ent.File, ownerID int, child string, eagerLoading bool) (*ent.File, error)
	// Get all files under a given root
	GetChildFiles(ctx context.Context, args *ListFileParameters, ownerID int, roots ...*ent.File) (*ListFileResult, error)
	// Root returns the root folder of a given user
	Root(ctx context.Context, user *ent.User) (*ent.File, error)
	// CreateOrGetFolder creates a folder with given name under root, or return the existed one
	CreateFolder(ctx context.Context, root *ent.File, args *CreateFolderParameters) (*ent.File, error)
	// GetByIDs returns files with given IDs. The result is paginated. Caller should keep calling this until
	// returned next page is negative.
	GetByIDs(ctx context.Context, ids []int, page int) ([]*ent.File, int, error)
	// GetByID returns a file by its ID.
	GetByID(ctx context.Context, ids int) (*ent.File, error)
	// GetEntitiesByIDs returns entities with given IDs. The result is paginated. Caller should keep calling this until
	// returned next page is negative.
	GetEntitiesByIDs(ctx context.Context, ids []int, page int) ([]*ent.Entity, int, error)
	// GetEntityByID returns an entity by its ID.
	GetEntityByID(ctx context.Context, id int) (*ent.Entity, error)
	// Rename renames a file
	Rename(ctx context.Context, original *ent.File, newName string) (*ent.File, error)
	// SetParent sets parent of group of files
	SetParent(ctx context.Context, files []*ent.File, parent *ent.File) error
	// CreateFile creates a file with given parameters, returns created File, default Entity, and storage diff for owner.
	CreateFile(ctx context.Context, root *ent.File, args *CreateFileParameters) (*ent.File, *ent.Entity, StorageDiff, error)
	// UpgradePlaceholder upgrades a placeholder entity to a real version entity
	UpgradePlaceholder(ctx context.Context, file *ent.File, modifiedAt *time.Time, entityId int, entityType types.EntityType) error
	// RemoveMetadata removes metadata from a file
	RemoveMetadata(ctx context.Context, file *ent.File, keys ...string) error
	// CreateEntity creates an entity with given parameters, returns created Entity, and storage diff for owner.
	CreateEntity(ctx context.Context, file *ent.File, args *EntityParameters) (*ent.Entity, StorageDiff, error)
	// RemoveStaleEntities hard-delete stale placeholder entities
	RemoveStaleEntities(ctx context.Context, file *ent.File) (StorageDiff, error)
	// RemoveEntitiesByID hard-delete entities by IDs.
	RemoveEntitiesByID(ctx context.Context, ids ...int) (map[int]int64, error)
	// CapEntities caps the number of entities of a given file. The oldest entities will be unlinked
	// if entity count exceed limit.
	CapEntities(ctx context.Context, file *ent.File, owner *ent.User, max int, entityType types.EntityType) (StorageDiff, error)
	// UpsertMetadata update or insert metadata
	UpsertMetadata(ctx context.Context, file *ent.File, data map[string]string, privateMask map[string]bool) error
	// Copy copies a layer of file to its corresponding destination folder. dstMap is a map from src parent ID to dst parent Files.
	Copy(ctx context.Context, args *CopyParameter) (map[int][]*ent.File, StorageDiff, error)
	// Delete deletes a group of files (and related models) with given entity recycle option
	Delete(ctx context.Context, files []*ent.File, options *types.EntityProps) ([]*ent.Entity, StorageDiff, error)
	// StaleEntities returns stale entities of a given file. If ID is not provided, all entities
	// will be examined.
	StaleEntities(ctx context.Context, ids ...int) ([]*ent.Entity, error)
	// QueryMetadata load metadata of a given file
	QueryMetadata(ctx context.Context, root *ent.File) error
	// SoftDelete soft-deletes a file, also renaming it to a random name
	SoftDelete(ctx context.Context, file *ent.File) error
	// SetPrimaryEntity sets primary entity of a file
	SetPrimaryEntity(ctx context.Context, file *ent.File, entity *ent.Entity) error
	// UnlinkEntity unlinks an entity from a file
	UnlinkEntity(ctx context.Context, entity *ent.Entity, file *ent.File, owner *ent.User) (StorageDiff, error)
	// CreateDirectLink creates a direct link for a file
	CreateDirectLink(ctx context.Context, fileID int, name string, speed int, reuse bool) (*ent.DirectLink, error)
	// CountIndexableFiles counts files suitable for FTS indexing (non-empty name, has parent, is file type).
	CountIndexableFiles(ctx context.Context) (int, error)
	// ListIndexableFiles lists files suitable for FTS indexing, returning up to limit files
	// with ID strictly greater than afterID. Use afterID=0 to start from the beginning.
	ListIndexableFiles(ctx context.Context, afterID, limit int) ([]*ent.File, error)
	// CountByTimeRange counts files created in a given time range
	CountByTimeRange(ctx context.Context, start, end *time.Time) (int, error)
	// CountEntityByTimeRange counts entities created in a given time range
	CountEntityByTimeRange(ctx context.Context, start, end *time.Time) (int, error)
	// CountEntityByStoragePolicyID counts entities by storage policy ID
	CountEntityByStoragePolicyID(ctx context.Context, storagePolicyID int) (int, int, error)
	// IsStoragePolicyUsedByEntities checks if a storage policy is used by entities
	IsStoragePolicyUsedByEntities(ctx context.Context, policyID int) (bool, error)
	// DeleteByUser deletes all files by a given user
	DeleteByUser(ctx context.Context, uid int) error
	// FlattenListFiles list files ignoring hierarchy
	FlattenListFiles(ctx context.Context, args *FlattenListFileParameters) (*ListFileResult, error)
	// Update updates a file
	Update(ctx context.Context, file *ent.File) (*ent.File, error)
	// ListEntities lists entities
	ListEntities(ctx context.Context, args *ListEntityParameters) (*ListEntityResult, error)
	// UpdateProps updates props of a file
	UpdateProps(ctx context.Context, file *ent.File, props *types.FileProps) (*ent.File, error)
	// UpdateModifiedAt updates modified at of a file
	UpdateModifiedAt(ctx context.Context, file *ent.File, modifiedAt time.Time) error
	// DeleteAllMetadataByName deletes all metadata by a given name
	DeleteAllMetadataByName(ctx context.Context, name string) error
}

func NewFileClient

func NewFileClient(client *ent.Client, dbType conf.DBType, hasher hashid.Encoder) FileClient

type FlattenListFileParameters

type FlattenListFileParameters struct {
	*PaginationArgs
	UserID          int
	Name            string
	StoragePolicyID int
	HasMetadata     string
	Shared          bool
	HasDirectLink   bool
}

type FsEventClient

type FsEventClient interface {
	TxOperator
	// Create a new FsEvent
	Create(ctx context.Context, uid int, subscriberId uuid.UUID, events ...string) error
	// Delete all FsEvents by subscriber
	DeleteBySubscriber(ctx context.Context, subscriberId uuid.UUID) error
	// Delete all FsEvents
	DeleteAll(ctx context.Context) error
	// Get all FsEvents by subscriber and user
	TakeBySubscriber(ctx context.Context, subscriberId uuid.UUID, userId int) ([]*ent.FsEvent, error)
}

func NewFsEventClient

func NewFsEventClient(client *ent.Client, dbType conf.DBType) FsEventClient

type GroupClient

type GroupClient interface {
	TxOperator
	// AnonymousGroup returns the anonymous group.
	AnonymousGroup(ctx context.Context) (*ent.Group, error)
	// ListAll returns all groups.
	ListAll(ctx context.Context) ([]*ent.Group, error)
	// GetByID returns the group by id.
	GetByID(ctx context.Context, id int) (*ent.Group, error)
	// ListGroups returns a list of groups with pagination.
	ListGroups(ctx context.Context, args *ListGroupParameters) (*ListGroupResult, error)
	// CountUsers returns the number of users in the group.
	CountUsers(ctx context.Context, id int) (int, error)
	// Upsert upserts a group.
	Upsert(ctx context.Context, group *ent.Group) (*ent.Group, error)
	// Delete deletes a group.
	Delete(ctx context.Context, id int) error
}

func NewGroupClient

func NewGroupClient(client *ent.Client, dbType conf.DBType, cache cache.Driver) GroupClient

type ListDavAccountArgs

type ListDavAccountArgs struct {
	*PaginationArgs
	UserID int
}

type ListDavAccountResult

type ListDavAccountResult struct {
	*PaginationResults
	Accounts []*ent.DavAccount
}

type ListEntityParameters

type ListEntityParameters struct {
	*PaginationArgs
	EntityType      *types.EntityType
	UserID          int
	StoragePolicyID int
}

type ListEntityResult

type ListEntityResult struct {
	Entities []*ent.Entity
	*PaginationResults
}

type ListFileParameters

type ListFileParameters struct {
	*PaginationArgs
	// Whether to mix folder with files in results, only applied to cursor pagination
	MixedType bool
	// Whether to include only folder in results, only applied to cursor pagination
	FolderOnly bool
	// SharedWithMe indicates whether to list files shared with the user
	SharedWithMe bool
	Search       *SearchFileParameters
}

Parameters for file list

type ListFileResult

type ListFileResult struct {
	Files     []*ent.File
	MixedType bool
	*PaginationResults
}

type ListGroupParameters

type ListGroupParameters struct {
	*PaginationArgs
}

type ListGroupResult

type ListGroupResult struct {
	*PaginationResults
	Groups []*ent.Group
}

type ListNodeParameters

type ListNodeParameters struct {
	*PaginationArgs
	Status node.Status
}

type ListNodeResult

type ListNodeResult struct {
	*PaginationResults
	Nodes []*ent.Node
}

type ListOAuthClientArgs

type ListOAuthClientArgs struct {
	*PaginationArgs
	Name      string
	IsEnabled *bool
}

type ListOAuthClientResult

type ListOAuthClientResult struct {
	*PaginationResults
	Clients []*ent.OAuthClient
}

type ListPolicyParameters

type ListPolicyParameters struct {
	*PaginationArgs
	Type types.PolicyType
}

type ListPolicyResult

type ListPolicyResult struct {
	*PaginationResults
	Policies []*ent.StoragePolicy
}

type ListShareArgs

type ListShareArgs struct {
	*PaginationArgs
	UserID     int
	FileID     int
	PublicOnly bool
	ShareIDs   []int
}

type ListShareResult

type ListShareResult struct {
	*PaginationResults
	Shares []*ent.Share
}

type ListTaskArgs

type ListTaskArgs struct {
	*PaginationArgs
	Types         []string
	Status        []task.Status
	UserID        int
	CorrelationID *uuid.UUID
}

type ListTaskResult

type ListTaskResult struct {
	*PaginationResults
	Tasks []*ent.Task
}

type ListUserParameters

type ListUserParameters struct {
	*PaginationArgs
	GroupID int
	Status  user.Status
	Nick    string
	Email   string
}

type ListUserResult

type ListUserResult struct {
	*PaginationResults
	Users []*ent.User
}

type LoadDirectLinkFile

type LoadDirectLinkFile struct{}

type LoadEntityFile

type LoadEntityFile struct{}

type LoadEntityStoragePolicy

type LoadEntityStoragePolicy struct{}

type LoadEntityUser

type LoadEntityUser struct{}
type LoadFileDirectLink struct{}

type LoadFileEntity

type LoadFileEntity struct{}

Ctx keys for eager loading options.

type LoadFileMetadata

type LoadFileMetadata struct{}

type LoadFilePublicMetadata

type LoadFilePublicMetadata struct{}

type LoadFileShare

type LoadFileShare struct{}

type LoadFileUser

type LoadFileUser struct{}

type LoadGroupPolicy

type LoadGroupPolicy struct{}

Ctx keys for eager loading options.

type LoadNodeStoragePolicy

type LoadNodeStoragePolicy struct{}

type LoadOAuthGrantClient

type LoadOAuthGrantClient struct{}

type LoadShareFile

type LoadShareFile struct{}

Ctx keys for eager loading options.

type LoadShareUser

type LoadShareUser struct{}

type LoadStoragePolicyGroup

type LoadStoragePolicyGroup struct{}

type LoadTaskUser

type LoadTaskUser struct{}

Ctx keys for eager loading options.

type LoadUserGroup

type LoadUserGroup struct{}

Ctx keys for eager loading options.

type LoadUserPasskey

type LoadUserPasskey struct{}

type MailTemplateContent

type MailTemplateContent struct {
	Language        string
	EmailIsAutoSend string // Translation of `此邮件由系统自动发送。`

	ActiveTitle  string // Translation of `激活你的账号`
	ActiveDes    string // Translation of `请点击下方按钮确认你的电子邮箱并完成账号注册,此链接有效期为 24 小时。`
	ActiveButton string // Translation of `确认激活`

	ResetTitle  string // Translation of `重设密码`
	ResetDes    string // Translation of `请点击下方按钮重设你的密码,此链接有效期为 1 小时。`
	ResetButton string // Translation of `重设密码`
}

type MetadataFilter

type MetadataFilter struct {
	Key   string
	Value string
	Exact bool
}

type NewUserArgs

type NewUserArgs struct {
	Email         string
	Nick          string // Optional
	PlainPassword string
	Status        user.Status
	GroupID       int
	Avatar        string // Optional
	Language      string // Optional
}

NewUserArgs args to create a new user

type NodeClient

type NodeClient interface {
	TxOperator
	// ListActiveNodes returns the active nodes.
	ListActiveNodes(ctx context.Context, subset []int) ([]*ent.Node, error)
	// ListNodes returns the nodes with pagination.
	ListNodes(ctx context.Context, args *ListNodeParameters) (*ListNodeResult, error)
	// GetNodeById returns the node by id.
	GetNodeById(ctx context.Context, id int) (*ent.Node, error)
	// GetNodeByIds returns the nodes by ids.
	GetNodeByIds(ctx context.Context, ids []int) ([]*ent.Node, error)
	// Upsert upserts a node.
	Upsert(ctx context.Context, n *ent.Node) (*ent.Node, error)
	// Delete deletes a node.
	Delete(ctx context.Context, id int) error
}

func NewNodeClient

func NewNodeClient(client *ent.Client) NodeClient

type OAuthClientClient

type OAuthClientClient interface {
	TxOperator
	// GetByGUID returns the OAuth client by its GUID (client_id).
	GetByGUID(ctx context.Context, guid string) (*ent.OAuthClient, error)
	// GetByGUIDWithGrants returns the OAuth client by its GUID (client_id) with the grants for the user.
	GetByGUIDWithGrants(ctx context.Context, guid string, uid int) (*ent.OAuthClient, error)
	// UpsertGrant creates or updates an OAuth grant for a user and client.
	UpsertGrant(ctx context.Context, userID, clientID int, scopes []string) error
	// UpdateGrantLastUsedAt updates the last used at for an OAuth grant for a user and client.
	UpdateGrantLastUsedAt(ctx context.Context, userID, clientID int) error
	// DeleteGrantByUserAndClientGUID deletes an OAuth grant for a user by the client GUID.
	// Returns true if the grant was deleted, false if it was not found.
	DeleteGrantByUserAndClientGUID(ctx context.Context, userID int, clientGUID string) (bool, error)
	// List returns a paginated list of OAuth clients.
	List(ctx context.Context, args *ListOAuthClientArgs) (*ListOAuthClientResult, error)
	// GetByID returns the OAuth client by its ID.
	GetByID(ctx context.Context, id int) (*ent.OAuthClient, error)
	// Create creates a new OAuth client.
	Create(ctx context.Context, client *ent.OAuthClient) (*ent.OAuthClient, error)
	// Update updates an existing OAuth client.
	Update(ctx context.Context, client *ent.OAuthClient) (*ent.OAuthClient, error)
	// Delete deletes an OAuth client by its ID.
	Delete(ctx context.Context, id int) error
	// CountGrants returns the number of grants for an OAuth client.
	CountGrants(ctx context.Context, id int) (int, error)
	// GetGrantsByUserID returns the OAuth grants for a user.
	GetGrantsByUserID(ctx context.Context, userID int) ([]*ent.OAuthGrant, error)
}

func NewOAuthClientClient

func NewOAuthClientClient(client *ent.Client, dbType conf.DBType) OAuthClientClient

type OrderDirection

type OrderDirection string

type PageToken

type PageToken struct {
	Time          *time.Time `json:"time,omitempty"`
	ID            int        `json:"-"`
	IDHash        string     `json:"id,omitempty"`
	String        string     `json:"string,omitempty"`
	Int           int        `json:"int,omitempty"`
	StartWithFile bool       `json:"start_with_file,omitempty"`
}

func (*PageToken) Encode

func (p *PageToken) Encode(hasher hashid.Encoder, encodeFunc hashid.EncodeFunc) (string, error)

type PaginationArgs

type PaginationArgs struct {
	UseCursorPagination bool
	Page                int
	PageToken           string
	PageSize            int
	OrderBy             string
	Order               OrderDirection
}

type PaginationResults

type PaginationResults struct {
	Page          int    `json:"page"`
	PageSize      int    `json:"page_size"`
	TotalItems    int    `json:"total_items,omitempty"`
	NextPageToken string `json:"next_token,omitempty"`
	IsCursor      bool   `json:"is_cursor,omitempty"`
}

type Patch

type Patch struct {
	Name       string
	EndVersion string
	Func       PatchFunc
}

type PatchFunc

type PatchFunc func(l logging.Logger, client *ent.Client, ctx context.Context) error

type RelocateEntityParameter

type RelocateEntityParameter struct {
	Entity                   *ent.Entity
	NewSource                string
	ParentFiles              []int
	PrimaryEntityParentFiles []int
}

type SearchFileParameters

type SearchFileParameters struct {
	Name []string
	// NameOperatorOr is true if the name should match any of the given names, false if all of them
	NameOperatorOr bool
	Metadata       []MetadataFilter
	Type           *types.FileType
	UseFullText    bool
	CaseFolding    bool
	Category       string
	SizeGte        int64
	SizeLte        int64
	CreatedAtGte   *time.Time
	CreatedAtLte   *time.Time
	UpdatedAtGte   *time.Time
	UpdatedAtLte   *time.Time
}

type SettingClient

type SettingClient interface {
	TxOperator
	// Get gets a setting value from DB, returns error if setting cannot be found.
	Get(ctx context.Context, name string) (string, error)
	// Set sets a setting value to DB.
	Set(ctx context.Context, settings map[string]string) error
	// Gets gets multiple setting values from DB, returns error if any setting cannot be found.
	Gets(ctx context.Context, names []string) (map[string]string, error)
}

func NewSettingClient

func NewSettingClient(client *ent.Client, kv cache.Driver) SettingClient

NewSettingClient creates a new SettingClient

type ShareClient

type ShareClient interface {
	TxOperator
	// GetByIDs returns the shares with given ids.
	GetByIDs(ctx context.Context, ids []int) ([]*ent.Share, error)
	// GetByID returns the share with given id.
	GetByID(ctx context.Context, id int) (*ent.Share, error)
	// GetByIDUser returns the share with given id and user id.
	GetByIDUser(ctx context.Context, id, uid int) (*ent.Share, error)
	// GetByHashID returns the share with given hash id.
	GetByHashID(ctx context.Context, idRaw string) (*ent.Share, error)
	// Upsert creates or update a new share record.
	Upsert(ctx context.Context, params *CreateShareParams) (*ent.Share, error)
	// Viewed increase the view count of the share.
	Viewed(ctx context.Context, share *ent.Share) error
	// Downloaded increase the download count of the share.
	Downloaded(ctx context.Context, share *ent.Share) error
	// Delete deletes the share.
	Delete(ctx context.Context, shareId int) error
	// List returns a list of shares with the given args.
	List(ctx context.Context, args *ListShareArgs) (*ListShareResult, error)
	// CountByTimeRange counts the number of shares created in the given time range.
	CountByTimeRange(ctx context.Context, start, end *time.Time) (int, error)
	// DeleteBatch deletes the shares with the given ids.
	DeleteBatch(ctx context.Context, shareIds []int) error
}

func NewShareClient

func NewShareClient(client *ent.Client, dbType conf.DBType, hasher hashid.Encoder) ShareClient

type SkipStoragePolicyCache

type SkipStoragePolicyCache struct{}

type StorageDiff

type StorageDiff map[int]int64

func (*StorageDiff) Merge

func (s *StorageDiff) Merge(diff StorageDiff)

type StoragePolicyClient

type StoragePolicyClient interface {
	TxOperator
	// GetByGroup returns the storage policies of the group.
	GetByGroup(ctx context.Context, group *ent.Group) (*ent.StoragePolicy, error)
	// GetPolicyByID returns the storage policy by id.
	GetPolicyByID(ctx context.Context, id int) (*ent.StoragePolicy, error)
	// UpdateAccessKey updates the access key of the storage policy. It also clear related cache in KV.
	UpdateAccessKey(ctx context.Context, policy *ent.StoragePolicy, token string) error
	// ListPolicyByType returns the storage policies by type.
	ListPolicyByType(ctx context.Context, t types.PolicyType) ([]*ent.StoragePolicy, error)
	// ListPolicies returns the storage policies with pagination.
	ListPolicies(ctx context.Context, args *ListPolicyParameters) (*ListPolicyResult, error)
	// Upsert upserts the storage policy.
	Upsert(ctx context.Context, policy *ent.StoragePolicy) (*ent.StoragePolicy, error)
	// Delete deletes the storage policy.
	Delete(ctx context.Context, policy *ent.StoragePolicy) error
}

func NewStoragePolicyClient

func NewStoragePolicyClient(client *ent.Client, cache cache.Driver) StoragePolicyClient

NewStoragePolicyClient returns a new StoragePolicyClient.

type TaskArgs

type TaskArgs struct {
	Status        task.Status
	Type          string
	PublicState   *types.TaskPublicState
	PrivateState  string
	OwnerID       int
	CorrelationID uuid.UUID
}

type TaskClient

type TaskClient interface {
	TxOperator
	// New creates a new task with the given args.
	New(ctx context.Context, task *TaskArgs) (*ent.Task, error)
	// Update updates the task with the given args.
	Update(ctx context.Context, task *ent.Task, args *TaskArgs) (*ent.Task, error)
	// GetPendingTasks returns all pending tasks of given type.
	GetPendingTasks(ctx context.Context, taskType ...string) ([]*ent.Task, error)
	// GetTaskByID returns the task with the given ID.
	GetTaskByID(ctx context.Context, taskID int) (*ent.Task, error)
	// SetCompleteByID sets the task with the given ID to complete.
	SetCompleteByID(ctx context.Context, taskID int) error
	// List returns a list of tasks with the given args.
	List(ctx context.Context, args *ListTaskArgs) (*ListTaskResult, error)
	// DeleteByIDs deletes the tasks with the given IDs.
	DeleteByIDs(ctx context.Context, ids ...int) error
	// DeleteBy deletes the tasks with the given args.
	DeleteBy(ctx context.Context, args *DeleteTaskArgs) error
}

func NewTaskClient

func NewTaskClient(client *ent.Client, dbType conf.DBType, hasher hashid.Encoder) TaskClient

type Tx

type Tx struct {
	// contains filtered or unexported fields
}

func InheritTx

func InheritTx[T TxOperator](ctx context.Context, c T) (T, *Tx)

InheritTx wraps the given inventory client with a transaction. If the transaction is already in the context, it will be inherited. Otherwise, original client will be returned.

func WithTx

func WithTx[T TxOperator](ctx context.Context, c T) (T, *Tx, context.Context, error)

WithTx wraps the given inventory client with a transaction.

func (*Tx) AppendStorageDiff

func (t *Tx) AppendStorageDiff(diff StorageDiff)

AppendStorageDiff appends the given storage diff to the transaction.

type TxCtx

type TxCtx struct{}

TxCtx is the context key for inherited transaction

type TxOperator

type TxOperator interface {
	SetClient(newClient *ent.Client) TxOperator
	GetClient() *ent.Client
}

type UserClient

type UserClient interface {
	TxOperator
	// New creates a new user. If user email registered, existed User will be returned.
	Create(ctx context.Context, args *NewUserArgs) (*ent.User, error)
	// GetByEmail get the user with given email, user status is ignored.
	GetByEmail(ctx context.Context, email string) (*ent.User, error)
	// GetByID get user by its ID, user status is ignored.
	GetByID(ctx context.Context, id int) (*ent.User, error)
	// GetActiveByID get user by its ID, only active user will be returned.
	GetActiveByID(ctx context.Context, id int) (*ent.User, error)
	// SetStatus Set user to given status
	SetStatus(ctx context.Context, u *ent.User, status user.Status) (*ent.User, error)
	// AnonymousUser returns the anonymous user.
	AnonymousUser(ctx context.Context) (*ent.User, error)
	// GetLoginUserByID returns the login user by its ID. It emits some errors and fallback to anonymous user.
	GetLoginUserByID(ctx context.Context, uid int) (*ent.User, error)
	// GetLoginUserByEmail returns the login user by its WebDAV credentials.
	GetActiveByDavAccount(ctx context.Context, email, pwd string) (*ent.User, error)
	// SaveSettings saves user settings.
	SaveSettings(ctx context.Context, u *ent.User) error
	// SearchActive search active users by Email or nickname.
	SearchActive(ctx context.Context, limit int, keyword string) ([]*ent.User, error)
	// ApplyStorageDiff apply storage diff to user.
	ApplyStorageDiff(ctx context.Context, diffs StorageDiff) error
	// UpdateAvatar updates user avatar.
	UpdateAvatar(ctx context.Context, u *ent.User, avatar string) (*ent.User, error)
	// UpdateNickname updates user nickname.
	UpdateNickname(ctx context.Context, u *ent.User, name string) (*ent.User, error)
	// UpdatePassword updates user password.
	UpdatePassword(ctx context.Context, u *ent.User, newPassword string) (*ent.User, error)
	// UpdateTwoFASecret updates user two factor secret.
	UpdateTwoFASecret(ctx context.Context, u *ent.User, secret string) (*ent.User, error)
	// ListPasskeys list user's passkeys.
	ListPasskeys(ctx context.Context, uid int) ([]*ent.Passkey, error)
	// AddPasskey add passkey to user.
	AddPasskey(ctx context.Context, uid int, name string, credential *webauthn.Credential) (*ent.Passkey, error)
	// RemovePasskey remove passkey from user.
	RemovePasskey(ctx context.Context, uid int, keyId string) error
	// MarkPasskeyUsed updates passkey used at.
	MarkPasskeyUsed(ctx context.Context, uid int, keyId string) error
	// CountByTimeRange count users by time range. Will return all records if start or end is nil.
	CountByTimeRange(ctx context.Context, start, end *time.Time) (int, error)
	// ListUsers list users with pagination.
	ListUsers(ctx context.Context, args *ListUserParameters) (*ListUserResult, error)
	// Upsert upserts a user.
	Upsert(ctx context.Context, u *ent.User, password, twoFa string) (*ent.User, error)
	// Delete deletes a user.
	Delete(ctx context.Context, uid int) error
	// CalculateStorage calculate user's storage from scratch and update user's storage.
	CalculateStorage(ctx context.Context, uid int) (int64, error)
}

func NewUserClient

func NewUserClient(client *ent.Client) UserClient

type UserCtx

type UserCtx struct{}

type UserIDCtx

type UserIDCtx struct{}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL