tstor/daemons/torrent/file_controller.go

100 lines
2.1 KiB
Go
Raw Permalink Normal View History

2024-07-08 21:19:04 +00:00
package torrent
import (
"context"
2024-07-10 09:26:17 +00:00
"log/slog"
2024-07-08 21:19:04 +00:00
"git.kmsign.ru/royalcat/tstor/pkg/kvsingle"
2024-07-10 09:26:17 +00:00
"git.kmsign.ru/royalcat/tstor/pkg/rlog"
2024-07-08 21:19:04 +00:00
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
"github.com/anacrolix/torrent/types"
"github.com/royalcat/kv"
)
type FileController struct {
file *torrent.File
properties *kvsingle.Value[string, FileProperties]
2024-07-10 09:26:17 +00:00
log *rlog.Logger
2024-07-08 21:19:04 +00:00
}
2024-07-10 09:26:17 +00:00
func NewFileController(f *torrent.File, properties *kvsingle.Value[string, FileProperties], log *rlog.Logger) *FileController {
2024-07-08 21:19:04 +00:00
return &FileController{
file: f,
properties: properties,
2024-07-10 09:26:17 +00:00
log: log.WithComponent("file-controller").With(slog.String("file", f.Path())),
2024-07-08 21:19:04 +00:00
}
}
func (s *FileController) Properties(ctx context.Context) (FileProperties, error) {
p, err := s.properties.Get(ctx)
if err == kv.ErrKeyNotFound {
return FileProperties{
Excluded: false,
Priority: defaultPriority,
}, nil
}
if err != nil {
return FileProperties{}, err
}
return p, nil
}
func (s *FileController) SetPriority(ctx context.Context, priority types.PiecePriority) error {
2024-07-10 09:26:17 +00:00
log := s.log.With(slog.Int("priority", int(priority)))
2024-07-08 21:19:04 +00:00
err := s.properties.Edit(ctx, func(ctx context.Context, v FileProperties) (FileProperties, error) {
v.Priority = priority
return v, nil
})
if err == kv.ErrKeyNotFound {
seterr := s.properties.Set(ctx, FileProperties{
Priority: priority,
})
if seterr != nil {
return err
}
err = nil
}
if err != nil {
return err
}
2024-07-10 09:26:17 +00:00
log.Debug(ctx, "file priority set")
2024-07-08 21:19:04 +00:00
s.file.SetPriority(priority)
return nil
}
func (s *FileController) FileInfo() metainfo.FileInfo {
return s.file.FileInfo()
}
func (s *FileController) Excluded(ctx context.Context) (bool, error) {
p, err := s.properties.Get(ctx)
if err == kv.ErrKeyNotFound {
return false, nil
}
if err != nil {
return false, err
}
return p.Excluded, nil
}
func (s *FileController) Path() string {
return s.file.Path()
}
func (s *FileController) Size() int64 {
return s.file.Length()
}
2024-07-10 09:26:17 +00:00
func (s *FileController) Priority() types.PiecePriority {
return s.file.Priority()
}
2024-07-08 21:19:04 +00:00
func (s *FileController) BytesCompleted() int64 {
return s.file.BytesCompleted()
}