2016-05-16 16:44:58 +08:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"path"
|
|
|
|
|
2016-05-16 20:32:00 +08:00
|
|
|
"github.com/anacrolix/missinggo/resource"
|
2016-05-16 16:44:58 +08:00
|
|
|
|
|
|
|
"github.com/anacrolix/torrent/metainfo"
|
|
|
|
)
|
|
|
|
|
|
|
|
type piecePerResource struct {
|
2016-05-16 20:32:00 +08:00
|
|
|
p resource.Provider
|
2016-05-16 16:44:58 +08:00
|
|
|
}
|
|
|
|
|
2016-09-02 13:10:57 +08:00
|
|
|
func NewResourcePieces(p resource.Provider) ClientImpl {
|
2016-05-16 16:44:58 +08:00
|
|
|
return &piecePerResource{
|
|
|
|
p: p,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-09-02 13:10:57 +08:00
|
|
|
func (s *piecePerResource) OpenTorrent(info *metainfo.Info, infoHash metainfo.Hash) (TorrentImpl, error) {
|
2016-05-16 16:44:58 +08:00
|
|
|
return s, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *piecePerResource) Close() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2016-09-02 13:10:57 +08:00
|
|
|
func (s *piecePerResource) Piece(p metainfo.Piece) PieceImpl {
|
2016-05-16 20:32:00 +08:00
|
|
|
completed, err := s.p.NewInstance(path.Join("completed", p.Hash().HexString()))
|
2016-05-16 16:44:58 +08:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2016-05-16 20:32:00 +08:00
|
|
|
incomplete, err := s.p.NewInstance(path.Join("incomplete", p.Hash().HexString()))
|
2016-05-16 16:44:58 +08:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return piecePerResourcePiece{
|
|
|
|
p: p,
|
|
|
|
c: completed,
|
|
|
|
i: incomplete,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type piecePerResourcePiece struct {
|
|
|
|
p metainfo.Piece
|
2016-05-16 20:32:00 +08:00
|
|
|
c resource.Instance
|
|
|
|
i resource.Instance
|
2016-05-16 16:44:58 +08:00
|
|
|
}
|
|
|
|
|
2017-10-12 13:09:32 +08:00
|
|
|
func (s piecePerResourcePiece) Completion() Completion {
|
2016-05-16 16:44:58 +08:00
|
|
|
fi, err := s.c.Stat()
|
2017-10-12 13:09:32 +08:00
|
|
|
return Completion{
|
|
|
|
Complete: err == nil && fi.Size() == s.p.Length(),
|
|
|
|
Ok: true,
|
|
|
|
}
|
2016-05-16 16:44:58 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s piecePerResourcePiece) MarkComplete() error {
|
2016-05-16 20:32:00 +08:00
|
|
|
return resource.Move(s.i, s.c)
|
2016-05-16 16:44:58 +08:00
|
|
|
}
|
|
|
|
|
2016-09-02 13:10:57 +08:00
|
|
|
func (s piecePerResourcePiece) MarkNotComplete() error {
|
|
|
|
return s.c.Delete()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s piecePerResourcePiece) ReadAt(b []byte, off int64) (int, error) {
|
2017-10-12 13:09:32 +08:00
|
|
|
if s.Completion().Complete {
|
2016-09-02 13:10:57 +08:00
|
|
|
return s.c.ReadAt(b, off)
|
|
|
|
} else {
|
|
|
|
return s.i.ReadAt(b, off)
|
2016-05-16 16:44:58 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s piecePerResourcePiece) WriteAt(b []byte, off int64) (n int, err error) {
|
|
|
|
return s.i.WriteAt(b, off)
|
|
|
|
}
|