files

package
v0.2.0 Latest Latest
Warning

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

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

Documentation

Overview

Package files 提供文件管理 HTTP 处理器

Package files 提供文件管理模块

Package files 提供文件管理模块

Package files 提供文件管理服务

Package files 缩略图生成服务

Index

Constants

View Source
const (
	ModuleID      = "files"
	ModuleName    = "File Manager"
	ModuleVersion = "1.0.0"
)
View Source
const (
	// ElevationDuration 管理员提权持续时间
	ElevationDuration = 5 * time.Minute
)

Variables

View Source
var (
	ErrPathEmpty        = errors.New("path is empty")
	ErrPathNotExist     = errors.New("path does not exist")
	ErrPathExists       = errors.New("path already exists")
	ErrNotFile          = errors.New("path is not a file")
	ErrNotDir           = errors.New("path is not a directory")
	ErrPermissionDenied = errors.New("permission denied")
	ErrMountedPath      = errors.New("cannot operate on mounted path")
	ErrSameSourceDest   = errors.New("source and destination are the same")
	ErrInvalidOperation = errors.New("invalid operation type")
)

Functions

func NewModule

func NewModule() module.Module

NewModule 创建模块实例

func SupportsThumbnail

func SupportsThumbnail(filePath string) bool

SupportsThumbnail 判断文件是否支持缩略图

Types

type AudioMetadataResponse

type AudioMetadataResponse struct {
	Title       string `json:"title,omitempty"`
	Artist      string `json:"artist,omitempty"`
	Album       string `json:"album,omitempty"`
	AlbumArtist string `json:"album_artist,omitempty"`
	Composer    string `json:"composer,omitempty"`
	Genre       string `json:"genre,omitempty"`
	Year        int    `json:"year,omitempty"`
	Track       int    `json:"track,omitempty"`
	TrackTotal  int    `json:"track_total,omitempty"`
	Disc        int    `json:"disc,omitempty"`
	DiscTotal   int    `json:"disc_total,omitempty"`
	Duration    int    `json:"duration,omitempty"` // 秒
	Lyrics      string `json:"lyrics,omitempty"`   // 内嵌歌词
	Format      string `json:"format,omitempty"`   // MP3, FLAC, etc.
	FileType    string `json:"file_type,omitempty"`
	HasPicture  bool   `json:"has_picture"`
}

AudioMetadataResponse 音频元数据响应

type BookmarkItem

type BookmarkItem struct {
	Icon  string `json:"icon"`
	Label string `json:"label"`
	Path  string `json:"path"`
}

BookmarkItem 书签条目

type BookmarksResponse

type BookmarksResponse struct {
	Default  []BookmarkItem `json:"default"`
	System   []BookmarkItem `json:"system"`
	HomePath string         `json:"home_path"`
}

BookmarksResponse 书签响应

type CompleteUploadRequest

type CompleteUploadRequest struct {
	UploadID string `json:"upload_id"`
}

CompleteUploadRequest 完成上传请求

type CreateRequest

type CreateRequest struct {
	Path    string `json:"path" binding:"required"`
	Name    string `json:"name"`
	IsDir   bool   `json:"is_dir"`
	Content string `json:"content,omitempty"`
}

CreateRequest 创建文件/目录请求

type DiskUsage

type DiskUsage struct {
	Path    string  `json:"path"`
	Total   int64   `json:"total"`
	Used    int64   `json:"used"`
	Free    int64   `json:"free"`
	UsedPct float64 `json:"used_percent"`
}

DiskUsage 磁盘使用情况

type DownloadRequest

type DownloadRequest struct {
	Files  []string `json:"files" form:"files"`   // 文件列表
	Format string   `json:"format" form:"format"` // 压缩格式: zip, tar, targz
}

DownloadRequest 下载请求

type ElevationManager

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

ElevationManager 管理员提权会话管理器

func NewElevationManager

func NewElevationManager() *ElevationManager

NewElevationManager 创建提权会话管理器

func (*ElevationManager) Elevate

func (em *ElevationManager) Elevate(userID, username string) *ElevationSession

Elevate 创建提权会话

func (*ElevationManager) GetStatus

func (em *ElevationManager) GetStatus(userID string) *ElevationSession

GetStatus 获取提权状态

func (*ElevationManager) IsElevated

func (em *ElevationManager) IsElevated(userID string) bool

IsElevated 检查用户是否处于提权状态

func (*ElevationManager) Revoke

func (em *ElevationManager) Revoke(userID string)

Revoke 撤销提权

type ElevationSession

type ElevationSession struct {
	UserID    string    `json:"user_id"`
	Username  string    `json:"username"`
	ExpiresAt time.Time `json:"expires_at"`
}

ElevationSession 提权会话信息

type FileInfo

type FileInfo struct {
	Name       string                 `json:"name"`
	Path       string                 `json:"path"`
	Size       int64                  `json:"size"`
	IsDir      bool                   `json:"is_dir"`
	IsSymlink  bool                   `json:"is_symlink,omitempty"`
	LinkTarget string                 `json:"link_target,omitempty"`
	ModTime    time.Time              `json:"modified"`
	Mode       string                 `json:"mode,omitempty"`
	Owner      string                 `json:"owner,omitempty"`
	Group      string                 `json:"group,omitempty"`
	MimeType   string                 `json:"mime_type,omitempty"`
	Extensions map[string]interface{} `json:"extensions,omitempty"`
}

FileInfo 文件/目录信息

type FileItem

type FileItem struct {
	Path          string `json:"path" binding:"required"`
	Size          int64  `json:"size"`
	ProcessedSize int64  `json:"processed_size"`
	Finished      bool   `json:"finished"`
}

FileItem 操作项

type FileOperation

type FileOperation struct {
	Type          string     `json:"type" binding:"required"` // move, copy
	Items         []FileItem `json:"items" binding:"required"`
	Destination   string     `json:"destination" binding:"required"`
	ConflictStyle string     `json:"conflict_style"` // skip, overwrite
	TotalSize     int64      `json:"total_size"`
	ProcessedSize int64      `json:"processed_size"`
	Finished      bool       `json:"finished"`
	Username      string     `json:"-"` // 执行操作的用户名,不从 JSON 读取
}

FileOperation 文件操作(复制/移动)

type FileStats

type FileStats struct {
	TotalFiles int64 `json:"total_files"`
	TotalDirs  int64 `json:"total_dirs"`
	TotalSize  int64 `json:"total_size"`
}

FileStats 文件统计

type Handler

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

Handler HTTP 处理器

func NewHandler

func NewHandler(service *Service, thumbnails *ThumbnailService, db *gorm.DB) *Handler

NewHandler 创建处理器

func (*Handler) AbortUpload

func (h *Handler) AbortUpload(c *gin.Context)

AbortUpload 取消上传 @Summary 取消分片上传 @Tags files @Accept json @Produce json @Param upload_id query string true "上传ID" @Success 200 {object} response @Router /api/v1/files/upload/abort [delete]

func (*Handler) CancelOperation

func (h *Handler) CancelOperation(c *gin.Context)

CancelOperation 取消操作 @Summary 取消文件操作 @Tags files @Accept json @Produce json @Param id query string true "操作ID" @Success 200 {object} response @Router /api/v1/files/operate/cancel [delete]

func (*Handler) CompleteUpload

func (h *Handler) CompleteUpload(c *gin.Context)

CompleteUpload 完成分片上传 @Summary 完成分片上传 @Tags files @Accept json @Produce json @Param body body CompleteUploadRequest true "上传信息" @Success 200 {object} response @Router /api/v1/files/upload/complete [post]

func (*Handler) CreateDir

func (h *Handler) CreateDir(c *gin.Context)

CreateDir 创建目录 @Summary 创建目录 @Tags files @Accept json @Produce json @Param body body CreateRequest true "创建请求" @Success 200 {object} response @Router /api/v1/files/mkdir [post]

func (*Handler) CreateFile

func (h *Handler) CreateFile(c *gin.Context)

CreateFile 创建文件 @Summary 创建文件 @Tags files @Accept json @Produce json @Param body body CreateRequest true "创建请求" @Success 200 {object} response @Router /api/v1/files/create [post]

func (*Handler) Delete

func (h *Handler) Delete(c *gin.Context)

Delete 删除文件/目录 @Summary 删除文件/目录 @Tags files @Accept json @Produce json @Param body body []string true "要删除的路径列表" @Success 200 {object} response @Router /api/v1/files/delete [delete]

func (*Handler) Download

func (h *Handler) Download(c *gin.Context)

Download 下载文件 @Summary 下载文件 @Tags files @Accept json @Produce octet-stream @Param path query string true "文件路径" @Param inline query string false "是否内嵌显示(1为内嵌,否则下载)" @Success 200 {file} binary @Router /api/v1/files/download [get]

func (*Handler) Elevate

func (h *Handler) Elevate(c *gin.Context)

Elevate 管理员提权 @Summary 管理员提权(输入密码后获取5分钟的超级权限) @Tags files @Accept json @Produce json @Param body body object true "密码" SchemaExample({"password": "xxx"}) @Success 200 {object} response @Router /api/v1/files/elevate [post]

func (*Handler) GetAudioLyrics

func (h *Handler) GetAudioLyrics(c *gin.Context)

GetAudioLyrics 获取音频歌词 @Summary 获取音频歌词 @Tags files @Accept json @Produce json @Param path query string true "文件路径" @Success 200 {object} map[string]interface{} @Router /files/audio/lyrics [get]

func (*Handler) GetAudioMetadata

func (h *Handler) GetAudioMetadata(c *gin.Context)

GetAudioMetadata 获取音频文件元数据 @Summary 获取音频元数据 @Tags files @Accept json @Produce json @Param path query string true "文件路径" @Success 200 {object} AudioMetadataResponse @Router /files/audio/metadata [get]

func (*Handler) GetBookmarks

func (h *Handler) GetBookmarks(c *gin.Context)

GetBookmarks 获取当前用户的快捷访问书签

func (*Handler) GetElevationStatus

func (h *Handler) GetElevationStatus(c *gin.Context)

GetElevationStatus 获取提权状态 @Summary 获取管理员提权状态 @Tags files @Produce json @Success 200 {object} response @Router /api/v1/files/elevate [get]

func (*Handler) GetInfo

func (h *Handler) GetInfo(c *gin.Context)

GetInfo 获取文件/目录信息 @Summary 获取文件/目录信息 @Tags files @Accept json @Produce json @Param path query string true "路径" @Success 200 {object} FileInfo @Router /api/v1/files/info [get]

func (*Handler) GetOperationStatus

func (h *Handler) GetOperationStatus(c *gin.Context)

GetOperationStatus 获取操作状态 @Summary 获取文件操作状态 @Tags files @Accept json @Produce json @Param id query string true "操作ID" @Success 200 {object} OperationStatus @Router /api/v1/files/operate/status [get]

func (*Handler) GetStats

func (h *Handler) GetStats(c *gin.Context)

GetStats 获取目录统计 @Summary 获取目录统计 @Tags files @Accept json @Produce json @Param path query string true "目录路径" @Success 200 {object} FileStats @Router /api/v1/files/stats [get]

func (*Handler) InitUpload

func (h *Handler) InitUpload(c *gin.Context)

InitUpload 初始化分片上传 @Summary 初始化分片上传 @Tags files @Accept json @Produce json @Param body body InitUploadRequest true "上传信息" @Success 200 {object} response @Router /api/v1/files/upload/init [post]

func (*Handler) List

func (h *Handler) List(c *gin.Context)

List 列出目录内容 @Summary 列出目录内容 @Tags files @Accept json @Produce json @Param path query string true "目录路径" @Param index query int false "页码" default(1) @Param size query int false "每页数量" default(50) @Success 200 {object} ListResponse @Router /api/v1/files/list [get]

func (*Handler) Operate

func (h *Handler) Operate(c *gin.Context)

Operate 文件操作(复制/移动) @Summary 复制或移动文件 @Tags files @Accept json @Produce json @Param body body FileOperation true "操作请求" @Success 200 {object} response @Router /api/v1/files/operate [post]

func (*Handler) Read

func (h *Handler) Read(c *gin.Context)

Read 读取文件内容 @Summary 读取文件内容 @Tags files @Accept json @Produce json @Param path query string true "文件路径" @Success 200 {string} string "文件内容" @Router /api/v1/files/read [get]

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(group *gin.RouterGroup)

RegisterRoutes 注册路由

func (*Handler) Rename

func (h *Handler) Rename(c *gin.Context)

Rename 重命名 @Summary 重命名文件/目录 @Tags files @Accept json @Produce json @Param body body RenameRequest true "重命名请求" @Success 200 {object} response @Router /api/v1/files/rename [put]

func (*Handler) RevokeElevation

func (h *Handler) RevokeElevation(c *gin.Context)

RevokeElevation 撤销提权 @Summary 撤销管理员提权 @Tags files @Produce json @Success 200 {object} response @Router /api/v1/files/elevate [delete]

func (*Handler) Search

func (h *Handler) Search(c *gin.Context)

Search 搜索文件 @Summary 搜索文件 @Tags files @Accept json @Produce json @Param path query string true "搜索路径" @Param keyword query string true "关键字" @Param recursive query bool false "是否递归" default(false) @Param file_type query string false "文件类型" Enums(all, file, dir) @Param max_results query int false "最大结果数" default(100) @Success 200 {object} SearchResult @Router /api/v1/files/search [get]

func (*Handler) Thumbnail

func (h *Handler) Thumbnail(c *gin.Context)

Thumbnail 获取文件缩略图 @Summary 获取文件缩略图 @Tags files @Accept json @Produce image/jpeg @Param path query string true "文件路径" @Param size query int false "缩略图大小" default(256) @Param token query string false "认证 token(用于 img src)" @Success 200 {file} binary @Router /api/v1/files/thumbnail [get]

func (*Handler) Update

func (h *Handler) Update(c *gin.Context)

Update 更新文件内容 @Summary 更新文件内容 @Tags files @Accept json @Produce json @Param body body UpdateContentRequest true "更新请求" @Success 200 {object} response @Router /api/v1/files/update [put]

func (*Handler) Upload

func (h *Handler) Upload(c *gin.Context)

Upload 上传文件 @Summary 上传文件(支持分片) @Tags files @Accept multipart/form-data @Produce json @Param file formance file true "文件" @Param path formance string true "目标目录" @Param filename formance string true "文件名" @Param chunkNumber formance int false "分片编号" @Param totalChunks formance int false "总分片数" @Success 200 {object} response @Router /api/v1/files/upload [post]

func (*Handler) UploadChunk

func (h *Handler) UploadChunk(c *gin.Context)

UploadChunk 上传分片 @Summary 上传分片 @Tags files @Accept multipart/form-data @Produce json @Param upload_id formData string true "上传ID" @Param chunk_index formData int true "分片索引" @Param file formData file true "分片数据" @Success 200 {object} response @Router /api/v1/files/upload/chunk [post]

type InitUploadRequest

type InitUploadRequest struct {
	Path      string `json:"path"`
	Filename  string `json:"filename"`
	Size      int64  `json:"size"`
	ChunkSize int64  `json:"chunk_size"`
}

InitUploadRequest 初始化上传请求

type ListRequest

type ListRequest struct {
	Path       string `json:"path" form:"path"`
	Index      int    `json:"index" form:"index"`             // 页码,从1开始
	Size       int    `json:"size" form:"size"`               // 每页数量
	ShowHidden bool   `json:"show_hidden" form:"show_hidden"` // 是否显示隐藏文件
}

ListRequest 目录列表请求

type ListResponse

type ListResponse struct {
	Content      []FileInfo `json:"content"`
	Total        int64      `json:"total"`
	Index        int        `json:"index"`
	Size         int        `json:"size"`
	ResolvedPath string     `json:"resolved_path,omitempty"` // 符号链接解析后的真实路径
}

ListResponse 目录列表响应

type Module

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

Module 文件管理模块

func New

func New() *Module

New 创建文件模块

func (*Module) Dependencies

func (m *Module) Dependencies() []string

Dependencies 返回依赖模块

func (*Module) GetService

func (m *Module) GetService() *Service

GetService 获取服务实例(供其他模块调用)

func (*Module) GetThumbnailService

func (m *Module) GetThumbnailService() *ThumbnailService

GetThumbnailService 获取缩略图服务(供其他模块调用)

func (*Module) ID

func (m *Module) ID() string

ID 返回模块ID

func (*Module) Init

func (m *Module) Init(ctx *module.Context) error

Init 初始化模块

func (*Module) Name

func (m *Module) Name() string

Name 返回模块名称

func (*Module) RegisterRoutes

func (m *Module) RegisterRoutes(group *gin.RouterGroup)

RegisterRoutes 注册路由

func (*Module) Start

func (m *Module) Start() error

Start 启动模块

func (*Module) Stop

func (m *Module) Stop() error

Stop 停止模块

func (*Module) Version

func (m *Module) Version() string

Version 返回模块版本

type MountChecker

type MountChecker interface {
	IsMounted(path string) bool
}

MountChecker 挂载点检查器接口

type OperationStatus

type OperationStatus struct {
	ID            string `json:"id"`
	Type          string `json:"type"`
	TotalSize     int64  `json:"total_size"`
	ProcessedSize int64  `json:"processed_size"`
	Progress      int    `json:"progress"` // 0-100
	Finished      bool   `json:"finished"`
}

OperationStatus 操作状态

type RenameRequest

type RenameRequest struct {
	OldPath string `json:"old_path" binding:"required"`
	NewPath string `json:"new_path" binding:"required"`
}

RenameRequest 重命名请求

type SearchRequest

type SearchRequest struct {
	Path       string `json:"path" form:"path"`
	Keyword    string `json:"keyword" form:"keyword" binding:"required"`
	Recursive  bool   `json:"recursive" form:"recursive"`
	FileType   string `json:"file_type" form:"file_type"` // all, file, dir
	MaxResults int    `json:"max_results" form:"max_results"`
}

SearchRequest 搜索请求

type SearchResult

type SearchResult struct {
	Files []FileInfo `json:"files"`
	Total int        `json:"total"`
}

SearchResult 搜索结果

type Service

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

Service 文件管理服务

func NewService

func NewService(logger *zap.Logger, rootPaths []string) *Service

NewService 创建文件服务

func (*Service) CancelOperation

func (s *Service) CancelOperation(ctx context.Context, opID string) error

CancelOperation 取消操作

func (*Service) CreateDir

func (s *Service) CreateDir(ctx context.Context, path string, username string) error

CreateDir 创建目录

func (*Service) CreateFile

func (s *Service) CreateFile(ctx context.Context, path string, content []byte, username string) error

CreateFile 创建文件

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, paths []string, username string) error

Delete 删除文件/目录

func (*Service) DeleteUploadMeta

func (s *Service) DeleteUploadMeta(uploadId string)

DeleteUploadMeta 删除上传元信息

func (*Service) GenerateUploadID

func (s *Service) GenerateUploadID(path, filename string) string

GenerateUploadID 生成上传ID

func (*Service) GetHash

func (s *Service) GetHash(ctx context.Context, path string, algorithm string) (string, error)

GetHash 计算文件哈希

func (*Service) GetInfo

func (s *Service) GetInfo(ctx context.Context, path string) (*FileInfo, error)

GetInfo 获取文件/目录信息

func (*Service) GetOperationStatus

func (s *Service) GetOperationStatus(ctx context.Context, opID string) (*OperationStatus, error)

GetOperationStatus 获取操作状态

func (*Service) GetStats

func (s *Service) GetStats(ctx context.Context, path string) (*FileStats, error)

GetStats 获取目录统计

func (*Service) GetUploadMeta

func (s *Service) GetUploadMeta(uploadId string) *UploadMeta

GetUploadMeta 获取上传元信息

func (*Service) GetUploadTempDir

func (s *Service) GetUploadTempDir(destDir, filename string, totalChunks int) string

GetUploadTempDir 获取上传临时目录

func (*Service) GetUploadTempDirByID

func (s *Service) GetUploadTempDirByID(uploadId string) string

GetUploadTempDirByID 根据上传ID获取临时目录

func (*Service) List

func (s *Service) List(ctx context.Context, req *ListRequest) (*ListResponse, error)

List 列出目录内容

func (*Service) MergeChunks

func (s *Service) MergeChunks(ctx context.Context, tempDir, destPath string, totalChunks int) error

MergeChunks 合并分片文件

func (*Service) ReadFile

func (s *Service) ReadFile(ctx context.Context, path string) ([]byte, error)

ReadFile 读取文件内容

func (*Service) Rename

func (s *Service) Rename(ctx context.Context, oldPath, newPath string, username string) error

Rename 重命名文件/目录

func (*Service) SaveUploadMeta

func (s *Service) SaveUploadMeta(uploadId, path, filename string, size int64, totalChunks int)

SaveUploadMeta 保存上传元信息

func (*Service) Search

func (s *Service) Search(ctx context.Context, req *SearchRequest) (*SearchResult, error)

Search 搜索文件

func (*Service) SetMountChecker

func (s *Service) SetMountChecker(mc MountChecker)

SetMountChecker 设置挂载检查器

func (*Service) StartOperation

func (s *Service) StartOperation(ctx context.Context, op *FileOperation) (string, error)

StartOperation 开始文件操作(复制/移动)

func (*Service) WriteFile

func (s *Service) WriteFile(ctx context.Context, path string, content []byte, perm os.FileMode, username string) error

WriteFile 写入文件内容

type ThumbnailResult

type ThumbnailResult struct {
	Path      string
	Data      []byte
	MimeType  string
	Width     int
	Height    int
	FromCache bool
}

ThumbnailResult 缩略图结果

type ThumbnailService

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

ThumbnailService 缩略图服务

func NewThumbnailService

func NewThumbnailService(logger *zap.Logger, cacheDir string) *ThumbnailService

NewThumbnailService 创建缩略图服务

func (*ThumbnailService) ClearCache

func (s *ThumbnailService) ClearCache(maxAge time.Duration) error

ClearCache 清理过期缓存

func (*ThumbnailService) GetThumbnail

func (s *ThumbnailService) GetThumbnail(filePath string, size ThumbnailSize) (*ThumbnailResult, error)

GetThumbnail 获取缩略图

func (*ThumbnailService) GetThumbnailReader

func (s *ThumbnailService) GetThumbnailReader(filePath string, size ThumbnailSize) (io.ReadCloser, string, error)

GetThumbnailReader 获取缩略图 Reader(用于流式传输)

type ThumbnailSize

type ThumbnailSize int

ThumbnailSize 缩略图尺寸

const (
	ThumbnailSmall  ThumbnailSize = 128
	ThumbnailMedium ThumbnailSize = 256
	ThumbnailLarge  ThumbnailSize = 512
	ThumbnailXLarge ThumbnailSize = 1024
)

type UpdateContentRequest

type UpdateContentRequest struct {
	Path    string `json:"path" binding:"required"`
	Content string `json:"content" binding:"required"`
}

UpdateContentRequest 更新文件内容请求

type UploadChunkInfo

type UploadChunkInfo struct {
	FileName     string `json:"filename" form:"filename"`
	RelativePath string `json:"relative_path" form:"relativePath"`
	ChunkNumber  int    `json:"chunk_number" form:"chunkNumber"`
	TotalChunks  int    `json:"total_chunks" form:"totalChunks"`
	Path         string `json:"path" form:"path"` // 目标目录
}

UploadChunkInfo 分片上传信息

type UploadMeta

type UploadMeta struct {
	Path        string
	Filename    string
	Size        int64
	TotalChunks int
	CreatedAt   time.Time
}

UploadMeta 上传元信息

Jump to

Keyboard shortcuts

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